From b5ff09096a80da0e37d6e126a363dd74c4dd5283 Mon Sep 17 00:00:00 2001 From: Universe Date: Sun, 22 Nov 2026 04:30:52 +0900 Subject: [PATCH] Add durable waiting steps for external workflow input --- .github/workflows/ci.yml | 2 + AGENT_READINESS.md | 12 +- CHANGELOG.md | 6 + .../grida-fx-core/src/builtins/catalog.json | 57 + crates/grida-fx-core/src/builtins/mod.rs | 32 +- crates/grida-fx-core/src/builtins/waiting.rs | 138 ++ crates/grida-fx-core/src/expand/node.rs | 17 + crates/grida-fx-core/src/plan/mod.rs | 4 +- crates/grida-fx-core/src/registry.rs | 5 + crates/grida-fx-core/src/spec.rs | 29 +- .../grida-fx-core/tests/expand_semantics.rs | 122 ++ crates/grida-fx-core/tests/planning.rs | 41 + crates/grida-fx-core/tests/routes_spec.rs | 7 +- crates/grida-fx-runtime/src/control.rs | 42 +- crates/grida-fx-runtime/src/events.rs | 27 + crates/grida-fx-runtime/src/executor/mod.rs | 5 +- crates/grida-fx-runtime/src/folder.rs | 34 +- crates/grida-fx-runtime/src/lib.rs | 2 + .../grida-fx-runtime/src/runner/awaiting.rs | 207 +++ crates/grida-fx-runtime/src/runner/mod.rs | 61 +- crates/grida-fx-runtime/src/runner/replay.rs | 48 + .../grida-fx-runtime/src/runner/schedule.rs | 37 +- crates/grida-fx-runtime/src/waiting.rs | 1555 +++++++++++++++++ crates/grida-fx-runtime/tests/events.rs | 8 + crates/grida-fx-runtime/tests/runner.rs | 512 ++++++ crates/grida-fx-viewer/src/export.rs | 1 + crates/grida-fx-viewer/src/export/tests.rs | 44 + crates/grida-fx-viewer/src/lib.rs | 9 +- crates/grida-fx-viewer/src/read.rs | 99 +- crates/grida-fx-viewer/src/service.rs | 51 +- crates/grida-fx-viewer/src/tests.rs | 223 +++ crates/grida-fx-viewer/src/waiting.rs | 126 ++ crates/grida-fx/src/args.rs | 3 +- crates/grida-fx/src/cli.rs | 29 +- crates/grida-fx/src/verbs/cache.rs | 49 +- crates/grida-fx/src/verbs/control.rs | 4 +- crates/grida-fx/src/verbs/inspect.rs | 106 +- crates/grida-fx/src/verbs/mod.rs | 1 + crates/grida-fx/src/verbs/project.rs | 11 + crates/grida-fx/src/verbs/run.rs | 24 + crates/grida-fx/src/verbs/run_set.rs | 15 +- crates/grida-fx/src/verbs/runs.rs | 38 +- crates/grida-fx/src/verbs/service.rs | 11 + crates/grida-fx/src/verbs/waiting.rs | 122 ++ crates/grida-fx/tests/cli.rs | 6 +- crates/grida-fx/tests/runs.rs | 34 + docs/guide/02-workflow-file.md | 43 + docs/guide/05-running.md | 28 + docs/guide/07-viewing.md | 38 +- docs/guide/README.md | 4 +- fixtures/waiting/README.md | 86 + fixtures/waiting/fx.yaml | 1 + fixtures/waiting/nodes.py | 64 + fixtures/waiting/showcase.yaml | 165 ++ fixtures/waiting/workflow.yaml | 53 + js/fx/README.md | 18 + js/fx/src/api.ts | 1 + js/fx/src/control.ts | 6 +- js/fx/src/documents.ts | 10 +- js/fx/src/engine.ts | 29 +- js/fx/src/index.ts | 1 + js/fx/src/request.ts | 6 + js/fx/src/runs.ts | 3 +- js/fx/src/waiting.ts | 112 ++ js/fx/test/control.test.ts | 43 +- js/fx/test/waiting.test.ts | 54 + llms.txt | 1 + package.json | 1 + python/README.md | 17 + python/src/grida/fx/__init__.py | 16 + python/src/grida/fx/_api.py | 15 +- python/src/grida/fx/_control.py | 12 +- python/src/grida/fx/_runs.py | 1 + python/src/grida/fx/_waiting.py | 147 ++ python/tests/test_api.py | 76 + python/tests/test_import.py | 7 + spec/README.md | 1 + spec/control.md | 6 +- spec/exports.md | 2 +- spec/identity.md | 4 + spec/observation.md | 6 + spec/protocol.md | 6 +- spec/schemas/fx-await-request-v1.schema.json | 51 + spec/schemas/fx-graph-v1.schema.json | 4 +- spec/schemas/fx-graph-v2.schema.json | 4 +- spec/schemas/fx-run-control-v1.schema.json | 2 + spec/schemas/fx-run-events-v1.schema.json | 42 +- spec/schemas/fx-run-export-v1.schema.json | 21 +- spec/schemas/fx-run-list-v1.schema.json | 1 + spec/schemas/fx-run-removal-v1.schema.json | 1 + spec/schemas/fx-viewer-run-v1.schema.json | 23 +- spec/sdk.md | 22 + spec/service.md | 17 + spec/store.md | 13 +- spec/viewer.md | 45 + spec/waiting.md | 99 ++ tools/check_viewer_browser.mjs | 2 +- tools/check_waiting.py | 208 +++ tools/check_waiting_browser.mjs | 483 +++++ web/fx-react/src/canvas.tsx | 16 +- web/fx-react/src/index.tsx | 18 +- web/fx-web/src/answer-draft.ts | 117 ++ web/fx-web/src/canvas.css | 18 + web/fx-web/src/canvas.ts | 39 +- web/fx-web/src/card.ts | 88 +- web/fx-web/src/deck.ts | 10 +- web/fx-web/src/graph.ts | 19 + web/fx-web/src/index.ts | 9 + web/fx-web/src/layout.ts | 16 +- web/fx-web/src/port-values.ts | 4 +- web/fx-web/src/ports.ts | 6 +- web/fx-web/src/scope-state.ts | 1 + web/fx-web/src/service.ts | 2 +- web/fx-web/src/waiting.ts | 256 +++ web/fx-web/tests/canvas.test.ts | 44 +- web/fx-web/tests/ports.test.ts | 12 + web/fx-web/tests/state-icon.test.ts | 1 + web/fx-web/tests/waiting.test.ts | 143 ++ web/viewer/public/favicon-awaiting.svg | 14 + web/viewer/src/main.tsx | 100 +- web/viewer/src/run-favicon.ts | 18 +- web/viewer/src/style.css | 50 + web/viewer/src/waiting-answer-fields.tsx | 203 +++ web/viewer/src/waiting-answer-summary.tsx | 85 + web/viewer/src/waiting-reviews.tsx | 170 ++ 125 files changed, 7359 insertions(+), 237 deletions(-) create mode 100644 crates/grida-fx-core/src/builtins/waiting.rs create mode 100644 crates/grida-fx-runtime/src/runner/awaiting.rs create mode 100644 crates/grida-fx-runtime/src/waiting.rs create mode 100644 crates/grida-fx-viewer/src/waiting.rs create mode 100644 crates/grida-fx/src/verbs/waiting.rs create mode 100644 fixtures/waiting/README.md create mode 100644 fixtures/waiting/fx.yaml create mode 100644 fixtures/waiting/nodes.py create mode 100644 fixtures/waiting/showcase.yaml create mode 100644 fixtures/waiting/workflow.yaml create mode 100644 js/fx/src/waiting.ts create mode 100644 js/fx/test/waiting.test.ts create mode 100644 python/src/grida/fx/_waiting.py create mode 100644 spec/schemas/fx-await-request-v1.schema.json create mode 100644 spec/waiting.md create mode 100755 tools/check_waiting.py create mode 100644 tools/check_waiting_browser.mjs create mode 100644 web/fx-web/src/answer-draft.ts create mode 100644 web/fx-web/src/waiting.ts create mode 100644 web/fx-web/tests/waiting.test.ts create mode 100644 web/viewer/public/favicon-awaiting.svg create mode 100644 web/viewer/src/waiting-answer-fields.tsx create mode 100644 web/viewer/src/waiting-answer-summary.tsx create mode 100644 web/viewer/src/waiting-reviews.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1ac96d9..fa9b1627 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,7 @@ jobs: - uses: astral-sh/setup-uv@v10.2.0 - run: uv sync --project python --locked - run: bun --no-env-file run test:viewer:notes-browser + - run: bun --no-env-file run test:viewer:waiting-browser # docs/guide and docs/wg are published on grida.co/docs (a docs source, see # gridaco/docs); this runs that site's rules on them: links, assets, markdown. @@ -242,6 +243,7 @@ jobs: --command "$PWD/python/src/grida/fx/_bin/grida-fx" - run: uv run --locked --project python python tools/check_observation.py --command "$PWD/python/src/grida/fx/_bin/grida-fx" - run: uv run --locked --project python python tools/check_control.py --command "$PWD/python/src/grida/fx/_bin/grida-fx" + - run: uv run --locked --project python python tools/check_waiting.py --command "$PWD/python/src/grida/fx/_bin/grida-fx" # `grida fx`, as the npm grida command carries it (spec/distribution.md): @grida/fx and this # machine's engine package, packed from a fresh build, installed beside the host fixture, and diff --git a/AGENT_READINESS.md b/AGENT_READINESS.md index e4384484..9627dd28 100644 --- a/AGENT_READINESS.md +++ b/AGENT_READINESS.md @@ -71,6 +71,7 @@ Existing tests are starting points for evidence, not proof of every scenario her | Pause | A future, explicitly defined suspension boundary from which work can continue. There is no pause operation today; cancellation is not a pause acknowledgment. | | Revise | Change authored inputs or workflow choices and plan again. Today this generally needs a new run folder; valid unchanged work can still be reused from the same cache. | | Take / reroll / pick | A take identifies an alternative. Reroll selects a later take for the next execution; pick selects a take. Neither command executes it immediately. | +| Waiting step | A workflow requests a schema-defined answer for one concrete occurrence. An exact run and request ID select it from any supported review surface. | | Observe / inspect | Read execution evidence or inspect a saved run. `--register` saves a viewer catalog entry and returns its route. `--open` launches the default browser. | | Service | A project-scoped process started by `start`, providing the dashboard, catalog and observation HTTP endpoints. Workflow execution has a separate owner and lifetime. | | Standalone | Independent inspection with its own available port and foreground owner. It does not mean a fresh cache or different execution semantics. | @@ -96,6 +97,7 @@ narrower target rules. | Intent / tool | What an agent receives | Conditions and effects | |---|---|---| +| Supply external input: `inspect RUN --requests --json`, `respond RUN REQUEST --json JSON` | Schema, optional message, frozen choices, deadline and receipt | Listing reads request state independently of viewer discovery. A valid answer commits without launching a runner or authorizing spending. Explicit `--viewer-url` or `--register` supports handoff. | | Discover: `--version`, `--help`, ` --help` | Installed version and human-readable command help | No common machine-readable capability manifest yet. | | Establish project: `init [directory] [--template NAME] --json`; `init --list-templates --json` | Resolved project, the files it wrote and the template it started from; the templates on offer | A new or empty directory gets the starter project (`fx.yaml`, `README.md`, `AGENTS.md`, `.gitignore`, `.env.example`, `workflows/icon.yaml`, and every FX skill under `.agents/skills/`), with no route set, or a named template: an example read from the release's source archive, with the starter's agent files added. Never asks a question under `--json`, without a terminal or in CI. An existing `fx.yaml` is validated and nothing is written. Any other non-empty directory is refused (exit 2): to add FX to an existing folder, write `fx.yaml` (`fx: project/v1`). Never overwrites; no dependencies, service, credentials or execution. | | Install a starter: `add NAME [DESTINATION] --json`; `add OWNER/REPO@REF [DESTINATION] [--workflow NAME] [--github-auth] --json` | Local project root, exact workflow entry, bundled preset when declared, missing inputs and declared prerequisites | A listed template with `workflow_entry` or a GitHub repository at an explicit tag or full commit gets its own fresh project folder. For a private template, `--github-auth` uses the user's configured GitHub CLI authentication. The destination must be absent and its parent must already be a directory. A GitHub repository must have a root `fx.yaml`. It can choose a starter in an optional root `fx-template.json` or supply a YAML workflow under `workflows/` or `fx/`. An agent can select a unique file stem with `--workflow`. Use the returned entry with the returned root. Setup validates copied source and requires network access for the archive. Diagnose runtime readiness separately with `doctor`. | @@ -428,7 +430,7 @@ promise through documentation alone. | AR-07 | "Pause and wait for me." | Proposed; cancellation and later-phase thresholds only cover narrower intents. | Explicit request/acknowledgment/boundary semantics; active work and reservations accounted for; resume survives the documented lifetime. | | AR-08 | "Change what has not started yet." | Partial: revise/replan/new run with cache reuse. Active mutation proposed. | Unchanged work is retained where identities match; an edit racing dispatch cannot silently change already accepted work; history and cost remain attributable. | | AR-09 | "Keep this result; try another there." | Current takes, reroll and pick; their `next` line repeats the run from its record (conformance `run-repeat`). | Selected recorded instance is addressed exactly; no command implies immediate execution; next-plan impact and possible cost are visible. | -| AR-10 | "Ask before the next expensive part." | Current later-phase `--yes-up-to`, within a separate ceiling. | Incomplete run can continue with an approved threshold; no claim of a general human-approval/pause system. | +| AR-10 | "Ask before the next expensive part." | Current later-phase `--yes-up-to`, within a separate ceiling. | Incomplete run can continue with an approved threshold; workflow-authored human decisions are covered separately in AR-31. | | AR-11 | "You disconnected; catch up." | Current in source: opaque cursors, bounded replay and snapshot reattachment; process liveness remains unknown. | Retained events can be read from a valid cursor; duplicates, unknown liveness and later invocations are handled without launching another run. | | AR-12 | "Put the result in my project." | Current output delivery and file verification. | Exact output destinations and missing/partial results are reported; immutable stored files remain intact. | | AR-13 | "Do it from Python or JavaScript." | Current: planning, named execution/resume, result files, saved RunRecord inspection, snapshot/batch/async following, exact-target control, portable evidence export and in-process stand-ins; node bodies, builders and stand-in files in Python or TypeScript, the TypeScript ones hosted by `@grida/fx` on Node 24+ with the Python host's whole protocol, and both in one project when needed. Built-in local types still need Python; Bun cannot host nodes. Only the TypeScript host checks param values against their schemas before a body runs and ends a body's programs when the node is cancelled or its run ends; the Python host does neither yet. | Each claimed job preserves engine semantics with native ergonomics. Recorded folders stay pinned; cursor attachment, bounded catch-up, errors, later resumes and observer cancellation have provider-free tests. A TypeScript project does every job a Python one does (describe, run, cache, build, judge, time out and cancel, run agents with tools, answer with a stand-in), with the guarantees [protocol.md](spec/protocol.md) §1 and §5 state, and its declarations refuse mistyped bodies at compile time; the evidence below names the tests. Execution readiness/browser lifetime and CLI maintenance are intentionally excluded. | @@ -449,6 +451,14 @@ promise through documentation alone. | AR-28 | "Start from this template and keep my edits for the next message." | CLI implemented in source for [#87](https://github.com/gridaco/fx/issues/87). [CLI listing and install](spec/service.md#21-templates) expose the authored workflow and preset for indexed examples and a starter from a pinned GitHub repository. Private sources can opt in to existing GitHub CLI authentication ([#151](https://github.com/gridaco/fx/issues/151)). Host reuse for delivery retries and follow-up messages is pending in [Grida #1160](https://github.com/gridaco/grida/issues/1160). | Discover an eligible template, install from a release-shaped or repository-shaped archive and plan the returned starter offline. Verify explicit workflow selection, ambiguous names, and refusal of an unpinned repository. Exercise opt-in authentication with a GitHub CLI stand-in, check failures leave the destination absent, and verify ordinary `add` never calls the stand-in. Repeats preserve edits and concurrent installs publish one complete folder. Report declared missing inputs and prerequisites without launching template code. | | AR-29 | "Generate one image on this route and give me the PNG." | [One-shot call](spec/call.md) for [#149](https://github.com/gridaco/fx/issues/149) exposes image generation directly in the CLI. Python and JavaScript callers can build a one-step workflow, run it, and resolve or deliver its output. Native one-shot SDK entry points and a `--fresh` equivalent on that API are deferred. | Exercise project discovery from a child directory, explicit override, empty override refusal and projectless selection. Dry-run never generates. Prove request, output and cache behavior with a stand-in, including fresh execution and ordinary replay. Verify budget and live admission, reject output names that cannot be reported as UTF-8, and preserve the saved image on delivery failure or interruption. An opt-in signed-in Codex invocation is the live smoke test. | | AR-30 | "Retrieve the result I already paid for." | Implemented in source for [#116](https://github.com/gridaco/fx/issues/116). A live resume collects a known completed task. CLI, Python and JavaScript expose recovery-only resume and recorded recovery events. | A charged success followed by download or answer validation failure retains the task. A repeat collects and publishes the original result with one generation and one charge. Concurrent invocations sharing a long-job call key serialize submission and collection. A settled handle from an older engine or an ambiguous project adapter outcome requires explicit recovery. Original bookings require task-specific evidence. Terminal generation failure and unavailable retention produce distinct next steps. Pruning preserves recovery candidates. | +| AR-31 | "Let my build supply its revision and let me choose a generated image." | [Durable workflow requests](spec/waiting.md) in CLI, Python, JavaScript and the live local viewer. | An SDK lists and answers a promptless revision. A reviewer chooses a frozen image through the viewer or CLI in the same run. Verify both values downstream, the winner on conflict and the exact selected file on resume. Timeout fallback follows normal spending rules. | + +The [waiting fixture](fixtures/waiting/workflow.yaml) synthesizes three PNGs, +provides a deterministic fallback and writes the revision and delivered image +digest into a build manifest. The [public-interface check](tools/check_waiting.py) +checks those outputs, attached and detached execution, validation, retries and expiry. +The [browser test](tools/check_waiting_browser.mjs) submits through both review surfaces +in both winning orders, reloads the viewer, and resumes a review with the agent disconnected. AR-25 uses the [notes fixture](fixtures/viewer/README.md#try-workflow-notes), [engine acceptance](tools/check_notes.py), browser acceptance and builder/core/viewer tests. diff --git a/CHANGELOG.md b/CHANGELOG.md index bee03cca..df2d23de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,10 +12,16 @@ with the tagged commit date for the lightweight `v0.4.0` tag. ## [Unreleased] +### Added + +- Workflows can request external input with `fx/await@1` and `with.schema`. An SDK can supply a promptless value, or a person can review a question and select an exact file. The viewer renders scalar enums as pickers, marks pending requests on the run and project home, and counts down to an optional deadline. The CLI and SDKs can list and answer requests without a viewer. [#62](https://github.com/gridaco/fx/issues/62) +- Waiting steps stand out on the canvas and open their form from a **Review** button. Resolved steps show the outcome and open a receipt with the answer, submission time, and channel. + ### Changed - Made `llms.txt` a shorter starting point for agents, with an introduction to FX, runnable recipes, and links organized by task. - The FX Viewer favicon pulses green during active execution and stays steady with reduced motion. [#158](https://github.com/gridaco/fx/issues/158) +- A run awaiting answers shows a steady amber favicon and its pending review count in the tab title. ### Fixed diff --git a/crates/grida-fx-core/src/builtins/catalog.json b/crates/grida-fx-core/src/builtins/catalog.json index 489736b7..aaa6a568 100644 --- a/crates/grida-fx-core/src/builtins/catalog.json +++ b/crates/grida-fx-core/src/builtins/catalog.json @@ -1070,6 +1070,63 @@ "retry": "service", "body": "none" }, + { + "uses": "fx/await@1", + "name": "await", + "major": 1, + "version": 1, + "description": "Request a schema-validated external input for this run and step.", + "inputs": {}, + "params": { + "message": { + "type": "string", + "minLength": 1, + "x-fx-optional": true + }, + "schema": { + "type": [ + "object", + "boolean" + ] + }, + "choices": { + "type": "object", + "x-fx-optional": true + }, + "choice_field": { + "type": "string", + "minLength": 1, + "x-fx-optional": true + }, + "show": { + "x-fx-optional": true + }, + "timeout_seconds": { + "type": "integer", + "minimum": 1, + "x-fx-optional": true + }, + "on_timeout": { + "type": "string", + "enum": [ + "fail", + "continue" + ], + "default": "fail" + } + }, + "outputs": { + "answer": "json?", + "selected": "value?" + }, + "judge": false, + "capability": null, + "calls": {}, + "resources": [], + "tools": [], + "retry": "service", + "body": "engine" + }, { "uses": "fx/select@1", "name": "select", diff --git a/crates/grida-fx-core/src/builtins/mod.rs b/crates/grida-fx-core/src/builtins/mod.rs index faf58655..806f4637 100644 --- a/crates/grida-fx-core/src/builtins/mod.rs +++ b/crates/grida-fx-core/src/builtins/mod.rs @@ -1,4 +1,4 @@ -//! The built-in node types (`fx/@`), embedded as data: `catalog.json`, the 37 +//! The built-in node types (`fx/@`), embedded as data: `catalog.json`, the 38 //! standard types. //! //! `catalog.json` is `{"kind": "fx-std-catalog-v1", "types": [...]}`; each type has `uses`, @@ -6,11 +6,13 @@ //! `capability`, `calls`, `resources`, `tools`, `retry`, and `body` (`capability`, `python`, //! `engine` or `none`), in declaration order. A built-in's identity is //! `fx/@.` (identity.md §6). The engine owns the capability types and -//! `fx/select@1` (protocol.md §4 "Engine types"); the Python host runs the `python` bodies. +//! the native `select` and `await` types (protocol.md §4 "Engine types"); the Python host runs the `python` bodies. //! //! The catalog is read once, with FX's JSON reader (one number type), and every spec is -//! validated through [`crate::spec::NodeSpec::from_type_spec`] with its capability. `nodes` -//! kinds are 11 paid, 5 judge, 21 free. +//! validated with its capability and its engine-native output notation when applicable. `nodes` +//! kinds are 11 paid, 5 judge, 22 free. + +pub mod waiting; use crate::spec::{BodyKind, NodeSpec}; use grida_fx_protocol::TypeSpec; @@ -133,7 +135,7 @@ fn parse_catalog(text: &str) -> Result, String> { version: Some(entry.version), retry: entry.retry, }; - let spec = NodeSpec::from_type_spec(&wire, entry.capability) + let spec = NodeSpec::read_type_spec(&wire, entry.capability, body == BodyKind::Engine) .map_err(|reason| format!("{uses}: {reason}"))?; types.push(BuiltinType { uses, @@ -152,7 +154,16 @@ mod tests { #[test] fn the_catalog_parses() { - assert_eq!(builtins().len(), 37); + assert_eq!(builtins().len(), 38); + for builtin in builtins() { + let wire = builtin.spec.to_type_spec(); + let restored = NodeSpec::read_type_spec( + &wire, + builtin.spec.capability.clone(), + builtin.body == BodyKind::Engine, + ); + assert_eq!(restored.as_ref(), Ok(&builtin.spec), "{}", builtin.uses); + } let generate = builtin("image.generate", 1).unwrap(); assert_eq!(generate.uses, "fx/image.generate@1"); assert_eq!(generate.identity(), "fx/image.generate@1.1"); @@ -161,6 +172,15 @@ mod tests { assert!(builtin("image.generate", 2).is_none()); assert!(builtin("nope", 1).is_none()); assert_eq!(builtin("select", 1).unwrap().body, BodyKind::Engine); + let review = &builtin("await", 1).unwrap().spec; + assert_eq!(review.outputs["selected"].notation(), "value?"); + assert_eq!(review.to_type_spec().outputs["selected"], "value?"); + for notation in ["value", "value?"] { + let mut host_spec = review.to_type_spec(); + host_spec.outputs.insert("selected".into(), notation.into()); + let error = NodeSpec::from_type_spec(&host_spec, None).unwrap_err(); + assert!(error.contains("port kind 'value'"), "{error}"); + } assert_eq!(builtin("image.resize", 1).unwrap().body, BodyKind::Python); assert_eq!(builtin("image.key", 1).unwrap().body, BodyKind::None); } diff --git a/crates/grida-fx-core/src/builtins/waiting.rs b/crates/grida-fx-core/src/builtins/waiting.rs new file mode 100644 index 00000000..86d0bec7 --- /dev/null +++ b/crates/grida-fx-core/src/builtins/waiting.rs @@ -0,0 +1,138 @@ +//! Offline checks for the inputs of a workflow-authored waiting step. + +use crate::val::Val; +use indexmap::IndexMap; +use serde_json::{Value, json}; + +/// The same offline draft and reference resolver are used to plan a gate and accept its answer. +pub fn answer_validator(schema: &Value) -> Result { + jsonschema::draft202012::options() + .with_retriever(LocalReferences) + .build(schema) + .map_err(|_| { + "schema must be a valid draft 2020-12 JSON Schema with only internal references".into() + }) +} + +/// Check the intersection of the declared answer schema with the known candidate keys. +/// A top-level key is a complete answer. For a named field, other properties can still +/// be supplied by the responder, so only reject constraints that adding fields cannot fix. +pub fn validate_choice_keys<'a>( + schema: &Value, + validator: &jsonschema::Validator, + mut keys: impl Iterator, + choice_field: Option<&str>, +) -> Result<(), &'static str> { + let Some(field) = choice_field else { + return keys + .any(|key| validator.is_valid(&Value::String(key.into()))) + .then_some(()) + .ok_or("no choice key satisfies the answer schema"); + }; + let possible = keys.any(|key| { + let partial = json!({(field): key}); + !validator.iter_errors(&partial).any(|error| { + // Only keywords reached directly from the root impose unconditional constraints + // on this particular field. A conditional may choose a different branch once + // a sibling exists. Use the evaluation path to preserve that distinction for refs. + let keyword = error.evaluation_path().as_str().split('/').nth(1); + matches!( + keyword, + Some( + "type" + | "properties" + | "patternProperties" + | "additionalProperties" + | "propertyNames" + | "maxProperties" + ) + ) + }) + }); + if schema != &Value::Bool(false) && possible { + Ok(()) + } else { + Err("no choice key can be supplied in choice_field under the answer schema") + } +} + +struct LocalReferences; + +impl jsonschema::Retrieve for LocalReferences { + fn retrieve( + &self, + _: &jsonschema::Uri, + ) -> Result> { + Err("waiting-step schemas cannot retrieve external resources".into()) + } +} + +/// Each known setting is checked as soon as it has a value, including settings produced at run time. +pub fn validate(values: &IndexMap) -> Result<(), String> { + let known = |name: &str| { + values + .get(name) + .filter(|v| !v.contains_pending() && !v.contains_failed()) + }; + if let Some(message) = known("message") + && !matches!(message, Val::Str(s) if !s.trim().is_empty()) + { + return Err("message must be nonempty text".into()); + } + // A literal map can have known keys even if its artifact values are still pending. + let choice_keys: Option> = match values.get("choices") { + Some(Val::Object(members)) => Some(members.keys().map(String::as_str).collect()), + Some(Val::Collection(collection)) => Some( + collection + .items + .iter() + .map(|(key, _)| key.as_str()) + .collect(), + ), + Some(choices) if !choices.contains_pending() && !choices.contains_failed() => { + return Err("choices must be a nonempty keyed object or collection".into()); + } + _ => None, + }; + if choice_keys + .as_ref() + .is_some_and(|keys| keys.is_empty() || keys.iter().any(|key| key.trim().is_empty())) + { + return Err("choices must be a nonempty keyed object or collection".into()); + } + if let Some(field) = known("choice_field") { + if !matches!(field, Val::Str(s) if !s.trim().is_empty()) { + return Err("choice_field must name a nonempty answer property".into()); + } + if !values.contains_key("choices") { + return Err("choice_field requires choices".into()); + } + } + if let Some(schema) = known("schema") { + let schema = schema + .plain() + .filter(|s| s.is_object() || s.is_boolean()) + .ok_or("schema must be a JSON Schema")?; + let validator = answer_validator(&schema)?; + if let Some(keys) = choice_keys { + match values.get("choice_field") { + None => validate_choice_keys(&schema, &validator, keys.into_iter(), None)?, + Some(Val::Str(field)) => { + validate_choice_keys(&schema, &validator, keys.into_iter(), Some(field))? + } + _ => {} // A dynamic choice_field will be checked once evaluated. + } + } + } + if let Some(timeout) = known("timeout_seconds") + && !matches!(timeout, Val::Number(n) if n.fract() == 0.0 && *n >= 1.0 && *n <= 9_007_199_254_740_991.0) + { + return Err("timeout_seconds must be a positive integer".into()); + } + if let Some(policy) = known("on_timeout") + && !matches!(policy, Val::Str(s) if s == "fail" || s == "continue") + { + return Err("on_timeout must be fail or continue".into()); + } + Ok(()) +} diff --git a/crates/grida-fx-core/src/expand/node.rs b/crates/grida-fx-core/src/expand/node.rs index 225b568c..6ced97ac 100644 --- a/crates/grida-fx-core/src/expand/node.rs +++ b/crates/grida-fx-core/src/expand/node.rs @@ -684,6 +684,23 @@ impl Expander<'_> { "an at: plan step makes no paid call", ); } + if resolved.is_await() { + if declared.at_plan { + self.problem( + &format!("{where_}.at"), + "a waiting step opens only during a run", + ); + } + if declared.timeout.is_some() { + self.problem( + &format!("{where_}.timeout"), + "set with.timeout_seconds for a waiting step's response deadline", + ); + } + if let Err(message) = crate::builtins::waiting::validate(&with) { + self.problem(&format!("{where_}.with"), message); + } + } let identity = step_identity_with_fresh_id(&resolved.identity, &with, &routes, &takes, self.fresh_id); // The engine runs select itself: it calls nothing and costs nothing. diff --git a/crates/grida-fx-core/src/plan/mod.rs b/crates/grida-fx-core/src/plan/mod.rs index a85fe096..ddfffcf7 100644 --- a/crates/grida-fx-core/src/plan/mod.rs +++ b/crates/grida-fx-core/src/plan/mod.rs @@ -286,6 +286,7 @@ fn ready(instance: &Instance, planner: &Planner) -> bool { && instance.state == State::Planned && !instance.with.values().any(|v| v.contains_pending()) && !instance.ty.spec.paid() + && !instance.ty.is_await() && !planner.results.contains_key(&instance.id) } @@ -354,6 +355,7 @@ pub fn make_plan( i.at_plan && i.state == State::Planned && !i.ty.spec.paid() + && !i.ty.is_await() && !planner.results.contains_key(&i.id) }) .map(|i| { @@ -371,7 +373,7 @@ pub fn make_plan( let cached = expansion .ordered() .filter(|i| i.state.is_live()) - .filter(|i| i.identity.is_some() && cache.has_result(i)) + .filter(|i| !i.ty.is_await() && i.identity.is_some() && cache.has_result(i)) .map(|i| i.id.clone()) .collect(); Ok(Plan { diff --git a/crates/grida-fx-core/src/registry.rs b/crates/grida-fx-core/src/registry.rs index 1846d42a..51df1a7d 100644 --- a/crates/grida-fx-core/src/registry.rs +++ b/crates/grida-fx-core/src/registry.rs @@ -171,6 +171,11 @@ pub struct ResolvedType { } impl ResolvedType { + /// A workflow-authored waiting step, owned by the scheduler. + pub fn is_await(&self) -> bool { + matches!(&self.origin, TypeOrigin::Builtin { name, major: 1 } if name == "await") + } + /// Whether this is the engine's `fx/select@1`. FX keys native select on the built-in, not on /// any type named `select`. pub fn is_select(&self) -> bool { diff --git a/crates/grida-fx-core/src/spec.rs b/crates/grida-fx-core/src/spec.rs index dfafbd74..746eb909 100644 --- a/crates/grida-fx-core/src/spec.rs +++ b/crates/grida-fx-core/src/spec.rs @@ -70,7 +70,7 @@ pub enum Shape { /// An input or output port (protocol.md §4 "Ports"). #[derive(Debug, Clone, PartialEq, Eq)] pub struct Port { - /// A family (`image`) or a media type in it (`image/png`). + /// A family (`image`), a media type (`image/png`), or an engine-native output (`value`). pub kind: String, pub shape: Shape, pub optional: bool, @@ -139,7 +139,7 @@ pub enum BodyKind { Capability, /// A built-in whose body is in `grida.fx.std`, run by the Python host. Python, - /// `fx/select@1`: the engine itself. + /// Built-in selection and waiting steps, executed by the engine. Engine, /// A built-in that plans, identifies and prices but has no body. None, @@ -170,6 +170,15 @@ pub struct NodeSpec { impl NodeSpec { /// Validates a wire spec (module doc). `capability` is set only for catalog types. pub fn from_type_spec(spec: &TypeSpec, capability: Option) -> Result { + Self::read_type_spec(spec, capability, false) + } + + /// The embedded catalog can describe native outputs whose concrete value is chosen at runtime. + pub(crate) fn read_type_spec( + spec: &TypeSpec, + capability: Option, + native_outputs: bool, + ) -> Result { let name = &spec.name; if !TYPE_NAME.is_match(name) { return Err(format!( @@ -177,12 +186,12 @@ impl NodeSpec { py_repr_str(name) )); } - let inputs = ports(name, "input", &spec.inputs)?; + let inputs = ports(name, "input", &spec.inputs, false)?; for (param, schema) in &spec.params { check_name(name, "param", param)?; check_param(name, param, schema)?; } - let outputs = ports(name, "output", &spec.outputs)?; + let outputs = ports(name, "output", &spec.outputs, native_outputs)?; let overlap: BTreeSet<&str> = spec .inputs .keys() @@ -367,11 +376,21 @@ fn ports( type_name: &str, what: &str, declared: &IndexMap, + native_outputs: bool, ) -> Result, String> { let mut ports = IndexMap::new(); for (name, notation) in declared { check_name(type_name, what, name)?; - ports.insert(name.clone(), Port::parse(notation)?); + let port = if native_outputs && matches!(notation.as_str(), "value" | "value?") { + Port { + kind: "value".into(), + shape: Shape::One, + optional: notation.ends_with('?'), + } + } else { + Port::parse(notation)? + }; + ports.insert(name.clone(), port); } Ok(ports) } diff --git a/crates/grida-fx-core/tests/expand_semantics.rs b/crates/grida-fx-core/tests/expand_semantics.rs index 1a611162..4a03dc39 100644 --- a/crates/grida-fx-core/tests/expand_semantics.rs +++ b/crates/grida-fx-core/tests/expand_semantics.rs @@ -2253,3 +2253,125 @@ fn notes_have_recorded_owner_occurrences_without_execution_members() { "workflow" ); } + +#[test] +fn waiting_steps_refuse_planning_execution_and_invalid_review_contracts() { + let project = Project::new(); + let expansion = project.expand( + r#"fx: workflow/v1 +id: case +title: Review contracts +steps: + early: + uses: fx/await@1 + at: plan + with: { message: Wait, schema: true } + schema: + uses: fx/await@1 + with: { message: Wait, schema: {type: invented} } + field: + uses: fx/await@1 + with: { message: Wait, schema: true, choice_field: pick } + legacy: + uses: fx/await@1 + with: { answer: {type: string} } + both: + uses: fx/await@1 + with: { schema: {type: string}, answer: {type: string} } + contradiction: + uses: fx/await@1 + with: { schema: {type: boolean}, choices: {a: first} } + disjoint: + uses: fx/await@1 + with: { schema: {enum: [other]}, choices: {a: first} } + field_type: + uses: fx/await@1 + with: + schema: {type: object, properties: {pick: {type: boolean}}} + choice_field: pick + choices: {a: first} + forbidden_field: + uses: fx/await@1 + with: + schema: {type: object, additionalProperties: false} + choice_field: pick + choices: {a: first} + clock: + uses: fx/await@1 + with: { message: Wait, schema: true, timeout_seconds: 0 } + remote: + uses: fx/await@1 + with: { message: Wait, schema: { $ref: 'https://example.test/schema' } } +"#, + ); + let problems = problems(&expansion); + for (step, message) in [ + ("early.at", "opens only during a run"), + ("schema.with", "valid draft 2020-12 JSON Schema"), + ("field.with", "choice_field requires choices"), + ("legacy.with.answer", "has no input or setting answer"), + ("legacy.with", "needs setting schema"), + ("both.with.answer", "has no input or setting answer"), + ("contradiction.with", "no choice key satisfies"), + ("disjoint.with", "no choice key satisfies"), + ("field_type.with", "no choice key can be supplied"), + ("forbidden_field.with", "no choice key can be supplied"), + ("clock.with", "positive integer"), + ("remote.with", "only internal references"), + ] { + assert!( + problems + .iter() + .any(|problem| problem.contains(step) && problem.contains(message)), + "{problems:?}" + ); + } +} + +#[test] +fn waiting_steps_price_a_paid_fallback_conditionally_until_the_outcome_is_known() { + const WORKFLOW: &str = r#"fx: workflow/v1 +id: case +title: Optional review +steps: + review: + uses: fx/await@1 + with: { message: Choose, schema: true, timeout_seconds: 30, on_timeout: continue } + fallback: + if: ${{ steps.review.facts.outcome == 'expired' }} + uses: fx/image.generate@1 + route: img-a@acme + with: { prompt: Generate another option } +"#; + let mut project = Project::new(); + for (outcome, lower, upper) in [ + (None, "0", "0.04"), + (Some("answered"), "0", "0"), + (Some("expired"), "0.01", "0.04"), + ] { + if let Some(outcome) = outcome { + project.results.insert( + "review#1".into(), + NodeResult { + status: ResultStatus::Succeeded, + outputs: IndexMap::new(), + facts: IndexMap::from([("outcome".into(), json!(outcome))]), + error: None, + }, + ); + } + let expansion = project.expand(WORKFLOW); + assert!(expansion.problems.is_empty(), "{:?}", expansion.problems); + let plan = grida_fx_core::plan::Plan { + expansion, + cached: BTreeSet::new(), + ceiling: None, + problems: Vec::new(), + }; + let estimate = plan.estimate(); + assert_eq!( + (estimate.low, estimate.high), + (Usd::parse(lower).unwrap(), Usd::parse(upper).unwrap()) + ); + } +} diff --git a/crates/grida-fx-core/tests/planning.rs b/crates/grida-fx-core/tests/planning.rs index 3d3743c0..5981dab5 100644 --- a/crates/grida-fx-core/tests/planning.rs +++ b/crates/grida-fx-core/tests/planning.rs @@ -1291,6 +1291,47 @@ fn request(fixture: &Fixture, target: &str) -> PlanRequest { } } +#[test] +fn compiled_waiting_plans_validate_the_native_selected_output_in_both_graph_versions() { + use grida_fx_core::docs::{Schema, validate}; + use grida_fx_core::plan::output::graph_document; + + let fixture = Fixture::new(); + fixture.write("fx.yaml", "fx: project/v1\nroute_tables: [routes.yaml]\n"); + fixture.write( + "workflows/case.yaml", + r#"fx: workflow/v1 +id: case +title: Reviewed choice +steps: + review: + uses: fx/await@1 + with: { message: Pick, schema: {type: string}, choices: {first: {label: blue}} } + draw: + uses: fx/image.generate@1 + route: img-a@acme + with: {prompt: Draw a leaf} +"#, + ); + for (price, kind, schema) in [ + ("price: {usd: 0.02}", "fx-graph-v1", Schema::Graph), + ("price: null", "fx-graph-v2", Schema::GraphV2), + ] { + fixture.write("routes.yaml", &format!("fx: routes/v1\nroutes:\n - {{capability: image.generate, route: img-a@acme, {price}}}\n")); + let mut host = FakeHost::new(); + let mut planner = make_planner(&request(&fixture, "case"), &mut host).unwrap(); + let plan = make_plan(&mut planner, &mut host, None, &NoCache).unwrap(); + assert!(plan.ok(), "{:?}", plan.problems); + let graph = graph_document(&plan, &planner); + assert_eq!(graph["kind"], kind); + assert_eq!( + graph["types"]["fx/await@1"]["ports"]["outputs"]["selected"], + "value?" + ); + validate(schema, &graph, "plan").unwrap(); + } +} + fn video_preview_project(outputs: &[(&str, &str)], render: Value) -> (Fixture, FakeHost) { let fixture = Fixture::new(); fixture.write("fx.yaml", "fx: project/v1\n"); diff --git a/crates/grida-fx-core/tests/routes_spec.rs b/crates/grida-fx-core/tests/routes_spec.rs index eac02fd7..6fef8ca4 100644 --- a/crates/grida-fx-core/tests/routes_spec.rs +++ b/crates/grida-fx-core/tests/routes_spec.rs @@ -576,9 +576,9 @@ fn a_declared_family_completes_its_provider_s_contracts_in_every_table() { #[test] fn the_built_in_catalog() { let all = builtins(); - assert_eq!(all.len(), 37); + assert_eq!(all.len(), 38); let count = |word: &str| all.iter().filter(|b| b.spec.kind_word() == word).count(); - assert_eq!((count("paid"), count("judge"), count("free")), (11, 5, 21)); + assert_eq!((count("paid"), count("judge"), count("free")), (11, 5, 22)); assert_eq!(all.iter().filter(|b| b.spec.paid()).count(), 13); for b in all { assert_eq!(b.uses, format!("fx/{}@{}", b.name, b.major)); @@ -587,9 +587,6 @@ fn the_built_in_catalog() { if let Some(capability) = &b.spec.capability { assert_eq!(capability, &b.name); } - // Every spec survives the wire form and validates again. - let again = NodeSpec::from_type_spec(&b.spec.to_type_spec(), b.spec.capability.clone()); - assert_eq!(again.as_ref(), Ok(&b.spec), "{}", b.uses); } let generate = builtin("image.generate", 1).unwrap(); assert_eq!(generate.identity(), "fx/image.generate@1.1"); diff --git a/crates/grida-fx-runtime/src/control.rs b/crates/grida-fx-runtime/src/control.rs index 9b4bbf54..7df0665f 100644 --- a/crates/grida-fx-runtime/src/control.rs +++ b/crates/grida-fx-runtime/src/control.rs @@ -262,7 +262,12 @@ impl Record { self.terminal = Some(event.clone()); } Some("run_finished") => { - self.state = if event.get("ok").and_then(Value::as_bool) == Some(true) { + self.state = if event["awaiting"] + .as_array() + .is_some_and(|ids| !ids.is_empty()) + { + "awaiting" + } else if event.get("ok").and_then(Value::as_bool) == Some(true) { "succeeded" } else { "failed" @@ -1277,6 +1282,41 @@ mod tests { control.terminal().unwrap() } + #[test] + fn parked_terminal_evidence_remains_bound_to_its_invocation_on_resume() { + let folder = tempfile::tempdir().unwrap(); + let plan = "0".repeat(64); + let invocation = "0123456789abcdef"; + std::fs::write( + folder.path().join("plan.json"), + json!({"kind":"fx-graph-v1","plan":plan}).to_string(), + ) + .unwrap(); + let event = |id: &str, mut e: Value| { + e["kind"] = json!("fx-run-events-v1"); + e["plan"] = json!(plan); + e["invocation_id"] = json!(id); + e["offset_ms"] = json!(0); + format!("{e}\n") + }; + let mut events = event(invocation, json!({"event":"run_started"})); + events += &event( + invocation, + json!({"event":"run_finished","ok":false,"incomplete":true,"awaiting":["a".repeat(64)]}), + ); + let path = folder.path().join("events.jsonl"); + std::fs::write(&path, &events).unwrap(); + let mut parked = Record::read(folder.path()).unwrap(); + assert_eq!(parked.state, "awaiting"); + let next = "fedcba9876543210"; + events += &event(next, json!({"event":"run_started"})); + std::fs::write(&path, events).unwrap(); + assert_eq!(Record::read(folder.path()).unwrap().state, "unfinished"); + assert!(parked.refresh_bound()); + assert_eq!(parked.state, "awaiting"); + assert!(parked.terminal.is_some()); + } + #[test] fn authenticated_cancellation_is_idempotent_and_keeps_private_identity_private() { let folder = tempfile::tempdir().unwrap(); diff --git a/crates/grida-fx-runtime/src/events.rs b/crates/grida-fx-runtime/src/events.rs index 1c8c64cb..2d06d2b5 100644 --- a/crates/grida-fx-runtime/src/events.rs +++ b/crates/grida-fx-runtime/src/events.rs @@ -160,6 +160,14 @@ pub enum Event { steps: usize, high_usd: Usd, }, + /// Observed state of a durable request. An out-of-process reply becomes an event only + /// when the scheduler observes it in an invocation. + WaitingRequest { + id: String, + request_id: String, + status: &'static str, + deadline: Option, + }, NodeStarted { id: String, path: String, @@ -288,6 +296,7 @@ pub enum Event { ok: bool, incomplete: bool, stopped: Option, + awaiting: Vec, charged_usd: Usd, failed: Vec, outputs: IndexMap, @@ -333,6 +342,7 @@ impl Event { Event::ScopesUpdated { .. } => "scopes_updated", Event::RunStarted { .. } => "run_started", Event::PhasePlanned { .. } => "phase_planned", + Event::WaitingRequest { .. } => "waiting_request", Event::NodeStarted { .. } => "node_started", Event::NodeFinished { .. } => "node_finished", Event::NodeFailed { .. } => "node_failed", @@ -437,6 +447,19 @@ impl Event { fields.put("steps", Value::from(*steps as u64)); fields.money("high_usd", *high_usd); } + Event::WaitingRequest { + id, + request_id, + status, + deadline, + } => { + fields.text("id", id); + fields.text("request_id", request_id); + fields.text("request_status", status); + if let Some(deadline) = deadline { + fields.text("deadline", deadline); + } + } Event::NodeStarted { id, path, @@ -695,6 +718,7 @@ impl Event { ok, incomplete, stopped, + awaiting, charged_usd, failed, outputs, @@ -702,6 +726,9 @@ impl Event { fields.put("ok", Value::Bool(*ok)); fields.put("incomplete", Value::Bool(*incomplete)); fields.text_or_null("stopped", stopped.as_deref()); + if !awaiting.is_empty() { + fields.put("awaiting", serde_json::json!(awaiting)); + } fields.money("charged_usd", *charged_usd); fields.put( "failed", diff --git a/crates/grida-fx-runtime/src/executor/mod.rs b/crates/grida-fx-runtime/src/executor/mod.rs index 7115e0a1..5f437055 100644 --- a/crates/grida-fx-runtime/src/executor/mod.rs +++ b/crates/grida-fx-runtime/src/executor/mod.rs @@ -203,7 +203,10 @@ impl InstanceJob { }, None => return Err(format!("{} is a paid type with no capability", ty.uses)), }, - (BodyKind::Engine, _) => JobBody::Select, + (BodyKind::Engine, _) if ty.is_select() => JobBody::Select, + (BodyKind::Engine, _) => { + return Err(format!("{} runs in the workflow scheduler", ty.uses)); + } (BodyKind::None, _) => JobBody::None, (BodyKind::Project, TypeOrigin::Builtin { .. }) => { return Err(format!("{} is a built-in, not a project type", ty.uses)); diff --git a/crates/grida-fx-runtime/src/folder.rs b/crates/grida-fx-runtime/src/folder.rs index 27f86f8e..04e99950 100644 --- a/crates/grida-fx-runtime/src/folder.rs +++ b/crates/grida-fx-runtime/src/folder.rs @@ -185,6 +185,20 @@ impl RunFolder { } } + /// Snapshot reviewed files that might have no output placement or visible input card. + /// An existing historical snapshot stays untouched. + pub fn capture_waiting_files<'a>(&self, files: impl IntoIterator) { + let directory = self.path.join("values"); + for file in files { + if is_digest(&file.digest) + && std::fs::symlink_metadata(directory.join(&file.digest)) + .is_err_and(|error| error.kind() == ErrorKind::NotFound) + { + let _ = self.capture_value_file(file); + } + } + } + #[cfg(unix)] fn capture_value_file(&self, value: &FileValue) -> std::io::Result<()> { use rustix::fs::{AtFlags, Mode, OFlags, open, openat, renameat, unlinkat}; @@ -264,8 +278,8 @@ impl RunFolder { } /// Removes what an earlier invocation left half placed: every file under the folder whose - /// name is a temporary one ([`is_temporary_name`]). Only the invocation holding the lock - /// places anything here, so none of them is being written. Best effort. + /// name is a temporary one ([`is_temporary_name`]). Waiting request files have their own + /// writer lock and are swept separately under it. Best effort. pub fn sweep(&self) { let mut folders = vec![self.path.clone()]; while let Some(folder) = folders.pop() { @@ -277,12 +291,16 @@ impl RunFolder { continue; }; if kind.is_dir() { - folders.push(entry.path()); + if folder != self.path || entry.file_name() != crate::waiting::REQUEST_DIRECTORY + { + folders.push(entry.path()); + } } else if is_temporary_name(&entry.file_name().to_string_lossy()) { let _ = std::fs::remove_file(entry.path()); } } } + crate::waiting::sweep(&self.path); } /// `relative` as a path under the folder; refused when it is empty, absolute or could leave @@ -327,6 +345,16 @@ pub fn same_file(file: &File, path: &Path) -> bool { /// The most bytes one name may hold on the file systems FX writes to (`NAME_MAX`). pub const NAME_BYTES: usize = 255; +/// A reserved name for the remains of a run undergoing removal. +pub fn is_tombstone_name(name: &str) -> bool { + name.strip_prefix(".removing-").is_some_and(|hex| { + hex.len() == 16 + && hex + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + }) +} + /// A temporary name in the destination folder: `.<16 hex>.part`, hidden, never a digest, unique /// in the process so two tasks placing at once do not share one, and short (22 bytes), so it fits /// wherever the final name does. diff --git a/crates/grida-fx-runtime/src/lib.rs b/crates/grida-fx-runtime/src/lib.rs index b975601b..8b9cbd2c 100644 --- a/crates/grida-fx-runtime/src/lib.rs +++ b/crates/grida-fx-runtime/src/lib.rs @@ -15,6 +15,7 @@ //! | [`agent`] | the agent loop (`agent.run`) | //! | [`executor`] | one attempt of one instance: result cache, select, paid built-ins, host runs, accepting results | //! | [`runner`] | one run invocation: refusals, resume, scheduling, dispatch, outputs | +//! | [`waiting`] | durable waiting-step requests and answers | //! | [`plantime`] | `at: plan` steps while planning | //! | [`host`] | node host processes, their connections and pool; the planning host | //! | [`tools`] | external programs (`GRIDA_FX_TOOL_`, then `PATH`) | @@ -41,3 +42,4 @@ pub mod stand_in; pub mod stderr; pub mod store; pub mod tools; +pub mod waiting; diff --git a/crates/grida-fx-runtime/src/runner/awaiting.rs b/crates/grida-fx-runtime/src/runner/awaiting.rs new file mode 100644 index 00000000..8348bc0a --- /dev/null +++ b/crates/grida-fx-runtime/src/runner/awaiting.rs @@ -0,0 +1,207 @@ +//! Workflow-authored waits use the run's request store; no worker or paid reservation is held. + +use super::{Message, Scheduler, node_started, place_file}; +use crate::events::{Event, encode}; +use crate::waiting::{self, RequestSpec, RequestState, TimeoutPolicy}; +use grida_fx_core::Error; +use grida_fx_core::expand::{Instance, NodeResult, ResultStatus}; +use grida_fx_core::val::Val; +use indexmap::IndexMap; +use serde_json::Value; +use std::time::Duration; + +fn waiting_error(error: waiting::WaitingError) -> Error { + Error::internal(error.to_string()) +} + +/// Freeze precisely the keyed candidates and review material that this occurrence saw. Files +/// are adopted by the scheduler before the request is published. +fn request_spec(instance: &Instance) -> Result { + let values = &instance.with; + let text = |name: &str| match values.get(name) { + Some(Val::Str(value)) => Some(value.clone()), + _ => None, + }; + let choices = match values.get("choices") { + None => None, + Some(Val::Object(map)) => Some( + map.iter() + .map(|(key, value)| (key.clone(), waiting::encode_reviewed(value))) + .collect(), + ), + Some(Val::Collection(c)) => Some( + c.items + .iter() + .map(|(key, value)| (key.clone(), waiting::encode_reviewed(value))) + .collect(), + ), + Some(_) => return Err(Error::internal("waiting step needs keyed choices")), + }; + Ok(RequestSpec { + step: instance.id.clone(), + message: text("message"), + schema: values + .get("schema") + .and_then(Val::plain) + .ok_or_else(|| Error::internal("waiting step needs an answer schema"))?, + show: values + .get("show") + .map_or(Value::Null, waiting::encode_reviewed), + choices, + choice_field: text("choice_field"), + timeout_seconds: values + .get("timeout_seconds") + .and_then(Val::plain) + .and_then(|v| v.as_u64()), + on_timeout: match text("on_timeout").as_deref() { + Some("continue") => TimeoutPolicy::Continue, + _ => TimeoutPolicy::Fail, + }, + }) +} + +impl Scheduler<'_> { + /// Wait for either an ordinary worker/control message or an independently written answer. + /// Use the same receiver while waiting so a cancellation does not have to wait for a deadline. + pub(super) fn wait_for_work(&mut self) -> Result, Error> { + if self.awaiting.is_empty() { + return Ok(self.wait()); + } + loop { + // Charging and dispatch use this runner. A write to the run folder can arrive from + // a different process with no service or connection to the attached runner. + let message = self.engine.handle.block_on(async { + tokio::time::timeout(Duration::from_millis(200), self.receiver.recv()).await + }); + match message { + Ok(Some(message)) => { + let mut messages = vec![message]; + while let Ok(message) = self.receiver.try_recv() { + messages.push(message); + } + return Ok(messages); + } + Ok(None) => return Ok(Vec::new()), + Err(_) => { + let pending = self.awaiting.values().map(String::as_str); + if waiting::any_resolved(&self.folder.path, pending).map_err(waiting_error)? { + return Ok(vec![Message::RequestResolved]); + } + } + } + } + } + + pub(super) fn waiting_step(&mut self, instance: &Instance) -> Result { + let opening = !self.awaiting.contains_key(&instance.id); + let request = if let Some(id) = self.awaiting.get(&instance.id) { + waiting::expire_due(&self.folder.path, id).map_err(waiting_error)? + } else { + for file in instance.with.values().flat_map(crate::store::files_in) { + self.engine + .store + .adopt(file) + .map_err(|e| Error::internal(self.engine.scrub(&e.to_string())))?; + } + self.folder.capture_waiting_files( + ["show", "choices"] + .into_iter() + .filter_map(|name| instance.with.get(name)) + .flat_map(crate::store::files_in), + ); + // Review material is exposed through the local request surface. The portable + // execution event retains the node, its links and its identity. + let mut started = node_started(instance); + if let Event::NodeStarted { with, .. } = &mut started { + with.clear(); + } + self.emit(&started)?; + let spec = request_spec(instance)?; + let request = + waiting::ensure_request(&self.folder.path, spec).map_err(waiting_error)?; + // Even when just reattaching, the window is measured from the original opening. + waiting::expire_due(&self.folder.path, &request.id).map_err(waiting_error)? + }; + if opening || !matches!(request.state, RequestState::Pending) { + self.emit(&Event::WaitingRequest { + id: instance.id.clone(), + request_id: request.id.clone(), + status: request.state.status(), + deadline: request.deadline.clone(), + })?; + } + match &request.state { + RequestState::Pending => { + if super::schedule::group_of(instance).is_some() { + self.groups.open_requests.insert(instance.id.clone()); + } + self.awaiting.insert(instance.id.clone(), request.id); + Ok(true) + } + state => { + let mut outputs = IndexMap::new(); + let mut facts = IndexMap::new(); + let expired = matches!(state, RequestState::Expired { .. }); + facts.insert( + "outcome".into(), + Value::from(if expired { "expired" } else { "answered" }), + ); + let error = (expired && matches!(request.spec.on_timeout, TimeoutPolicy::Fail)) + .then(|| "the response deadline expired".to_owned()); + if let RequestState::Answered { answer, .. } = state { + outputs.insert("answer".into(), Val::from_json(answer)); + if let Some(value) = request.selected(answer) { + let selected = waiting::decode_reviewed(value, &self.engine.store) + .map_err(Error::internal)?; + outputs.insert("selected".into(), selected); + } + } + let status = if let Some(error) = &error { + self.emit(&Event::NodeFailed { + id: instance.id.clone(), + path: instance.path.clone(), + error: Some(error.clone()), + facts: Some(facts.clone()), + code: None, + diagnostic: None, + duration_ms: None, + display: super::terminal_display(instance), + })?; + self.failed.push((instance.id.clone(), Some(error.clone()))); + ResultStatus::Failed + } else { + for (relative, digest) in + crate::folder::step_files(&instance.path, &instance.takes, &outputs) + { + place_file(&self.engine.store, &self.folder, &relative, &digest) + .map_err(Error::internal)?; + } + self.emit(&Event::NodeFinished { + id: instance.id.clone(), + path: instance.path.clone(), + cache_hit: false, + outputs: outputs + .iter() + .map(|(key, val)| (key.clone(), encode(val))) + .collect(), + facts: facts.clone(), + duration_ms: 0, + })?; + ResultStatus::Succeeded + }; + self.awaiting.shift_remove(&instance.id); + self.groups.open_requests.remove(&instance.id); + self.planner.results.insert( + instance.id.clone(), + NodeResult { + outputs, + facts, + status, + error, + }, + ); + Ok(false) + } + } + } +} diff --git a/crates/grida-fx-runtime/src/runner/mod.rs b/crates/grida-fx-runtime/src/runner/mod.rs index 36185e55..47b1a459 100644 --- a/crates/grida-fx-runtime/src/runner/mod.rs +++ b/crates/grida-fx-runtime/src/runner/mod.rs @@ -86,6 +86,7 @@ //! incomplete: true, stopped: }` where it still can, and is returned as //! [`RunError::Fatal`]. The host pool is shut down whatever happened. +mod awaiting; pub mod dispatch; pub mod replay; pub mod schedule; @@ -128,6 +129,8 @@ pub struct RunOptions { pub name: Option, /// `--yes-up-to`. pub yes_up_to: Option, + /// Keep the invoking runner attached while workflow steps wait for an external answer. + pub wait_for_answers: bool, /// Require applicable forecasts for uncached chargeable work, including new expansions. pub require_estimates: bool, /// Permit only call cache hits and collection of retained jobs. @@ -549,9 +552,13 @@ fn invoke( } }; let events_label = in_folder(&options.label, "events.jsonl"); - planner - .results - .extend(replay::replay(&prior, &engine.store)); + match replay::replay_run(&prior, &engine.store, &folder.path) { + Ok(results) => planner.results.extend(results), + Err(error) => { + watchers(); + return Err(RunError::Fatal(error)); + } + } let invocation_id = crate::events::new_invocation_id(); let log = match EventLog::open(&folder.events_path(), &invocation_id, &digest) { Ok(log) => Arc::new(log), @@ -604,8 +611,10 @@ fn invoke( sender, receiver, running: IndexMap::new(), + awaiting: IndexMap::new(), + parked: false, overturned: IndexMap::new(), - groups: schedule::Groups::default(), + groups: schedule::Groups::resume(&prior), gate: schedule::Gate::new(), failed: Vec::new(), tasks: Vec::new(), @@ -869,6 +878,8 @@ enum Message { Interrupted, /// A stand-in run's answerer is gone ([`crate::stand_in::StandIn::lost`]). AnswererLost, + /// A workflow waiting step has accepted an answer or reached its deadline. + RequestResolved, } /// The loop's state (module doc). @@ -892,6 +903,10 @@ struct Scheduler<'a> { workflow: String, sender: mpsc::UnboundedSender, receiver: mpsc::UnboundedReceiver, + /// Request IDs for the waiting step occurrences reached in this invocation. + awaiting: IndexMap, + /// Reached quiescence and returned execution to the caller for these external requests. + parked: bool, /// Running instances by id. running: IndexMap, /// Running instances a run-time assertion failed and the run stopped: the assertion's @@ -1202,27 +1217,40 @@ impl Scheduler<'_> { for planned in &check.planned { self.emit(planned)?; } - let mut failed_at_once = false; + let mut result_ready = false; // Nothing new starts once a person stopped the run. if check.stop.is_none() && !self.interrupted() { let ready = schedule::ready(&expansion, &self.planner.results, &running, &self.groups); for id in ready { if let Some(instance) = expansion.instances.get(&id) { - failed_at_once |= !self.start(instance)?; + result_ready |= !self.start(instance)?; } } } + if result_ready { + continue; + } if self.running.is_empty() { if check.stop.is_some() { return Ok(check.stop); } - if failed_at_once { - continue; + if self.awaiting.is_empty() { + return Ok(None); + } + if !self.options.wait_for_answers { + self.parked = true; + return Ok(Some(format!( + "awaiting external answers for {}", + self.awaiting + .keys() + .map(String::as_str) + .collect::>() + .join(", ") + ))); } - return Ok(None); } - let messages = self.wait(); + let messages = self.wait_for_work()?; if messages.is_empty() { // Every sender is gone, so nothing running can report any more. return Err(Error::internal( @@ -1239,7 +1267,7 @@ impl Scheduler<'_> { } } Message::AnswererLost => lost = true, - Message::Interrupted => {} + Message::Interrupted | Message::RequestResolved => {} } } // A call that met the loss first has already stopped the run with it. @@ -1290,11 +1318,14 @@ impl Scheduler<'_> { self.engine.handle.block_on(self.services.calls_settled()); } - /// Dispatches an instance; `false` when its job could not be made and it failed at once. + /// Dispatches a job or opens a waiting step. `false` means an immediate result needs expansion. fn start(&mut self, instance: &Instance) -> Result { let Some(admission) = self.services.control.admit() else { return Ok(true); }; + if instance.ty.is_await() { + return self.waiting_step(instance); + } let env = |name: &str| std::env::var(name).ok(); let job = match InstanceJob::from_instance(instance, self.planner, &env) { Ok(job) => job, @@ -1495,6 +1526,11 @@ impl Scheduler<'_> { ok, incomplete, stopped: stopped.clone(), + awaiting: if self.parked { + self.awaiting.values().cloned().collect() + } else { + Vec::new() + }, charged_usd: charged, failed: self.failed.iter().map(|(id, _)| id.clone()).collect(), outputs: outputs @@ -1536,6 +1572,7 @@ impl Scheduler<'_> { ok: false, incomplete: true, stopped: Some(fault.message.clone()), + awaiting: Vec::new(), charged_usd: self.ledger.charged(), failed: self.failed.iter().map(|(id, _)| id.clone()).collect(), outputs: IndexMap::new(), diff --git a/crates/grida-fx-runtime/src/runner/replay.rs b/crates/grida-fx-runtime/src/runner/replay.rs index 09c407fa..a49cfa5f 100644 --- a/crates/grida-fx-runtime/src/runner/replay.rs +++ b/crates/grida-fx-runtime/src/runner/replay.rs @@ -23,6 +23,54 @@ pub fn replay(events: &[Value], store: &Store) -> IndexMap { replay_with(events, &|value| crate::events::decode(value, store)) } +/// Restore a waiting step's original selected value. A choice can be a structured object +/// containing typed files. Its request keeps the types that a plain JSON event output omits. +pub(super) fn replay_run( + events: &[Value], + store: &Store, + folder: &std::path::Path, +) -> Result, grida_fx_core::Error> { + let mut results = replay(events, store); + let mut restored = std::collections::HashSet::new(); + for event in events + .iter() + .rev() + .filter(|event| event["event"] == "waiting_request") + { + let (Some(step), Some(id)) = (event["id"].as_str(), event["request_id"].as_str()) else { + continue; + }; + let Some(result) = results.get_mut(step) else { + continue; + }; + if !restored.insert(step) || !result.outputs.contains_key("selected") { + continue; + } + let request = crate::waiting::lookup(folder, id) + .map_err(|error| grida_fx_core::Error::internal(error.to_string()))?; + let selected = match &request.state { + crate::waiting::RequestState::Answered { answer, .. } if request.spec.step == step => { + request.selected(answer) + } + _ => None, + } + .ok_or_else(|| { + grida_fx_core::Error::internal("the finished step's recorded choice is unavailable") + })?; + match crate::waiting::decode_reviewed(selected, store) { + Ok(value) => { + result.outputs.insert("selected".into(), value); + } + // Normal expansion can recover a missing file, then match the frozen review inputs + // before reusing the answer. A different input cannot silently satisfy that gate. + Err(_) => { + results.shift_remove(step); + } + } + } + Ok(results) +} + /// [`replay`] with the decoder given, so the walk can be tested on its own. fn replay_with( events: &[Value], diff --git a/crates/grida-fx-runtime/src/runner/schedule.rs b/crates/grida-fx-runtime/src/runner/schedule.rs index f58be5cd..5b7741c1 100644 --- a/crates/grida-fx-runtime/src/runner/schedule.rs +++ b/crates/grida-fx-runtime/src/runner/schedule.rs @@ -42,9 +42,25 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Groups { running: HashMap, + pub(super) open_requests: HashSet, } impl Groups { + /// Reserve the places of already-open requests before admitting new repeat + /// instances on resume. A request can exist before its first waiting_request event. + pub(super) fn resume(events: &[serde_json::Value]) -> Self { + let mut groups = Self::default(); + for event in events { + if let Some((step, published)) = crate::waiting::recorded_step(event) { + if !published || event["request_status"] == "pending" { + groups.open_requests.insert(step.to_owned()); + } else { + groups.open_requests.remove(step); + } + } + } + groups + } /// One more member of `group` runs. pub fn start(&mut self, group: &str) { *self.running.entry(group.to_string()).or_insert(0) += 1; @@ -129,7 +145,15 @@ pub fn ready( groups: &Groups, ) -> Vec { // The instances chosen in this call take their places too. - let mut groups = groups.clone(); + let mut occupied = groups.running.clone(); + // Waiting uses no worker, but a repeat's authored concurrency still bounds + // how many of its requests can be open together. Existing requests can settle + // even when every slot is occupied. + for id in &groups.open_requests { + if let Some((group, _)) = expansion.instances.get(id).and_then(group_of) { + *occupied.entry(group.to_owned()).or_default() += 1; + } + } let identity_of = |id: &String| expansion.instances.get(id)?.identity.as_deref(); let succeeded = succeeded_identities(expansion, results); let mut identities: HashSet<&str> = running.iter().filter_map(identity_of).collect(); @@ -160,15 +184,18 @@ pub fn ready( let identity = instance .identity .as_deref() - .filter(|identity| !succeeded.contains(identity)); + .filter(|identity| !instance.ty.is_await() && !succeeded.contains(identity)); if identity.is_some_and(|identity| identities.contains(identity)) { continue; } - if let Some((group, limit)) = group_of(instance) { - if groups.running(group) >= limit { + if !groups.open_requests.contains(&instance.id) + && let Some((group, limit)) = group_of(instance) + { + let count = occupied.entry(group.to_owned()).or_default(); + if *count >= limit { continue; } - groups.start(group); + *count += 1; } identities.extend(identity); ready.push(instance.id.clone()); diff --git a/crates/grida-fx-runtime/src/waiting.rs b/crates/grida-fx-runtime/src/waiting.rs new file mode 100644 index 00000000..a90d55d0 --- /dev/null +++ b/crates/grida-fx-runtime/src/waiting.rs @@ -0,0 +1,1555 @@ +//! Durable waiting-step requests. Responders and the scheduler share a short-lived request lock, +//! independent of the invocation's run.lock. Only the scheduler writes invocation events. + +use crate::store::Store; +use chrono::{DateTime, SecondsFormat, TimeDelta, Utc}; +use grida_fx_core::val::{Collection, Val, Verdict}; +use grida_fx_core::value::{canon, check_markers, digest, is_digest, parse_json}; +use indexmap::IndexMap; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; + +pub const REQUEST_DIRECTORY: &str = "awaiting"; +pub const REQUEST_LOCK: &str = "awaiting.lock"; +const RECORD_KIND: &str = "fx-await-request-v1"; +const MAX_SPEC_BYTES: usize = 1024 * 1024; +const MAX_ANSWER_BYTES: usize = 1024 * 1024; +const MAX_RECORD_BYTES: usize = 3 * 1024 * 1024; +const MAX_PLAN_BYTES: usize = 16 * 1024 * 1024; +const MAX_START_BYTES: usize = 4 * 1024 * 1024; + +/// Encode a reviewed value without losing nested typed files or collection verdicts. +pub fn encode_reviewed(value: &Val) -> Value { + match value { + Val::Object(items) if items.values().any(has_typed_member) => { + let fields: Map = items + .iter() + .map(|(key, value)| (key.clone(), encode_reviewed(value))) + .collect(); + json!({"object": fields}) + } + Val::List(items) => json!({"list": items.iter().map(encode_reviewed).collect::>()}), + Val::Collection(collection) => { + let items: Vec = collection + .items + .iter() + .map(|(key, value)| json!([key, encode_reviewed(value)])) + .collect(); + let mut encoded = json!({"collection": items}); + if !collection.verdicts.is_empty() { + let verdicts: Map = collection + .verdicts + .iter() + .map(|(key, verdict)| { + let value = match verdict { + Some(Verdict::Accept) => json!("accept"), + Some(Verdict::Reject) => json!("reject"), + Some(Verdict::Failed) => json!("failed"), + None => Value::Null, + }; + (key.clone(), value) + }) + .collect(); + encoded["verdicts"] = Value::Object(verdicts); + } + encoded + } + Val::Null => json!({"value": null}), + _ => crate::events::encode(value), + } +} + +fn has_typed_member(value: &Val) -> bool { + match value { + Val::Null | Val::Bool(_) | Val::Number(_) | Val::Str(_) => false, + Val::Object(value) => value.values().any(has_typed_member), + Val::List(value) => value.iter().any(has_typed_member), + _ => true, + } +} + +/// Restore a frozen candidate. A file is bound only through the content-addressed store. +pub fn decode_reviewed(value: &Value, store: &Store) -> Result { + let invalid = || "The request contains an invalid reviewed value.".to_string(); + if let Some(items) = value.get("collection") { + let mut collection = Collection::default(); + for item in items.as_array().ok_or_else(invalid)? { + let Some([Value::String(key), encoded]) = item.as_array().map(Vec::as_slice) else { + return Err(invalid()); + }; + collection + .items + .push((key.clone(), decode_reviewed(encoded, store)?)); + } + if let Some(verdicts) = value.get("verdicts") { + for (key, value) in verdicts.as_object().ok_or_else(invalid)? { + let verdict = match value { + Value::Null => None, + Value::String(value) if value == "accept" => Some(Verdict::Accept), + Value::String(value) if value == "reject" => Some(Verdict::Reject), + Value::String(value) if value == "failed" => Some(Verdict::Failed), + _ => return Err(invalid()), + }; + collection.verdicts.insert(key.clone(), verdict); + } + } + return Ok(Val::Collection(Box::new(collection))); + } + if let Some(items) = value.get("list") { + return items + .as_array() + .ok_or_else(invalid)? + .iter() + .map(|item| decode_reviewed(item, store)) + .collect::>() + .map(Val::List); + } + if let Some(items) = value.get("object") { + return items + .as_object() + .ok_or_else(invalid)? + .iter() + .map(|(name, item)| Ok((name.clone(), decode_reviewed(item, store)?))) + .collect::>() + .map(Val::Object); + } + if value.get("none") == Some(&Value::Bool(true)) { + return Ok(Val::Missing); + } + crate::events::decode(value, store) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum TimeoutPolicy { + #[default] + Fail, + Continue, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ResponseChannel { + Cli, + Sdk, + Viewer, +} + +/// Evaluated review inputs, frozen when the concrete instance first opens this request. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RequestSpec { + pub step: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + pub schema: Value, + pub show: Value, + #[serde(skip_serializing_if = "Option::is_none")] + pub choices: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub choice_field: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_seconds: Option, + pub on_timeout: TimeoutPolicy, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "status", deny_unknown_fields)] +pub enum RequestState { + Pending, + Answered { + answer: Value, + channel: ResponseChannel, + at: String, + }, + Expired { + at: String, + }, +} + +impl RequestState { + pub fn status(&self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Answered { .. } => "answered", + Self::Expired { .. } => "expired", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Request { + pub id: String, + #[serde(flatten)] + pub spec: RequestSpec, + pub opened_at: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub deadline: Option, + pub state: RequestState, +} + +impl Request { + /// Resolve the selected key against the original, frozen candidates. + pub fn selected(&self, answer: &Value) -> Option<&Value> { + self.spec + .choices + .as_ref()? + .get(choice_key(&self.spec, answer)?) + } + + fn expire(&mut self, now: DateTime) -> bool { + if matches!(self.state, RequestState::Pending) + && let Some(deadline) = self.deadline.as_deref().and_then(parse_time) + && now >= deadline + { + self.state = RequestState::Expired { + at: time_text(deadline), + }; + true + } else { + false + } + } +} + +#[derive(Debug)] +pub struct WaitingError { + code: &'static str, + message: &'static str, + request: Option>, +} + +impl WaitingError { + fn new(code: &'static str, message: &'static str) -> Self { + Self { + code, + message, + request: None, + } + } + + fn with_request(mut self, request: Request) -> Self { + self.request = Some(Box::new(request)); + self + } + + pub fn code(&self) -> &'static str { + self.code + } + + pub fn request(&self) -> Option<&Request> { + self.request.as_deref() + } +} + +impl fmt::Display for WaitingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.message) + } +} + +impl std::error::Error for WaitingError {} + +fn invalid_run() -> WaitingError { + WaitingError::new( + "invalid_run", + "The selected run evidence is invalid or inaccessible.", + ) +} + +fn invalid_record() -> WaitingError { + WaitingError::new( + "invalid_run", + "The saved waiting request does not match this run.", + ) +} + +fn storage_error() -> WaitingError { + WaitingError::new( + "storage_error", + "The waiting request could not be read or recorded.", + ) +} + +fn not_found() -> WaitingError { + WaitingError::new("not_found", "No such request exists in the selected run.") +} + +fn time_text(time: DateTime) -> String { + time.to_rfc3339_opts(SecondsFormat::Millis, true) +} + +fn parse_time(time: &str) -> Option> { + DateTime::parse_from_rfc3339(time).ok().map(|t| t.to_utc()) +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Record { + kind: String, + plan: String, + run: String, + request: Request, +} + +struct Run { + root: PathBuf, + plan: String, + id: String, +} + +impl Run { + fn open(path: &Path, write: bool) -> Result { + let root = path.canonicalize().map_err(|_| invalid_run())?; + if root + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(crate::folder::is_tombstone_name) + { + return Err(invalid_run()); + } + let directory = fs::symlink_metadata(&root).map_err(|_| invalid_run())?; + if !directory.is_dir() || (write && !owned(&directory)) { + return Err(invalid_run()); + } + + let (plan, plan_meta) = + read_value(&root.join("plan.json"), MAX_PLAN_BYTES).map_err(|_| invalid_run())?; + let plan = plan["plan"] + .as_str() + .filter(|hash| is_digest(hash)) + .ok_or_else(invalid_run)?; + let file = + open_file(&root.join("events.jsonl"), false, false).map_err(|_| invalid_run())?; + if write && (!owned(&plan_meta) || !owned(&file.metadata().map_err(|_| invalid_run())?)) { + return Err(invalid_run()); + } + let mut line = Vec::new(); + let count = BufReader::new(file) + .take((MAX_START_BYTES + 1) as u64) + .read_until(b'\n', &mut line) + .map_err(|_| invalid_run())?; + if count > MAX_START_BYTES || line.pop() != Some(b'\n') { + return Err(invalid_run()); + } + let start = std::str::from_utf8(&line) + .ok() + .and_then(|text| parse_json(text).ok()) + .ok_or_else(invalid_run)?; + if start["kind"] != "fx-run-events-v1" + || start["event"] != "run_started" + || start["plan"] != plan + { + return Err(invalid_run()); + } + let id = start["invocation_id"] + .as_str() + .filter(|id| { + id.len() == 16 + && id + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) + .ok_or_else(invalid_run)?; + Ok(Self { + root, + plan: plan.to_owned(), + id: id.to_owned(), + }) + } + + fn request_id(&self, step: &str) -> String { + digest(&json!(["fx-await-request-v1", self.plan, self.id, step])) + } + + fn directory(&self) -> PathBuf { + self.root.join(REQUEST_DIRECTORY) + } + + fn path(&self, id: &str) -> PathBuf { + self.directory().join(format!("{id}.json")) + } + + fn read(&self, id: &str) -> Result, WaitingError> { + if !request_directory(&self.root, false)? { + return Ok(None); + } + let value = match read_value(&self.path(id), MAX_RECORD_BYTES) { + Ok((value, meta)) if owned(&meta) => value, + Ok(_) => return Err(invalid_record()), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(_) => return Err(invalid_record()), + }; + let record: Record = serde_json::from_value(value).map_err(|_| invalid_record())?; + if record.kind != RECORD_KIND + || record.plan != self.plan + || record.run != self.id + || record.request.id != id + || self.request_id(&record.request.spec.step) != id + || parse_time(&record.request.opened_at).is_none() + || record + .request + .deadline + .as_deref() + .is_some_and(|time| parse_time(time).is_none()) + { + return Err(invalid_record()); + } + Ok(Some(record)) + } + + fn write(&self, record: &Record) -> Result<(), WaitingError> { + if !request_directory(&self.root, true)? { + return Err(invalid_record()); + } + let value = serde_json::to_value(record).map_err(|_| storage_error())?; + // Persist compact JSON so indentation cannot inflate a valid submission over + // the record limit. The request settings and answer already have independent limits. + let bytes = canon(&value); + if bytes.len() > MAX_RECORD_BYTES || parse_json(&bytes).is_err() { + return Err(WaitingError::new( + "invalid_request", + "The waiting request exceeds its storage size or nesting limit.", + )); + } + crate::store::atomic_write(&self.path(&record.request.id), bytes.as_bytes(), false) + .map_err(|_| storage_error())?; + self.sync() + } + + fn sync(&self) -> Result<(), WaitingError> { + sync_directory(&self.directory())?; + sync_directory(&self.root) + } +} + +/// Open a request once, or restore its exact saved review inputs and resolution. +pub fn ensure_request(run: &Path, spec: RequestSpec) -> Result { + ensure_at(run, spec, Utc::now) +} + +fn ensure_at( + run: &Path, + spec: RequestSpec, + now: impl FnOnce() -> DateTime, +) -> Result { + let run = Run::open(run, true)?; + let _lock = lock(&run.root, true)?.ok_or_else(storage_error)?; + let id = run.request_id(&spec.step); + if let Some(record) = run.read(&id)? { + let saved = serde_json::to_value(&record.request.spec).map_err(|_| invalid_record())?; + let current = serde_json::to_value(&spec).map_err(|_| invalid_record())?; + if canon(&saved) != canon(¤t) { + return Err(WaitingError::new( + "invalid_request", + "The reviewed inputs changed since this request opened. Start a new run.", + )); + } + return Ok(record.request); + } + let validator = request_validator(&spec)?; + if let Some(choices) = &spec.choices { + grida_fx_core::builtins::waiting::validate_choice_keys( + &spec.schema, + &validator, + choices.keys().map(String::as_str), + spec.choice_field.as_deref(), + ) + .map_err(|message| WaitingError::new("invalid_request", message))?; + } + // Use the recorded opening precision for both the opening and the attached timeout. + let opened_at = + DateTime::from_timestamp_millis(now().timestamp_millis()).ok_or_else(storage_error)?; + let deadline = spec + .timeout_seconds + .map(|seconds| { + i64::try_from(seconds) + .ok() + .and_then(TimeDelta::try_seconds) + .and_then(|duration| opened_at.checked_add_signed(duration)) + .map(time_text) + .filter(|deadline| parse_time(deadline).is_some()) + .ok_or_else(invalid_timeout) + }) + .transpose()?; + create_request_directory(&run.root)?; + let record = Record { + kind: RECORD_KIND.into(), + plan: run.plan.clone(), + run: run.id.clone(), + request: Request { + id, + spec, + opened_at: time_text(opened_at), + deadline, + state: RequestState::Pending, + }, + }; + run.write(&record)?; + Ok(record.request) +} + +fn invalid_timeout() -> WaitingError { + WaitingError::new( + "invalid_request", + "The waiting-step timeout must be a positive, bounded duration.", + ) +} + +fn request_validator(spec: &RequestSpec) -> Result { + if serde_json::to_vec(spec).map_or(true, |bytes| bytes.len() > MAX_SPEC_BYTES) { + return Err(WaitingError::new( + "invalid_request", + "The waiting request exceeds its size limit.", + )); + } + if spec.step.is_empty() + || spec + .message + .as_ref() + .is_some_and(|message| message.trim().is_empty()) + { + return Err(WaitingError::new( + "invalid_request", + "A waiting step needs a concrete instance and any supplied message must be nonempty.", + )); + } + if spec.timeout_seconds == Some(0) { + return Err(invalid_timeout()); + } + if spec.choices.as_ref().is_some_and(|choices| { + choices.is_empty() || choices.keys().any(|key| key.trim().is_empty()) + }) || spec + .choice_field + .as_ref() + .is_some_and(|field| field.trim().is_empty() || spec.choices.is_none()) + { + return Err(WaitingError::new( + "invalid_request", + "Waiting-step choices must be nonempty, and a choice field requires choices.", + )); + } + grida_fx_core::builtins::waiting::answer_validator(&spec.schema).map_err(|_| { + WaitingError::new( + "invalid_request", + "The answer schema must be a valid draft 2020-12 JSON Schema with only internal references.", + ) + }) +} + +fn choice_key<'a>(spec: &RequestSpec, answer: &'a Value) -> Option<&'a str> { + match &spec.choice_field { + Some(field) => answer.get(field)?.as_str(), + None => answer.as_str(), + } +} + +fn check_id(id: &str) -> Result<(), WaitingError> { + if !is_digest(id) { + return Err(WaitingError::new( + "invalid_request", + "A waiting request ID must be 64 lowercase hexadecimal characters.", + )); + } + Ok(()) +} + +/// List the selected run's stored requests. An elapsed deadline is reflected without a write. +pub fn list(run: &Path) -> Result, WaitingError> { + // Older or purely planned records can have no request directory or run_started evidence. + // Avoid turning those records into errors on a read-only viewer attachment. + if !fs::metadata(run).is_ok_and(|meta| meta.is_dir()) { + return Err(invalid_run()); + } + let directory = match fs::symlink_metadata(run.join(REQUEST_DIRECTORY)) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(_) => return Err(storage_error()), + }; + let has_lock = fs::symlink_metadata(run.join(REQUEST_LOCK)) + .is_ok_and(|meta| meta.is_file() && meta.len() == 0 && owned(&meta)); + // A caller can point a run at an existing user directory. Without a request lock, + // consult the run log before treating anything named "awaiting" as engine data. + let recorded = if has_lock { + None + } else { + let steps = recorded_wait_steps(run)?; + if steps.is_empty() { + return Ok(Vec::new()); + } + Some(steps) + }; + if !directory.is_dir() { + return Err(invalid_record()); + } + let run = Run::open(run, false)?; + let mut requests = Vec::new(); + let now = Utc::now(); + if let Some(steps) = recorded { + // A copied folder may omit its ephemeral lock. Inspect just the files that + // correspond to the waiting step occurrences in this run's event history. + for (step, published) in steps { + match run.read(&run.request_id(&step))? { + Some(record) => requests.push(record.request), + None if published => return Err(invalid_record()), + None => {} + } + } + } else { + for item in fs::read_dir(run.directory()).map_err(|_| storage_error())? { + let item = item.map_err(|_| storage_error())?; + let filename = item.file_name(); + if let Some(id) = filename + .to_str() + .and_then(|name| name.strip_suffix(".json")) + && is_digest(id) + { + requests.push(run.read(id)?.ok_or_else(invalid_record)?.request); + } + } + } + for request in &mut requests { + request.expire(now); + } + requests.sort_by(|left, right| { + left.opened_at + .cmp(&right.opened_at) + .then_with(|| left.spec.step.cmp(&right.spec.step)) + }); + Ok(requests) +} + +/// Even when an invocation stops between publishing the request and emitting +/// `waiting_request`, its preceding `node_started` identifies that exact occurrence. +fn recorded_wait_steps( + run: &Path, +) -> Result, WaitingError> { + let mut steps = std::collections::BTreeMap::new(); + let file = match open_file(&run.join("events.jsonl"), false, false) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(steps), + Err(_) => return Err(invalid_run()), + }; + let mut reader = BufReader::new(file); + let mut line = Vec::new(); + loop { + line.clear(); + reader + .read_until(b'\n', &mut line) + .map_err(|_| invalid_run())?; + if line.last() != Some(&b'\n') { + break; + } + let Ok(line) = std::str::from_utf8(&line) else { + break; + }; + if line.trim().is_empty() { + continue; + } + let Ok(event) = parse_json(line) else { break }; + if let Some((step, published)) = recorded_step(&event) { + *steps.entry(step.to_owned()).or_default() |= published; + } + } + Ok(steps) +} + +/// A concrete waiting step in the event log, and whether the engine observed a saved request. +pub(crate) fn recorded_step(event: &Value) -> Option<(&str, bool)> { + if event["kind"] != "fx-run-events-v1" { + return None; + } + let published = match event["event"].as_str()? { + "waiting_request" => true, + "node_started" + if event["uses"] + .as_str()? + .strip_prefix("fx/await@")? + .trim_start_matches('0') + == "1" => + { + false + } + _ => return None, + }; + Some((event["id"].as_str()?, published)) +} + +/// Read one exact request from an existing run without writing. +pub fn lookup(run: &Path, id: &str) -> Result { + check_id(id)?; + if !request_directory(run, false)? { + return Err(not_found()); + } + let mut request = Run::open(run, false)? + .read(id)? + .ok_or_else(not_found)? + .request; + request.expire(Utc::now()); + Ok(request) +} + +/// An attached scheduler observes its open requests together. Verify the run and read its +/// plan once per poll, even when a repeated step has many pending occurrences. +pub(crate) fn any_resolved<'a>( + run: &Path, + ids: impl Iterator, +) -> Result { + let run = Run::open(run, false)?; + let now = Utc::now(); + for id in ids { + check_id(id)?; + let mut request = run.read(id)?.ok_or_else(not_found)?.request; + request.expire(now); + if !matches!(request.state, RequestState::Pending) { + return Ok(true); + } + } + Ok(false) +} + +/// Accept a valid answer. A conflicting response returns the already recorded resolution. +pub fn respond( + run: &Path, + id: &str, + answer: Value, + channel: ResponseChannel, +) -> Result { + respond_at(run, id, answer, channel, Utc::now) +} + +fn respond_at( + run: &Path, + id: &str, + answer: Value, + channel: ResponseChannel, + now: impl FnOnce() -> DateTime, +) -> Result { + check_id(id)?; + if crate::events::nesting(&answer) > crate::events::VALUE_DEPTH { + return Err(WaitingError::new( + "invalid_answer", + "The answer is too deeply nested for the run's record.", + )); + } + let text = serde_json::to_string(&answer).map_err(|_| invalid_answer_value())?; + if text.len() > MAX_ANSWER_BYTES { + return Err(WaitingError::new( + "invalid_answer", + "The answer exceeds its size limit.", + )); + } + // Native callers can construct unnormalized serde_json numbers directly. Apply exactly + // the same profile as CLI and viewer text, before schema validation and idempotency comparison. + let answer = parse_json(&text).map_err(|_| invalid_answer_value())?; + check_markers(&answer, "answer").map_err(|_| { + WaitingError::new( + "invalid_answer", + "The answer contains a reserved FX value marker.", + ) + })?; + let run = Run::open(run, true)?; + let _lock = lock(&run.root, false)?.ok_or_else(not_found)?; + let mut record = run.read(id)?.ok_or_else(not_found)?; + if let RequestState::Answered { + answer: recorded, .. + } = &record.request.state + { + run.sync()?; + if canon(recorded) == canon(&answer) { + return Ok(record.request); + } + return Err(WaitingError::new( + "answer_conflict", + "The request already has a different answer.", + ) + .with_request(record.request)); + } + let now = now(); + if record.request.expire(now) { + run.write(&record)?; + } + if matches!(record.request.state, RequestState::Expired { .. }) { + return Err( + WaitingError::new("expired", "The waiting request has expired.") + .with_request(record.request), + ); + } + let validator = request_validator(&record.request.spec)?; + if !validator.is_valid(&answer) { + return Err(WaitingError::new( + "invalid_answer", + "The answer does not match the request's JSON Schema.", + )); + } + if record.request.spec.choices.is_some() && record.request.selected(&answer).is_none() { + return Err(WaitingError::new( + "invalid_answer", + "The answer does not identify one of the frozen choices.", + )); + } + record.request.state = RequestState::Answered { + answer, + channel, + at: time_text(now), + }; + run.write(&record)?; + Ok(record.request) +} + +fn invalid_answer_value() -> WaitingError { + WaitingError::new( + "invalid_answer", + "The answer is outside the FX JSON value profile.", + ) +} + +/// Close an elapsed response window under the same lock that accepts answers. +pub fn expire_due(run: &Path, id: &str) -> Result { + expire_at(run, id, Utc::now) +} + +fn expire_at( + run: &Path, + id: &str, + now: impl FnOnce() -> DateTime, +) -> Result { + check_id(id)?; + let run = Run::open(run, true)?; + let _lock = lock(&run.root, false)?.ok_or_else(not_found)?; + let mut record = run.read(id)?.ok_or_else(not_found)?; + if record.request.expire(now()) { + run.write(&record)?; + } + Ok(record.request) +} + +/// A remover first acquires run.lock, then this lock, before moving or removing the folder. +pub fn lock_for_removal(run: &Path) -> Result, WaitingError> { + lock(run, false) +} + +pub(crate) fn sweep(run: &Path) { + let Ok(Some(_lock)) = lock(run, false) else { + return; + }; + if matches!(request_directory(run, true), Ok(true)) + && let Ok(entries) = fs::read_dir(run.join(REQUEST_DIRECTORY)) + { + for entry in entries.flatten() { + if crate::folder::is_temporary_name(&entry.file_name().to_string_lossy()) { + let _ = fs::remove_file(entry.path()); + } + } + } +} + +fn lock(root: &Path, create: bool) -> Result, WaitingError> { + let path = root.join(REQUEST_LOCK); + let file = match open_file(&path, true, create) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound && !create => return Ok(None), + Err(_) => return Err(storage_error()), + }; + let metadata = file.metadata().map_err(|_| storage_error())?; + if !owned(&metadata) || metadata.len() != 0 { + return Err(invalid_run()); + } + file.lock().map_err(|_| storage_error())?; + if !crate::folder::same_file(&file, &path) { + return Err(invalid_run()); + } + Ok(Some(file)) +} + +fn request_directory(root: &Path, write: bool) -> Result { + match fs::symlink_metadata(root.join(REQUEST_DIRECTORY)) { + Ok(metadata) if metadata.is_dir() && (!write || owned(&metadata)) => Ok(true), + Ok(_) => Err(invalid_record()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(_) => Err(storage_error()), + } +} + +fn create_request_directory(root: &Path) -> Result<(), WaitingError> { + if !request_directory(root, true)? { + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder + .create(root.join(REQUEST_DIRECTORY)) + .map_err(|_| storage_error())?; + sync_directory(root)?; + } + Ok(()) +} + +#[cfg(unix)] +fn sync_directory(path: &Path) -> Result<(), WaitingError> { + File::open(path) + .and_then(|directory| directory.sync_all()) + .map_err(|_| storage_error()) +} + +#[cfg(not(unix))] +fn sync_directory(_: &Path) -> Result<(), WaitingError> { + Ok(()) +} + +#[cfg(unix)] +fn owned(metadata: &fs::Metadata) -> bool { + use std::os::unix::fs::MetadataExt; + metadata.uid() == rustix::process::geteuid().as_raw() && metadata.mode() & 0o022 == 0 +} + +#[cfg(not(unix))] +fn owned(_: &fs::Metadata) -> bool { + true +} + +fn read_value(path: &Path, limit: usize) -> io::Result<(Value, fs::Metadata)> { + let file = open_file(path, false, false)?; + let metadata = file.metadata()?; + let mut text = String::new(); + file.take((limit + 1) as u64).read_to_string(&mut text)?; + if text.len() > limit { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "record exceeds its limit", + )); + } + let value = parse_json(&text) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid JSON record"))?; + Ok((value, metadata)) +} + +fn open_file(path: &Path, write: bool, create: bool) -> io::Result { + #[cfg(unix)] + let file = { + use rustix::fs::{Mode, OFlags, open}; + let mut flags = OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK; + flags |= if write { OFlags::RDWR } else { OFlags::RDONLY }; + if create { + flags |= OFlags::CREATE; + } + File::from(open(path, flags, Mode::RUSR | Mode::WUSR)?) + }; + #[cfg(not(unix))] + let file = { + if let Ok(meta) = fs::symlink_metadata(path) + && !meta.is_file() + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "record is not regular", + )); + } + fs::OpenOptions::new() + .read(true) + .write(write) + .create(create) + .truncate(false) + .open(path)? + }; + if !file.metadata()?.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "record is not regular", + )); + } + Ok(file) +} + +#[cfg(test)] +mod tests { + use super::*; + use grida_fx_core::value::write_json; + use std::sync::{Arc, Barrier}; + use std::thread; + use tempfile::TempDir; + + fn run(start: &str) -> TempDir { + let root = tempfile::tempdir().unwrap(); + let plan = "a".repeat(64); + fs::write( + root.path().join("plan.json"), + write_json(&json!({"kind": "fx-graph-v2", "plan": plan})), + ) + .unwrap(); + fs::write( + root.path().join("events.jsonl"), + format!( + "{}\n", + canon(&json!({ + "kind": "fx-run-events-v1", + "event": "run_started", + "plan": plan, + "invocation_id": start + })) + ), + ) + .unwrap(); + root + } + + fn now() -> DateTime { + parse_time("2026-01-01T00:00:00Z").unwrap() + } + + fn reviewed() -> RequestSpec { + RequestSpec { + step: "review#1".into(), + message: Some("Choose a variant.".into()), + schema: json!({ + "type": "object", "required": ["variant"], + "properties": {"variant": {"type": "string"}}, + "additionalProperties": false + }), + show: json!({"none": true}), + choices: Some(IndexMap::from([ + ("a".into(), json!({"value": "first"})), + ("b".into(), json!({"value": "second"})), + ])), + choice_field: Some("variant".into()), + timeout_seconds: Some(10), + on_timeout: TimeoutPolicy::Continue, + } + } + + #[test] + fn same_run_replays_frozen_choices_and_fresh_occurrences_get_distinct_ids() { + let original = run("0123456789abcdef"); + let fresh = run("fedcba9876543210"); + let first = ensure_at(original.path(), reviewed(), now).unwrap(); + let replayed = + ensure_at(original.path(), reviewed(), || now() + TimeDelta::hours(1)).unwrap(); + assert_eq!( + (replayed.id, replayed.deadline), + (first.id.clone(), first.deadline) + ); + let another_instance = ensure_at( + original.path(), + RequestSpec { + step: "review#2".into(), + ..reviewed() + }, + now, + ) + .unwrap(); + assert_ne!(another_instance.id, first.id); + assert_ne!( + ensure_at(fresh.path(), reviewed(), now).unwrap().id, + first.id + ); + assert_eq!( + ensure_at( + original.path(), + RequestSpec { + show: json!({"value": "different"}), + ..reviewed() + }, + now, + ) + .unwrap_err() + .code(), + "invalid_request" + ); + } + + #[test] + fn selected_objects_restore_typed_files_inside_keyed_collections() { + use grida_fx_core::val::FileValue; + + let root = tempfile::tempdir().unwrap(); + let store = Store::open(root.path()); + let recorded = store.put_bytes(b"example").unwrap(); + let file = Val::File(Box::new(FileValue { + digest: recorded.digest, + size: recorded.size, + kind: "text/plain".into(), + name: "sample.txt".into(), + key: None, + content: None, + location: None, + })); + let collection = Val::Collection(Box::new(Collection { + items: vec![("draft".into(), file)], + verdicts: IndexMap::from([("draft".into(), Some(Verdict::Accept))]), + })); + let value = Val::Object(IndexMap::from([ + ("files".into(), Val::List(vec![collection])), + ("notes".into(), Val::Null), + ])); + let encoded = encode_reviewed(&value); + assert!(encoded["object"]["files"]["list"][0]["collection"][0][1]["file"].is_object()); + assert_eq!(decode_reviewed(&encoded, &store).unwrap(), value); + } + + #[test] + fn two_clients_converge_and_invalid_choices_do_not_claim_the_request() { + let folder = Arc::new(run("0123456789abcdef")); + let request = ensure_at( + folder.path(), + RequestSpec { + timeout_seconds: None, + ..reviewed() + }, + now, + ) + .unwrap(); + for answer in [json!({"variant": "unknown"}), json!(false)] { + assert_eq!( + respond(folder.path(), &request.id, answer, ResponseChannel::Cli) + .unwrap_err() + .code(), + "invalid_answer" + ); + } + assert!(matches!( + lookup(folder.path(), &request.id).unwrap().state, + RequestState::Pending + )); + + let barrier = Arc::new(Barrier::new(2)); + let clients = [("a", ResponseChannel::Cli), ("b", ResponseChannel::Viewer)].map( + |(choice, channel)| { + let folder = Arc::clone(&folder); + let barrier = Arc::clone(&barrier); + let id = request.id.clone(); + thread::spawn(move || { + barrier.wait(); + respond(folder.path(), &id, json!({"variant": choice}), channel) + }) + }, + ); + let results = clients.map(|client| client.join().unwrap()); + let winner = results + .iter() + .find_map(|result| result.as_ref().ok()) + .unwrap(); + let disagreement = results + .iter() + .find_map(|result| result.as_ref().err()) + .unwrap(); + assert_eq!(disagreement.code(), "answer_conflict"); + assert_eq!( + serde_json::to_value(disagreement.request().unwrap()).unwrap(), + serde_json::to_value(winner).unwrap() + ); + let RequestState::Answered { answer, .. } = &winner.state else { + panic!("winner was not recorded") + }; + assert!(winner.selected(answer).is_some()); + let retry = respond( + folder.path(), + &request.id, + answer.clone(), + ResponseChannel::Sdk, + ) + .unwrap(); + assert_eq!( + serde_json::to_value(retry).unwrap(), + serde_json::to_value(winner).unwrap() + ); + } + + #[test] + fn elapsed_request_rejects_a_first_answer_but_identical_accepted_null_can_retry() { + let folder = run("0123456789abcdef"); + let elapsed = ensure_at(folder.path(), reviewed(), now).unwrap(); + let timeout = respond_at( + folder.path(), + &elapsed.id, + json!({"variant": "a"}), + ResponseChannel::Cli, + || now() + TimeDelta::seconds(10), + ) + .unwrap_err(); + assert_eq!(timeout.code(), "expired"); + assert!(matches!( + timeout.request().unwrap().state, + RequestState::Expired { .. } + )); + let nullable = ensure_at( + folder.path(), + RequestSpec { + step: "affirm#1".into(), + schema: json!({"type": ["boolean", "null"]}), + choices: None, + choice_field: None, + ..reviewed() + }, + now, + ) + .unwrap(); + let accepted = respond_at( + folder.path(), + &nullable.id, + Value::Null, + ResponseChannel::Cli, + || now() + TimeDelta::seconds(9), + ) + .unwrap(); + assert!(matches!( + accepted.state, + RequestState::Answered { + answer: Value::Null, + .. + } + )); + let retry = respond_at( + folder.path(), + &nullable.id, + Value::Null, + ResponseChannel::Sdk, + || now() + TimeDelta::seconds(11), + ) + .unwrap(); + assert!(matches!( + retry.state, + RequestState::Answered { + channel: ResponseChannel::Cli, + .. + } + )); + } + + #[test] + fn expiry_and_a_response_at_the_deadline_agree_on_one_resolution() { + let folder = Arc::new(run("0123456789abcdef")); + let request = ensure_at(folder.path(), reviewed(), now).unwrap(); + let barrier = Arc::new(Barrier::new(2)); + let timer = { + let folder = Arc::clone(&folder); + let barrier = Arc::clone(&barrier); + let id = request.id.clone(); + thread::spawn(move || { + barrier.wait(); + expire_at(folder.path(), &id, || now() + TimeDelta::seconds(10)).unwrap() + }) + }; + barrier.wait(); + let late = respond_at( + folder.path(), + &request.id, + json!({"variant": "a"}), + ResponseChannel::Viewer, + || now() + TimeDelta::seconds(10), + ) + .unwrap_err(); + assert_eq!(late.code(), "expired"); + let timer = timer.join().unwrap(); + assert_eq!( + serde_json::to_value(late.request().unwrap()).unwrap(), + serde_json::to_value(timer).unwrap() + ); + } + + #[test] + fn timer_and_acceptance_share_the_recorded_millisecond_boundary() { + let folder = run("0123456789abcdef"); + let request = ensure_at(folder.path(), reviewed(), || { + now() + TimeDelta::nanoseconds(999_999) + }) + .unwrap(); + assert_eq!(request.opened_at, "2026-01-01T00:00:00.000Z"); + assert_eq!( + request.deadline.as_deref(), + Some("2026-01-01T00:00:10.000Z") + ); + let accepted = respond_at( + folder.path(), + &request.id, + json!({"variant":"a"}), + ResponseChannel::Cli, + || now() + TimeDelta::seconds(10) - TimeDelta::nanoseconds(1), + ) + .unwrap(); + assert!( + matches!(accepted.state, RequestState::Answered { at, .. } if at == "2026-01-01T00:00:09.999Z") + ); + } + + #[test] + fn a_deadline_outside_the_wire_calendar_is_refused_before_publication() { + let folder = run("0123456789abcdef"); + let error = ensure_at( + folder.path(), + RequestSpec { + timeout_seconds: Some(350_000_000_000), + ..reviewed() + }, + now, + ) + .unwrap_err(); + assert_eq!(error.code(), "invalid_request"); + assert!(list(folder.path()).unwrap().is_empty()); + } + + #[test] + fn equivalent_json_from_different_clients_retries_the_original_answer() { + let folder = run("0123456789abcdef"); + let request = ensure_at( + folder.path(), + RequestSpec { + schema: json!(true), + choices: None, + choice_field: None, + timeout_seconds: None, + ..reviewed() + }, + now, + ) + .unwrap(); + assert_eq!( + respond( + folder.path(), + &request.id, + json!(9_007_199_254_740_993_i64), + ResponseChannel::Sdk + ) + .unwrap_err() + .code(), + "invalid_answer" + ); + let first = respond( + folder.path(), + &request.id, + json!({"a":1.0,"b":-0.0}), + ResponseChannel::Viewer, + ) + .unwrap(); + let retry = respond( + folder.path(), + &request.id, + json!({"b":0,"a":1}), + ResponseChannel::Cli, + ) + .unwrap(); + assert_eq!( + serde_json::to_value(first).unwrap(), + serde_json::to_value(retry).unwrap() + ); + } + + #[test] + fn a_removal_tombstone_cannot_be_answered_even_if_its_records_still_exist() { + let parent = tempfile::tempdir().unwrap(); + let folder = run("0123456789abcdef"); + let request = ensure_at(folder.path(), reviewed(), now).unwrap(); + let tombstone = parent.path().join(".removing-0123456789abcdef"); + fs::rename(folder.path(), &tombstone).unwrap(); + assert!(tombstone.join("plan.json").is_file()); + assert_eq!( + respond( + &tombstone, + &request.id, + json!({"variant":"a"}), + ResponseChannel::Cli + ) + .unwrap_err() + .code(), + "invalid_run" + ); + } + + #[cfg(unix)] + #[test] + fn cannot_answer_through_a_replaced_request_path() { + use std::os::unix::fs::symlink; + + let folder = run("0123456789abcdef"); + let request = ensure_at(folder.path(), reviewed(), now).unwrap(); + let outside = tempfile::NamedTempFile::new().unwrap(); + fs::write(outside.path(), b"outside").unwrap(); + let path = folder + .path() + .join(REQUEST_DIRECTORY) + .join(format!("{}.json", request.id)); + fs::remove_file(&path).unwrap(); + symlink(outside.path(), &path).unwrap(); + for id in [&request.id, "../../outside"] { + assert!(respond(folder.path(), id, Value::Null, ResponseChannel::Cli).is_err()); + } + assert_eq!(fs::read(outside.path()).unwrap(), b"outside"); + } + + #[test] + fn a_schema_is_local_and_validated_before_publication() { + let folder = run("0123456789abcdef"); + let fault = ensure_at( + folder.path(), + RequestSpec { + schema: json!({"$ref": "https://example.invalid/schema"}), + ..reviewed() + }, + now, + ) + .unwrap_err(); + assert_eq!(fault.code(), "invalid_request"); + assert!(list(folder.path()).unwrap().is_empty()); + assert!( + ensure_at( + folder.path(), + RequestSpec { + schema: json!({"$defs": {"text": {"type": "string"}}, "$ref": "#/$defs/text"}), + choice_field: None, + ..reviewed() + }, + now + ) + .is_ok() + ); + } + + #[test] + fn choices_must_allow_an_answer_before_the_request_opens() { + let folder = run("0123456789abcdef"); + for (schema, field) in [ + (json!({"type": "boolean"}), None), + (json!({"type": "string"}), Some("variant")), + ( + json!({"properties": {"variant": {"enum": ["absent"]}}}), + Some("variant"), + ), + ] { + let error = ensure_at( + folder.path(), + RequestSpec { + schema, + choice_field: field.map(str::to_owned), + ..reviewed() + }, + now, + ) + .unwrap_err(); + assert_eq!(error.code(), "invalid_request"); + } + assert!(list(folder.path()).unwrap().is_empty()); + + // A sibling supplied by the responder selects the branch that admits the key. + let request = ensure_at( + folder.path(), + RequestSpec { + message: None, + schema: json!({ + "required": ["mode"], + "if": {"required": ["mode"]}, + "then": {"properties": {"variant": {"enum": ["a"]}}}, + "else": {"properties": {"variant": {"type": "boolean"}}} + }), + ..reviewed() + }, + now, + ) + .unwrap(); + assert!(json!(request).get("message").is_none()); + assert_eq!( + respond_at( + folder.path(), + &request.id, + json!({"mode": "print", "variant": "b"}), + ResponseChannel::Sdk, + now + ) + .unwrap_err() + .code(), + "invalid_answer" + ); + respond_at( + folder.path(), + &request.id, + json!({"mode": "print", "variant": "a"}), + ResponseChannel::Sdk, + now, + ) + .unwrap(); + } + + #[test] + fn answers_preserve_the_workflow_value_domain_and_can_fill_the_record() { + let folder = run("0123456789abcdef"); + let request = ensure_at( + folder.path(), + RequestSpec { + schema: Value::Bool(true), + choices: None, + choice_field: None, + timeout_seconds: None, + ..reviewed() + }, + now, + ) + .unwrap(); + let nest = |mut value, levels| { + for _ in 0..levels { + value = Value::Array(vec![value]); + } + value + }; + for invalid in [ + json!({"items":[{"missing": true}]}), + nest(Value::Null, crate::events::VALUE_DEPTH + 1), + ] { + let error = + respond(folder.path(), &request.id, invalid, ResponseChannel::Sdk).unwrap_err(); + assert_eq!(error.code(), "invalid_answer"); + assert!(matches!( + lookup(folder.path(), &request.id).unwrap().state, + RequestState::Pending + )); + } + // Its compact JSON fits the input limit. Indenting each element at this depth + // used to exceed the 3 MiB record limit during publication. + let answer = nest(Value::Array(vec![json!(0); 32_000]), 100); + respond( + folder.path(), + &request.id, + answer.clone(), + ResponseChannel::Sdk, + ) + .unwrap(); + assert!(matches!(lookup(folder.path(), &request.id).unwrap().state, + RequestState::Answered { answer: stored, .. } if stored == answer)); + } + + #[test] + fn inspection_distinguishes_user_files_from_a_copied_waiting_step() { + use std::io::Write; + let root = run("0123456789abcdef"); + let directory = root.path().join(REQUEST_DIRECTORY); + fs::write(&directory, "user file").unwrap(); + assert!(list(root.path()).unwrap().is_empty()); + fs::remove_file(&directory).unwrap(); + fs::create_dir(&directory).unwrap(); + fs::write(directory.join("user.json"), "unrelated").unwrap(); + fs::write( + directory.join(format!("{}.json", "a".repeat(64))), + "unrelated", + ) + .unwrap(); + assert!(list(root.path()).unwrap().is_empty()); + let request = ensure_at(root.path(), reviewed(), now).unwrap(); + fs::remove_file(root.path().join(REQUEST_LOCK)).unwrap(); + let mut events = fs::OpenOptions::new() + .append(true) + .open(root.path().join("events.jsonl")) + .unwrap(); + write!(events, "{}", json!({"kind":"fx-run-events-v1","event":"node_started","id":request.spec.step,"uses":"fx/await@01"})).unwrap(); + assert!( + list(root.path()).unwrap().is_empty(), + "a torn event is invisible" + ); + writeln!(events).unwrap(); + assert_eq!(list(root.path()).unwrap()[0].id, request.id); + writeln!(events, "{}", json!({"kind":"fx-run-events-v1","event":"waiting_request","id":request.spec.step,"request_id":request.id})).unwrap(); + fs::write(directory.join(format!("{}.json", request.id)), "damaged").unwrap(); + assert_eq!(list(root.path()).unwrap_err().code(), "invalid_run"); + } +} diff --git a/crates/grida-fx-runtime/tests/events.rs b/crates/grida-fx-runtime/tests/events.rs index cd0c66e9..f6603330 100644 --- a/crates/grida-fx-runtime/tests/events.rs +++ b/crates/grida-fx-runtime/tests/events.rs @@ -206,6 +206,7 @@ fn every_event() -> Vec { ok: false, incomplete: true, stopped: None, + awaiting: vec!["a".repeat(64)], charged_usd: Usd(40_000), failed: vec!["a#1".into()], outputs: IndexMap::from([ @@ -217,6 +218,7 @@ fn every_event() -> Vec { ok: false, incomplete: true, stopped: Some("phase 2 may cost up to $1.00".into()), + awaiting: vec![], charged_usd: Usd::ZERO, failed: vec![], outputs: IndexMap::new(), @@ -258,6 +260,12 @@ fn every_event() -> Vec { "waiting_on": ["leaf#1"], }]), }, + Event::WaitingRequest { + id: "review#1".into(), + request_id: DIGEST.into(), + status: "pending", + deadline: Some("2026-01-01T00:00:10.000Z".into()), + }, ] } diff --git a/crates/grida-fx-runtime/tests/runner.rs b/crates/grida-fx-runtime/tests/runner.rs index cf70d5c8..2858e92f 100644 --- a/crates/grida-fx-runtime/tests/runner.rs +++ b/crates/grida-fx-runtime/tests/runner.rs @@ -215,6 +215,7 @@ struct Invocation<'a> { inputs: &'a [&'a str], folder: &'a str, yes_up_to: Option<&'a str>, + wait_for_answers: bool, live: bool, require_estimates: bool, /// `--max-usd`. @@ -232,6 +233,7 @@ impl Default for Invocation<'_> { inputs: &[], folder: "runs/one", yes_up_to: None, + wait_for_answers: false, live: false, require_estimates: false, max_usd: None, @@ -380,6 +382,7 @@ fn run_in( label: invocation.folder.to_string(), name: None, yes_up_to: invocation.yes_up_to.map(|text| Usd::parse(text).unwrap()), + wait_for_answers: invocation.wait_for_answers, require_estimates: invocation.require_estimates, takes_file: format!("workflows/{}.takes.yaml", invocation.target), ..RunOptions::default() @@ -2132,3 +2135,512 @@ def flip_image(ctx): "resume must not repair historical missing bytes from a current project source" ); } + +#[test] +fn waiting_steps_open_per_occurrence_and_replay_only_this_runs_decisions() { + use grida_fx_core::val::Val; + use grida_fx_runtime::waiting::{self, ResponseChannel}; + + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Choose twice +steps: + first: + uses: fx/await@1 + with: + message: Pick an item + schema: { type: object, required: [chosen], properties: { chosen: { type: string } } } + choice_field: chosen + choices: { a: one, b: two } + second: + uses: fx/await@1 + with: + message: Pick an item + schema: { type: object, required: [chosen], properties: { chosen: { type: string } } } + choice_field: chosen + choices: { a: one, b: two } + independent: + uses: fx/select@1 + with: { first_of: [ready] } +outputs: + first: ${{ steps.first.outputs.selected }} + second: ${{ steps.second.outputs.selected }} +"#, + )]); + let Some(result) = run_in(&project, Invocation::default(), None) else { + return; + }; + let parked = result.unwrap(); + assert!(parked.incomplete && parked.failed.is_empty(), "{parked:?}"); + let waiting = waiting::list(&parked.folder).unwrap(); + assert_eq!(waiting.len(), 2); + assert_ne!(waiting[0].id, waiting[1].id); + let events = project.events("runs/one"); + let parked_receipt = events.last().unwrap(); + assert_eq!(parked_receipt["event"], "run_finished"); + assert_eq!(parked_receipt["awaiting"].as_array().unwrap().len(), 2); + assert!( + named(&events, "node_finished") + .iter() + .any(|e| e["id"] == "independent#1") + ); + for request in waiting { + let key = if request.spec.step == "first#1" { + "b" + } else { + "a" + }; + let invalid = waiting::respond( + &parked.folder, + &request.id, + json!({"chosen":"absent"}), + ResponseChannel::Cli, + ); + assert!(invalid.is_err()); + waiting::respond( + &parked.folder, + &request.id, + json!({"chosen":key}), + ResponseChannel::Cli, + ) + .unwrap(); + } + let resumed = run_in(&project, Invocation::default(), None) + .unwrap() + .unwrap(); + assert!(resumed.ok, "{resumed:?}"); + assert_eq!(resumed.outputs["first"], Val::Str("two".into())); + assert_eq!(resumed.outputs["second"], Val::Str("one".into())); + let replayed = run_in(&project, Invocation::default(), None) + .unwrap() + .unwrap(); + assert_eq!(replayed.outputs, resumed.outputs); + let fresh = run_in( + &project, + Invocation { + folder: "runs/new", + ..Default::default() + }, + None, + ) + .unwrap() + .unwrap(); + assert!(fresh.incomplete && fresh.failed.is_empty()); + assert!( + waiting::list(&fresh.folder) + .unwrap() + .iter() + .all(|r| matches!(r.state, waiting::RequestState::Pending)) + ); +} + +#[test] +fn waiting_repeat_limits_open_requests_across_detach_and_reattach() { + use grida_fx_runtime::waiting::{self, RequestState, ResponseChannel}; + + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Review in sequence +steps: + review: + for_each: [a, b, c] + key: ${{ item }} + concurrency: 1 + uses: fx/await@01 + with: { schema: {type: string}, timeout_seconds: 15 } + release: + uses: fx/await@1 + with: { schema: {type: boolean} } +"#, + )]); + let Some(result) = run_in(&project, Invocation::default(), None) else { + return; + }; + let folder = result.unwrap().folder; + let initial = waiting::list(&folder).unwrap(); + assert_eq!( + initial.len(), + 2, + "the independent request and the first review can open together" + ); + let release = initial.iter().find(|r| r.spec.step == "release#1").unwrap(); + let first = initial + .iter() + .find(|r| r.spec.step == "review['a']#1") + .unwrap() + .id + .clone(); + waiting::respond(&folder, &release.id, json!(true), ResponseChannel::Sdk).unwrap(); + let answer = move || { + let deadline = Instant::now() + Duration::from_secs(10); + for key in ["a", "b", "c"] { + loop { + let requests = waiting::list(&folder).unwrap(); + let pending: Vec<_> = requests + .iter() + .filter(|r| matches!(r.state, RequestState::Pending)) + .collect(); + assert!(pending.len() <= 1); + if let [request] = pending.as_slice() { + assert_eq!(request.spec.step, format!("review['{key}']#1")); + if key == "a" { + assert_eq!(request.id, first); + } + waiting::respond(&folder, &request.id, json!(key), ResponseChannel::Cli) + .unwrap(); + break; + } + assert!(Instant::now() < deadline, "next occurrence did not open"); + std::thread::sleep(Duration::from_millis(15)); + } + } + }; + let completed = run_in( + &project, + Invocation { + wait_for_answers: true, + ..Invocation::default() + }, + Some(Box::new(answer)), + ) + .unwrap() + .unwrap(); + assert!(completed.ok, "{completed:?}"); +} + +#[test] +fn waiting_steps_reject_disjoint_generated_choices_before_parking() { + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Generated keys +steps: + candidates: + uses: fx/select@1 + with: { first_of: [{draft: first, proof: second}] } + pick: + uses: fx/await@1 + with: + schema: {enum: [final]} + choices: ${{ steps.candidates.outputs.value }} +"#, + )]); + let Some(result) = run_in(&project, Invocation::default(), None) else { + return; + }; + let result = result.unwrap(); + assert!(!result.ok, "{result:?}"); + assert!( + result + .stopped + .as_deref() + .unwrap() + .contains("no choice key satisfies") + ); + assert!( + grida_fx_runtime::waiting::list(&result.folder) + .unwrap() + .is_empty() + ); + assert!(named(&project.events("runs/one"), "waiting_request").is_empty()); +} + +#[test] +fn waiting_steps_route_expiry_through_the_authored_fallback() { + use grida_fx_core::val::Val; + + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Expiry +steps: + choice: + uses: fx/await@1 + with: + message: Pick a color + schema: { type: string } + choices: { a: red, b: blue } + timeout_seconds: 1 + on_timeout: continue + fallback: + if: ${{ steps.choice.facts.outcome == 'expired' }} + uses: fx/select@1 + with: { first_of: [red] } + finish: + uses: fx/select@1 + with: + first_of: ["${{ steps.choice.outputs.selected }}", "${{ steps.fallback.outputs.value }}"] +outputs: + color: ${{ steps.finish.outputs.value }} +"#, + )]); + let Some(result) = run_in( + &project, + Invocation { + wait_for_answers: true, + ..Default::default() + }, + None, + ) else { + return; + }; + let result = result.unwrap(); + assert!(result.ok, "{result:?}"); + assert_eq!(result.outputs["color"], Val::Str("red".into())); + let events = project.events("runs/one"); + let finished = named(&events, "node_finished"); + assert_eq!( + finished.iter().filter(|e| e["id"] == "fallback#1").count(), + 1 + ); + assert!( + finished + .iter() + .any(|e| e["id"] == "choice#1" && e["facts"]["outcome"] == "expired") + ); +} + +#[test] +fn waiting_steps_deliver_the_selected_artifact_in_an_attached_run() { + use grida_fx_core::val::Val; + use grida_fx_runtime::waiting::{self, ResponseChannel}; + + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Select generated material +steps: + variants: + for_each: [green, violet] + key: ${{ item }} + uses: ./nodes/cases.py#shout + with: { text: "${{ item }}" } + pick: + uses: fx/await@1 + with: + message: Which variant? + choices: ${{ steps.variants.*.outputs.text }} + schema: { type: string } + timeout_seconds: 12 + downstream: + uses: ./nodes/cases.py#upper + with: { text: "${{ steps.pick.outputs.selected }}" } +outputs: + text: ${{ steps.downstream.outputs.text }} +"#, + )]); + let folder = project.root.join("runs/one"); + let answer = move || { + let deadline = Instant::now() + Duration::from_secs(8); + loop { + if let Ok(requests) = waiting::list(&folder) + && let Some(request) = requests.first() + { + let choice = &request.spec.choices.as_ref().unwrap()["violet"]; + assert_eq!( + choice["file"]["digest"], + grida_fx_core::value::file_digest(b"VIOLET") + ); + waiting::respond(&folder, &request.id, json!("violet"), ResponseChannel::Cli) + .unwrap(); + break; + } + assert!(Instant::now() < deadline, "a waiting request never opened"); + std::thread::sleep(Duration::from_millis(15)); + } + }; + let Some(result) = run_in( + &project, + Invocation { + wait_for_answers: true, + ..Default::default() + }, + Some(Box::new(answer)), + ) else { + return; + }; + let result = result.unwrap(); + assert!(result.ok, "{result:?}"); + let Val::File(file) = &result.outputs["text"] else { + panic!("selected artifact was not a file"); + }; + assert_eq!(file.digest, grida_fx_core::value::file_digest(b"VIOLET")); +} + +#[test] +fn waiting_steps_restore_nested_selected_files_and_literal_json_on_resume() { + use grida_fx_core::val::Val; + use grida_fx_runtime::waiting::{self, ResponseChannel}; + + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Nested review data +steps: + variant: + uses: ./nodes/cases.py#shout + with: { text: chosen } + pick: + uses: fx/await@1 + with: + message: Choose a candidate + schema: { type: string } + choices: + alpha: + artifact: ${{ steps.variant.outputs.text }} + caption: { object: { file: literal } } +outputs: + result: ${{ steps.pick.outputs.selected }} +"#, + )]); + let Some(result) = run_in(&project, Invocation::default(), None) else { + return; + }; + let folder = result.unwrap().folder; + let requests = waiting::list(&folder).unwrap(); + waiting::respond( + &folder, + &requests[0].id, + json!("alpha"), + ResponseChannel::Cli, + ) + .unwrap(); + for _ in 0..2 { + let result = run_in(&project, Invocation::default(), None) + .unwrap() + .unwrap(); + assert!(result.ok, "{result:?}"); + let Val::Object(members) = &result.outputs["result"] else { + panic!("expected a structured selection"); + }; + let Val::File(artifact) = &members["artifact"] else { + panic!("nested artifact lost its file type"); + }; + assert_eq!( + artifact.digest, + grida_fx_core::value::file_digest(b"CHOSEN") + ); + assert_eq!( + members["caption"].plain(), + Some(json!({"object":{"file":"literal"}})) + ); + } +} + +#[test] +fn waiting_steps_expire_without_scheduling_dependent_work_by_default() { + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Required approval +steps: + review: + uses: fx/await@1 + with: { message: Approve, schema: {type: boolean}, timeout_seconds: 1 } + publish: + if: ${{ steps.review.outputs.answer }} + uses: fx/select@1 + with: { first_of: [published] } +"#, + )]); + let Some(result) = run_in( + &project, + Invocation { + wait_for_answers: true, + ..Default::default() + }, + None, + ) else { + return; + }; + let result = result.unwrap(); + assert!( + !result.ok && result.failed.iter().any(|(id, _)| id == "review#1"), + "{result:?}" + ); + let events = project.events("runs/one"); + assert!( + named(&events, "node_started") + .iter() + .all(|e| e["id"] != "publish#1") + ); + assert!(events.last().unwrap().get("awaiting").is_none()); +} + +#[test] +fn waiting_steps_keep_the_open_request_and_deadline_after_cancellation() { + use grida_fx_runtime::waiting::{self, RequestState, ResponseChannel}; + + let _serial = serial(); + let project = Project::new(&[( + "case", + r#"fx: workflow/v1 +id: case +title: Cancel an attached review +steps: + review: + uses: fx/await@1 + with: { message: Approve, schema: {type: boolean}, timeout_seconds: 30 } +outputs: + approval: ${{ steps.review.outputs.answer }} +"#, + )]); + let folder = project.root.join("runs/one"); + let cancel_folder = folder.clone(); + let cancel = move || { + let limit = Instant::now() + Duration::from_secs(10); + loop { + if waiting::list(&cancel_folder).is_ok_and(|requests| !requests.is_empty()) { + assert!( + std::process::Command::new("kill") + .args(["-INT", &std::process::id().to_string()]) + .status() + .unwrap() + .success() + ); + return; + } + assert!(Instant::now() < limit, "the review never opened"); + std::thread::sleep(Duration::from_millis(20)); + } + }; + let Some(outcome) = run_in( + &project, + Invocation { + wait_for_answers: true, + ..Default::default() + }, + Some(Box::new(cancel)), + ) else { + return; + }; + assert!(outcome.unwrap().cancelled); + let events = project.events("runs/one"); + assert_eq!(events.last().unwrap()["event"], "run_cancelled"); + let open = waiting::list(&folder).unwrap().pop().unwrap(); + assert!(matches!(open.state, RequestState::Pending)); + let answer = waiting::respond(&folder, &open.id, json!(true), ResponseChannel::Cli).unwrap(); + assert_eq!(answer.deadline, open.deadline); + assert_eq!(project.events("runs/one"), events); + let resumed = run_in(&project, Invocation::default(), None) + .unwrap() + .unwrap(); + assert!(resumed.ok); + assert_eq!(resumed.outputs["approval"].plain(), Some(json!(true))); +} diff --git a/crates/grida-fx-viewer/src/export.rs b/crates/grida-fx-viewer/src/export.rs index 240ec1bc..8a895182 100644 --- a/crates/grida-fx-viewer/src/export.rs +++ b/crates/grida-fx-viewer/src/export.rs @@ -476,6 +476,7 @@ fn project_view(view: &Value, options: ExportOptions) -> Value { "routes", "routing", "state", + "review_outcome", "reads", "needs", "judges", diff --git a/crates/grida-fx-viewer/src/export/tests.rs b/crates/grida-fx-viewer/src/export/tests.rs index 7e120038..7ed1e802 100644 --- a/crates/grida-fx-viewer/src/export/tests.rs +++ b/crates/grida-fx-viewer/src/export/tests.rs @@ -365,6 +365,50 @@ fn admission_requires_existing_inactive_lock_and_terminal_latest_invocation() { ); } +#[test] +fn parked_invocation_exports_historical_waiting_evidence_without_a_response_surface() { + let fixture = source("image/png"); + let parent = tempfile::tempdir().unwrap(); + let request = grida_fx_core::value::file_digest(b"waiting request"); + let events = [ + json!({"event":"run_started","charged_usd":0}), + json!({"event":"node_started","id":"draw#1","path":"draw","uses":"fx/await@1","with":{},"reads":[]}), + json!({"event":"waiting_request","id":"draw#1","request_id":request,"request_status":"pending"}), + json!({"event":"run_finished","ok":false,"incomplete":true,"awaiting":[request],"charged_usd":0,"outputs":{}}), + ]; + let mut log = OpenOptions::new() + .append(true) + .open(fixture.root().join("events.jsonl")) + .unwrap(); + for (offset, mut event) in events.into_iter().enumerate() { + event["kind"] = json!("fx-run-events-v1"); + event["plan"] = json!("a".repeat(64)); + event["invocation_id"] = json!("second-invocation"); + event["offset_ms"] = json!(offset); + writeln!(log, "{event}").unwrap(); + } + drop(log); + export(&fixture, &parent, ExportOptions::default()).unwrap(); + let data = manifest(&parent); + assert_eq!(data["view"]["state"], "awaiting"); + assert!( + data["view"]["nodes"] + .as_array() + .unwrap() + .iter() + .any(|n| n["id"] == "draw#1" && n["state"] == "awaiting") + ); + assert!(!serde_json::to_string(&data).unwrap().contains(&request)); + let schema: Value = serde_json::from_str(include_str!( + "../../../../spec/schemas/fx-run-export-v1.schema.json" + )) + .unwrap(); + jsonschema::validator_for(&schema) + .unwrap() + .validate(&data) + .unwrap(); +} + #[test] fn failed_and_cancelled_latest_invocations_export_terminal_evidence() { let schema: Value = serde_json::from_str(include_str!( diff --git a/crates/grida-fx-viewer/src/lib.rs b/crates/grida-fx-viewer/src/lib.rs index ad6912f2..07fd5822 100644 --- a/crates/grida-fx-viewer/src/lib.rs +++ b/crates/grida-fx-viewer/src/lib.rs @@ -1,5 +1,5 @@ -//! Read-only browser views for FX runs and materialized plans, hosted independently or by a -//! project service with a private local catalog. +//! Browser views for FX runs and materialized plans, hosted independently or by a project +//! service with a private local catalog. Local run views can answer a workflow's open request. //! //! The caller owns argument parsing, browser opening and process interruption. This crate binds //! loopback only and starts no workflow, provider adapter or node host. Service discovery is @@ -13,6 +13,7 @@ mod read; mod scopes; pub mod service; mod values; +mod waiting; pub use read::{Artifact, Node, RunDocument}; @@ -22,7 +23,7 @@ use axum::extract::{Path as RoutePath, Query, Request, State}; use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; -use axum::routing::get; +use axum::routing::{get, post}; use axum::{Json, Router}; use grida_fx_core::docs::project::{Project, ViewerConfig}; use grida_fx_core::docs::{Schema, validate}; @@ -167,6 +168,8 @@ fn router(state: AppState) -> Router { .route("/api/snapshot", get(observation_snapshot)) .route("/api/layout", get(layout_report)) .route("/api/events", get(observation_events)) + .route("/api/requests", get(waiting::list)) + .route("/api/requests/{id}/respond", post(waiting::respond)) .route("/api/files", get(file_inventory)) .route("/api/artifacts/{digest}", get(artifact)) .route("/api/{*path}", get(api_missing)) diff --git a/crates/grida-fx-viewer/src/read.rs b/crates/grida-fx-viewer/src/read.rs index c66646d6..946ce839 100644 --- a/crates/grida-fx-viewer/src/read.rs +++ b/crates/grida-fx-viewer/src/read.rs @@ -76,6 +76,9 @@ pub struct Node { #[serde(skip_serializing_if = "Option::is_none")] pub routing: Option, pub state: String, + /// The terminal fact recorded by a version-one waiting step for this occurrence. + #[serde(skip_serializing_if = "Option::is_none")] + pub review_outcome: Option<&'static str>, pub reads: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub ports: Option, @@ -462,6 +465,7 @@ fn node(value: &Value, steps: &Map, types: &Map) - judges: value.get("judges").cloned(), parameters: object(value.get("with")), outputs: json!({}), + review_outcome: None, cache: None, error: text(value, "reason").map(str::to_string), diagnostic: None, @@ -477,6 +481,23 @@ fn node(value: &Value, steps: &Map, types: &Map) - }) } +fn is_waiting_step(uses: Option<&str>) -> bool { + // The registry accepts leading zeros in a built-in major version. + uses.and_then(|name| name.strip_prefix("fx/await@")) + .is_some_and(|major| major.trim_start_matches('0') == "1") +} + +fn review_outcome(uses: Option<&str>, event_name: &str, event: &Value) -> Option<&'static str> { + if !is_waiting_step(uses) { + return None; + } + match (event_name, text(event.get("facts")?, "outcome")?) { + ("node_finished", "answered") => Some("answered"), + ("node_finished" | "node_failed", "expired") => Some("expired"), + _ => None, + } +} + impl Node { /// Leaves every open wait behind untimed, keeping how long the admitted ones took. fn end_waits(&mut self) { @@ -565,7 +586,8 @@ pub(crate) fn read_observed( root: &Path, observed: &grida_fx_runtime::observation::RunSnapshot, ) -> io::Result { - verify_inventory(root, project_records(root, observed)?) + let snapshot = project_records(root, observed)?; + verify_inventory(root, with_reviewed_artifacts(root, snapshot)) } /// The projection of exactly the observation prefix, without opening artifact bytes. The layout @@ -629,6 +651,14 @@ fn verify_inventory(root: &Path, mut snapshot: Snapshot) -> io::Result /// Loads records and artifact references without opening artifact bytes. An artifact request /// uses this inventory, then validates only its selected digest through `open_artifact`. pub(crate) fn read_inventory(root: &Path) -> io::Result { + Ok(with_reviewed_artifacts( + root, + read_recorded_inventory(root)?, + )) +} + +/// Catalog state and layout use the recorded projection without reading review payloads. +pub(crate) fn read_recorded_inventory(root: &Path) -> io::Result { let path = confined_file(root, "plan.json")?; let plan = parse_json(&std::fs::read_to_string(path)?) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "plan.json is not valid JSON"))?; @@ -668,6 +698,48 @@ pub(crate) fn read_inventory(root: &Path) -> io::Result { project_inventory(root, &plan, &events, warnings) } +fn with_reviewed_artifacts(root: &Path, mut snapshot: Snapshot) -> Snapshot { + // The runner emits node_started before it publishes the durable request. An exit + // before its subsequent waiting_request event still leaves a reviewable request. + let review_steps = snapshot + .document + .nodes + .iter() + .filter(|node| { + is_waiting_step(node.uses.as_deref()) && snapshot.recorded.started.contains(&node.id) + }) + .map(|node| node.id.as_str()) + .collect::>(); + if !review_steps.is_empty() { + match grida_fx_runtime::waiting::list(root) { + Ok(requests) => { + for request in requests { + if !review_steps.contains(request.spec.step.as_str()) { + continue; + } + collect_object( + &json!({"show": request.spec.show}), + Some(Placement::Value(root)), + &mut snapshot.candidates, + ); + if let Some(choices) = request.spec.choices { + collect_object( + &json!(choices), + Some(Placement::Value(root)), + &mut snapshot.candidates, + ); + } + } + } + Err(_) => snapshot + .document + .warnings + .push("Reviewed values cannot be read from the run's waiting records.".into()), + } + } + snapshot +} + fn project_inventory( root: &Path, plan: &Value, @@ -804,7 +876,14 @@ fn project_inventory( } } Some("run_finished") => { - state = if event.get("ok") == Some(&Value::Bool(true)) { + state = if event.get("incomplete") == Some(&Value::Bool(true)) + && event + .get("awaiting") + .and_then(Value::as_array) + .is_some_and(|ids| !ids.is_empty()) + { + "awaiting" + } else if event.get("ok") == Some(&Value::Bool(true)) { "succeeded" } else { "failed" @@ -819,6 +898,20 @@ fn project_inventory( charged = event.get("charged_usd").and_then(Value::as_f64); outputs = json!({}); } + Some("waiting_request") => { + let state = match text(event, "request_status") { + Some("pending") => "awaiting", + Some("answered" | "expired") => "running", + _ => continue, + }; + if let Some(current) = nodes + .iter_mut() + .find(|node| Some(node.id.as_str()) == text(event, "id")) + { + current.review_outcome = None; + current.state = state.into(); + } + } Some(name @ ("node_started" | "node_finished" | "node_failed" | "node_skipped")) => { let Some(id) = text(event, "id") else { continue; @@ -849,6 +942,7 @@ fn project_inventory( if let Some(uses) = text(event, "uses") { current.uses = Some(uses.to_string()); } + current.review_outcome = review_outcome(current.uses.as_deref(), name, event); if let Some(routes) = super::values::routes(event.get("routes")) { current.routes = Some(routes); } @@ -941,6 +1035,7 @@ fn project_inventory( if let Some(current) = text(event, "id").and_then(|id| nodes.iter_mut().find(|entry| entry.id == id)) { + current.review_outcome = None; current.end_waits(); } } diff --git a/crates/grida-fx-viewer/src/service.rs b/crates/grida-fx-viewer/src/service.rs index 22246924..aae089fd 100644 --- a/crates/grida-fx-viewer/src/service.rs +++ b/crates/grida-fx-viewer/src/service.rs @@ -6,6 +6,7 @@ use axum::http::Uri; use axum::routing::post; use chrono::{DateTime, SecondsFormat, Utc}; use grida_fx_core::value::digest; +use grida_fx_runtime::waiting::{self as requests, RequestState}; use serde::{Deserialize, Serialize}; use serde_json::json; use std::fs::{self, File}; @@ -173,6 +174,25 @@ impl Catalog { self.register_matching_run(run, None) } + /// Return the scoped route only if this exact run already has a catalog entry. + pub fn registered_run_route(&self, run: &Path) -> io::Result> { + let root = run.canonicalize()?; + let identity = run_identity(&root)?; + let id = local_run_id(&root, &identity); + match self.record(&id) { + Ok(Record::Run { + root: recorded, + identity: original, + .. + }) if recorded == root && original == identity => { + Ok(Some(format!("/p/{}/runs/{id}/", self.project_id))) + } + Ok(_) => Err(invalid("The registered run no longer matches.")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } + } + /// Registers a run only if it still matches the recorded evidence read by inspection. pub fn register_inspected_run( &self, @@ -196,7 +216,7 @@ impl Catalog { if expected.is_some_and(|expected| expected != identity) { return Err(invalid("The inspected run folder has been replaced.")); } - let id = digest(&json!(["fx-local-run-v1", root, identity])); + let id = local_run_id(&root, &identity); let record = Record::Run { id, root, @@ -328,8 +348,8 @@ impl Catalog { let state = details .as_ref() .ok_or_else(|| invalid("The registered run folder is unavailable.")) - .and_then(|_| read::read_inventory(root)) - .map(|snapshot| snapshot.document.state) + .and_then(|_| read::read_recorded_inventory(root)) + .map(|snapshot| catalog_run_state(root, snapshot.document.state)) .unwrap_or_else(|_| "unavailable".into()); let metadata = metadata.clone().or_else(|| details.map(|run| run.metadata)); ("run", title.clone(), state, metadata) @@ -435,6 +455,25 @@ impl Catalog { } } +fn catalog_run_state(root: &Path, recorded: String) -> String { + if matches!(recorded.as_str(), "unfinished" | "awaiting") + && let Ok(requests) = requests::list(root) + && !requests.is_empty() + { + // A detached response or elapsed deadline can change what needs attention + // before a runner records the resolution in the event log. + return if requests + .iter() + .any(|request| matches!(request.state, RequestState::Pending)) + { + "awaiting".into() + } else { + "unfinished".into() + }; + } + recorded +} + /// A run the project's catalog registered, read without creating or changing local state. #[derive(Clone, Debug, PartialEq, Eq)] pub struct RegisteredRun { @@ -568,7 +607,7 @@ fn read_entry(entries: &Path, id: &str) -> io::Result { let record: Record = serde_json::from_reader(file).map_err(|_| invalid("The catalog entry cannot be read."))?; let expected = match &record { - Record::Run { root, identity, .. } => digest(&json!(["fx-local-run-v1", root, identity])), + Record::Run { root, identity, .. } => local_run_id(root, identity), Record::Plan { graph, .. } => digest(&json!(["fx-local-plan-v1", graph])), }; if record.id() != id || expected != id { @@ -648,6 +687,10 @@ fn recorded_run_identity(graph: &Value, mut first: Value) -> String { digest(&json!([graph, first])) } +fn local_run_id(root: &Path, identity: &str) -> String { + digest(&json!(["fx-local-run-v1", root, identity])) +} + fn checked_run(root: &Path, identity: &str) -> io::Result<()> { if run_details(root)?.identity == identity { Ok(()) diff --git a/crates/grida-fx-viewer/src/tests.rs b/crates/grida-fx-viewer/src/tests.rs index 5d881455..6ff6e0e1 100644 --- a/crates/grida-fx-viewer/src/tests.rs +++ b/crates/grida-fx-viewer/src/tests.rs @@ -89,7 +89,175 @@ impl Fixture { } } +#[tokio::test] +async fn answers_are_exact_run_same_origin_and_share_the_runtime_winner() { + use grida_fx_runtime::waiting::{self, RequestSpec, ResponseChannel}; + + let fixture = Fixture::new("image/png"); + let root = fixture.root(); + let path = root.join("events.jsonl"); + let history = std::fs::read_to_string(&path).unwrap(); + std::fs::write(path, history.replace("offline-fixture", "0123456789abcdef")).unwrap(); + let opened = waiting::ensure_request( + &root, + RequestSpec { + step: "choose#1".into(), + message: None, + schema: json!({"type":"boolean"}), + show: Value::Null, + choices: None, + choice_field: None, + timeout_seconds: None, + on_timeout: Default::default(), + }, + ) + .unwrap(); + let endpoint = format!("/api/requests/{}/respond", opened.id); + let app = fixture.app(); + for (origin, marker, mime, expected) in [ + (None, true, "application/json", StatusCode::FORBIDDEN), + ( + Some("http://unrelated.invalid"), + true, + "application/json", + StatusCode::FORBIDDEN, + ), + ( + Some("http://127.0.0.1:43123"), + false, + "application/json", + StatusCode::FORBIDDEN, + ), + ( + Some("http://127.0.0.1:43123"), + true, + "text/plain", + StatusCode::UNSUPPORTED_MEDIA_TYPE, + ), + ] { + let mut req = Fixture::request(&endpoint) + .method(Method::POST) + .header(header::CONTENT_TYPE, mime); + if let Some(origin) = origin { + req = req.header(header::ORIGIN, origin); + } + if marker { + req = req.header("x-fx-action", "respond"); + } + let response = app + .clone() + .oneshot(req.body(Body::from(r#"{"answer":true}"#)).unwrap()) + .await + .unwrap(); + assert_eq!(response.status(), expected); + } + let submit = |json: &'static str| { + Fixture::request(&endpoint) + .method(Method::POST) + .header(header::ORIGIN, "http://127.0.0.1:43123") + .header("sec-fetch-site", "same-origin") + .header("x-fx-action", "respond") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(json)) + .unwrap() + }; + assert_eq!( + app.clone() + .oneshot(submit(r#"{"answer":9007199254740993}"#)) + .await + .unwrap() + .status(), + StatusCode::BAD_REQUEST + ); + let response = app + .clone() + .oneshot(submit(r#"{"answer":"invalid"}"#)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); + let winner = waiting::respond(&root, &opened.id, json!(false), ResponseChannel::Cli).unwrap(); + let response = app + .clone() + .oneshot(submit(r#"{"answer":true}"#)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::CONFLICT); + let body: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 100_000).await.unwrap()).unwrap(); + assert_eq!(body["request"], json!(winner)); + let response = app.oneshot(submit(r#"{"answer":false}"#)).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 100_000).await.unwrap()).unwrap(); + assert_eq!(body, json!(winner)); +} + +#[test] +fn an_open_request_can_preview_its_files_before_the_runner_logs_the_wait() { + use grida_fx_runtime::waiting::{self, RequestSpec}; + use std::fs; + + let fixture = Fixture::new("image/png"); + let root = fixture.root(); + fs::write(root.join("events.jsonl"), "").unwrap(); + let mut log = FileForEvents::new(&root); + let invocation = "0123456789abcdef"; + log.append(json!({"event":"run_started","invocation_id":invocation})); + let before_step = observation::snapshot(&root).unwrap(); + log.append(json!({"event":"node_started","invocation_id":invocation,"id":"draw#1","path":"draw","uses":"fx/await@1"})); + + let bytes = b"synthetic review image"; + let digest = file_digest(bytes); + fs::create_dir(root.join("values")).unwrap(); + fs::write(root.join("values").join(&digest), bytes).unwrap(); + let image = + json!({"file":{"digest":digest,"kind":"image/png","name":"review.png","size":bytes.len()}}); + waiting::ensure_request( + &root, + RequestSpec { + step: "draw#1".into(), + message: None, + schema: json!({"type":"string"}), + show: Value::Null, + choices: Some([("swatch".into(), image)].into()), + choice_field: None, + timeout_seconds: None, + on_timeout: Default::default(), + }, + ) + .unwrap(); + + let current = observation::snapshot(&root).unwrap(); + assert!( + read::read_observed(&root, ¤t) + .unwrap() + .document + .artifacts + .iter() + .any(|a| a.digest == digest && a.available) + ); + assert!( + read::read_inventory(&root) + .unwrap() + .open_artifact(&root, &digest) + .is_ok() + ); + assert!( + read::read_observed(&root, &before_step) + .unwrap() + .open_artifact(&root, &digest) + .is_err() + ); + assert!( + read::project_export_records(&root, ¤t) + .unwrap() + .open_artifact(&root, &digest) + .is_err() + ); +} + struct FileForEvents(std::fs::File); + impl FileForEvents { fn new(root: &Path) -> Self { Self( @@ -126,6 +294,61 @@ fn imported_scope(nodes: &[&str]) -> Value { }) } +#[test] +fn review_outcome_uses_the_terminal_wait_fact_and_survives_export_without_answers() { + let fixture = Fixture::new("image/png"); + let root = fixture.root(); + let mut log = FileForEvents::new(&root); + let outcome = |id: &str| { + read::read_inventory(&root) + .unwrap() + .document + .nodes + .into_iter() + .find(|node| node.id == id) + .unwrap() + .review_outcome + }; + log.append(json!({"event":"run_started"})); + log.append(json!({"event":"node_started","id":"draw#1","path":"draw","uses":"fx/await@01"})); + log.append(json!({"event":"waiting_request","id":"draw#1","request_status":"answered"})); + assert_eq!(outcome("draw#1"), None); + log.append(json!({"event":"node_finished","id":"draw#1","facts":{"outcome":"answered"},"outputs":{"answer":{"value":false}}})); + assert_eq!(outcome("draw#1"), Some("answered")); + log.append(json!({"event":"node_finished","id":"later#1","facts":{"outcome":"answered"}})); + assert_eq!(outcome("later#1"), None); // A different builtin or project node can publish an identically named fact. + log.append(json!({"event":"run_finished","ok":true,"outputs":{}})); + std::fs::File::create(root.join("run.lock")).unwrap(); + let package = tempfile::tempdir().unwrap(); + let target = package.path().join("export"); + export::run_export(&root, &target, "export", export::ExportOptions::default()).unwrap(); + let manifest: Value = + serde_json::from_slice(&std::fs::read(target.join("manifest.json")).unwrap()).unwrap(); + let draw = manifest["view"]["nodes"] + .as_array() + .unwrap() + .iter() + .find(|node| node["id"] == "draw#1") + .unwrap(); + assert_eq!(draw["review_outcome"], "answered"); + assert_eq!(draw["outputs"]["answer"], json!({"withheld":true})); + + log.append(json!({"event":"run_started"})); + assert_eq!(outcome("draw#1"), Some("answered")); // A resume can preserve a completed checkpoint. + log.append(json!({"event":"node_started","id":"draw#1","path":"draw","uses":"fx/await@1"})); + assert_eq!(outcome("draw#1"), None); + log.append(json!({"event":"node_finished","id":"draw#1","facts":{"outcome":"expired"}})); + assert_eq!(outcome("draw#1"), Some("expired")); + log.append(json!({"event":"node_retry","id":"draw#1"})); + assert_eq!(outcome("draw#1"), None); + log.append( + json!({"event":"node_failed","id":"draw#1","error":"the response deadline expired"}), + ); + assert_eq!(outcome("draw#1"), None); + log.append(json!({"event":"node_failed","id":"draw#1","facts":{"outcome":"expired"}})); + assert_eq!(outcome("draw#1"), Some("expired")); +} + #[test] fn video_preview_metadata_survives_plan_and_dynamic_event_projection() { let fixture = Fixture::new("image/png"); diff --git a/crates/grida-fx-viewer/src/waiting.rs b/crates/grida-fx-viewer/src/waiting.rs new file mode 100644 index 00000000..8cfb082c --- /dev/null +++ b/crates/grida-fx-viewer/src/waiting.rs @@ -0,0 +1,126 @@ +//! Browser adapter for the runtime's exact-run response operation. +use super::{AppState, Source, failure, observed_json}; +use axum::body::Bytes; +use axum::extract::{FromRequest, Path, Request, State}; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use grida_fx_core::value::parse_json; +use grida_fx_runtime::waiting::{self, ResponseChannel, WaitingError}; +use serde_json::json; +use std::sync::Arc; + +pub(super) async fn list(State(host): State>) -> Response { + let Source::Run(root) = &host.source else { + return failure(StatusCode::NOT_FOUND, "A plan has no run requests."); + }; + let root = root.clone(); + match tokio::task::spawn_blocking(move || waiting::list(&root)).await { + Ok(Ok(requests)) => observed_json(json!({ "requests": requests })), + Ok(Err(error)) => waiting_error(error), + Err(_) => failure( + StatusCode::INTERNAL_SERVER_ERROR, + "Could not read run requests.", + ), + } +} + +// A non-simple header prevents submission by an HTML form. Require the browser's +// exact Origin as well. The enclosing router binds loopback, validates Host and +// Fetch Metadata and does not grant cross-origin preflights. No service or +// run-control credential is serialized to JavaScript. +fn local_submission(headers: &HeaderMap, authority: &str) -> bool { + let mut origins = headers.get_all(header::ORIGIN).iter(); + let Some(origin) = origins.next().and_then(|value| value.to_str().ok()) else { + return false; + }; + origins.next().is_none() + && origin.strip_prefix("http://") == Some(authority) + && headers + .get("x-fx-action") + .is_some_and(|value| value == "respond") + && headers + .get("sec-fetch-site") + .is_none_or(|value| value == "same-origin") +} + +pub(super) async fn respond( + State(host): State>, + Path(id): Path, + request: Request, +) -> Response { + let Source::Run(root) = &host.source else { + return failure(StatusCode::NOT_FOUND, "A plan has no run requests."); + }; + if !local_submission(request.headers(), &host.authority) { + return failure( + StatusCode::FORBIDDEN, + "Submit the answer from this local viewer.", + ); + } + let json = request + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value + .split(';') + .next() + .is_some_and(|mime| mime.trim().eq_ignore_ascii_case("application/json")) + }); + if !json { + return failure( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "Submit the answer as application/json.", + ); + } + let bytes = match Bytes::from_request(request, &()).await { + Ok(body) => body, + Err(rejection) => { + return failure(rejection.status(), "Could not read the submitted answer."); + } + }; + let answer = std::str::from_utf8(&bytes) + .ok() + .and_then(|text| parse_json(text).ok()) + .and_then(|mut body| { + let object = body.as_object_mut()?; + (object.len() == 1) + .then(|| object.remove("answer")) + .flatten() + }); + let Some(answer) = answer else { + return failure( + StatusCode::BAD_REQUEST, + "Expected a JSON object containing only an answer.", + ); + }; + let root = root.clone(); + match tokio::task::spawn_blocking(move || { + waiting::respond(&root, &id, answer, ResponseChannel::Viewer) + }) + .await + { + Ok(Ok(request)) => observed_json(json!(request)), + Ok(Err(error)) => waiting_error(error), + Err(_) => failure( + StatusCode::INTERNAL_SERVER_ERROR, + "Could not record the answer.", + ), + } +} + +fn waiting_error(error: WaitingError) -> Response { + let status = match error.code() { + "not_found" | "invalid_run" => StatusCode::NOT_FOUND, + "answer_conflict" | "expired" => StatusCode::CONFLICT, + "invalid_answer" | "invalid_request" => StatusCode::UNPROCESSABLE_ENTITY, + _ => StatusCode::INTERNAL_SERVER_ERROR, + }; + ( + status, + observed_json(json!({ + "code": error.code(), "error": error.to_string(), "request": error.request(), + })), + ) + .into_response() +} diff --git a/crates/grida-fx/src/args.rs b/crates/grida-fx/src/args.rs index 8eb847ca..a1015de0 100644 --- a/crates/grida-fx/src/args.rs +++ b/crates/grida-fx/src/args.rs @@ -53,9 +53,10 @@ const RUN_VALUE_OPTIONS: [&str; 6] = [ "--resume", ]; /// Flags of `run` alone. -const RUN_FLAGS: [&str; 6] = [ +const RUN_FLAGS: [&str; 7] = [ "--live", "--recover", + "--wait-for-answers", "--no-view", "--open", "--standalone", diff --git a/crates/grida-fx/src/cli.rs b/crates/grida-fx/src/cli.rs index 84eed792..586b9d9f 100644 --- a/crates/grida-fx/src/cli.rs +++ b/crates/grida-fx/src/cli.rs @@ -110,6 +110,8 @@ pub enum Verb { Files(FilesArgs), /// a run's summary, from its own folder Inspect(InspectArgs), + /// answer one recorded waiting step in an exact run + Respond(RespondArgs), /// request cancellation of one exact run invocation, without starting a service Cancel(CancelArgs), /// list the project's runs, or remove runs it no longer needs @@ -331,6 +333,9 @@ pub struct RunArgs { /// stop before a later phase that may take the run past this amount #[arg(long = "yes-up-to", value_name = "USD", allow_negative_numbers = true)] pub yes_up_to: Option, + /// stay attached while a workflow waits for external answers or deadlines + #[arg(long)] + pub wait_for_answers: bool, /// copy an output after the run: OUTPUT=PATH, {key} for each element; repeatable; names are /// checked before the run #[arg(long = "deliver", value_name = "OUTPUT=PATH")] @@ -478,9 +483,10 @@ pub struct RunsListArgs { } /// The states `runs remove --state` matches (spec/store.md §9). -pub const RUN_STATES: [&str; 9] = [ +pub const RUN_STATES: [&str; 10] = [ "planned", "unfinished", + "awaiting", "succeeded", "failed", "incomplete", @@ -648,6 +654,12 @@ pub struct InspectArgs { /// observe verified local control for an exact run folder or WORKFLOW_ID/NAME #[arg(long, conflicts_with_all = ["open", "standalone", "verify"])] pub control: bool, + /// list external answer requests for an exact run folder or WORKFLOW_ID/NAME + #[arg(long, conflicts_with_all = ["control", "open", "standalone", "verify"])] + pub requests: bool, + /// include the viewer URL for an already registered run when the service is running + #[arg(long, requires = "requests", conflicts_with = "register")] + pub viewer_url: bool, /// register the recorded run in the project catalog and print its viewer route #[arg(long, conflicts_with_all = ["open", "standalone", "control"])] pub register: bool, @@ -659,6 +671,20 @@ pub struct InspectArgs { pub standalone: bool, } +#[derive(Debug, Args, Clone)] +pub struct RespondArgs { + /// exact run folder or WORKFLOW_ID/NAME + pub run: String, + /// the request ID reported by inspect --requests + pub request: String, + /// the answer as JSON, or - to read JSON from standard input + #[arg(long, value_name = "ANSWER", allow_hyphen_values = true)] + pub json: String, + /// Ingress channel for SDK command wrappers. + #[arg(long, hide = true, value_parser = ["cli", "sdk"], default_value = "cli")] + pub source: String, +} + #[derive(Debug, Args, Clone)] pub struct CancelArgs { /// an explicit run folder, or exact WORKFLOW_ID/NAME; no implicit latest run @@ -854,6 +880,7 @@ fn dispatch(verb: Verb, rest: Vec) -> Result { Verb::Export(args) => verbs::export::run(&args), Verb::Files(args) => verbs::files::run(&args), Verb::Inspect(args) => verbs::inspect::run(&args), + Verb::Respond(args) => verbs::waiting::respond(&args), Verb::Cancel(args) => verbs::control::cancel(&args), Verb::Runs(args) => verbs::runs::run(&args), Verb::Cache(args) => verbs::cache::run(&args), diff --git a/crates/grida-fx/src/verbs/cache.rs b/crates/grida-fx/src/verbs/cache.rs index bcd24e56..4e38b359 100644 --- a/crates/grida-fx/src/verbs/cache.rs +++ b/crates/grida-fx/src/verbs/cache.rs @@ -14,9 +14,9 @@ //! naming the call (`legacy_interrupted_run`); and, with `--yes`, a store or run in use //! (`cache_in_use`: its lock, a run's `run.lock` or a work claim is held) or a file system that //! cannot lock (`lock_unsupported`). -//! - **What stays**: every 64-hex token in every run's `plan.json` and `events.jsonl` names what -//! stays (file digests, step identities, call keys), and so do the tokens of every record that -//! stays, and of every job record; a store file linked from anywhere else (a run folder the +//! - **What stays**: every 64-hex token in a run's `plan.json`, `events.jsonl` and frozen reviewed +//! values names what stays (file digests, step identities, call keys), and so do the tokens of +//! every record that stays, and of every job record; a store file linked from anywhere else (a run folder the //! project does not know) stays with every record that names it. Everything else under //! `results/`, `calls/` and `files/` goes, records first, with what killed invocations left //! (`Store::sweep`). @@ -378,17 +378,19 @@ fn held(path: &Path) -> bool { /// cannot be read refuses the prune. fn roots(set: &RunSet, stand_in: bool, cwd: &Path) -> Result, Refusal> { let mut roots = BTreeSet::new(); - let mut read = |folder: &Path, name: &str| match fs::read(folder.join(name)) { - Ok(bytes) => { - roots.extend(tokens(&bytes)); - Ok(()) - } - Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), - Err(error) => Err(refusal( - "unreadable_run", - format!("{}: {name}: {error}", shown_path(folder, cwd)), - )), - }; + let read = + |roots: &mut BTreeSet, folder: &Path, name: &str| match fs::read(folder.join(name)) + { + Ok(bytes) => { + roots.extend(tokens(&bytes)); + Ok(()) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(refusal( + "unreadable_run", + format!("{}: {name}: {error}", shown_path(folder, cwd)), + )), + }; for found in &set.found { let Some(recorded) = found.recorded() else { continue; @@ -396,12 +398,25 @@ fn roots(set: &RunSet, stand_in: bool, cwd: &Path) -> Result, R if recorded.stand_in != stand_in { continue; } - read(&found.folder, "plan.json")?; - read(&found.folder, "events.jsonl")?; + read(&mut roots, &found.folder, "plan.json")?; + read(&mut roots, &found.folder, "events.jsonl")?; + let unreadable = |error: &dyn std::fmt::Display| { + refusal( + "unreadable_run", + format!("{}: {error}", shown_path(&found.folder, cwd)), + ) + }; + let requests = + grida_fx_runtime::waiting::list(&found.folder).map_err(|error| unreadable(&error))?; + for request in requests { + let views = serde_json::json!([request.spec.show, request.spec.choices]); + let bytes = serde_json::to_vec(&views).map_err(|error| unreadable(&error))?; + roots.extend(tokens(&bytes)); + } } for problem in &set.problems { if problem.kind == ProblemKind::NoPlan { - read(&problem.path, "events.jsonl")?; + read(&mut roots, &problem.path, "events.jsonl")?; } } Ok(roots) diff --git a/crates/grida-fx/src/verbs/control.rs b/crates/grida-fx/src/verbs/control.rs index fa628965..41d67e65 100644 --- a/crates/grida-fx/src/verbs/control.rs +++ b/crates/grida-fx/src/verbs/control.rs @@ -33,7 +33,7 @@ pub fn parse_timeout(text: &str) -> Result { /// Exact selectors reuse the recorded-source catalog, including its bounded traversal. A /// relative spelling that names both a folder and a distinct named run is refused. -fn exact_folder( +pub(super) fn exact_folder( given: &str, cwd: &Path, wait: Option<(Instant, Duration)>, @@ -94,7 +94,7 @@ fn exact_folder( return Ok(found); } if matches!(parts.as_slice(), [Component::Normal(_)]) { - return Err(("invalid_target", "control requires an explicit run folder or exact WORKFLOW_ID/NAME; bare workflow IDs do not select a run".into())); + return Err(("invalid_target", "select an explicit run folder or exact WORKFLOW_ID/NAME; bare workflow IDs do not select a run".into())); } Ok(path) } diff --git a/crates/grida-fx/src/verbs/inspect.rs b/crates/grida-fx/src/verbs/inspect.rs index 6b16f642..3ab56246 100644 --- a/crates/grida-fx/src/verbs/inspect.rs +++ b/crates/grida-fx/src/verbs/inspect.rs @@ -74,6 +74,9 @@ use std::path::{Component, Path, PathBuf}; /// Runs `grida-fx inspect`. pub fn run(args: &InspectArgs) -> Result { + if args.requests { + return super::waiting::inspect(args); + } if args.control { return super::control::inspect(args); } @@ -81,7 +84,32 @@ pub fn run(args: &InspectArgs) -> Result { let (folder, label) = find_folder(&args.run, &cwd)?; let plan = read_plan(&folder, &label)?; let events = read_log(&folder, &label, false)?; - let view = RunView::new(&plan, &events); + let mut view = RunView::new(&plan, &events); + let requests = if args.verify || (args.json && !args.register) { + super::waiting::requests(&folder)? + } else { + Vec::new() + }; + // The finish event uses plain JSON for object outputs. The frozen choice retains + // the file types needed to locate and verify any placements inside those objects. + let selected: BTreeMap<_, _> = requests + .iter() + .filter_map(|request| { + let grida_fx_runtime::waiting::RequestState::Answered { answer, .. } = &request.state + else { + return None; + }; + Some((request.spec.step.as_str(), request.selected(answer)?)) + }) + .collect(); + for step in &mut view.steps { + if step.state == "succeeded" + && let Some(value) = selected.get(step.id.as_str()) + { + let folder = step_folder(&step.path, &takes_of_id(&step.id)); + step.files = placed_port_files(&folder, "selected", value); + } + } let verification = args.verify.then(|| verify(&view, &folder)); let receipt = args .register @@ -97,7 +125,11 @@ pub fn run(args: &InspectArgs) -> Result { } receipt } else { - json_document(&view, &label, verification.as_ref()) + let mut document = json_document(&view, &label, verification.as_ref()); + if !requests.is_empty() { + document["run"]["requests"] = json!(requests); + } + document }; print_json(&document); } else { @@ -265,7 +297,16 @@ impl RunView { } Some("run_finished") => { let ok = event.get("ok").and_then(Value::as_bool) == Some(true); - state = if ok { "succeeded" } else { "failed" }; + state = if event["awaiting"] + .as_array() + .is_some_and(|ids| !ids.is_empty()) + { + "awaiting" + } else if ok { + "succeeded" + } else { + "failed" + }; charged = event.get("charged_usd").cloned(); } Some("run_cancelled") => { @@ -298,6 +339,11 @@ impl RunView { entry.waits.clear(); } } + Some("waiting_request") => { + if let Some(entry) = text(event, "id").and_then(|id| entries.get_mut(id)) { + entry.last = Some(event.clone()); + } + } Some("call_attempt_failed") => call_attempt_failures.push(event.clone()), Some("call_recovery") => call_recoveries.push(event.clone()), Some(name @ ("call_waiting" | "call_admitted")) => { @@ -383,7 +429,12 @@ fn step_view(id: String, entry: Entry, ended: bool) -> StepView { view.state = "skipped"; view.error = error_of(event); } - Some((Some("node_started"), _)) if ended => { + Some((Some("waiting_request"), event)) + if !ended && text(event, "request_status") == Some("pending") => + { + view.state = "awaiting"; + } + Some((Some("node_started" | "waiting_request"), _)) if ended => { view.state = "failed"; view.error = Some("the run ended before this step finished".into()); } @@ -433,6 +484,10 @@ fn encoded_files(value: &Value, item_key: Option<&str>, out: &mut Vec, out: &mut Vec) -> Vec { let step = step_folder(step_path, &takes_of_id(id)); - let mut placed = Vec::new(); - for (port, value) in outputs { - let mut files = Vec::new(); - encoded_files(value, None, &mut files); - let one = files.len() == 1; - for (index, file) in files.into_iter().enumerate() { - let path = if one { - step_file_path(&step, port, None, &file.kind) - } else { - let label = file - .key - .map_or_else(|| index.to_string(), |key| keyed_path(&key)); - step_file_path(&step, port, Some(&label), &file.kind) - }; - placed.push(Placed { - path, + outputs + .iter() + .flat_map(|(port, value)| placed_port_files(&step, port, value)) + .collect() +} + +fn placed_port_files(step: &str, port: &str, value: &Value) -> Vec { + let mut files = Vec::new(); + encoded_files(value, None, &mut files); + let one = files.len() == 1; + files + .into_iter() + .enumerate() + .map(|(index, file)| { + let label = (!one).then(|| { + file.key + .map_or_else(|| index.to_string(), |key| keyed_path(&key)) + }); + Placed { + path: step_file_path(step, port, label.as_deref(), &file.kind), digest: file.digest, size: file.size, - }); - } - } - placed + } + }) + .collect() } /// What `--verify` found. diff --git a/crates/grida-fx/src/verbs/mod.rs b/crates/grida-fx/src/verbs/mod.rs index aa1a2c28..607d705f 100644 --- a/crates/grida-fx/src/verbs/mod.rs +++ b/crates/grida-fx/src/verbs/mod.rs @@ -27,6 +27,7 @@ pub mod schema; pub mod service; pub mod takes; pub mod view; +pub mod waiting; use grida_fx_core::project::Planner; use grida_fx_core::registry::relative_inside; diff --git a/crates/grida-fx/src/verbs/project.rs b/crates/grida-fx/src/verbs/project.rs index af3defeb..4c5c169c 100644 --- a/crates/grida-fx/src/verbs/project.rs +++ b/crates/grida-fx/src/verbs/project.rs @@ -87,6 +87,17 @@ pub(crate) fn projection(events: &[Value]) -> Value { } instances.insert(id.to_string(), entry); } + (Some("waiting_request"), Some(id)) => { + if let Some(entry) = instances.get_mut(id) { + if object.get("request_status").and_then(Value::as_str) == Some("pending") { + entry["state"] = json!("awaiting"); + entry["request_id"] = object["request_id"].clone(); + } else { + entry["state"] = json!("running"); + entry.as_object_mut().unwrap().remove("request_id"); + } + } + } (Some("node_retry"), Some(id)) => settle(&mut instances, id, None), (Some(call @ ("call_waiting" | "call_admitted")), Some(id)) => { if !matches!( diff --git a/crates/grida-fx/src/verbs/run.rs b/crates/grida-fx/src/verbs/run.rs index c8adfb20..5af179a7 100644 --- a/crates/grida-fx/src/verbs/run.rs +++ b/crates/grida-fx/src/verbs/run.rs @@ -309,6 +309,7 @@ fn plan_and_run( }; print_line(&text); let options = RunOptions { + wait_for_answers: args.wait_for_answers, require_estimates: args.require_estimates, recover: args.recover, folder: folder.clone(), @@ -339,6 +340,13 @@ fn plan_and_run( invocation_id = Some(ready.invocation_id.clone()); crate::interrupt::runner_started(); print_line(&format!("run {label}")); + if args.wait_for_answers { + stderr::line(format_args!( + "requests {} inspect {} --requests --json", + crate::invoker::command(), + super::repeat::path_word(&label), + )); + } stderr::line(format_args!("invocation {}", ready.invocation_id)); stderr::line(if ready.control_available { "control available" @@ -388,6 +396,22 @@ fn plan_and_run( if let Some(invocation_id) = invocation_id.as_deref() && let Ok(mut events) = super::read_log(&folder, &label, true) { + if events.iter().any(|event| { + super::event_name(event) == Some("run_finished") + && super::text(event, "invocation_id") == Some(invocation_id) + && event["awaiting"] + .as_array() + .is_some_and(|ids| !ids.is_empty()) + }) { + lines.push(labelled( + "requests", + &format!( + "{} inspect {} --requests --json", + crate::invoker::command(), + super::repeat::path_word(&label) + ), + )); + } events.retain(|event| { matches!(super::event_name(event), Some("call_recovery" | "call")) && super::text(event, "invocation_id") == Some(invocation_id) diff --git a/crates/grida-fx/src/verbs/run_set.rs b/crates/grida-fx/src/verbs/run_set.rs index 393be55e..444afbb2 100644 --- a/crates/grida-fx/src/verbs/run_set.rs +++ b/crates/grida-fx/src/verbs/run_set.rs @@ -32,6 +32,7 @@ use grida_fx_core::docs::project::Project; use grida_fx_core::docs::takes::read_takes; use grida_fx_core::value::{is_digest, sha256_hex}; use grida_fx_runtime::events::{read_events_tolerant, run_metadata}; +pub(crate) use grida_fx_runtime::folder::is_tombstone_name; use grida_fx_runtime::folder::{holds_stand_in, safe_name}; use serde_json::Value; use std::collections::{BTreeMap, BTreeSet}; @@ -542,13 +543,6 @@ pub(crate) struct Picks { pub unreadable: BTreeMap, } -/// `.removing-<16 lowercase hex>`. -pub(crate) fn is_tombstone_name(name: &str) -> bool { - name.strip_prefix(".removing-").is_some_and(|hex| { - hex.len() == 16 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) - }) -} - enum PlanFile { None, Graph, @@ -635,6 +629,13 @@ fn read_recorded(folder: &Path) -> Result { let incomplete = event.get("incomplete") == Some(&Value::Bool(true)); state = match (ok, incomplete) { (true, _) => "succeeded", + (false, true) + if event["awaiting"] + .as_array() + .is_some_and(|ids| !ids.is_empty()) => + { + "awaiting" + } (false, true) => "incomplete", (false, false) => "failed", }; diff --git a/crates/grida-fx/src/verbs/runs.rs b/crates/grida-fx/src/verbs/runs.rs index 025beb2e..974297a6 100644 --- a/crates/grida-fx/src/verbs/runs.rs +++ b/crates/grida-fx/src/verbs/runs.rs @@ -41,7 +41,7 @@ use crate::print::{labelled, print_json, print_line, shown_path}; use grida_fx_core::Error; use grida_fx_core::docs::project::Project; use grida_fx_core::money::Usd; -use grida_fx_core::value::sha256_hex; +use grida_fx_core::value::{is_digest, sha256_hex}; use grida_fx_runtime::folder::same_file; use serde_json::{Map, Value, json}; use std::collections::{BTreeMap, BTreeSet}; @@ -648,12 +648,16 @@ fn preview_one(set: &RunSet, selected: Selected) -> Outcome { /// The first top-level entry of a run folder or claim that FX did not write: anything but its /// `plan.json`, `events.jsonl`, `run.lock`, `files/`, `outputs/`, `views/`, `values/`, temporary names, -/// `.DS_Store` and folders holding no file. A tombstone's leftovers are all its own. +/// the waiting request records and their lock, `.DS_Store` and folders holding no file. +/// A tombstone's leftovers are all its own. fn foreign_entry(found: &Found) -> Option { if matches!(found.holds, Holds::Tombstone | Holds::Missing) { return None; } let listing = fs::read_dir(&found.folder).ok()?; + let waiting_lock = found.folder.join(grida_fx_runtime::waiting::REQUEST_LOCK); + let recorded_requests = fs::symlink_metadata(&waiting_lock) + .is_ok_and(|metadata| metadata.is_file() && metadata.len() == 0); for item in listing.flatten() { let name = item.file_name().to_string_lossy().into_owned(); let ours = matches!( @@ -666,7 +670,12 @@ fn foreign_entry(found: &Found) -> Option { | "views" | "values" | ".DS_Store" - ) || grida_fx_runtime::folder::is_temporary_name(&name); + ) || grida_fx_runtime::folder::is_temporary_name(&name) + || (recorded_requests && name == grida_fx_runtime::waiting::REQUEST_LOCK) + || (recorded_requests + && name == grida_fx_runtime::waiting::REQUEST_DIRECTORY + && item.file_type().is_ok_and(|kind| kind.is_dir()) + && owns_request_directory(&found.folder, &item.path())); let empty_folder = item.file_type().is_ok_and(|kind| kind.is_dir()) && !holds_a_file(&item.path()); if !ours && !empty_folder { @@ -676,6 +685,22 @@ fn foreign_entry(found: &Found) -> Option { None } +fn owns_request_directory(run: &Path, directory: &Path) -> bool { + // The request reader verifies that every JSON record belongs to this run and step. + // It ignores other names, so separately check that only engine temporary files remain. + fs::read_dir(directory).is_ok_and(|mut entries| { + entries.all(|entry| { + entry.is_ok_and(|entry| { + entry.file_type().is_ok_and(|kind| kind.is_file()) + && entry.file_name().to_str().is_some_and(|name| { + grida_fx_runtime::folder::is_temporary_name(name) + || name.strip_suffix(".json").is_some_and(is_digest) + }) + }) + }) + }) && grida_fx_runtime::waiting::list(run).is_ok() +} + /// Whether a folder holds a file anywhere below it (a symbolic link counts). fn holds_a_file(folder: &Path) -> bool { let mut pending = vec![folder.to_path_buf()]; @@ -753,6 +778,13 @@ fn remove_one(set: &RunSet, project: &Project, selected: Selected) -> Outcome { return outcome; } } + let _waiting_lock = match grida_fx_runtime::waiting::lock_for_removal(folder) { + Ok(lock) => lock, + Err(error) => { + refused(&mut outcome, "not_removable", error.to_string()); + return outcome; + } + }; // Under its lock, the folder must still hold what was selected, and only what FX wrote. if !same_file(&lock, &folder.join("run.lock")) || !still_selected(found) { refused( diff --git a/crates/grida-fx/src/verbs/service.rs b/crates/grida-fx/src/verbs/service.rs index a7e30d0b..1465d511 100644 --- a/crates/grida-fx/src/verbs/service.rs +++ b/crates/grida-fx/src/verbs/service.rs @@ -774,6 +774,17 @@ fn registered_url(catalog: &Catalog, path: &str) -> Option { Some(format!("{}{}", base.trim_end_matches('/'), path)) } +/// An exact, already-registered run URL from the currently verified project service. +pub(super) fn existing_run_url(folder: &Path) -> Option { + let project = project(None).ok()?; + let catalog = Catalog::locate(&project.root).ok()?; + if !catalog.has_state().ok()? { + return None; + } + let route = catalog.registered_run_route(folder).ok()??; + registered_url(&catalog, &route) +} + #[cfg(all(test, unix))] mod tests { use super::*; diff --git a/crates/grida-fx/src/verbs/waiting.rs b/crates/grida-fx/src/verbs/waiting.rs new file mode 100644 index 00000000..dcd67350 --- /dev/null +++ b/crates/grida-fx/src/verbs/waiting.rs @@ -0,0 +1,122 @@ +//! Inspect or answer one run's durable requests without starting a workflow. + +use crate::cli::{InspectArgs, RespondArgs}; +use crate::print::{print_json, print_line}; +use grida_fx_core::{Error, value::parse_json}; +use grida_fx_runtime::waiting::{self, Request, ResponseChannel}; +use serde_json::{Value, json}; +use std::io::Read; +use std::path::{Path, PathBuf}; + +fn exact_run(run: &str) -> Result { + let cwd = super::planning::working_directory()?; + let folder = super::control::exact_folder(run, &cwd, None) + .map_err(|(_, message)| Error::usage(message))?; + super::read_plan(&folder, run)?; + Ok(folder) +} + +pub(super) fn requests(folder: &Path) -> Result, Error> { + waiting::list(folder).map_err(|error| Error::input(error.to_string())) +} + +pub fn inspect(args: &InspectArgs) -> Result { + let folder = exact_run(&args.run)?; + let plan_path = folder.join("plan.json"); + let plan_file = std::fs::File::open(&plan_path).map_err(|e| Error::io("recorded plan", &e))?; + let requests = requests(&folder)?; + let viewer_url = if args.register { + let project = + grida_fx_core::docs::project::Project::find(&super::planning::working_directory()?)?; + super::service::register_run(&project, &folder)? + } else if args.viewer_url { + super::service::existing_run_url(&folder) + } else { + None + }; + if !grida_fx_runtime::folder::same_file(&plan_file, &plan_path) { + return Err(Error::input( + "The run was replaced during request inspection.", + )); + } + if args.json { + let mut result = json!({"requests": requests}); + if args.viewer_url || args.register { + result["viewer_url"] = json!(viewer_url); + } + print_json(&result); + } else if requests.is_empty() { + print_line("no answer requests"); + } else { + for request in requests { + let line = format!( + "{} {} {}", + request.id, + request.state.status(), + request.spec.step + ); + if let Some(message) = &request.spec.message { + print_line(&format!("{line} {message}")); + } else { + print_line(&line); + } + } + } + if !args.json + && let Some(url) = viewer_url + { + print_line(&url); + } + Ok(0) +} + +fn answer_json(input: &str) -> Result { + const LIMIT: usize = 1 << 20; + let mut buffer = String::new(); + let input = if input == "-" { + std::io::stdin() + .take(LIMIT as u64 + 1) + .read_to_string(&mut buffer) + .map_err(|e| Error::io("answer on standard input", &e))?; + &buffer + } else { + input + }; + if input.len() > LIMIT { + return Err(Error::input("the answer exceeds 1 MiB")); + } + parse_json(input).map_err(|_| Error::input("the answer must be valid JSON")) +} + +pub fn respond(args: &RespondArgs) -> Result { + let channel = if args.source == "sdk" { + ResponseChannel::Sdk + } else { + ResponseChannel::Cli + }; + let (folder, answer) = + match exact_run(&args.run).and_then(|folder| Ok((folder, answer_json(&args.json)?))) { + Ok(inputs) => inputs, + Err(error) => { + print_json(&json!({"code": "invalid_input", "message": error.message})); + return Ok(2); + } + }; + match waiting::respond(&folder, &args.request, answer, channel) { + Ok(request) => { + print_json(&json!({"request": request})); + Ok(0) + } + Err(error) => { + let mut receipt = json!({"code": error.code(), "message": error.to_string()}); + if let Some(request) = error.request() { + receipt["request"] = json!(request); + } + print_json(&receipt); + Ok(match error.code() { + "answer_conflict" | "expired" | "not_found" | "invalid_answer" => 1, + _ => 2, + }) + } + } +} diff --git a/crates/grida-fx/tests/cli.rs b/crates/grida-fx/tests/cli.rs index d163c463..9cc1818e 100644 --- a/crates/grida-fx/tests/cli.rs +++ b/crates/grida-fx/tests/cli.rs @@ -197,16 +197,16 @@ fn integrated_nodes_lists_every_built_in() { assert_eq!(status(&output), 0, "{}", stderr(&output)); let text = stdout(&output); let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 37, "{text}"); + assert_eq!(lines.len(), 38, "{text}"); assert_eq!(lines[0], format!("{:34} free", "fx/annotations.filter@1")); - assert_eq!(lines[36], format!("{:34} judge", "fx/vision.review@1")); + assert_eq!(lines[37], format!("{:34} judge", "fx/vision.review@1")); let kinds = |kind: &str| { lines .iter() .filter(|l| l.ends_with(&format!(" {kind}"))) .count() }; - assert_eq!((kinds("paid"), kinds("judge"), kinds("free")), (11, 5, 21)); + assert_eq!((kinds("paid"), kinds("judge"), kinds("free")), (11, 5, 22)); let mut sorted = lines.clone(); sorted.sort(); assert_eq!(sorted, lines, "sorted by name"); diff --git a/crates/grida-fx/tests/runs.rs b/crates/grida-fx/tests/runs.rs index 198f396d..8d4befbd 100644 --- a/crates/grida-fx/tests/runs.rs +++ b/crates/grida-fx/tests/runs.rs @@ -1051,6 +1051,40 @@ fn integrated_a_real_run_is_indexed_outside_the_tree_removed_and_never_resumed() ); } +#[test] +fn only_verified_waiting_request_files_are_removable() { + let project = Project::new(); + let folder = "runs/review"; + fs::write( + project.root.join("review.yaml"), + "fx: workflow/v1\nid: review\ntitle: Review\nsteps:\n input:\n uses: fx/await@1\n with: {schema: {type: string}}\n", + ) + .unwrap(); + let parked = project.fx(&["run", "review.yaml", "--run", folder, "--no-view"]); + assert_eq!(status(&parked), 1, "{}", text(&parked.stderr)); + let requests = json_of(&project.fx(&["inspect", folder, "--requests", "--json"])); + assert_eq!(requests["requests"].as_array().unwrap().len(), 1); + + let foreign = project + .root + .join(folder) + .join("awaiting") + .join(format!("{}.json", "0".repeat(64))); + fs::write(&foreign, r#"{"title":"keep this file"}"#).unwrap(); + for apply in [false, true] { + let mut args = vec!["runs", "remove", folder, "--json"]; + if apply { + args.push("--yes"); + } + let result = json_of(&project.fx(&args)); + assert_eq!(result["runs"][0]["code"], "not_removable", "{result}"); + assert!(foreign.is_file()); + } + fs::rename(&foreign, project.root.join("preserved.json")).unwrap(); + let result = json_of(&project.fx(&["runs", "remove", folder, "--yes", "--json"])); + assert_eq!(result["runs"][0]["outcome"], "removed", "{result}"); +} + #[test] fn recorded_input_snapshots_are_owned_run_data_for_listing_and_removal() { let project = Project::new(); diff --git a/docs/guide/02-workflow-file.md b/docs/guide/02-workflow-file.md index f0490653..a57c37f8 100644 --- a/docs/guide/02-workflow-file.md +++ b/docs/guide/02-workflow-file.md @@ -325,6 +325,49 @@ To use whichever result exists, pick explicitly, or use `??`: `select` skips results whose step was skipped or rejected. Its output keeps the candidates' name: `steps.chosen.outputs.image` above. +## Wait for external input + +Use `fx/await@1` when a person or program supplies a value during a run. Declare +the accepted value with `with.schema`. A build system can supply a revision +without a prompt. A human review can add a question and show an artifact. + +```yaml +steps: + revision: + uses: fx/await@1 + with: { schema: { type: string } } + approve: + uses: fx/await@1 + with: + message: "Approve this concept?" + schema: { type: boolean } + timeout_seconds: 300 + on_timeout: continue + render: + if: ${{ steps.approve.outputs.answer ?? false }} + uses: ./nodes.py#render + fallback: + if: ${{ steps.approve.facts.outcome == 'expired' }} + uses: ./nodes.py#judge +``` + +Read the supplied revision from `steps.revision.outputs.answer`. +A timely `false` on the approval skips both branches in this example. With `on_timeout: fail` +(the default), expiry fails the step. Omit `timeout_seconds` for an open-ended wait. +Use `show` to provide context, and `choices` to offer keyed values or files. A string +answer names the chosen key directly. For a structured answer, set `choice_field` +to the member holding that key. The step's `outputs.selected` carries the original +candidate. Each expanded occurrence opens its own request. See the [three-variant +workflow](../../fixtures/waiting/workflow.yaml) and [how to answer](05-running.md#answer-a-waiting-step). + +For fixed values such as a paper finish, use +`schema: { type: string, enum: [matte, satin] }`. The viewer offers a picker, +and `outputs.answer` contains the chosen string. When upstream work produces +images, use `choices` to bind each key to the exact image the next step needs. +The [review showcase](../../fixtures/waiting/showcase.yaml) demonstrates both. +The [form examples](../../fixtures/waiting/README.md#answer-types-in-the-viewer) +show how the viewer renders other JSON Schema types. + ## Judges A judge is a step that looks at another step's result and reports a verdict, `accept` or `reject`. diff --git a/docs/guide/05-running.md b/docs/guide/05-running.md index 41e423b4..c2604b63 100644 --- a/docs/guide/05-running.md +++ b/docs/guide/05-running.md @@ -39,6 +39,34 @@ The service uses loopback port 8787 by default and keeps run pages available aft `--open` requests browser launch. Commands never start a background service implicitly. Execution still works when the service is stopped. +## Answer a waiting step + +A workflow can ask for a boolean, a candidate key or a JSON value matching its +answer schema. A named run gives both a person and an agent the same review target. +In the [three-variant fixture](../../fixtures/waiting/workflow.yaml), a build +system supplies a promptless revision and a reviewer picks an image. To try +both from the terminal, copy each step's request ID from the inspection. + +```sh +grida fx run workflow.yaml --name review +grida fx inspect review-variants/review --requests --json +# Set REVISION_ID and CHOOSE_ID to the IDs for revision#1 and choose#1. +grida fx respond review-variants/review "$REVISION_ID" --json '"rev-42"' +grida fx respond review-variants/review "$CHOOSE_ID" --json '{"variant":"b"}' +grida fx run workflow.yaml --resume review +``` + +By default the first invocation exits with status 1 and an incomplete result once +only open requests block progress. Add `--wait-for-answers` to keep it running. +A second terminal, an SDK or the local viewer can answer. The result pairs the +revision and selected image digest in `outputs/manifest.json`. Use `--viewer-url` +with request inspection to look up an existing viewer link, or `--register` +to register the run for handoff. +Use `--json=-` to read an answer from standard input. Invalid input leaves a +request open. If another client has answered, a conflicting submission reports +the winner. When a detached request expires, resume to run its configured fallback. +Answering needs no sign-in or credential setup. [Workflow contract](../../spec/waiting.md) + ## Generate one image `grida fx call` runs a single `image.generate` from a literal prompt. It uses the nearest diff --git a/docs/guide/07-viewing.md b/docs/guide/07-viewing.md index 715fde51..c62f4f6a 100644 --- a/docs/guide/07-viewing.md +++ b/docs/guide/07-viewing.md @@ -1,7 +1,8 @@ # Viewing workflows and runs The local FX service keeps a project's plans and recorded runs available at one -loopback address. Its bundled viewer displays each workflow on a read-only canvas. +loopback address. The canvas shows the graph defined in the workflow file. +On a live run, **Review** opens a pending input for submission. The service needs FX 0.2 or later; `grida fx --version` names yours. ## Start the project service @@ -46,6 +47,30 @@ workflow processes. Restarting it restores access to retained run URLs. Closing browser tab has no effect on service or execution. Service commands accept `--project DIRECTORY` when you are outside the project. +## Answer a waiting step + +An exact run page lets you **answer a waiting step**. An amber outline and tinted +header mark the step awaiting an answer. Pending requests with a deadline show a +countdown on the card and in the review panel. Open-ended requests show +**Awaiting answer**. Click **Review** to see the optional question and artifacts in the +right-hand panel. A promptless request uses the step title or ID. A scalar enum +offers a picker, and an image candidate can include a preview. Fill in the answer, then click +**Submit answer**. + +The run header and project home also show **Awaiting answer** while the +unfinished run has a pending request. The home status updates automatically. + +If someone has already answered through the CLI, an SDK, or another tab, the +panel shows the recorded selection or answer fields and the submission channel. Invalid input keeps the request +open. A run started with `--wait-for-answers` can continue as soon as FX records +the answer. If the invocation has exited, resume the same run to continue. +After the runner resolves the step, the canvas card shows the review outcome +alongside its execution status, such as **Selected** or **Expired**. Use +**View answer** on an answered step to revisit its receipt. +Portable exports are read-only. See the [waiting-step contract](../../spec/waiting.md). +The [dogfood workflow](../../fixtures/waiting/README.md) shows concurrent reviews, +repeated instances, follow-up questions and both timeout policies in one local run. + ## Register a plan or saved run When installed help lists `--register`, use it to get the exact project viewer @@ -327,9 +352,12 @@ constructing it from a folder name. `--open` requests one browser launch; omit i to visit the printed URL yourself. Planning-time code can execute before the URL exists. Browser or service failures do not change the workflow's result. -The browser tab's `f(x)` icon pulses green while the viewer can verify the run is -executing. With reduced motion enabled, the green icon stays steady. Plans, finished -runs and unfinished records without a verified runner use the standard icon. +The browser tab shows a steady amber `f(x)` icon and **Awaiting answer** while a +review is open. If several reviews are open, the title gives their count. The +amber icon follows the requests, including when the runner stops or another +branch is still executing. Once all requests resolve, the icon pulses green +while the viewer can verify an active runner and uses the standard icon +otherwise. Reduced motion keeps the green icon steady. `run` stays foreground and exits normally after execution. The separate FX service keeps its page available afterward, including for failed and cancelled runs. @@ -542,7 +570,7 @@ The bar shows `cancelling` after a recorded `cancel_requested` event and returns to the terminal state when that invocation ends. A resume resets the intent. This label does not prove the runner is still alive or that cleanup finished. Use [`inspect --control` or `cancel --wait`](08-run-control.md) for verified local control. -The viewer has no cancellation button or write endpoint in this version. +Request cancellation through the CLI or SDK. To connect a chat, editor, or browser automation to the current selection and presentation, see [Connect to the FX viewer](16-viewer-api.md). diff --git a/docs/guide/README.md b/docs/guide/README.md index 5a3fc383..9da86da9 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -12,7 +12,7 @@ awaiting implementation as **planned**. Stable FX releases start at `0.1.0`; [the overview](../wg/overview.md) records the decisions, what shipped and what comes later. The local FX service gives a project a stable address, a run/plan index, and a -read-only node canvas. Start with `grida fx init` and `grida fx start --background`; +node canvas with review actions for pending workflow inputs. Start with `grida fx init` and `grida fx start --background`; standalone workflows remain supported. These service commands describe current source behavior: check your installed version's help before using them. Custom step pages remain planned. Portable recorded-run exports are described in @@ -27,7 +27,7 @@ custom node bodies and workflow builders: Python's on Python, TypeScript's on No The engine owns planning, scheduling, result identities, caching, spending limits, provider retries, and run records. SDKs and node bodies use that engine rather than implementing their own execution or billing layer. AI generation is one application; ordinary code can run as workflow -steps too. The bundled viewer is a read-only canvas for plans and recorded runs. +steps too. The bundled viewer displays plans and recorded runs. ## Chapters diff --git a/fixtures/waiting/README.md b/fixtures/waiting/README.md new file mode 100644 index 00000000..7b0bb0da --- /dev/null +++ b/fixtures/waiting/README.md @@ -0,0 +1,86 @@ +# Waiting-step dogfood + +Copy this directory to a fresh project folder with the Grida Python package +installed. Both workflows draw three PNG swatches locally and run with a +zero-dollar ceiling. + +## Supply a revision and review an image + +`workflow.yaml` opens two independent requests. A build system can supply the +revision through the SDK, while a person chooses one of the generated PNGs. +Start a named run in one terminal: + +```sh +grida fx start --background +grida fx run workflow.yaml --name review --wait-for-answers --max-usd 0 --open +``` + +From the same project in a second terminal, run this once the revision card appears: + +```python +from grida import fx + +run = "review-variants/review" +request = next(r for r in fx.list_requests(run) if r["step"] == "revision#1") +fx.respond(run, request["id"], "rev-42") +``` + +In the viewer, open **Review** on `choose`, select a swatch and submit. Either +request can be answered first. The run's `outputs/image.png` is the chosen +image. Its `outputs/manifest.json` records the supplied revision and that +image's digest. The revision declares only a string schema. The image request +adds a message and a map from keys to the frozen image files. + +## Try the form showcase + +```sh +grida fx start --background +grida fx run showcase.yaml --name dogfood --wait-for-answers --max-usd 0 --open +``` + +`showcase.yaml` has several independently answerable steps in one run. + +| Card | What to try | +| --- | --- | +| Choose the cover | Pick one of three PNGs. The next review opens with the exact swatch you picked. | +| Approve public use | Choose **No** to record a decision and skip marking the sample public. | +| Annotate the cover | Enter a review note, add two requested changes, and set the assigned designer to **No value**. This review opens after the cover is chosen. | +| Set label length | Click the front `placement` card to expand the stack. Answer Print and Web independently. They use the same options and keep separate request IDs and drafts. | +| Set the print settings | Pick **satin**, enter **12** copies, a scale of **0.95**, and a top margin of **3.5** mm. Check **No value** under Color profile override to send an explicit null. Click **Include Production labels**, then **Add field**, and enter **batch** with the value **proof**. | +| Choose the thumbnail | Pick a swatch or let the deadline expire. The local fallback selects C and the thumbnail still completes. | +| Verify the print proof | Enter a code such as `FX-042`, try an invalid code, or leave it unanswered. On expiry, certification is skipped and this branch fails. Other open requests remain available. | + +## Answer types in the viewer + +| Workflow schema or setting | Editor | +| --- | --- | +| `enum: [matte, satin]` | A picker for literal values. The paper finish is a string in the submitted answer. | +| `choices` | A candidate picker with previews of recorded files. A key identifies the original value exposed as `outputs.selected`. Use `choice_field` to put the key in an object answer. | +| `type: boolean` | **Yes** and **No** radio buttons. | +| `type: string`, `integer`, or `number` | Text, whole-number, or decimal input. FX validates constraints such as `pattern`, `enum`, and numeric bounds. | +| `type: "null"` | **No value** checkbox. For an optional field, leaving it unset omits the field. | +| `type: [string, "null"]` | A type selector with **Text** and **No value**. | +| `type: array` | Add or remove items, with an editor for each item. | +| `type: object` | Named and nested fields, including custom field names where the schema permits them. | + +Click **Review** on one card, edit a draft, close it, and open a different +card. Reopen the first card to check that its draft is still there. Expand +the repeated cards to review each item separately. Use **View answer** or +**View outcome** to reopen a completed or expired review. + +Each review also has its own ID when inspected from a second terminal. Submit +to an exact request while the viewer is open to see the result appear on its +card. + +```sh +grida fx inspect review-showcase/dogfood --requests --json +``` + +To see the timeout states sooner, pass an inputs file with +`continue_seconds: 10` and `fail_seconds: 30`. Keep the original command's +inputs file when resuming that run. + +For a detached run, start with a fresh name and omit `--wait-for-answers`. +The invocation returns incomplete when only requests remain. The viewer or +CLI can still record an answer. Resume with the same input options when ready +to let the workflow consume those answers or run any timeout fallback. diff --git a/fixtures/waiting/fx.yaml b/fixtures/waiting/fx.yaml new file mode 100644 index 00000000..73cef7c5 --- /dev/null +++ b/fixtures/waiting/fx.yaml @@ -0,0 +1 @@ +fx: project/v1 diff --git a/fixtures/waiting/nodes.py b/fixtures/waiting/nodes.py new file mode 100644 index 00000000..887838ef --- /dev/null +++ b/fixtures/waiting/nodes.py @@ -0,0 +1,64 @@ +"""Generate three distinct PNG swatches and select one locally on timeout.""" + +import struct +import zlib + +from grida.fx import Ctx, node + + +def chunk(kind: bytes, payload: bytes) -> bytes: + return ( + struct.pack(">I", len(payload)) + + kind + + payload + + struct.pack(">I", zlib.crc32(kind + payload)) + ) + + +@node( + "draw_swatches", + outputs={"a": "image/png", "b": "image/png", "c": "image/png"}, + version=1, +) +def draw(ctx: Ctx) -> dict: + outputs = {} + for key, color in { + "a": (194, 79, 75), + "b": (62, 128, 112), + "c": (80, 102, 169), + }.items(): + header = struct.pack(">2I5B", 32, 32, 8, 2, 0, 0, 0) + pixels = (b"\0" + bytes(color) * 32) * 32 + path = ctx.out.path(f"{key}.png") + path.write_bytes( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(pixels)) + + chunk(b"IEND", b"") + ) + outputs[key] = ctx.out.file(path, "image/png") + return outputs + + +@node( + "judge_swatches", + inputs={"a": "image", "b": "image", "c": "image"}, + outputs={"image": "image/png"}, + version=1, +) +def judge(ctx: Ctx) -> dict: + return {"image": ctx.inputs["c"]} + + +@node( + "build_manifest", + inputs={"image": "image"}, + params={"revision": str}, + outputs={"record": "json"}, +) +def manifest(ctx: Ctx) -> dict: + return { + "record": ctx.out.json( + {"revision": ctx.params["revision"], "image_digest": ctx.inputs["image"].digest} + ) + } diff --git a/fixtures/waiting/showcase.yaml b/fixtures/waiting/showcase.yaml new file mode 100644 index 00000000..9a800bdb --- /dev/null +++ b/fixtures/waiting/showcase.yaml @@ -0,0 +1,165 @@ +fx: workflow/v1 +id: review-showcase +title: Review a field guide palette +description: Choose cover and thumbnail colors, set print and web options, and record the print proof. + +inputs: + continue_seconds: + type: integer + minimum: 1 + default: 150 + description: Seconds to pick a thumbnail color before the local judge chooses swatch C. + fail_seconds: + type: integer + minimum: 1 + default: 300 + description: Seconds to enter the print proof code before certification expires. + +steps: + draw: + title: Draw three swatches + uses: ./nodes.py#draw + + choose: + title: Choose the cover + uses: fx/await@1 + with: + message: Which swatch should go on the cover? + schema: { type: string } + choices: + a: ${{ steps.draw.outputs.a }} + b: ${{ steps.draw.outputs.b }} + c: ${{ steps.draw.outputs.c }} + + feedback: + title: Annotate the cover + uses: fx/await@1 + with: + message: What should the designer know about this cover color? + show: ${{ steps.choose.outputs.selected }} + schema: + type: object + additionalProperties: false + required: [summary, actions, owner] + properties: + summary: { title: Review note, type: string, minLength: 1 } + actions: + title: Requested changes + description: Leave the list empty if the cover is ready. + type: array + items: { type: string, minLength: 1 } + owner: + title: Assigned designer + description: Choose null to leave this work unassigned. + type: [string, "null"] + + approve: + title: Approve public use + uses: fx/await@1 + with: + message: May the field guide appear in the public sample? + schema: { type: boolean } + + publish: + title: Mark the sample public + if: ${{ steps.approve.outputs.answer }} + uses: fx/select@1 + with: { first_of: [public] } + + placement: + title: Set label length + for_each: [print, web] + key: ${{ item }} + uses: fx/await@1 + with: + message: "Which label style should the ${{ item }} edition use?" + schema: { type: string, enum: [compact, full] } + + print_settings: + title: Set the print settings + uses: fx/await@1 + with: + message: How should the print edition be produced? + schema: + type: object + additionalProperties: false + required: [finish, copies, scale, margins] + properties: + finish: { title: Paper finish, type: string, enum: [matte, satin] } + copies: { title: Print copies, type: integer, minimum: 1 } + scale: { title: Scale factor, type: number, exclusiveMinimum: 0, maximum: 2 } + margins: + title: Margins + type: object + additionalProperties: false + required: [top_mm] + properties: + top_mm: { title: Top margin in mm, type: number, minimum: 0 } + profile_override: + title: Color profile override + description: Choose No value to explicitly use the standard profile, or leave this field unset. + type: "null" + labels: + title: Production labels + description: Add a text label such as batch for the print shop. + type: object + additionalProperties: { type: string } + + backup: + title: Choose the thumbnail + uses: fx/await@1 + with: + message: Pick a thumbnail swatch before the timer ends, or let the local judge choose C. + schema: + type: object + properties: { swatch: { type: string } } + required: [swatch] + additionalProperties: false + choices: + a: ${{ steps.draw.outputs.a }} + b: ${{ steps.draw.outputs.b }} + c: ${{ steps.draw.outputs.c }} + choice_field: swatch + timeout_seconds: ${{ inputs.continue_seconds }} + on_timeout: continue + + judge: + title: Use the blue thumbnail + if: ${{ steps.backup.facts.outcome == 'expired' }} + uses: ./nodes.py#judge + with: + a: ${{ steps.draw.outputs.a }} + b: ${{ steps.draw.outputs.b }} + c: ${{ steps.draw.outputs.c }} + + thumbnail: + title: Deliver the thumbnail + uses: fx/select@1 + with: + first_of: + - ${{ steps.backup.outputs.selected ?? null }} + - ${{ steps.judge.outputs.image ?? null }} + + signoff: + title: Verify the print proof + uses: fx/await@1 + with: + message: Enter the print proof code before certification expires (for example, FX-042). + schema: { type: string, pattern: "^[A-Z]{2}-[0-9]{3}$" } + timeout_seconds: ${{ inputs.fail_seconds }} + on_timeout: fail + + certify: + title: Record the proof code + uses: fx/select@1 + with: + first_of: ["${{ steps.signoff.outputs.answer }}"] + +outputs: + cover: ${{ steps.choose.outputs.selected }} + feedback: ${{ steps.feedback.outputs.answer }} + public_sample: ${{ steps.approve.outputs.answer }} + labels: ${{ steps.placement.*.outputs.answer }} + print_settings: ${{ steps.print_settings.outputs.answer }} + thumbnail: ${{ steps.thumbnail.outputs.value }} + proof: ${{ steps.certify.outputs.value }} diff --git a/fixtures/waiting/workflow.yaml b/fixtures/waiting/workflow.yaml new file mode 100644 index 00000000..708a8750 --- /dev/null +++ b/fixtures/waiting/workflow.yaml @@ -0,0 +1,53 @@ +fx: workflow/v1 +id: review-variants +title: Review three variants + +inputs: + seconds: { type: integer, minimum: 1, default: 300 } + +steps: + revision: + title: Build revision + uses: fx/await@1 + with: { schema: { type: string } } + draw: + uses: ./nodes.py#draw + choose: + uses: fx/await@1 + with: + message: Choose a variant + schema: + type: object + properties: { variant: { type: string } } + required: [variant] + additionalProperties: false + choices: + a: ${{ steps.draw.outputs.a }} + b: ${{ steps.draw.outputs.b }} + c: ${{ steps.draw.outputs.c }} + choice_field: variant + timeout_seconds: ${{ inputs.seconds }} + on_timeout: continue + judge: + if: ${{ steps.choose.facts.outcome == 'expired' }} + uses: ./nodes.py#judge + with: + a: ${{ steps.draw.outputs.a }} + b: ${{ steps.draw.outputs.b }} + c: ${{ steps.draw.outputs.c }} + deliver: + uses: fx/select@1 + with: + first_of: + - ${{ steps.choose.outputs.selected ?? null }} + - ${{ steps.judge.outputs.image ?? null }} + + manifest: + uses: ./nodes.py#manifest + with: + revision: ${{ steps.revision.outputs.answer }} + image: ${{ steps.deliver.outputs.value }} + +outputs: + manifest: ${{ steps.manifest.outputs.record }} + image: ${{ steps.deliver.outputs.value }} diff --git a/js/fx/README.md b/js/fx/README.md index 4ca7d640..7ba72ba5 100644 --- a/js/fx/README.md +++ b/js/fx/README.md @@ -596,3 +596,21 @@ and captures notes. See the [note contract](https://github.com/gridaco/fx/blob/m For note selection context, construct `ViewerClient` with `includeNotes: true`. The default preserves protocol-v1 selection shapes; see the [viewer API](https://github.com/gridaco/fx/blob/main/spec/viewer.md). + +## Answer a waiting step + +Use `run(target, { name: "review", waitForAnswers: true })` to keep a named run attached while another client supplies input. In the [waiting example](https://github.com/gridaco/fx/blob/main/fixtures/waiting/workflow.yaml), a build system supplies a revision without a prompt and a reviewer picks one of the saved images. + +```js +import { listRequests, respond } from "@grida/fx"; + +const run = "review-variants/review"; +const pending = (await listRequests(run)).filter(r => r.state.status === "pending"); +const revision = pending.find(r => r.step === "revision#1"); +if (revision) await respond(run, revision.id, "rev-42"); + +const image = pending.find(r => r.step === "choose#1"); +if (image) await respond(run, image.id, { variant: "b" }); +``` + +`listRequests(run)` reads the durable requests directly. For a viewer link, call `inspectRequests(run)`, or pass `{ register: true }` to register the run too. The result includes `viewer_url` when the local service can serve the run. The engine checks every response against the saved schema and any frozen candidate keys. A conflicting submission raises `AnswerError` with the recorded winner. diff --git a/js/fx/src/api.ts b/js/fx/src/api.ts index 182103ea..a86c112e 100644 --- a/js/fx/src/api.ts +++ b/js/fx/src/api.ts @@ -419,6 +419,7 @@ export function decode(encoded: Encoded, placed: ReadonlyMap): R const RUN_ONLY: readonly string[] = [ "live", "yesUpTo", + "waitForAnswers", "runDir", "name", "resume", diff --git a/js/fx/src/control.ts b/js/fx/src/control.ts index eae923db..118f4c3a 100644 --- a/js/fx/src/control.ts +++ b/js/fx/src/control.ts @@ -18,7 +18,7 @@ export interface RunControlResult { | "completed" | "error"; readonly request_status: "accepted" | "not_accepted" | "unknown"; - readonly recorded_state: "planned" | "unfinished" | "succeeded" | "failed" | "cancelled" | "unknown"; + readonly recorded_state: "planned" | "unfinished" | "awaiting" | "succeeded" | "failed" | "cancelled" | "unknown"; readonly cleanup: "pending" | "complete" | "unknown"; readonly external_completion: "not_verified"; readonly code?: string; @@ -80,7 +80,7 @@ const ERROR_STATUS: Readonly> = { const ENUMS: Readonly> = { outcome: ["inspected", "accepted", "already_requested", "already_terminal", "finishing", "completed", "error"], request_status: ["accepted", "not_accepted", "unknown"], - recorded_state: ["planned", "unfinished", "succeeded", "failed", "cancelled", "unknown"], + recorded_state: ["planned", "unfinished", "awaiting", "succeeded", "failed", "cancelled", "unknown"], cleanup: ["pending", "complete", "unknown"], external_completion: ["not_verified"], }; @@ -147,7 +147,7 @@ function parseResult(done: Exit, operation: "inspect" | "cancel", wait: boolean) throw new Error("unknown result enum"); } if (data.outcome === "completed" && (data.invocation_id === null || data.cleanup !== "complete" - || !["succeeded", "failed", "cancelled"].includes(data.recorded_state as string))) { + || !["awaiting", "succeeded", "failed", "cancelled"].includes(data.recorded_state as string))) { throw new Error("completion lacks invocation, cleanup or terminal evidence"); } if (operation === "inspect") { diff --git a/js/fx/src/documents.ts b/js/fx/src/documents.ts index d06625f7..409e2779 100644 --- a/js/fx/src/documents.ts +++ b/js/fx/src/documents.ts @@ -200,6 +200,7 @@ export interface CallRecovery extends RunEvent { /** The `run_finished` event. */ export interface RunFinished extends RunEvent { + awaiting?: string[]; event: "run_finished"; ok: boolean; incomplete: boolean; @@ -212,7 +213,8 @@ export interface RunFinished extends RunEvent { /** One instance in {@link Projection}. */ export interface ProjectedInstance { /** `waiting`: started, its paid call waiting for its route's slot (older records never have it). */ - state: "running" | "waiting" | "succeeded" | "failed" | "skipped"; + state: "running" | "waiting" | "awaiting" | "succeeded" | "failed" | "skipped"; + request_id?: string; path: string; /** Waiting: the route it waits for. */ waiting_for?: string | null; @@ -240,7 +242,7 @@ export interface Projection { export interface InspectedStep { id: string; path: string; - state: "succeeded" | "failed" | "skipped" | "running" | "waiting" | "pending"; + state: "succeeded" | "failed" | "skipped" | "running" | "waiting" | "awaiting" | "pending"; error?: string; cache?: "hit" | "miss"; /** Waiting: the route whose slot it waits for. */ @@ -253,10 +255,12 @@ export interface InspectedStep { /** `grida-fx inspect --json`: a run's summary. */ export interface Inspection { run: { + /** Recorded external requests when the workflow has opened any. */ + requests?: import("./waiting.js").WaitingRequest[]; workflow: string; /** The run folder, as it was named. */ folder: string; - state: "planned" | "unfinished" | "succeeded" | "failed" | "cancelled"; + state: "planned" | "unfinished" | "awaiting" | "succeeded" | "failed" | "cancelled"; /** What the run was charged; null before it ended. */ charged_usd: number | null; steps: InspectedStep[]; diff --git a/js/fx/src/engine.ts b/js/fx/src/engine.ts index d09ee3ad..7473f7a2 100644 --- a/js/fx/src/engine.ts +++ b/js/fx/src/engine.ts @@ -75,13 +75,12 @@ export function hostVariables(): Record { return variables; } -/** Runs the engine with `args` and collects what it prints. `stdin`, a socket, becomes the - * engine's standard input (a stand-in run's): it is closed here once the engine holds it, so the - * engine alone keeps that end open. */ +/** Run the engine and collect its output. A string is written to its standard input. + * A stand-in socket is transferred to the engine and closed here once the child holds it. */ export async function call( args: readonly string[], options: CallOptions = {}, - stdin?: Socket, + stdin?: Socket | string, ): Promise { const cwd = options.cwd ?? process.cwd(); // An explicit `options.env` wins over the host variables. @@ -98,13 +97,23 @@ export async function call( const child = spawn(engine, [...args], { cwd, env, - stdio: [stdin ?? "ignore", "pipe", "pipe"], + stdio: [typeof stdin === "string" ? "pipe" : stdin ?? "ignore", "pipe", "pipe"], }); - stdin?.destroy(); + if (typeof stdin === "string") { + // Early command refusal can close stdin before the answer is fully read. + child.stdin!.on("error", (error: NodeJS.ErrnoException) => { + if (error.code !== "EPIPE") reject(error); + }); + child.stdin!.end(stdin); + } else { + stdin?.destroy(); + } const stdout: Buffer[] = []; const stderr: Buffer[] = []; - child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk)); - child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk)); + const output = child.stdout!; + const errors = child.stderr!; + output.on("data", (chunk: Buffer) => stdout.push(chunk)); + errors.on("data", (chunk: Buffer) => stderr.push(chunk)); let killTimer: NodeJS.Timeout | undefined; let interrupted = false; const onAbort = () => { @@ -142,8 +151,8 @@ export async function call( const closed = new Promise((done) => child.once("close", () => done())); const drained = new Promise((done) => setTimeout(done, DRAIN_MS).unref()); void Promise.race([closed, drained]).then(() => { - child.stdout.destroy(); - child.stderr.destroy(); + output.destroy(); + errors.destroy(); if (options.signal?.aborted) { reject(options.signal.reason); return; diff --git a/js/fx/src/index.ts b/js/fx/src/index.ts index 34c08532..ed7dacb8 100644 --- a/js/fx/src/index.ts +++ b/js/fx/src/index.ts @@ -65,6 +65,7 @@ export { } from "./api.js"; export { BINARY_VARIABLE, type BinaryOptions, binary, type Environment } from "./binary.js"; export { cancel, type CancelOptions, inspectControl, RunControlError, type RunControlResult } from "./control.js"; +export { AnswerError, type AnswerState, type WaitingRequest, inspectRequests, listRequests, respond } from "./waiting.js"; export { loadRun, type ObservedRunEvent, type RunEventBatch, type RunEventsOptions, type RunFollowOptions, RunObservationError, type RunObservationFailure, diff --git a/js/fx/src/request.ts b/js/fx/src/request.ts index 05f07bfd..7d7241e2 100644 --- a/js/fx/src/request.ts +++ b/js/fx/src/request.ts @@ -39,6 +39,8 @@ export interface RunOptions extends PlanOptions { readonly live?: boolean; /** Stop before a later phase that may take the run past this amount (`--yes-up-to`). */ readonly yesUpTo?: number | string; + /** Keep this invocation attached while external requests are pending. */ + readonly waitForAnswers?: boolean; /** The run folder, relative to `cwd` (`--run`); a folder holding a run of the same plan is * resumed. Default: a new folder under the project's runs folder. */ readonly runDir?: string; @@ -145,6 +147,10 @@ export function runArgs(options: RunOptions): string[] { if (options.live !== undefined && typeof options.live !== "boolean") { throw new TypeError(`live is true or false, not ${JSON.stringify(options.live)}`); } + if (options.waitForAnswers !== undefined && typeof options.waitForAnswers !== "boolean") { + throw new TypeError("waitForAnswers is true or false"); + } + if (options.waitForAnswers) args.push("--wait-for-answers"); if (options.recover !== undefined && typeof options.recover !== "boolean") { throw new TypeError("recover is true or false"); } diff --git a/js/fx/src/runs.ts b/js/fx/src/runs.ts index 381d2476..b2a71bd5 100644 --- a/js/fx/src/runs.ts +++ b/js/fx/src/runs.ts @@ -17,6 +17,7 @@ export type RunPlacement = "allocated" | "named" | "explicit" | "external"; export type RunState = | "planned" | "unfinished" + | "awaiting" | "succeeded" | "failed" | "incomplete" @@ -129,7 +130,7 @@ const LIST_KIND = "fx-run-list-v1"; const REMOVAL_KIND = "fx-run-removal-v1"; const PLACEMENTS: readonly string[] = ["allocated", "named", "explicit", "external"]; const STATES: readonly string[] = [ - "planned", "unfinished", "succeeded", "failed", "incomplete", "cancelled", "empty", "removing", "missing", + "planned", "unfinished", "awaiting", "succeeded", "failed", "incomplete", "cancelled", "empty", "removing", "missing", ]; const PREVIEW_OUTCOMES: readonly string[] = ["would_remove", "would_forget", "refused"]; const APPLIED_OUTCOMES: readonly string[] = ["removed", "forgotten", "refused", "partial"]; diff --git a/js/fx/src/waiting.ts b/js/fx/src/waiting.ts new file mode 100644 index 00000000..ed996d3b --- /dev/null +++ b/js/fx/src/waiting.ts @@ -0,0 +1,112 @@ +/** External answers to a concrete waiting step. */ +import { call, failure, type CallOptions, type Exit } from "./engine.js"; +import { FxError } from "./errors.js"; +import type { JsonSchemaObject } from "./node.js"; +import { checkValue, isPlainObject } from "./protocol.js"; +import type { JsonInput, JsonValue } from "./workflow.js"; + +export type AnswerState = + | { readonly status: "pending" } + | { readonly status: "answered"; readonly answer: JsonValue; readonly channel: "cli" | "sdk" | "viewer"; readonly at: string } + | { readonly status: "expired"; readonly at: string }; + +export interface WaitingRequest { + readonly id: string; + readonly step: string; + readonly message?: string; + readonly schema: JsonSchemaObject | boolean; + readonly choices?: Readonly>; + readonly show: JsonValue; + readonly choice_field?: string; + readonly timeout_seconds?: number; + readonly on_timeout: "fail" | "continue"; + readonly opened_at: string; + readonly deadline?: string; + readonly state: AnswerState; +} + +export class AnswerError extends FxError { + constructor( + readonly code: string, + message: string, + readonly request: WaitingRequest | undefined, + status: number, + ) { + super(message, { exitCode: status }); + this.name = "AnswerError"; + } +} + +function readReply(verb: string, done: Exit): Record { + try { + const body: unknown = JSON.parse(done.stdout); + if (isPlainObject(body)) return body; + } catch { + // A malformed engine reply is reported with its exit status below. + } + throw failure(verb, done); +} + +function isRequest(value: unknown): value is WaitingRequest { + if (!isPlainObject(value) || typeof value.id !== "string" || !/^[0-9a-f]{64}$/.test(value.id) + || typeof value.step !== "string" || typeof value.opened_at !== "string" + || !(typeof value.schema === "boolean" || isPlainObject(value.schema)) || !("show" in value) + || (value.on_timeout !== "fail" && value.on_timeout !== "continue") + || ["message", "choice_field", "deadline"].some(key => key in value && typeof value[key] !== "string") + || ("choices" in value && !isPlainObject(value.choices)) + || ("timeout_seconds" in value && !(typeof value.timeout_seconds === "number" + && Number.isSafeInteger(value.timeout_seconds) && value.timeout_seconds > 0))) return false; + const state = value.state; + if (!isPlainObject(state)) return false; + if (state.status === "pending") return true; + if (typeof state.at !== "string") return false; + return state.status === "expired" || (state.status === "answered" && "answer" in state + && (state.channel === "cli" || state.channel === "sdk" || state.channel === "viewer")); +} + +async function requestInspection(run: string, options: CallOptions, viewer?: "--register" | "--viewer-url") { + const args = ["inspect", "--requests", "--json"]; + if (viewer) args.push(viewer); + const done = await call([...args, "--", run], options); + if (done.status !== 0) throw failure("inspect", done); + const result = readReply("inspect", done); + if (!Array.isArray(result.requests) || !result.requests.every(isRequest)) throw failure("inspect", done); + const url = viewer ? result.viewer_url : null; + if (url !== null && typeof url !== "string") throw failure("inspect", done); + return { requests: result.requests, viewer_url: url }; +} + +/** Inspect requests and discover the local viewer URL. Registration is explicit. */ +export async function inspectRequests( + run: string, options: CallOptions & { register?: boolean } = {}, +): Promise<{ + requests: WaitingRequest[]; + viewer_url: string | null; +}> { + return requestInspection(run, options, options.register ? "--register" : "--viewer-url"); +} + +/** List pending and resolved requests in the exact run folder or workflow/name. */ +export async function listRequests(run: string, options: CallOptions = {}): Promise { + return (await requestInspection(run, options)).requests; +} + +/** Record a schema-validated answer. Conflicts and expirations retain the winning request. */ +export async function respond( + run: string, requestId: string, answer: JsonInput, options: CallOptions = {}, +): Promise { + checkValue(answer); + const done = await call( + ["respond", "--source=sdk", "--json=-", "--", run, requestId], options, JSON.stringify(answer), + ); + const receipt = readReply("respond", done); + const request = receipt.request; + if (request !== undefined && (!isRequest(request) || request.id !== requestId)) throw failure("respond", done); + if (done.status === 0 && request?.state.status === "answered") return request; + if ((done.status === 1 || done.status === 2) && typeof receipt.code === "string" && typeof receipt.message === "string") { + if ((receipt.code === "answer_conflict" && request?.state.status !== "answered") + || (receipt.code === "expired" && request?.state.status !== "expired")) throw failure("respond", done); + throw new AnswerError(receipt.code, receipt.message, request, done.status); + } + throw failure("respond", done); +} diff --git a/js/fx/test/control.test.ts b/js/fx/test/control.test.ts index eff4017d..d7ef8584 100644 --- a/js/fx/test/control.test.ts +++ b/js/fx/test/control.test.ts @@ -3,8 +3,8 @@ import { spawnSync } from "node:child_process"; import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { call } from "../src/engine.js"; -import { cancel, FxError, inspectControl, RunControlError } from "../src/index.js"; -import type { CancelOptions, RunControlResult } from "../src/index.js"; +import { AnswerError, cancel, FxError, inspectControl, inspectRequests, listRequests, respond, RunControlError } from "../src/index.js"; +import type { CancelOptions, RunControlResult, WaitingRequest } from "../src/index.js"; import { SLOW, temporaryFolder } from "./support.js"; const NODE = spawnSync("node", ["--version"]).status === 0; @@ -78,6 +78,42 @@ async function until(check: () => boolean): Promise { } describe.skipIf(!NODE || process.platform === "win32")("exact-target run control", () => { + test("waiting clients verify listed requests, viewer handoffs and the exact submission receipt", async () => { + const engine = fake(); + try { + const run = "test/one"; + const id = "a".repeat(64); + const at = "2026-11-22T00:00:00Z"; + const pending = { id, step: "review#1", schema: true, show: null, on_timeout: "fail", opened_at: at, state: { status: "pending" } } satisfies WaitingRequest; + const answer = ["proof"] as const; + const winner = { ...pending, state: { status: "answered", answer: [...answer], channel: "sdk", at } } satisfies WaitingRequest; + for (const stdout of ["broken", '{"requests":[null]}', '{"requests":[{"state":{"status":"pending"}}]}']) { + engine.reply({ stdout }); + await expect(listRequests(run, engine.options)).rejects.toBeInstanceOf(FxError); + } + engine.reply({ stdout: JSON.stringify({ requests: [pending] }) }); + expect(await listRequests(run, engine.options)).toEqual([pending]); + await expect(inspectRequests(run, engine.options)).rejects.toBeInstanceOf(FxError); + engine.reply({ stdout: JSON.stringify({ requests: [], viewer_url: false }) }); + await expect(inspectRequests(run, engine.options)).rejects.toBeInstanceOf(FxError); + engine.reply({ stdout: JSON.stringify({ request: winner }) }); + expect(await respond(run, id, answer, engine.options)).toEqual(winner); + for (const [status, body] of [ + [0, { request: pending }], + [0, { request: { ...winner, id: "b".repeat(64) } }], + [1, { code: "answer_conflict", message: "Conflict", request: pending }], + [1, { code: "expired", message: "Expired" }], + ] as const) { + engine.reply({ status, stdout: JSON.stringify(body) }); + const error = await respond(run, id, answer, engine.options).catch((e: unknown) => e); + expect(error).toBeInstanceOf(FxError); + expect(error).not.toBeInstanceOf(AnswerError); + } + } finally { + engine.cleanup(); + } + }); + test("forwards options and preserves inspect, acceptance and terminal result", async () => { const engine = fake(); try { @@ -94,6 +130,9 @@ describe.skipIf(!NODE || process.platform === "win32")("exact-target run control const completed = await cancel("runs/one", { ...engine.options, wait: true, timeout: "2m" }); expect(completed.recorded_state).toBe("failed"); expect(completed.external_completion).toBe("not_verified"); + engine.reply({ stdout: JSON.stringify(result("cancel", { outcome: "completed", recorded_state: "awaiting", cleanup: "complete" })) }); + const parked = await cancel("runs/one", { ...engine.options, wait: true, timeout: "2m" }); + expect(parked.recorded_state).toBe("awaiting"); expect(engine.log().at(-1)?.args).toEqual(["cancel", "runs/one", "--source=sdk", "--wait", "--timeout=2m", "--json"]); } finally { engine.cleanup(); diff --git a/js/fx/test/waiting.test.ts b/js/fx/test/waiting.test.ts new file mode 100644 index 00000000..84d3a04a --- /dev/null +++ b/js/fx/test/waiting.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { AnswerError, inspectRequests, listRequests, respond, run } from "../src/index.js"; +import { SLOW, temporaryFolder, testEngine } from "./support.js"; + +const engine = testEngine(); + +test.skipIf(engine === null)("answer another invocation and recover the recorded SDK decision", async () => { + const folder = temporaryFolder("sdk-waiting"); + try { + const options = { + cwd: folder.path, + env: { GRIDA_FX_BIN: engine!, GRIDA_FX_NETWORK: "off", GRIDA_FX_DISABLE_DOTENV: "1" }, + }; + writeFileSync(join(folder.path, "fx.yaml"), "fx: project/v1\n"); + writeFileSync(join(folder.path, "workflow.yaml"), JSON.stringify({ + fx: "workflow/v1", id: "decision", title: "Review", + steps: { + gate: { uses: "fx/await@1", with: { + message: "Approve this step?", schema: { type: ["boolean", "null"] }, timeout_seconds: 20, + } }, + revision: { uses: "fx/await@1", with: { schema: { type: "string" } } }, + }, + outputs: { result: "${{ steps.gate.outputs.answer }}", revision: "${{ steps.revision.outputs.answer }}" }, + })); + const selector = "decision/review"; + const parked = await run("workflow.yaml", { ...options, name: "review" }); + expect(parked.incomplete).toBe(true); + expect(parked.inspection.run.state).toBe("awaiting"); + const requests = await listRequests(selector, options); + const request = requests.find(item => item.step === "gate#1"); + const revision = requests.find(item => item.step === "revision#1"); + expect(request!.state.status).toBe("pending"); + expect(revision!.schema).toEqual({ type: "string" }); + expect(revision).not.toHaveProperty("message"); + expect((await inspectRequests(selector, options)).viewer_url).toBeNull(); + expect((await inspectRequests(selector, { ...options, register: true })).viewer_url).toBeNull(); + await respond(selector, revision!.id, "build-104", options); + const execution = run("workflow.yaml", { ...options, resume: "review", waitForAnswers: true }); + const winner = await respond(selector, request!.id, null, options); + expect(winner.state).toMatchObject({ status: "answered", channel: "sdk", answer: null }); + expect(await respond(selector, request!.id, null, options)).toEqual(winner); + const conflict = await respond(selector, request!.id, false, options).catch(error => error); + expect(conflict).toBeInstanceOf(AnswerError); + expect(conflict.code).toBe("answer_conflict"); + expect(conflict.request).toEqual(winner); + const result = await execution; + expect(result.ok).toBe(true); + expect(result.outputs.revision).toBe("build-104"); + } finally { + folder.cleanup(); + } +}, SLOW); diff --git a/llms.txt b/llms.txt index 83951513..592f8f9a 100644 --- a/llms.txt +++ b/llms.txt @@ -180,6 +180,7 @@ workflow ID alone selects its latest run. | Run local work or admit paid calls | `grida fx run TARGET`. After approval, add `--live --max-usd N` for dollar-billed work. `--yes-up-to N` adds an approval gate for later phases. | | Run with simulated provider answers | `grida fx run TARGET --stand-in FILE#FUNCTION`. A stand-in runs offline, uses a separate cache, and conflicts with `--live` and `--yes-up-to`. | | Inspect a result and verify files | `grida fx inspect RUN --verify --json`. Use `grida fx observe RUN --snapshot` or `grida fx observe RUN --after CURSOR` to read recorded state and events. | +| Supply external input during a run | An `fx/await@1` step declares `with.schema` and can add a human-readable `message`. List requests using `grida fx inspect RUN --requests --json` and submit `grida fx respond RUN REQUEST_ID --json JSON`. Use the exact folder or `WORKFLOW_ID/NAME`. Read the value from `outputs.answer`. An optional candidate map also yields `outputs.selected`. A parked run continues on `run --resume NAME`. With `--wait-for-answers` the attached runner continues automatically. [Waiting steps](https://github.com/gridaco/fx/blob/main/spec/waiting.md). | | Check or cancel one exact invocation | `grida fx inspect RUN --control --json`, then `grida fx cancel RUN --invocation ID --wait --json`. Use an exact run folder or `WORKFLOW_ID/NAME`. Local completion and provider completion are separate. See [run control](https://github.com/gridaco/fx/blob/main/docs/guide/08-run-control.md). | | Deliver or share outputs | `grida fx run TARGET --deliver output=path` copies declared outputs. Use `{key}` in the destination for keyed collections. `grida fx export RUN --out DIR --json` creates a portable export of a finished run. See [export disclosure options](https://github.com/gridaco/fx/blob/main/docs/guide/11-exports.md). | | Choose another result | `grida fx reroll RUN STEP` and `grida fx pick RUN STEP TAKE` change the selection for later runs. Re-plan before repeating the run because a new take or changed downstream work may cost money. | diff --git a/package.json b/package.json index a360386a..02d7f597 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "test:viewer:media-browser": "bun --no-env-file tools/check_media_preview_browser.mjs", "test:viewer:files-browser": "bun --no-env-file tools/check_external_files_browser.mjs", "test:viewer:notes-browser": "bun --no-env-file tools/check_notes_browser.mjs", + "test:viewer:waiting-browser": "bun --no-env-file tools/check_waiting_browser.mjs", "demo:viewer:media": "uv run --project python python tools/demo_media_previews.py" }, "devDependencies": { diff --git a/python/README.md b/python/README.md index 94fb4284..0e2a2506 100644 --- a/python/README.md +++ b/python/README.md @@ -486,3 +486,20 @@ one of `text` or `file`, plus optional `format="markdown"` (default) or `format= The SDK preserves declarations; the engine reads local files and records snapshots. Notes never evaluate expressions or execute as steps. See the [note contract](https://github.com/gridaco/fx/blob/main/spec/notes.md). + +## Answer a waiting step + +Use `run_async(..., name="review", wait_for_answers=True)` to keep a named run attached while another client supplies input. In the [waiting example](https://github.com/gridaco/fx/blob/main/fixtures/waiting/workflow.yaml), a build system supplies a revision without a prompt and a reviewer picks one of the saved images. + +```python +from grida import fx + +run = "review-variants/review" +pending = {r["step"]: r for r in fx.list_requests(run) if r["state"]["status"] == "pending"} +if revision := pending.get("revision#1"): + fx.respond(run, revision["id"], "rev-42") +if image := pending.get("choose#1"): + fx.respond(run, image["id"], {"variant": "b"}) +``` + +`list_requests(run)` reads the durable requests directly. For a viewer link, call `inspect_requests(run)`, or pass `register=True` to register the run too. The result includes `viewer_url` when the local service can serve the run. The request methods also have asynchronous forms. The engine checks every response against the saved schema and any frozen candidate keys. A conflicting submission raises `AnswerError` with the recorded winner. diff --git a/python/src/grida/fx/__init__.py b/python/src/grida/fx/__init__.py index 5eaf2936..db646a32 100644 --- a/python/src/grida/fx/__init__.py +++ b/python/src/grida/fx/__init__.py @@ -102,6 +102,15 @@ ) from grida.fx._spec import NodeSpec, PortSpec, SpecError, node, param, spec_of from grida.fx._stand_in import DECLINE, Answer, StandInCall +from grida.fx._waiting import ( + AnswerError, + inspect_requests, + inspect_requests_async, + list_requests, + list_requests_async, + respond, + respond_async, +) __all__ = [ "DECLINE", @@ -113,6 +122,7 @@ "AdapterRoute", "Agent", "Answer", + "AnswerError", "Answered", "CallFailed", "CallRefused", @@ -166,6 +176,10 @@ "inspect_control", "inspect_control_async", "list_runs", + "inspect_requests", + "inspect_requests_async", + "list_requests", + "list_requests_async", "list_runs_async", "list_files", "list_files_async", @@ -179,6 +193,8 @@ "remove_runs_async", "resolve_file", "resolve_file_async", + "respond", + "respond_async", "run", "run_async", "spec_of", diff --git a/python/src/grida/fx/_api.py b/python/src/grida/fx/_api.py index b2d54bf6..8fb14668 100644 --- a/python/src/grida/fx/_api.py +++ b/python/src/grida/fx/_api.py @@ -79,7 +79,7 @@ from dataclasses import dataclass, replace from decimal import Decimal from pathlib import Path -from typing import Any +from typing import Any, BinaryIO from grida.fx._builder import Workflow from grida.fx._protocol import ( @@ -794,7 +794,9 @@ async def _read_into(stream: asyncio.StreamReader | None, sink: bytearray) -> No sink.extend(chunk) -async def _call(args: Sequence[str], cwd: Path, stdin: socket.socket | None = None) -> _Exit: +async def _call( + args: Sequence[str], cwd: Path, stdin: socket.socket | BinaryIO | None = None +) -> _Exit: """Runs the binary, retaining ownership of a cancelled run until its engine has exited. Repeated task cancellation is the same request, never emergency force authority. Non-run commands keep their process-owned interruption and force deadline.""" @@ -824,7 +826,7 @@ async def _call(args: Sequence[str], cwd: Path, stdin: socket.socket | None = No async def _call_owned( args: Sequence[str], cwd: Path, - stdin: socket.socket | None = None, + stdin: socket.socket | BinaryIO | None = None, stop_requested: asyncio.Event | None = None, ) -> _Exit: """Runs the binary with ``args`` in ``cwd``. Its output is what it @@ -1237,6 +1239,7 @@ async def run_async( max_usd: float | None = None, require_estimates: bool = False, yes_up_to: float | None = None, + wait_for_answers: bool = False, run_dir: str | Path | None = None, name: str | None = None, resume: str | None = None, @@ -1285,6 +1288,10 @@ async def run_async( arguments=arguments, ) options = ["--live"] if live else [] + if not isinstance(wait_for_answers, bool): + raise TypeError("wait_for_answers is True or False") + if wait_for_answers: + options.append("--wait-for-answers") if yes_up_to is not None: options.append(f"--yes-up-to={_amount('yes_up_to', yes_up_to)}") if run_dir is not None: @@ -1379,6 +1386,7 @@ def run( max_usd: float | None = None, require_estimates: bool = False, yes_up_to: float | None = None, + wait_for_answers: bool = False, run_dir: str | Path | None = None, name: str | None = None, resume: str | None = None, @@ -1399,6 +1407,7 @@ def run( max_usd=max_usd, require_estimates=require_estimates, yes_up_to=yes_up_to, + wait_for_answers=wait_for_answers, run_dir=run_dir, name=name, resume=resume, diff --git a/python/src/grida/fx/_control.py b/python/src/grida/fx/_control.py index 8e6821d1..1e7af11d 100644 --- a/python/src/grida/fx/_control.py +++ b/python/src/grida/fx/_control.py @@ -140,7 +140,15 @@ def _result(document: Any, operation: str, wait: bool, status: int) -> RunContro enums = { "outcome": _OUTCOMES, "request_status": {"accepted", "not_accepted", "unknown"}, - "recorded_state": {"planned", "unfinished", "succeeded", "failed", "cancelled", "unknown"}, + "recorded_state": { + "planned", + "unfinished", + "awaiting", + "succeeded", + "failed", + "cancelled", + "unknown", + }, "cleanup": {"pending", "complete", "unknown"}, "external_completion": {"not_verified"}, } @@ -162,7 +170,7 @@ def _result(document: Any, operation: str, wait: bool, status: int) -> RunContro if outcome == "completed" and ( document["invocation_id"] is None or document["cleanup"] != "complete" - or document["recorded_state"] not in {"succeeded", "failed", "cancelled"} + or document["recorded_state"] not in {"awaiting", "succeeded", "failed", "cancelled"} ): raise ValueError("completion lacks invocation, cleanup or terminal evidence") if outcome == "error": diff --git a/python/src/grida/fx/_runs.py b/python/src/grida/fx/_runs.py index b001c098..1ec1e1c2 100644 --- a/python/src/grida/fx/_runs.py +++ b/python/src/grida/fx/_runs.py @@ -27,6 +27,7 @@ _STATES = { "planned", "unfinished", + "awaiting", "succeeded", "failed", "incomplete", diff --git a/python/src/grida/fx/_waiting.py b/python/src/grida/fx/_waiting.py new file mode 100644 index 00000000..23dcb8b1 --- /dev/null +++ b/python/src/grida/fx/_waiting.py @@ -0,0 +1,147 @@ +"""Discover and answer a workflow's run-scoped external requests.""" + +from __future__ import annotations + +import asyncio +import json +import re +import tempfile +from pathlib import Path +from typing import Any + +from grida.fx._api import FxError, _call, _Exit, _failure, _no_running_loop +from grida.fx._control import _target +from grida.fx._protocol import encode_message + + +class AnswerError(FxError): + """A refused submission. A conflict or expiry carries the recorded request.""" + + def __init__(self, receipt: dict[str, Any], status: int) -> None: + super().__init__(receipt["message"], status) + self.code: str = receipt["code"] + self.request: dict[str, Any] | None = receipt.get("request") + + +def _read_reply(verb: str, done: _Exit) -> dict[str, Any]: + try: + body = json.loads(done.stdout) + except ValueError: + raise _failure(verb, done) from None + if not isinstance(body, dict): + raise _failure(verb, done) + return body + + +def _is_request(value: Any) -> bool: + if not ( + isinstance(value, dict) + and isinstance(value.get("id"), str) + and re.fullmatch(r"[0-9a-f]{64}", value["id"]) + and isinstance(value.get("step"), str) + and isinstance(value.get("opened_at"), str) + and isinstance(value.get("schema"), bool | dict) + and "show" in value + and value.get("on_timeout") in ("fail", "continue") + and all( + key not in value or isinstance(value[key], str) + for key in ("message", "choice_field", "deadline") + ) + and ("choices" not in value or isinstance(value["choices"], dict)) + and ( + "timeout_seconds" not in value + or (type(value["timeout_seconds"]) is int and 0 < value["timeout_seconds"] < 2**53) + ) + ): + return False + state = value.get("state") + if not isinstance(state, dict): + return False + if state.get("status") == "pending": + return True + if not isinstance(state.get("at"), str): + return False + return state.get("status") == "expired" or ( + state.get("status") == "answered" + and "answer" in state + and state.get("channel") in ("cli", "sdk", "viewer") + ) + + +async def _request_inspection( + run: str | Path, cwd: str | Path | None, *options: str +) -> dict[str, Any]: + args = ["inspect", "--requests", "--json", *options, "--", _target(run)] + done = await _call(args, Path(cwd or ".").absolute()) + if done.status != 0: + raise _failure("inspect", done) + result = _read_reply("inspect", done) + if not isinstance(result.get("requests"), list) or not all( + _is_request(r) for r in result["requests"] + ): + raise _failure("inspect", done) + if options and ("viewer_url" not in result or not isinstance(result["viewer_url"], str | None)): + raise _failure("inspect", done) + return result + + +async def inspect_requests_async( + run: str | Path, *, cwd: str | Path | None = None, register: bool = False +) -> dict[str, Any]: + """Inspect requests and discover the local viewer URL. Registration is explicit.""" + return await _request_inspection(run, cwd, "--register" if register else "--viewer-url") + + +def inspect_requests( + run: str | Path, *, cwd: str | Path | None = None, register: bool = False +) -> dict[str, Any]: + """Inspect requests and their run's viewer URL synchronously.""" + _no_running_loop("inspect_requests") + return asyncio.run(inspect_requests_async(run, cwd=cwd, register=register)) + + +async def list_requests_async( + run: str | Path, *, cwd: str | Path | None = None +) -> list[dict[str, Any]]: + """List pending and resolved requests in an exact run folder or workflow/name.""" + return (await _request_inspection(run, cwd))["requests"] + + +def list_requests(run: str | Path, *, cwd: str | Path | None = None) -> list[dict[str, Any]]: + """List requests synchronously.""" + _no_running_loop("list_requests") + return asyncio.run(list_requests_async(run, cwd=cwd)) + + +async def respond_async( + run: str | Path, request_id: str, answer: Any, *, cwd: str | Path | None = None +) -> dict[str, Any]: + """Submit a JSON value and return the durably answered request.""" + args = ["respond", "--source=sdk", "--json=-", "--", _target(run), request_id] + with tempfile.TemporaryFile() as stream: + stream.write(encode_message(answer)) + stream.seek(0) + done = await _call(args, Path(cwd or ".").absolute(), stream) + receipt = _read_reply("respond", done) + request = receipt.get("request") + if "request" in receipt and (not _is_request(request) or request["id"] != request_id): + raise _failure("respond", done) + status = request["state"]["status"] if request is not None else None + if done.status == 0 and status == "answered": + return request + code = receipt.get("code") + if done.status in (1, 2) and isinstance(code, str) and isinstance(receipt.get("message"), str): + if (code == "answer_conflict" and status != "answered") or ( + code == "expired" and status != "expired" + ): + raise _failure("respond", done) + raise AnswerError(receipt, done.status) + raise _failure("respond", done) + + +def respond( + run: str | Path, request_id: str, answer: Any, *, cwd: str | Path | None = None +) -> dict[str, Any]: + """Submit an answer synchronously.""" + _no_running_loop("respond") + return asyncio.run(respond_async(run, request_id, answer, cwd=cwd)) diff --git a/python/tests/test_api.py b/python/tests/test_api.py index 07ea626c..abaf308c 100644 --- a/python/tests/test_api.py +++ b/python/tests/test_api.py @@ -1279,6 +1279,9 @@ def test_control_wrappers_forward_exact_target_options_and_preserve_outcomes( result = fx.cancel("runs/one", cwd=project, wait=True, timeout="2m") assert result.outcome == "completed" and result.recorded_state == "failed" assert result.external_completion == "not_verified" + parked = _control_result(outcome="completed", recorded_state="awaiting", cleanup="complete") + fake.reply(cancel={"stdout": json.dumps(parked)}) + assert fx.cancel("runs/one", cwd=project, wait=True, timeout="2m").recorded_state == "awaiting" assert fake.invocations[-1] == [ "cancel", "runs/one", @@ -1289,6 +1292,79 @@ def test_control_wrappers_forward_exact_target_options_and_preserve_outcomes( ] +def test_list_requests_only_discovers_a_viewer_for_explicit_inspection( + fake: Fake, project: Path +) -> None: + target = "revisions/build" + request = { + "id": D1, + "step": "revision#1", + "schema": {"type": "string"}, + "show": None, + "on_timeout": "fail", + "opened_at": "2026-11-22T00:00:00Z", + "state": {"status": "pending"}, + } + fake.reply(inspect={"stdout": json.dumps({"requests": [request]})}) + assert fx.list_requests(target, cwd=project) == [request] + assert fake.invocations[-1] == ["inspect", "--requests", "--json", "--", target] + + access = {"requests": [request], "viewer_url": None} + fake.reply(inspect={"stdout": json.dumps(access)}) + assert fx.inspect_requests(target, cwd=project) == access + assert fake.invocations[-1] == ["inspect", "--requests", "--json", "--viewer-url", "--", target] + assert fx.inspect_requests(target, cwd=project, register=True) == access + assert fake.invocations[-1] == ["inspect", "--requests", "--json", "--register", "--", target] + + +def test_respond_preserves_json_object_keys(fake: Fake, project: Path) -> None: + with pytest.raises(ValueError, match="key 1 is not a string"): + fx.respond("review/one", "a" * 64, {"options": {1: True}}, cwd=project) + assert fake.invocations == [] + + +def test_waiting_rejects_malformed_engine_replies(fake: Fake, project: Path) -> None: + run = "review/one" + for stdout in [ + "broken", + '{"requests":[null]}', + '{"requests":[{"state":{"status":"pending"}}]}', + ]: + fake.reply(inspect={"stdout": stdout}) + with pytest.raises(fx.FxError): + fx.list_requests(run, cwd=project) + for result in [{"requests": []}, {"requests": [], "viewer_url": False}]: + fake.reply(inspect={"stdout": json.dumps(result)}) + with pytest.raises(fx.FxError): + fx.inspect_requests(run, cwd=project) + at = "2026-11-22T00:00:00Z" + pending = { + "id": D1, + "step": "review#1", + "schema": True, + "show": None, + "on_timeout": "fail", + "opened_at": at, + "state": {"status": "pending"}, + } + winner = { + **pending, + "state": {"status": "answered", "answer": None, "channel": "sdk", "at": at}, + } + fake.reply(respond={"stdout": json.dumps({"request": winner})}) + assert fx.respond(run, D1, None, cwd=project) == winner + for status, result in [ + (0, {"request": pending}), + (0, {"request": {**winner, "id": D2}}), + (1, {"code": "answer_conflict", "message": "Conflict", "request": pending}), + (1, {"code": "expired", "message": "Expired"}), + ]: + fake.reply(respond={"status": status, "stdout": json.dumps(result)}) + with pytest.raises(fx.FxError) as err: + fx.respond(run, D1, None, cwd=project) + assert not isinstance(err.value, fx.AnswerError) + + def test_async_control_and_structured_errors(fake: Fake, project: Path) -> None: failure = _control_result( outcome="error", code="wait_timeout", message="local cleanup is still pending" diff --git a/python/tests/test_import.py b/python/tests/test_import.py index 7bef2a85..4e4ce1c3 100644 --- a/python/tests/test_import.py +++ b/python/tests/test_import.py @@ -12,6 +12,7 @@ def test_the_sdk_imports() -> None: "AdapterRoute", "Agent", "Answer", + "AnswerError", "Answered", "CallFailed", "CallRefused", @@ -64,6 +65,10 @@ def test_the_sdk_imports() -> None: "cancel_async", "inspect_control", "inspect_control_async", + "inspect_requests", + "inspect_requests_async", + "list_requests", + "list_requests_async", "list_runs", "list_runs_async", "list_files", @@ -78,6 +83,8 @@ def test_the_sdk_imports() -> None: "remove_runs_async", "resolve_file", "resolve_file_async", + "respond", + "respond_async", "run", "run_async", "spec_of", diff --git a/spec/README.md b/spec/README.md index e235c961..9e16d64d 100644 --- a/spec/README.md +++ b/spec/README.md @@ -19,6 +19,7 @@ These documents define FX independently of any implementation. The Rust engine, | [previews.md](previews.md) | Workflow-authored video selection and image posters, recorded per node instance without execution dependencies | | [model-previews.md](model-previews.md) | Read-only self-contained GLB inspection, camera and animation controls, local resources and format fallbacks | | [skip-reasons.md](skip-reasons.md) | Recorded engine causes for skipped nodes, related-instance references, lifecycle and portable presentation | +| [waiting.md](waiting.md) | External answer contracts, frozen choices, durable decisions, deadlines and resuming | | [control.md](control.md) | Local run control: exact invocation targeting, cancellation acceptance, verified local completion and force boundaries | | [sdk.md](sdk.md) | SDK user jobs: prepared model snapshots, named execution/resume, pinned saved records, independent observation and in-process stand-ins | | [call.md](call.md) | One-shot CLI capability calls, project route defaults, fresh execution, records and output delivery | diff --git a/spec/control.md b/spec/control.md index e60889b8..a71d327e 100644 --- a/spec/control.md +++ b/spec/control.md @@ -166,7 +166,7 @@ has begun; it does not report B's unfinished state as A's. | `already_requested` | This invocation already accepted cancellation. | 0 without `--wait` | | `already_terminal` | A terminal record already exists; no cancellation performed. | 0 without `--wait` | | `finishing` | The owner already committed to finishing; no cancellation performed. | 0 without `--wait` | -| `completed` | Matching terminal result and local completion receipt verified. The result may be succeeded, failed or cancelled. | 0 with `--wait` | +| `completed` | Matching terminal result and local completion receipt verified. The invocation may have succeeded, failed, been cancelled or parked awaiting a workflow answer. | 0 with `--wait` | | `error` | Refused, unsupported, unknown outcome, or unverified completion. | See codes below | Inspection exits 0 when it can report a valid observation, including known @@ -234,8 +234,8 @@ targeting; it is not isolation from malicious code already running as this user. The project service may later adapt this interface for a viewer action with explicit browser mutation protections. Observation HTTP endpoints remain -read-only; merely opening a run URL never authorizes cancellation. No browser -write endpoint, remote worker transport, broker or cloud supervisor is in v1. +read-only; merely opening a run URL never authorizes cancellation. Browser answering for a workflow-declared [waiting step](waiting.md) uses its run-scoped +HTTP endpoint. Cancellation remains available through local process control. ## 6. External work, signals and SDKs diff --git a/spec/exports.md b/spec/exports.md index d1838e10..a7dcffad 100644 --- a/spec/exports.md +++ b/spec/exports.md @@ -22,7 +22,7 @@ The observation reader captures the plan and complete event prefix. The latest invocation must start with `run_started` and end with `run_finished` or `run_cancelled`, and no unreadable or incomplete event tail may follow it. Refuse unfinished, crashed, malformed and actively resumed records. Failed terminal -runs are valid inspection sources. A terminal recording never appears live. +runs are valid inspection sources. A parked invocation ending in `run_finished.awaiting` can also be exported. Its recorded request state is frozen at that invocation, and opening the package cannot submit an answer. A terminal recording never appears live. `source.plan_sha256` hashes the exact saved UTF-8 `plan.json` bytes. `source.events_sha256` hashes the RFC 8785 canonical JSON encoding of the captured diff --git a/spec/identity.md b/spec/identity.md index 02b2501e..1501bff0 100644 --- a/spec/identity.md +++ b/spec/identity.md @@ -188,6 +188,10 @@ Up to and including the 0.6.1 release, the contract was hashed as the entry decl ## 8. Step identity +An [external waiting step](waiting.md) opens a request for each run and concrete +occurrence. Its decision replays only for that occurrence on same-run resume. +Downstream values continue to enter computation identities by content. + Each expanded step instance has an identity, the key of the result cache: ``` diff --git a/spec/observation.md b/spec/observation.md index 25ad88b1..32d9bbc7 100644 --- a/spec/observation.md +++ b/spec/observation.md @@ -87,6 +87,12 @@ Its additive `cancel_requested` event follows the unknown-event compatibility ru below. The bundled viewer derives cancellation intent from this event; its existing run-state enum remains unchanged. +A workflow-authored [waiting step](waiting.md) records `waiting_request` for the +instance and an invocation parked on external answers lists their IDs in +`run_finished.awaiting`. The inspection state for that step or parked run is +`awaiting`. A detached submission is visible in the request list immediately. +The runner records its observation when attached or resumed. + The additive `call_waiting` and `call_admitted` events ([store.md](store.md) §8, "Waiting for a route") follow the same rule. The `fx-viewer-run-v1` projection adds the instance state `waiting`: a started instance that has not ended and has an open diff --git a/spec/protocol.md b/spec/protocol.md index a8f09b68..c0a610f1 100644 --- a/spec/protocol.md +++ b/spec/protocol.md @@ -185,7 +185,9 @@ A param with neither `default` nor `x-fx-optional` is required, and a step that **Validation.** The engine validates every spec it receives against these rules and refuses an invalid one while planning. An SDK SHOULD refuse it when it is declared. -**Engine types.** The body-less built-ins belong to the engine: the paid capability types (`fx/image.generate@1`, …) and `fx/select@1`. A host never describes them, and the engine never sends `run` for them. +**Engine types.** The body-less built-ins belong to the engine: the paid capability types (`fx/image.generate@1`, …), `fx/select@1`, and [`fx/await@1`](waiting.md). A host never describes them, and the engine never sends `run` for them. + +An engine-native output can declare `value` or `value?` when its concrete type depends on the workflow. It carries one FX value, which can itself be JSON, a typed file, a list, a keyed collection or an object containing typed values. The optional form may be absent. The node catalog, plan and viewer use this notation for the `selected` output of `fx/await@1`. Host ports use the file families above. ## 5. Engine to host @@ -273,7 +275,7 @@ After the host answers, the engine: 2. checks the result: no undeclared output port, every non-optional port present, each value's shape matching its port; no fact named `cost_usd`, which is the engine's (step 5), no reserved marker in a fact or a mark (§3.2), every mark well formed as `annotate` requires (§6.4), and no fact or mark nested deeper than 509 arrays and objects, which the run's record could not hold. A failed check fails the node, with `-32602` for a refused fact or mark, and it is not retried. A result FX cannot read at all fails the node with `the node host answered run with something FX cannot read: ` and the first place that is not what §3.4 describes (`output : a file is {"work_path", "kind"?} or {"file": }`). 3. writes `{"kind": "fx-annotations-v1", "annotations": marks}` as the `annotations` output when the type declares one, the body returned none, and there are marks. 4. requires a judge's `verdict` node fact to be `accept` or `reject`. -5. stores the output files, sets the node fact `cost_usd`, and writes the result record (`fx-result-record-v1`) under the step identity when that is known. An output file under `work_dir` that cannot be read, or that changes while it is stored, fails the node: it is the body's, not the store's. The engine always writes `cost_usd` itself for a node a host ran: what this run booked for the node's calls (including conservative reservations when the provider reported no charge), or `null` when it booked none (a call answered from the cache costs nothing and counts as none; a stand-in's answer, §5.7, costs nothing and counts as paid, so a node it answered has `0`), the same value as the result record's `cost_usd` ([store.md](store.md) §3). `fx/select@1` and other engine types report no node facts. +5. stores the output files, sets the node fact `cost_usd`, and writes the result record (`fx-result-record-v1`) under the step identity when that is known. An output file under `work_dir` that cannot be read, or that changes while it is stored, fails the node: it is the body's, not the store's. The engine always writes `cost_usd` itself for a node a host ran: what this run booked for the node's calls (including conservative reservations when the provider reported no charge), or `null` when it booked none (a call answered from the cache costs nothing and counts as none; a stand-in's answer, §5.7, costs nothing and counts as paid, so a node it answered has `0`), the same value as the result record's `cost_usd` ([store.md](store.md) §3). The waiting step reports its resolution as `facts.outcome`. `fx/select@1` reports no node facts. **Failure.** The host answers `run` with an error: - `node_failure` when the body failed on purpose (Python: `raise ctx.fail(…)` or `NodeFailure`; TypeScript: `throw ctx.fail(…)` or a `NodeFailure`), or, in TypeScript, was given a param value its schema refuses, before it ran (§8.2), or loaded a source file outside its module's closure (§5.1); diff --git a/spec/schemas/fx-await-request-v1.schema.json b/spec/schemas/fx-await-request-v1.schema.json new file mode 100644 index 00000000..971457d7 --- /dev/null +++ b/spec/schemas/fx-await-request-v1.schema.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:grida-fx:schema:fx-await-request-v1", + "title": "Durable external answer request", + "type": "object", + "required": ["kind", "plan", "run", "request"], + "properties": { + "kind": { "const": "fx-await-request-v1" }, + "plan": { "$ref": "#/$defs/digest" }, + "run": { "type": "string", "pattern": "^[a-f0-9]{16}$" }, + "request": { "$ref": "#/$defs/request" } + }, + "$defs": { + "digest": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "timestamp": { "type": "string", "format": "date-time" }, + "request": { + "type": "object", + "required": ["id", "step", "schema", "show", "on_timeout", "opened_at", "state"], + "properties": { + "id": { "$ref": "#/$defs/digest" }, + "step": { "type": "string", "minLength": 1 }, + "message": { "type": "string", "minLength": 1 }, + "schema": { "type": ["object", "boolean"] }, + "show": {}, + "choices": { "type": "object", "minProperties": 1 }, + "choice_field": { "type": "string", "minLength": 1 }, + "timeout_seconds": { "type": "integer", "minimum": 1 }, + "on_timeout": { "enum": ["fail", "continue"] }, + "opened_at": { "$ref": "#/$defs/timestamp" }, + "deadline": { "$ref": "#/$defs/timestamp" }, + "state": { + "oneOf": [ + { "type": "object", "properties": { "status": { "const": "pending" } }, "required": ["status"], "additionalProperties": false }, + { + "type": "object", + "properties": { + "status": { "const": "answered" }, "answer": {}, + "at": { "$ref": "#/$defs/timestamp" }, "channel": { "enum": ["cli", "sdk", "viewer"] } + }, + "required": ["status", "answer", "at", "channel"], "additionalProperties": false + }, + { + "type": "object", "properties": { "status": { "const": "expired" }, "at": { "$ref": "#/$defs/timestamp" } }, + "required": ["status", "at"], "additionalProperties": false + } + ] + } + } + } + } +} diff --git a/spec/schemas/fx-graph-v1.schema.json b/spec/schemas/fx-graph-v1.schema.json index 986c8de2..3343a9bd 100644 --- a/spec/schemas/fx-graph-v1.schema.json +++ b/spec/schemas/fx-graph-v1.schema.json @@ -631,7 +631,7 @@ } }, "ports": { - "description": "Declared input/output file ports and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", + "description": "Declared file ports, engine-native value outputs and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", "type": "object", "additionalProperties": false, "required": [ @@ -659,7 +659,7 @@ }, "additionalProperties": { "type": "string", - "pattern": "^(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?\\??$" + "pattern": "^(?:value|(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?)\\??$" } }, "params": { diff --git a/spec/schemas/fx-graph-v2.schema.json b/spec/schemas/fx-graph-v2.schema.json index b7bbe612..12e8be00 100644 --- a/spec/schemas/fx-graph-v2.schema.json +++ b/spec/schemas/fx-graph-v2.schema.json @@ -769,7 +769,7 @@ } }, "ports": { - "description": "Declared input/output file ports and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", + "description": "Declared file ports, engine-native value outputs and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", "type": "object", "additionalProperties": false, "required": [ @@ -797,7 +797,7 @@ }, "additionalProperties": { "type": "string", - "pattern": "^(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?\\??$" + "pattern": "^(?:value|(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?)\\??$" } }, "params": { diff --git a/spec/schemas/fx-run-control-v1.schema.json b/spec/schemas/fx-run-control-v1.schema.json index f644626f..0a7ac07d 100644 --- a/spec/schemas/fx-run-control-v1.schema.json +++ b/spec/schemas/fx-run-control-v1.schema.json @@ -54,6 +54,7 @@ "enum": [ "planned", "unfinished", + "awaiting", "succeeded", "failed", "cancelled", @@ -152,6 +153,7 @@ }, "recorded_state": { "enum": [ + "awaiting", "succeeded", "failed", "cancelled" diff --git a/spec/schemas/fx-run-events-v1.schema.json b/spec/schemas/fx-run-events-v1.schema.json index a68484fa..91b843bf 100644 --- a/spec/schemas/fx-run-events-v1.schema.json +++ b/spec/schemas/fx-run-events-v1.schema.json @@ -22,6 +22,7 @@ "run_cancelled", "cancel_requested", "phase_planned", + "waiting_request", "node_started", "node_finished", "node_failed", @@ -57,6 +58,27 @@ "description": "The instance id.", "type": "string" }, + "request_id": { + "description": "The opaque waiting request ID, scoped to the run and step occurrence.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "request_status": { + "description": "The state of a waiting request as observed by this invocation.", + "enum": ["pending", "answered", "expired"] + }, + "deadline": { + "description": "The request's original absolute deadline when set.", + "type": "string", + "format": "date-time" + }, + "awaiting": { + "description": "Requests blocking this invocation when it returned at a waiting boundary.", + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + }, "path": { "type": "string" }, @@ -736,6 +758,22 @@ ] } }, + { + "if": { + "properties": { + "event": { + "const": "waiting_request" + } + } + }, + "then": { + "required": [ + "id", + "request_id", + "request_status" + ] + } + }, { "if": { "properties": { @@ -1126,7 +1164,7 @@ ] }, "ports": { - "description": "Declared input/output file ports and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", + "description": "Declared file ports, engine-native value outputs and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", "type": "object", "additionalProperties": false, "required": [ @@ -1154,7 +1192,7 @@ }, "additionalProperties": { "type": "string", - "pattern": "^(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?\\??$" + "pattern": "^(?:value|(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?)\\??$" } }, "params": { diff --git a/spec/schemas/fx-run-export-v1.schema.json b/spec/schemas/fx-run-export-v1.schema.json index cf70de39..114fece1 100644 --- a/spec/schemas/fx-run-export-v1.schema.json +++ b/spec/schemas/fx-run-export-v1.schema.json @@ -236,6 +236,7 @@ "enum": [ "pending", "running", + "awaiting", "succeeded", "failed", "skipped" @@ -315,6 +316,10 @@ "preview": { "$ref": "#/$defs/preview" }, + "review_outcome": { + "description": "Terminal outcome recorded for this version-one waiting step. Answer contents depend on the view's disclosure of outputs.", + "enum": ["answered", "expired"] + }, "skip_reason": { "$ref": "#/$defs/skip_reason" }, @@ -392,6 +397,17 @@ } }, "allOf": [ + { + "if": { "required": ["review_outcome"] }, + "then": { + "properties": { + "uses": { "type": "string", "pattern": "^fx/await@0*1$" }, + "state": { "enum": ["succeeded", "failed"] } + }, + "if": { "properties": { "state": { "const": "failed" } } }, + "then": { "properties": { "review_outcome": { "const": "expired" } } } + } + }, { "if": { "required": [ @@ -443,7 +459,7 @@ } }, "ports": { - "description": "Declared input/output file ports and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", + "description": "Declared file ports, engine-native value outputs and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", "type": "object", "additionalProperties": true, "required": [ @@ -471,7 +487,7 @@ }, "additionalProperties": { "type": "string", - "pattern": "^(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?\\??$" + "pattern": "^(?:value|(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?)\\??$" } }, "params": { @@ -786,6 +802,7 @@ "enum": [ "planned", "unfinished", + "awaiting", "succeeded", "failed", "cancelled" diff --git a/spec/schemas/fx-run-list-v1.schema.json b/spec/schemas/fx-run-list-v1.schema.json index 513ad000..780d9511 100644 --- a/spec/schemas/fx-run-list-v1.schema.json +++ b/spec/schemas/fx-run-list-v1.schema.json @@ -81,6 +81,7 @@ "enum": [ "planned", "unfinished", + "awaiting", "succeeded", "failed", "incomplete", diff --git a/spec/schemas/fx-run-removal-v1.schema.json b/spec/schemas/fx-run-removal-v1.schema.json index 296d6556..1e6775fc 100644 --- a/spec/schemas/fx-run-removal-v1.schema.json +++ b/spec/schemas/fx-run-removal-v1.schema.json @@ -161,6 +161,7 @@ "enum": [ "planned", "unfinished", + "awaiting", "succeeded", "failed", "incomplete", diff --git a/spec/schemas/fx-viewer-run-v1.schema.json b/spec/schemas/fx-viewer-run-v1.schema.json index 8134cda0..42e07519 100644 --- a/spec/schemas/fx-viewer-run-v1.schema.json +++ b/spec/schemas/fx-viewer-run-v1.schema.json @@ -51,6 +51,7 @@ "enum": [ "planned", "unfinished", + "awaiting", "succeeded", "failed", "cancelled" @@ -203,11 +204,12 @@ "pending", "running", "waiting", + "awaiting", "succeeded", "failed", "skipped" ], - "description": "`waiting` is a started instance that has not ended and has an open wait: a `call_waiting` not yet closed by the `call_admitted` of the same `call`, by the instance starting again or making a new attempt (`node_retry`), or by a new invocation (`run_started`) (store.md \u00a78). A body that makes several calls at once is `waiting` while any of them waits, though another may be drawing. `running` is any other started instance that has not ended." + "description": "`waiting` is a started instance that has not ended and has an open wait: a `call_waiting` not yet closed by the `call_admitted` of the same `call`, by the instance starting again or making a new attempt (`node_retry`), or by a new invocation (`run_started`) (store.md \u00a78). A body that makes several calls at once is `waiting` while any of them waits, though another may be drawing. `awaiting` is a waiting step whose latest recorded request status is pending. `running` is any other started instance that has not ended." }, "reads": { "type": "array", @@ -298,6 +300,10 @@ "preview": { "$ref": "#/$defs/preview" }, + "review_outcome": { + "description": "Terminal outcome recorded for this version-one waiting step. Answer contents depend on the view's disclosure of outputs.", + "enum": ["answered", "expired"] + }, "skip_reason": { "$ref": "#/$defs/skip_reason" }, @@ -375,6 +381,17 @@ } }, "allOf": [ + { + "if": { "required": ["review_outcome"] }, + "then": { + "properties": { + "uses": { "type": "string", "pattern": "^fx/await@0*1$" }, + "state": { "enum": ["succeeded", "failed"] } + }, + "if": { "properties": { "state": { "const": "failed" } } }, + "then": { "properties": { "review_outcome": { "const": "expired" } } } + } + }, { "if": { "required": [ @@ -430,7 +447,7 @@ } }, "ports": { - "description": "Declared input/output file ports and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", + "description": "Declared file ports, engine-native value outputs and JSON parameter schemas for display. Absent in older documents. Does not participate in identity.", "type": "object", "additionalProperties": false, "required": [ @@ -458,7 +475,7 @@ }, "additionalProperties": { "type": "string", - "pattern": "^(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?\\??$" + "pattern": "^(?:value|(?:image|audio|video|model|text|json|annotations|file)(?:/[a-z0-9.+-]+)?(?:\\[\\]|\\{\\})?)\\??$" } }, "params": { diff --git a/spec/sdk.md b/spec/sdk.md index 0ece136b..5dd075dd 100644 --- a/spec/sdk.md +++ b/spec/sdk.md @@ -66,6 +66,28 @@ The event's optional `original_charged_usd` is the amount FX booked for the orig Older records can lack the evidence needed to identify that amount, even when the run's accumulated spend is available. Recovery adds zero to that accumulated spend. +## Answer external requests + +Use `list_requests` / `listRequests` with an exact run directory or `workflow/name`. +Listing reads the run's request records without discovering a viewer. They include +the frozen schema and any authored message, reviewed values, choices, original +deadline and current state. Use `respond(run, request_id, answer)` for a durable +receipt. An engine refusal raises `AnswerError` with a machine-readable `code`. +Before submission, the SDK checks that it can encode the value. Python raises +`ValueError` for invalid JSON values, including a mapping with non-string keys. +JavaScript raises `TypeError` for values outside its SDK profile, including +integral numbers with magnitude greater than 2⁵³. +A conflict or expiry supplies the winning `request`. Python also supports the +`_async` forms. See [waiting steps](waiting.md). + +Pass `wait_for_answers=True` / `waitForAnswers: true` and an explicit run directory +or name before starting an asynchronous run. Once initialized, a second client can +inspect and respond while the execution call is pending. `inspect_requests` / +`inspectRequests` returns `{requests, viewer_url}`. Requesting registration +(`register=True` / `{register: true}`) makes an SDK-started run available to an +already running local project viewer. The URL is null when no verified viewer +is available. Neither inspection nor registration starts a server. + ## Provider-native calls and diagnostics A project node may declare and call a custom capability through `ctx.capability`; diff --git a/spec/service.md b/spec/service.md index 6f086440..bcfca6a4 100644 --- a/spec/service.md +++ b/spec/service.md @@ -384,6 +384,11 @@ plans in the same group. Older recorded running/unfinished runs remain visible without opening history; recorded state still does not prove process liveness. Resuming never promotes an old run as a new one. +For unfinished runs, the catalog displays `awaiting` while a locally recorded +workflow request is pending. Once all recorded requests are answered or expired, +it displays `unfinished` until an invocation records a new outcome. This +read-only projection uses the same deadlines as request inspection. + Under a selected entry route, `/api/view`, `/api/snapshot`, `/api/events`, and `/api/artifacts/DIGEST` retain their existing contracts and validation. Plans have no run observation or artifact bytes. Artifact URLs are confined to the selected @@ -391,12 +396,24 @@ entry. A wrong project or entry ID returns an error, never the current project's unrelated run. Browser readers use explicit scoped API bases and reject URLs outside that scope. The standalone root API remains supported. +For a live run, `GET /api/requests` lists external requests and their recorded state. +The bundled viewer can submit a JSON answer to `POST /api/requests/ID/respond` under +the same run. A write requires the exact loopback Host and matching browser Origin, +a JSON content type and the explicit `X-FX-Action: respond` header. The engine verifies +the exact run, request, schema and deadline. Private service-control credentials stay +inside the service. The authority is local-machine access, with no reviewer sign-in. +Project roots, plan pages and portable exports have no answer endpoint. +See [waiting steps](waiting.md) for the resolution and resume contract. + The bundled viewer uses an optional `X-FX-Run-Active: 1` response header for tab activity. An unfinished snapshot can carry it after a read-only owner handshake for the recorded invocation. An empty event batch can carry it when the caller supplies the observed `plan` digest and `invocation_id` and the same check succeeds. The signal is sampled independently of the event cursor and contains no private control data. +For a live run page, open requests from `GET /api/requests` take precedence over +this activity signal in the tab's icon and title. The request count reflects +answers and elapsed deadlines even while a run is parked. `GET /api/viewer_config` under the selected entry returns the owning project's current resolved display settings ([viewer.md](viewer.md#project-display-settings)), with diff --git a/spec/store.md b/spec/store.md index 5d27d25a..7ad8f2f4 100644 --- a/spec/store.md +++ b/spec/store.md @@ -276,7 +276,8 @@ them with their call keys, even when a step succeeded on retry. - **`plan.json`** is the fx-graph-v1 document that `grida-fx expand` prints, `types` included, with `plan` (the plan digest), `steps` (each declared step by its declaration path, with its declaration `order`), `inputs` and `view_origins` added, and `takes_file`: the POSIX path of the workflow's takes file relative to the planning project's root, which `reroll` and `pick` write to (found as *Repeating a run* says). A stand-in run's also has `"stand_in": true`; no other run's has the member. The first invocation writes it before any step runs, under a temporary name and then renamed (§6). Later invocations compare its `plan` and never rewrite it. An inline call records its `inline_workflow` and omits `takes_file`. A fresh call also records `fresh_id` ([identity.md](identity.md) §10). -- **`events.jsonl`** is the record, and the source of truth for every command that reads the run. Each line is one fx-run-events-v1 event, written as `canon(event)` and then one line feed (U+000A), oldest first. Each line is written whole and flushed before the run goes on, in one write. A line that cannot be written whole (a full disk can take part of one) MUST NOT stay: the engine cuts the file back to its length before the line, writes nothing more if it cannot, and stops the run, so no line ever follows part of a line. A last line without its line feed is a line an invocation began and never finished (it was killed): readers leave it out, and the next invocation cuts it off, says so, and appends after it. A resumed run appends lines under a new `invocation_id`. Lines are never rewritten or removed otherwise. Every line reads back as JSON ([identity.md](identity.md) §2, nested at most 512 deep): a node fact or mark nested deeper than 509 fails its node ([protocol.md](protocol.md) §5.3), and an encoded list (fx-run-events-v1 `encoded`) nested so deep that its `{"list": …}` levels would pass that is written once as `{"value": }`, which reads back as the same list. +- **`events.jsonl`** is the invocation record. It is authoritative for transitions recorded by the engine during execution. Each line is one fx-run-events-v1 event, written as `canon(event)` and then one line feed (U+000A), oldest first. Each line is written whole and flushed before the run goes on, in one write. A line that cannot be written whole (a full disk can take part of one) MUST NOT stay: the engine cuts the file back to its length before the line, writes nothing more if it cannot, and stops the run, so no line ever follows part of a line. A last line without its line feed is a line an invocation began and never finished (it was killed): readers leave it out, and the next invocation cuts it off, says so, and appends after it. A resumed run appends lines under a new `invocation_id`. Lines are never rewritten or removed otherwise. Every line reads back as JSON ([identity.md](identity.md) §2, nested at most 512 deep): a node fact or mark nested deeper than 509 fails its node ([protocol.md](protocol.md) §5.3), and an encoded list (fx-run-events-v1 `encoded`) nested so deep that its `{"list": …}` levels would pass that is written once as `{"value": }`, which reads back as the same list. +- **`awaiting/` and `awaiting.lock`.** [Waiting steps](waiting.md) defines the authoritative request records and their separate response lock. Request state survives invocation exit. A detached response changes the request record when it is accepted. A later invocation records its observation in `events.jsonl`. - **Waiting for a route.** A paid call takes its route's slot before each send: the route's `concurrency` and `requests_per_minute` ([providers.md](providers.md) §3). A call that cannot take one at once writes `call_waiting` (`id`, `capability`, `route`, and `call`, its key) before it waits, and `call_admitted` with the same members once it has the slot; a call admitted at once writes neither, so a run on unpaced routes records nothing more. A wait that the run's cancellation ends writes no `call_admitted`. A wait is open from its `call_waiting` until the `call_admitted` of the same call, or until the step starts again, makes a new attempt (`node_retry`) or its run a new invocation (`run_started`): a wait those leave behind is no longer the step's. Readers show a started step that has not ended and has an open wait as `waiting` rather than `running` (`inspect`, `project`, the viewer), and time the work a step did from its start less the time it waited. A step whose body makes several calls at once is shown `waiting` while any of them waits, though another may be drawing: the record names only calls that waited. - **`run.lock`** holds an exclusive operating-system file lock (`flock` on POSIX), taken without waiting, for as long as an invocation runs the folder. A second invocation that cannot take the lock is refused at once ("another invocation is running "). The lock ends with the process, so a crashed run leaves no stale lock. The file's content means nothing. It stays in place while the folder holds a run; a removal (§9) unlinks it last. An invocation that took the lock then checks that the file it locked is still the folder's `run.lock` (the same device and inode), and is refused otherwise (" was removed while this invocation started"), since that lock was taken on a folder that is gone. - **`files/`** gets an instance's output files when it succeeds, whether it ran or came from the cache, before its `node_finished` event is written. Each take of a step has a folder of its own (`` below), so `files/` holds every take's files and `inspect --verify` checks each against its record. @@ -419,7 +420,7 @@ Besides runs, the project can hold two leftovers. An **empty claim** is a folder A `plan.json` of another kind, a folder at a run's place that holds files but no `plan.json` (`no_plan`: it is searched for runs and never removed), a folder of the tree that cannot be read, a symbolic link or special file among the tree's folders, and a run index or catalog entry that cannot be read are reported as skipped, with the reason. -**States.** The list ([schemas/fx-run-list-v1.schema.json](schemas/fx-run-list-v1.schema.json)) gives each run its creation time (the first `run_started`'s, else, for a record older than that field or a run that never started, `plan.json`'s modification time; none for a leftover) and the state `inspect` reads from its log (`planned`, `unfinished`, `succeeded`, `cancelled`), with inspect's `failed` split in two: `incomplete` for a `run_finished` with `ok: false` and `incomplete: true`, which a later invocation can finish, and `failed` for every other. The leftovers are `empty`, `removing` and `missing`. A recorded `unfinished` says nothing about whether a process is running; only `run.lock` does. +**States.** The list ([schemas/fx-run-list-v1.schema.json](schemas/fx-run-list-v1.schema.json)) gives each run its creation time (the first `run_started`'s, else, for a record older than that field or a run that never started, `plan.json`'s modification time; none for a leftover) and the state `inspect` reads from its log (`planned`, `unfinished`, `succeeded`, `cancelled`), with unsuccessful finishes distinguished as `awaiting` for a `run_finished` with blocking `awaiting` request IDs, `incomplete` for other finishes with `ok: false` and `incomplete: true`, and `failed` for other failures. A detached response does not change the recorded finish. The leftovers are `empty`, `removing` and `missing`. A recorded `unfinished` says nothing about whether a process is running; only `run.lock` does. **Selecting runs to remove.** `runs remove` takes runs or filters, never both. - A run is a run folder, an empty claim or a tombstone that the list shows; `WORKFLOW_ID/NAME` of a named run, found by its place, so that an empty named claim is found too (a name of several sources is ambiguous); or a missing folder that the run index or the catalog still names, which is then only forgotten. Every run named is checked before anything is removed. One that is not a run, a folder that is or holds the project root, its `runs` folder, its store or `.fx`, and a folder that holds other runs fail the command, and nothing is removed. @@ -430,10 +431,10 @@ A `plan.json` of another kind, a folder at a run's place that holds files but no **Picks.** A run **holds a pick** when the takes file its `plan.json` names records a `result` for a step, and the run's log has a `node_finished` of that step's picked take whose result is that digest (the digest `pick` records: its first output port holding exactly one file). Stand-in runs hold none. The last run holding a pick is not removed: naming it is refused (`holds_pick`) and filters pass it over. Pick again, or keep the run. A run whose takes file exists but cannot be read may hold any pick, and is kept the same way. **Removing a run.** -1. The remover takes the folder's `run.lock` without waiting, making the file when the folder has none. A lock an invocation holds refuses the run (`active`). The locked file must still be the folder's `run.lock`, and the folder must still hold what was selected (the same workflow, source and creation time, or still only a claim); otherwise the run is refused (`changed`). A run folder or claim that holds anything FX did not write at its top (anything but `plan.json`, `events.jsonl`, `run.lock`, `files/`, `outputs/`, `views/`, `values/`, temporary names, `.DS_Store` and folders holding no file) is refused (`not_removable`): a run pointed at a folder of the user's keeps the user's files. +1. The remover takes the folder's `run.lock` without waiting, making the file when the folder has none. A lock an invocation holds refuses the run (`active`). It then takes `awaiting.lock` if it exists, to serialize removal with detached responses. The locked file must still be the folder's `run.lock`, and the folder must still hold what was selected (the same workflow, source and creation time, or still only a claim); otherwise the run is refused (`changed`). A run folder or claim that holds anything FX did not write at its top (anything but `plan.json`, `events.jsonl`, `run.lock`, `files/`, `outputs/`, `views/`, `values/`, temporary names, `.DS_Store`, folders holding no file and engine-managed waiting request files with their lock) is refused (`not_removable`): a run pointed at a folder of the user's keeps the user's files. 2. It removes the folder's run index entry, so a run that starts at the folder's place from now on records itself anew. 3. It renames the folder to a tombstone beside it, so the folder's place is free at once. A rename that fails refuses the run and changes nothing (`not_removable`; the index entry is written again). A tombstone that holds a run below its top, or a `run.lock` someone holds there (a run that started inside the folder since it was selected), is renamed back and the run refused (`changed`); when the folder's place was taken meanwhile, the tombstone stays as it is, and nothing in it is removed. A tombstone that is removed is checked the same way first. -4. It removes everything in the tombstone but `run.lock`: `plan.json` and `events.jsonl` first, so a tombstone never reads as a run. Placed files share their bytes with the store, so their permissions are never changed; only folders are made writable where needed. +4. It removes everything in the tombstone but `run.lock`: `plan.json` and `events.jsonl` first. A waiting response requires the original run path and matching lock. It refuses a tombstone even when those records still exist. Placed files share their bytes with the store, so their permissions are never changed; only folders are made writable where needed. 5. It lets the lock go, removes `run.lock`, then the tombstone. 6. It removes the catalog entries that bind the folder and its recorded identity ([service.md](service.md) §4). @@ -448,13 +449,13 @@ It is refused, before anything is removed and in the preview too, when: - `shared_cache`: `projects/` names a user other than the planning project, `legacy` included, or the store holds anything and has no `projects/`. `--forget-user

` drops a user once it no longer uses the store; the refusal names each; - `job_outstanding`: a job record is `submitting` or `submitted` (§5): collect it by running the workflow again, or forget it once the provider is checked; - `unreadable_store`: a folder or record of the store, or a job record, cannot be read: what it names would be taken to name nothing; -- the project's runs cannot all be read: a folder of the runs tree that cannot be read, or a symbolic link or special file among its folders (`incomplete_walk`), a `plan.json` of another kind (`foreign_run`), a run's `plan.json` or `events.jsonl` (`unreadable_run`), a run index or catalog entry (`unreadable_entry`), an external run folder that cannot be reached (`unreachable_run`) or that is gone (`missing_run`; `runs remove ` forgets it); +- the project's runs cannot all be read: a folder of the runs tree that cannot be read, or a symbolic link or special file among its folders (`incomplete_walk`), a `plan.json` of another kind (`foreign_run`), a run's `plan.json`, `events.jsonl` or waiting request records (`unreadable_run`), a run index or catalog entry (`unreadable_entry`), an external run folder that cannot be reached (`unreachable_run`) or that is gone (`missing_run`; `runs remove ` forgets it); - `legacy_interrupted_run`: an invocation of a run that is not a stand-in run ended with no `run_finished` or `run_cancelled` after a `budget_reserved` without `call`, so a paid answer it received may be named by no event, and no later invocation of the run succeeded; run it again to finish it, or remove it; - with `--yes`: `cache_in_use`, when the lock of either store, the `run.lock` of a run folder the project holds, or a work claim is held, and `lock_unsupported`, when the file system cannot lock. A folder at a run's place that holds files but no `plan.json` refuses nothing: what its `events.jsonl` names stays, in both stores. The `legacy` user also stands for this project's run folders outside its runs folder from before the run index, which pruning cannot see. A confirmed prune holds `.fx/runs/lock` while it reads the runs, so no removal runs meanwhile, and records its project among the store's users. -**What stays.** Every run's `plan.json` and `events.jsonl` name what it needs: file digests, step identities and call keys, each 64 lowercase hexadecimal characters. Every such token names what stays: the result record, call record or file of that name, in the run's store (the stand-in store for a stand-in run). So do the tokens of every record that stays and of every job record, until nothing new is named. This includes `recoverable`, `unavailable` and `settled` job records. A file the store holds that is linked from anywhere else (a link count above one, such as a run folder outside the project's knowledge) stays, with every record that names it. Every `budget_reserved` names the key of the call it holds money for (fx-run-events-v1), written before anything is sent, so a paid answer is named even when its `call` event never got written. +**What stays.** Every retained run's `plan.json`, `events.jsonl` and frozen reviewed values and choices in its waiting request records name what it needs: file digests, step identities and call keys, each 64 lowercase hexadecimal characters. Removal tombstones are not retained runs. Every such token names what stays: the result record, call record or file of that name, in the run's store (the stand-in store for a stand-in run). So do the tokens of every record that stays and of every job record, until nothing new is named. This includes `recoverable`, `unavailable` and `settled` job records. A file the store holds that is linked from anywhere else (a link count above one, such as a run folder outside the project's knowledge) stays, with every record that names it. Every `budget_reserved` names the key of the call it holds money for (fx-run-events-v1), written before anything is sent, so a paid answer is named even when its `call` event never got written. **What goes.** Every other result record, call record and file under `results/`, `calls/` and `files/`, records before files, and the leftovers of §6. Nothing else under the store root is touched: not `jobs/`, `projects/`, `lock` or a name that is not a digest. With `--yes` the stores are locked exclusively first, and everything above is checked and counted again under the lock. diff --git a/spec/viewer.md b/spec/viewer.md index a4ee565f..b90ddefc 100644 --- a/spec/viewer.md +++ b/spec/viewer.md @@ -4,6 +4,51 @@ Protocol v1 exposes inspection context and presentation in an existing viewer page. It does not execute workflows, mutate records or picks, launch processes, activate windows, or navigate to arbitrary sources. +## Answering a waiting step in the local viewer + +For a run, `GET /requests` returns `{"requests":[...]}` with the +pending, answered and expired [waiting requests](waiting.md). The browser polls this +resource independently of the invocation's event cursor. A second client can record +an answer after an invocation exits. Each request binds the optional message, answer schema, +reviewed inputs, any candidate keys and deadline to a concrete run and step. +The selected run's artifact inventory supplies names, previews and verified byte URLs. +The live canvas marks an awaiting step and opens its request from that card's +**Review** action. One request occupies the panel at a time. Dismissal preserves +the draft in the open page. A resolved request remains available from its card. +For a promptless request, use the step title or identifier as the review heading. +The viewer may render a scalar schema enum as a picker. It submits the literal +JSON value, preserving its type. Only a workflow-authored candidate mapping +binds a submitted key to an additional `selected` output. + +A completed `fx/await@1` instance can carry `review_outcome` alongside its +execution state in live and exported run views. Its terminal node event supplies +`facts.outcome`: `answered` for an answer, or `expired` for a deadline under +either timeout policy. A pending request, a receipt written while the runner is +stopped, or an older record without the terminal fact leaves this field absent. +A new start or retry of that instance clears the previous outcome. Cards may +describe a disclosed choice as selected or a disclosed boolean as yes or no. +When an export withholds answers, cards retain only the recorded outcome. + +The local viewer sends `POST /requests//respond` with +`Content-Type: application/json`, `X-FX-Action: respond` and a JSON object whose +only field is `answer`. JSON null and false are valid when the schema permits them. +The run-scoped server passes the answer to the same runtime operation as the CLI +and SDKs. HTTP 200 returns the durable request including its resolution. Invalid +answers return 422. A conflicting or late submission returns 409 with `code`, +`error` and the winning `request`. Retrying the same recorded answer returns 200. +An answer can be recorded while execution is stopped. Work resumes according to +the invocation lifecycle in [waiting.md](waiting.md). + +The server requires a loopback Host, the exact local Origin and the explicit +action header for submission. Browser fetch metadata, when present, must identify +a same-origin request. The server grants no cross-origin browser preflights. +The viewer's page protocol, portable exports and plan pages have no response +operation. Service and runner control tokens stay in private local coordination +state. This local HTTP interface trusts native programs with access to the +loopback listener. The browser protections guard against foreign web pages, and +the submission channel identifies the interface used. See [the service +boundary](service.md#5-http-boundary). + ## Recognizing a viewer document The engine-shipped viewer includes this marker in the initial HTML head for its diff --git a/spec/waiting.md b/spec/waiting.md new file mode 100644 index 00000000..b76c3095 --- /dev/null +++ b/spec/waiting.md @@ -0,0 +1,99 @@ +# Waiting steps + +A workflow uses `fx/await@1` to declare a JSON value that an external caller can supply during a run. The [request schema](schemas/fx-await-request-v1.schema.json) defines the durable record. The request belongs to the selected run and expanded step instance, including its item and take. A workflow may open several requests. Independent steps continue while their dependencies are ready. + +## Authoring + +| Setting in `with` | Meaning | +|---|---| +| `schema` | Required JSON Schema for the submitted value. The engine validates it locally for every submission channel. | +| `message` | Optional nonempty text describing what to supply. A promptless request omits this field in its record. | +| `show` | Optional reviewed values or artifact references. | +| `choices` | Optional keyed values. Freeze the actual mapping when the request opens. | +| `choice_field` | For object answers, the top-level member naming the chosen key. With choices and no field, the answer is the key string itself. | +| `timeout_seconds` | Optional positive window measured from first opening the request. | +| `on_timeout` | `fail` (default) or `continue`. | + +The minimal declaration is `with: { schema: { type: string } }`. A scalar `enum` +constrains the value directly. Use `choices` when a key binds the submission to a +specific candidate from this run. A submission must satisfy both constraints. +For a whole-answer key at least one offered key must satisfy the schema. For a +named choice field, reject directly detectable contradictions, such as requiring +a boolean where the key must be a string. Check known settings during planning +and check evaluated settings before persisting the request. Controls for selecting +or entering a value are a client decision. + +An answered step exposes `outputs.answer`, and `outputs.selected` when a choice was offered. The latter carries the original selected value, including its file identity. `facts.outcome` is `answered`. False and schema-permitted null are actual answers. On expiry with `continue`, the step reports `facts.outcome == 'expired'` without an answer. A workflow can run a normal conditional fallback using the reviewed candidates. Its existing route, admission and budget rules apply. No paid reservation or node worker is required during the wait. + +## Identity, scheduling and recovery + +A repeated waiting step honors its declared `concurrency`. At most that many +of its requests can be open at once. Other ready steps continue to run. + +Persist the schema, optional message and reviewed values before making a request available. Opening is idempotent across invocations of the same run. Distinct occurrences and fresh runs open independent requests, even for identical settings. The supplied value is run-local. Downstream computation uses its normal content-based identity. Resume verifies the existing plan and execution mode. Planning never opens a request. A branch conditional on the outcome uses the existing conditional cost range. Before the answer, the lower bound can omit the branch and the upper bound includes what it could spend. After resolution the engine prices the eligible work. + +When only outstanding requests block progress, the default invocation exits 1 (incomplete). Inspection reports `awaiting` and preserves completed work. With `run --wait-for-answers` the runner stays attached, dispatches eligible work on an answer or deadline, and remains cancellable. A foreground invocation owns its timer. After exit, the original deadline still governs new answers and the run continues on explicit resume. Reading the run or submitting a decision cannot start an invocation or change its spending authority. + +One durable resolution wins per request. Validate against both schema and frozen choices before committing. A rejected input leaves the request open. Retry of the same accepted JSON is idempotent, including after the deadline. A conflicting answer or late first answer reports the winning state. Time and channel describe the submission, without asserting the identity of a named reviewer. + +## Local interfaces + +`inspect RUN --requests --json` selects an exact folder or workflow/name and returns `{requests}`, including the winner of a resolved request. Listing reads request state independently of the viewer service. Add `--viewer-url` to look up an existing viewer link, or `--register` to register the run in the local project catalog. These explicit forms return `{requests, viewer_url}`. The URL is null until a verified project service can serve the registered run. + +`respond RUN REQUEST --json JSON` returns a JSON receipt. A successful first or duplicate answer exits 0. A refused answer exits 1 for `invalid_answer`, `answer_conflict`, `expired` or `not_found`. A malformed JSON input exits 2. Success returns `{request}`. A refusal returns `{code, message, request?}`, including the winning request on conflict or expiry. Use `--json=-` for standard input. Python and JavaScript expose the same operations. Passing an explicit run folder or name allows a second client to observe a pending SDK invocation. + +The live local viewer submits to a run-scoped JSON POST and polls for changes. The CLI, SDKs and viewer require no sign-in or credential setup. Preserve the loopback HTTP boundary, verify the browser origin for writes, and keep private control credentials out of browser documents, URLs and exports. An external agent can ask in chat and submit a user's answer while the viewer remains available to the user. Both clients observe the same recorded winner. + +## Storage + +The run's authoritative request records are in `awaiting/REQUEST_ID.json`. Each file is an +`fx-await-request-v1` object with `kind`, `plan` (the saved plan digest), `run` (the first +`run_started` invocation ID) and `request`. The request contains `id`, `step` (the concrete +instance ID), `schema`, `show`, optional `message`, `choices`, `choice_field` and +`timeout_seconds`, `on_timeout`, `opened_at`, optional `deadline` and `state`. Times are +absolute UTC RFC 3339 timestamps recorded at millisecond precision. The `deadline` is the +recorded opening time plus `timeout_seconds`. `state.status` is `pending`, `answered` or `expired`. +The evaluated request settings and the submitted JSON answer each have a 1 MiB limit. +Answers follow the same value rules as other workflow data. The engine rejects +[reserved runtime markers](identity.md#3-the-plain-projection) at any depth +and values nested beyond the run event's 509-level limit before recording an answer. +Pass large media as reviewed artifact references. +An answer stores `answer` (including explicit null), `channel` (`cli`, `sdk` or `viewer`) +and `at`. An expiry stores `at` equal to the deadline. + +The opaque ID is the SHA-256 digest of the canonical JSON array +`["fx-await-request-v1", plan, run, step]`. It identifies a request within the exact run and +does not grant authority to answer it. The schema is Draft 2020-12 with no external +resource retrieval. Reviewed values and candidate mappings use the portable run-event value +encoding for typed references, with an `object` form for typed nested members and optional +`verdicts` on collections. Explicit null is `{"value":null}`. Reopening under the same ID +checks the frozen schema, optional message, reviewed values, choices and timeout policy. A mismatch +is refused. + +`awaiting.lock` is an empty per-run operating-system lock. Within it, opening, answering +and expiring take one snapshot of the saved request, arbitrate by the engine clock and +atomically replace that request's file. A valid first response may be accepted only if the +engine sampled time before the deadline while holding the lock. It acknowledges after flushing +the file and publishing the replacement. Expiry and new answers serialize. Answer inputs use +the [FX JSON value profile](identity.md#1-values), and the engine compares retries using +canonical JSON. An equivalent response to an already answered request returns the saved +answer and original channel regardless of the current time. Listing requests can report an +elapsed deadline based on the current wall clock. Until a writer records expiry, that read-only +projection follows any system clock correction. Once a writer commits a resolution it is final. + +The runner retains its separate `run.lock`. A responder does not acquire `run.lock`, so it +can answer an attached or exited run. Run removal acquires `run.lock` before `awaiting.lock`. +Invocations alone append `waiting_request` events with the instance ID, request ID, observed +request status and optional deadline. That summary omits the message, schema, choices and +answer. A detached answer is visible to request inspection immediately and to invocation +events when an invocation next observes it. A quiescent invocation records its blocking +request IDs in `run_finished.awaiting`. Cancellation ends the invocation, leaving request +state and the deadline intact for the same recorded run. A response cannot resume an ended +invocation. + +Run-folder copies can retain request records alongside the plan and event log. The public +export does not copy the request files or make requests answerable. Any separately recorded +workflow values remain subject to the existing [export disclosure rules](exports.md). +For local review, the runner snapshots reviewed file bytes that might lack an ordinary output +placement and the viewer resolves them by recorded digest. Cache pruning keeps the digests +referenced by frozen reviewed values and choices. diff --git a/tools/check_viewer_browser.mjs b/tools/check_viewer_browser.mjs index 3dcdf893..c5d24172 100644 --- a/tools/check_viewer_browser.mjs +++ b/tools/check_viewer_browser.mjs @@ -69,7 +69,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) if (pathname.endsWith("/api/layout")) return new Response("No fixture report", { status: 404 }); if (pathname === "/viewer-client.js") return new Response(clientScript, { headers: { "Content-Type": "text/javascript" } }); if (pathname === "/host") return hostHtml(); - const asset = /\/(assets\/[^/]+|favicon(?:-active(?:-dim)?)?\.svg)$/.exec(pathname); + const asset = /\/(assets\/[^/]+|favicon(?:-active(?:-dim)?|-awaiting)?\.svg)$/.exec(pathname); return new Response(Bun.file(resolve(assets, asset?.[1] ?? "index.html"))); } }); const foreign = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: hostHtml }); diff --git a/tools/check_waiting.py b/tools/check_waiting.py new file mode 100755 index 00000000..64d3ca7c --- /dev/null +++ b/tools/check_waiting.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Exercise promptless SDK input, image review, and expiry in the same provider-free workflow.""" + +import argparse +import asyncio +import hashlib +import json +import os +import shutil +import subprocess +import tempfile +import time +from pathlib import Path + +from check_control import environment, validator +from grida import fx + +ROOT = Path(__file__).resolve().parents[1] +SELECTOR = "review-variants/review" + + +def by_step(requests: list[dict]) -> dict[str, dict]: + return {request["step"]: request for request in requests} + + +def check_delivery(folder: Path, revision: str, image_digest: str) -> None: + assert hashlib.sha256((folder / "outputs/image.png").read_bytes()).hexdigest() == image_digest + assert json.loads((folder / "outputs/manifest.json").read_text()) == { + "revision": revision, + "image_digest": image_digest, + } + + +def check_cli(command: Path, project: Path) -> None: + def call(*args: str, status: int = 0) -> str: + proc = subprocess.run( + [command, *args], cwd=project, capture_output=True, text=True, timeout=20, check=False + ) + assert proc.returncode == status, (args, proc.stdout, proc.stderr) + return proc.stdout + + def requests() -> dict[str, dict]: + result = json.loads(call("inspect", SELECTOR, "--requests", "--json")) + assert result.keys() == {"requests"} + return by_step(result["requests"]) + + def submit(request: dict, key: str, status: int = 0) -> dict: + return json.loads( + call( + "respond", + SELECTOR, + request["id"], + "--json", + json.dumps({"variant": key}), + status=status, + ) + ) + + call("plan", "showcase.yaml", "--check", "--max-usd", "0") + (project / "short.yaml").write_text("seconds: 1\n") + call("run", "workflow.yaml", "--name", "review", "--no-view", status=1) + opened = requests() + pending = opened["choose#1"] + revision = opened["revision#1"] + assert "message" not in revision and revision["schema"] == {"type": "string"} + assert pending["state"]["status"] == "pending" + run = json.loads(call("inspect", SELECTOR, "--json"))["run"] + assert run["state"] == "awaiting" and len(pending["choices"]) == 3 + folder = project / run["folder"] + graph = json.loads((folder / "plan.json").read_text()) + validator(graph["kind"]).validate(graph) + for request in opened.values(): + stored = folder / "awaiting" / (request["id"] + ".json") + validator("fx-await-request-v1").validate(json.loads(stored.read_text())) + assert submit(pending, "missing", 1)["code"] == "invalid_answer" + assert requests() == opened + revision_winner = fx.respond(SELECTOR, revision["id"], "rev-42", cwd=project) + assert revision_winner["state"]["channel"] == "sdk" + # Lose the first client's acknowledgment. A fresh client can recover exactly what won. + subprocess.run( + [command, "respond", SELECTOR, pending["id"], "--json", '{"variant":"b"}'], + cwd=project, + stdout=subprocess.DEVNULL, + check=True, + timeout=10, + ) + winner = fx.respond(SELECTOR, pending["id"], {"variant": "b"}, cwd=project) + assert winner["state"]["channel"] == "cli" + assert submit(pending, "b")["request"] == winner + assert submit(pending, "a", 1)["request"] == winner + call("run", "workflow.yaml", "--resume", "review", "--no-view") + check_delivery(folder, "rev-42", pending["choices"]["b"]["file"]["digest"]) + assert requests() == {"choose#1": winner, "revision#1": revision_winner} + event_schema = validator("fx-run-events-v1") + for line in (folder / "events.jsonl").read_text().splitlines(): + event_schema.validate(json.loads(line)) + + call( + "run", + "workflow.yaml", + "--name", + "expired", + "--inputs", + "short.yaml", + "--no-view", + status=1, + ) + expired_selector = "review-variants/expired" + opened = by_step(fx.list_requests(expired_selector, cwd=project)) + short = opened["choose#1"] + fx.respond(expired_selector, opened["revision#1"]["id"], "rev-43", cwd=project) + assert short["id"] != pending["id"] + limit = time.monotonic() + 10 + while ( + by_step(fx.list_requests(expired_selector, cwd=project))["choose#1"]["state"]["status"] + == "pending" + ): + assert time.monotonic() < limit, "the detached request did not expire" + time.sleep(0.05) + try: + fx.respond(expired_selector, short["id"], {"variant": "b"}, cwd=project) + except fx.AnswerError as error: + assert error.code == "expired" and error.request["state"]["at"] == short["deadline"] + else: + raise AssertionError("late approval was accepted") + expired = json.loads(call("inspect", expired_selector, "--json"))["run"] + expired_folder = project / expired["folder"] + assert not (expired_folder / "outputs/image.png").exists(), ( + "a detached response started the fallback" + ) + call("run", "workflow.yaml", "--resume", "expired", "--inputs", "short.yaml", "--no-view") + check_delivery(expired_folder, "rev-43", short["choices"]["c"]["file"]["digest"]) + + # A frozen choice may carry a file inside an ordinary object. Verification must + # check the selected step's placement independently of the producer's intact file. + (project / "bundle.yaml").write_text("""fx: workflow/v1 +id: bundle +title: Review an image bundle +steps: + draw: {uses: "./nodes.py#draw"} + choose: + uses: fx/await@1 + with: + schema: {type: string} + choices: + cover: {image: "${{ steps.draw.outputs.a }}"} +""") + target = "bundle/proof" + call("run", "bundle.yaml", "--name", "proof", "--no-view", status=1) + (request,) = fx.list_requests(target, cwd=project) + fx.respond(target, request["id"], "cover", cwd=project) + call("run", "bundle.yaml", "--resume", "proof", "--no-view") + inspected = json.loads(call("inspect", target, "--verify", "--json"))["run"] + selected = next(step for step in inspected["steps"] if step["id"] == "choose#1") + (placed,) = selected["files"] + assert placed["digest"] == request["choices"]["cover"]["object"]["image"]["file"]["digest"] + (project / inspected["folder"] / placed["path"]).rename(project / "saved-cover.png") + verified = json.loads(call("inspect", target, "--verify", "--json", status=1))["verification"] + assert verified == {"verified": False, "problems": [f"choose#1: {placed['path']} is missing"]} + + +async def check_sdk(project: Path) -> None: + folder = project / "sdk-run" + async with asyncio.timeout(30): + async with asyncio.TaskGroup() as group: + task = group.create_task( + fx.run_async("workflow.yaml", cwd=project, run_dir=folder, wait_for_answers=True) + ) + while not (folder / "plan.json").is_file(): + await asyncio.sleep(0.03) + while len(items := await fx.list_requests_async(folder, cwd=project)) < 2: + await asyncio.sleep(0.03) + opened = by_step(items) + request = opened["choose#1"] + revision = opened["revision#1"] + assert "message" not in revision and "choices" not in revision + info = await fx.inspect_requests_async(folder, cwd=project, register=True) + assert info == {"requests": items, "viewer_url": None} + try: + await fx.respond_async(folder, revision["id"], False, cwd=project) + except fx.AnswerError as error: + assert error.code == "invalid_answer" + else: + raise AssertionError("the promptless string request accepted a boolean") + await fx.respond_async(folder, revision["id"], "rev-44", cwd=project) + winner = await fx.respond_async(folder, request["id"], {"variant": "a"}, cwd=project) + assert winner["state"]["channel"] == "sdk" + assert task.result().ok + check_delivery(folder, "rev-44", request["choices"]["a"]["file"]["digest"]) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--command", type=Path, required=True) + command = parser.parse_args().command.resolve(strict=True) + env = environment() + os.environ.clear() + os.environ.update(env, GRIDA_FX_BIN=str(command)) + with tempfile.TemporaryDirectory(prefix="fx-waiting-") as tmp: + project = Path(tmp) / "project" + shutil.copytree(ROOT / "fixtures/waiting", project) + check_cli(command, project) + asyncio.run(check_sdk(project)) + print("Passed CLI and Python SDK waiting-step journeys.") + + +if __name__ == "__main__": + main() diff --git a/tools/check_waiting_browser.mjs b/tools/check_waiting_browser.mjs new file mode 100644 index 00000000..a19ec4dd --- /dev/null +++ b/tools/check_waiting_browser.mjs @@ -0,0 +1,483 @@ +#!/usr/bin/env bun +/** Exercise both race orders and disconnected clients through the bundled run viewer and CLI. */ +import assert from "node:assert/strict"; +import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { chromium } from "playwright-core"; +import { respond } from "../js/fx/dist/index.js"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const engine = process.env.GRIDA_FX_BIN ?? resolve(root, "target/debug/grida-fx"); +const directory = mkdtempSync(resolve(tmpdir(), "fx-review-browser-")); +const project = resolve(directory, "project"); +cpSync(resolve(root, "fixtures/waiting"), project, { recursive: true }); +const env = { + ...process.env, GRIDA_FX_NETWORK: "off", GRIDA_FX_DISABLE_DOTENV: "1", + GRIDA_FX_PYTHON: process.env.GRIDA_FX_PYTHON ?? resolve(root, "python/.venv/bin/python"), +}; +const cli = args => Bun.spawnSync([engine, ...args], { cwd: project, env }); +const json = args => { + const result = cli(args); + assert.equal(result.exitCode, 0, result.stderr.toString() || result.stdout.toString()); + return JSON.parse(result.stdout.toString()); +}; +const spawn = args => Bun.spawn([engine, ...args], { cwd: project, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" }); +async function eventually(check, description) { + const end = Date.now() + 20_000; + while (Date.now() < end) { + const result = await check(); + if (result) return result; + await Bun.sleep(100); + } + throw new Error(`Timed out waiting for ${description}`); +} + +function reviewCard(page, step) { + const card = page.locator(`[data-node-id="instance:${step}#1"]`); + return { + card, + review: card.getByRole("button", { name: /^Review(?: |$)/ }), + receipt: card.getByRole("button", { name: /^View answer(?: |$)/ }), + }; +} + +const reviewPanel = page => page.getByRole("complementary", { name: "Workflow requests" }); +async function assertPanelClosed(page) { + await reviewPanel(page).waitFor({ state: "hidden" }); + assert.equal(await page.getByRole("button", { name: "Submit answer" }).count(), 0); +} + +// Call with zero after the runner parks or finishes, when the ordinary run icon is idle. +async function waitForReviewTab(page, count) { + const title = count === 0 ? "Run" : count === 1 ? "Awaiting answer" : `Awaiting ${count} answers`; + const href = new URL(count ? "favicon-awaiting.svg" : "favicon.svg", page.url()).href; + await page.waitForFunction(({ title, href }) => { + const icon = document.querySelector('link[rel="icon"]'); + return document.title.startsWith(`${title} · `) && icon?.href === href; + }, { title, href }); + return href; +} + +// The service accepts fixed ports. Release an OS-selected loopback port immediately before binding. +const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response() }); +const port = probe.port; +await probe.stop(true); +const origin = `http://127.0.0.1:${port}`; +const service = spawn(["start", "--port", String(port)]); +let browser, runner, responder; +try { + await eventually(async () => (await fetch(`${origin}/api/catalog`).catch(() => null))?.ok, "project readiness"); + browser = await chromium.launch({ headless: true, ...(process.env.FX_CHROMIUM_EXECUTABLE ? { executablePath: process.env.FX_CHROMIUM_EXECUTABLE } : {}) }); + const context = await browser.newContext({ viewport: { width: 1280, height: 840 }, reducedMotion: "reduce" }); + await context.route("**/*", route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); + const home = await context.newPage(); + await home.goto(origin); + await home.getByRole("heading", { name: "Workflows", exact: true }).waitFor(); + for (const name of ["viewer-first", "agent-first", "agent-disconnected"]) { + const browserWins = name !== "agent-first"; + const attached = name === "viewer-first"; + const agentOnline = name !== "agent-disconnected"; + const target = `review-variants/${name}`; + runner = spawn(["run", "./workflow.yaml", "--name", name, "--no-view", ...(attached ? ["--wait-for-answers"] : [])]); + // The agent's CLI observes the exact named run before the foreground run call returns. + const pending = await eventually(() => { + const result = cli(["inspect", target, "--requests", "--json"]); + if (result.exitCode !== 0) return; + const { requests } = JSON.parse(result.stdout.toString()); + if (requests.length === 2) return requests; + }, "the variant and revision requests"); + const opened = pending.find(item => item.step === "choose#1"); + const revision = pending.find(item => item.step === "revision#1"); + assert.ok(opened && revision); + assert.equal(Object.hasOwn(revision, "message"), false); + if (!attached) assert.equal(await runner.exited, 1, "detached invocation returns incomplete"); + const access = json(["inspect", target, "--requests", "--register", "--json"]); + assert.deepEqual(access.requests, pending); + assert.equal(Object.hasOwn(json(["inspect", target, "--requests", "--json"]), "viewer_url"), false); + assert.equal(json(["inspect", target, "--requests", "--viewer-url", "--json"]).viewer_url, access.viewer_url); + const url = new URL(access.viewer_url); + assert.equal(url.origin, origin); + const page = await context.newPage(); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + if (attached) await page.emulateMedia({ reducedMotion: "no-preference" }); + await page.goto(url.href); + const panel = reviewPanel(page); + const runHeader = page.getByRole("navigation", { name: "Workflow location" }); + const homeRun = home.locator(`a.fx-project-entry[href="${url.pathname}"]`); + const choose = reviewCard(page, "choose"); + try { + await choose.review.waitFor({ timeout: 10_000 }); + await assertPanelClosed(page); + await waitForReviewTab(page, 2); + await reviewCard(page, "revision").review.click(); + await panel.getByRole("heading", { name: "Build revision", exact: true }).waitFor(); + const supplied = await respond(target, revision.id, "rev-42", { cwd: project, env: { ...env, GRIDA_FX_BIN: engine } }); + assert.equal(supplied.state.channel, "sdk"); + const revisionReceipt = panel.getByRole("status").filter({ hasText: "Answered via sdk" }); + await revisionReceipt.getByText("rev-42", { exact: true }).waitFor(); + await panel.getByRole("button", { name: "Close review" }).click(); + const icon = await waitForReviewTab(page, 1); + await runHeader.getByText("Awaiting answer", { exact: true }).waitFor(); + await homeRun.getByText("Awaiting answer", { exact: true }).waitFor(); + if (attached) { + const snapshot = await page.request.get(new URL("api/snapshot", url).href); + assert.equal(snapshot.headers()["x-fx-run-active"], "1", "the service should observe the attached runner"); + const asset = await page.request.get(icon); + assert.equal(asset.status(), 200); + assert.match(asset.headers()["content-type"], /^image\/svg\+xml\b/); + assert.match(await asset.text(), /]/); + // The live green icon normally alternates every 650 ms. Amber must remain steady. + const changes = await page.evaluate(async () => { + const link = document.querySelector('link[rel="icon"]'); + const urls = new Set([link.href]); + const observer = new MutationObserver(() => urls.add(link.href)); + observer.observe(link, { attributes: true, attributeFilter: ["href"] }); + await new Promise(resolve => setTimeout(resolve, 1450)); + observer.disconnect(); + return [...urls]; + }); + assert.deepEqual(changes, [icon]); + } + if (attached && process.env.FX_WAITING_CARD_SCREENSHOT) + await page.screenshot({ path: process.env.FX_WAITING_CARD_SCREENSHOT }); + if (attached) { + await page.getByRole("navigation", { name: "Workflow location" }).locator("[aria-current=page]").click(); + await page.getByRole("complementary", { name: "Details", exact: true }).waitFor(); + await choose.review.press("Enter"); + } else { + await choose.review.click(); + } + await panel.getByRole("heading", { name: "Choose a variant" }).waitFor({ timeout: 10_000 }); + if (attached) { + assert.equal(await page.getByRole("complementary", { name: "Details", exact: true }).count(), 0); + const pane = page.getByRole("main", { name: "Workflow canvas" }); + const toolbar = page.getByRole("navigation", { name: "Workflow location" }); + for (const width of [1280, 550]) { + await page.setViewportSize({ width, height: 840 }); + const frame = await pane.boundingBox(); + const review = await panel.boundingBox(); + assert.equal(frame.x + frame.width - review.x - review.width, 12); + if (width === 550) { + const bar = await toolbar.boundingBox(); + assert.ok(review.y >= bar.y + bar.height, "the narrow panel should sit beneath the toolbar"); + } + } + await page.setViewportSize({ width: 1280, height: 840 }); + } + const cardCountdown = choose.card.getByRole("timer"); + const panelCountdown = panel.getByRole("timer"); + await cardCountdown.waitFor(); + await panelCountdown.waitFor(); + assert.equal(await panelCountdown.getAttribute("datetime"), opened.deadline); + if (attached) { + const initial = await panelCountdown.textContent(); + assert.match(initial, /^\d+:\d{2} left$/); + await eventually(async () => (await panelCountdown.textContent()) !== initial, "the panel countdown to tick"); + const initialCard = await cardCountdown.textContent(); + await eventually(async () => (await cardCountdown.textContent()) !== initialCard, "the canvas countdown to tick"); + } + } catch (cause) { + const view = await (await fetch(new URL("api/run", url))).json(); + throw new Error(JSON.stringify({ run: view.state, nodes: view.nodes?.map(n => [n.id, n.uses, n.state]), + page: await page.locator("body").innerText(), errors }), { cause }); + } + await page.waitForFunction(() => { + const images = [...document.querySelectorAll(".fx-review-choice img")]; + return images.length === 3 && images.every(image => image.complete && image.naturalWidth > 0); + }); + if (attached) { + await panel.getByRole("button", { name: "Submit answer" }).press("Enter"); + await panel.getByRole("alert").filter({ hasText: "Choose a candidate." }).waitFor(); + const first = panel.getByRole("radio", { name: "a", exact: true }); + assert.ok(await first.evaluate(radio => radio === document.activeElement)); + assert.equal(await first.getAttribute("aria-invalid"), "true"); + assert.ok((await first.locator("..").boundingBox()).height >= 44, "the candidate label should be a large pointer target"); + await first.press("ArrowRight"); + assert.ok(await panel.getByRole("radio", { name: "b", exact: true }).isChecked()); + assert.equal(await first.getAttribute("aria-invalid"), null); + } else { + await panel.getByRole("radio", { name: "b", exact: true }).check(); + } + if (attached) { + await panel.getByRole("button", { name: "Close review" }).click(); + await assertPanelClosed(page); + await page.getByRole("complementary", { name: "Details", exact: true }).waitFor(); + await choose.review.focus(); + await choose.review.press("Enter"); + const choice = panel.getByRole("radio", { name: "b", exact: true }); + await choice.waitFor(); + assert.ok(await choice.isChecked(), "closing a pending review discarded the selected variant"); + } + if (attached && process.env.FX_WAITING_SCREENSHOT) await page.screenshot({ path: process.env.FX_WAITING_SCREENSHOT }); + // For the two races, hold one writer in flight. The disconnected case leaves both the + // runner and CLI offline until the browser has recorded its answer and reloaded. + responder = agentOnline ? spawn(["respond", target, opened.id, "--json", "-"]) : null; + const sendAgent = () => { responder.stdin.write('{"variant":"c"}'); responder.stdin.end(); return responder.exited; }; + const apiPath = `**/api/requests/${opened.id}/respond`; + let agentExit; + if (!browserWins) await page.route(apiPath, async route => { + agentExit = await sendAgent(); + await route.continue(); + }, { times: 1 }); + const receipt = page.waitForResponse(response => response.url().endsWith(`/requests/${opened.id}/respond`)); + await panel.getByRole("button", { name: "Submit answer" }).click(); + const response = await receipt; + assert.equal(response.status(), browserWins ? 200 : 409); + if (browserWins && agentOnline) agentExit = await sendAgent(); + const body = await response.json(); + const winner = (browserWins ? body : body.request).state; + const key = browserWins ? "b" : "c"; + assert.equal(winner.answer.variant, key); + assert.equal(winner.channel, browserWins ? "viewer" : "cli"); + const receiptPanel = panel.getByRole("status").filter({ hasText: `Answered via ${winner.channel}` }); + const verifyWinner = async () => { + await receiptPanel.waitFor(); + assert.equal(await panel.getByRole("timer").count(), 0); + assert.equal(await choose.card.getByRole("timer").count(), 0); + const choice = receiptPanel.getByRole("figure", { name: `Variant: ${key}`, exact: true }); + await choice.getByText(key, { exact: true }).waitFor(); + const preview = choice.getByRole("img", { name: opened.choices[key].file.name, exact: true }); + await preview.waitFor(); + const previewUrl = new URL(await preview.getAttribute("src"), url); + assert.equal(previewUrl.href, new URL(`api/artifacts/${opened.choices[key].file.digest}`, url).href); + assert.equal(await receiptPanel.locator("pre,code").count(), 0); + assert.equal(await receiptPanel.locator("time").getAttribute("datetime"), winner.at); + assert.equal(await panel.getByRole("button", { name: "Submit answer" }).count(), 0); + }; + await verifyWinner(); + if (!attached) await waitForReviewTab(page, 0); + await panel.getByRole("button", { name: "Close review" }).click(); + await assertPanelClosed(page); + await page.reload(); + await choose.receipt.waitFor(); + await assertPanelClosed(page); + await choose.receipt.click(); + await verifyWinner(); + if (attached && process.env.FX_WAITING_RECEIPT_SCREENSHOT) + await page.screenshot({ path: process.env.FX_WAITING_RECEIPT_SCREENSHOT }); + await panel.getByRole("button", { name: "Close review" }).click(); + await assertPanelClosed(page); + if (agentOnline) { + assert.equal(agentExit === 0, !browserWins); + const agentReceipt = JSON.parse(await new Response(responder.stdout).text()); + assert.deepEqual(agentReceipt.request.state, winner); + } + const observed = json(["inspect", target, "--requests", "--json"]).requests.find(item => item.id === opened.id); + assert.deepEqual(observed.state, winner); + if (!attached) { + await waitForReviewTab(page, 0); + // The detached answer updates both surfaces without a reload or a new invocation. + await runHeader.getByText("unfinished", { exact: true }).waitFor(); + await homeRun.getByText("unfinished", { exact: true }).waitFor(); + runner = spawn(["run", "./workflow.yaml", "--resume", name, "--no-view"]); + } + assert.equal(await runner.exited, 0, await new Response(runner.stderr).text()); + const { card } = choose; + await card.getByText("succeeded · Selected", { exact: true }).waitFor(); + await waitForReviewTab(page, 0); + await runHeader.getByText("succeeded", { exact: true }).waitFor(); + await homeRun.getByText("succeeded", { exact: true }).waitFor(); + assert.match(await card.getAttribute("aria-label"), /succeeded, Selected/); + if (attached && process.env.FX_WAITING_OUTCOME_SCREENSHOT) + await page.screenshot({ path: process.env.FX_WAITING_OUTCOME_SCREENSHOT }); + const view = await (await fetch(new URL("api/run", url))).json(); + assert.equal(view.outputs.image.file.digest, opened.choices[key].file.digest); + const { run } = json(["inspect", target, "--json"]); + const manifest = JSON.parse(readFileSync(resolve(project, run.folder, "outputs/manifest.json"), "utf8")); + assert.deepEqual(manifest, { revision: "rev-42", image_digest: opened.choices[key].file.digest }); + assert.deepEqual(errors, []); + await page.close(); + console.log(`ok ${name}: CLI, viewer and downstream agree on variant ${key}`); + } + writeFileSync(resolve(project, "feedback.yaml"), `fx: workflow/v1 +id: feedback +title: Give review feedback +steps: + review: + uses: fx/await@1 + with: + message: How did this variant do? + schema: + type: object + required: [approved, note, scores, metadata, flags] + additionalProperties: false + properties: + approved: { title: Approve the variant, type: boolean } + note: { title: Review note, type: string, minLength: 3, description: Describe what should change. } + scores: { type: array, items: { type: integer } } + metadata: { type: object, additionalProperties: false } + flags: { type: array, items: { type: boolean } } + alternate: { type: object, required: [reason], properties: { reason: { type: string } } } + tags: { type: array, items: { type: string } } + counters: { type: object, patternProperties: { '^count_': { type: integer } }, additionalProperties: { type: boolean } } + delivery: + uses: fx/await@1 + with: { message: Which delivery format?, schema: { type: string } } + confirmation: + needs: [delivery] + uses: fx/await@1 + with: { message: Confirm the delivery format, schema: { type: boolean }, timeout_seconds: 8, on_timeout: continue } +`); + runner = spawn(["run", "./feedback.yaml", "--name", "structured", "--no-view"]); + assert.equal(await runner.exited, 1, "park with both reviews open"); + const structured = json(["inspect", "feedback/structured", "--requests", "--register", "--json"]); + assert.equal(structured.requests.length, 2); + const page = await context.newPage(); + await page.goto(structured.viewer_url); + const panel = reviewPanel(page); + const feedback = reviewCard(page, "review"); + const delivery = reviewCard(page, "delivery"); + const confirmation = reviewCard(page, "confirmation"); + const feedbackHeading = panel.getByRole("heading", { name: "How did this variant do?", exact: true }); + const deliveryHeading = panel.getByRole("heading", { name: "Which delivery format?", exact: true }); + await feedback.review.waitFor(); + await delivery.review.waitFor(); + await assertPanelClosed(page); + await waitForReviewTab(page, 2); + await feedback.review.click(); + await feedbackHeading.waitFor(); + assert.equal(await feedback.card.getByRole("timer").count(), 0); + const awaiting = feedback.card.getByText("Awaiting answer", { exact: true }); + await awaiting.waitFor(); + assert.equal(await awaiting.evaluate(text => text.previousElementSibling?.classList.contains("fx-state-icon") ?? false), false); + await panel.getByText("Awaiting answer", { exact: true }).waitFor(); + assert.equal(await panel.getByRole("timer").count(), 0); + assert.equal(await deliveryHeading.count(), 0); + const submit = panel.getByRole("button", { name: "Submit answer" }); + await panel.getByRole("group", { name: "Approve the variant" }).getByRole("radio", { name: "No" }).check(); + const note = panel.getByRole("textbox", { name: "Review note", exact: true }); + assert.equal(await note.getAttribute("aria-required"), "true"); + await submit.press("Enter"); + const missingNote = panel.getByRole("alert").filter({ hasText: "Enter Review note." }); + await missingNote.waitFor(); + assert.ok(await note.evaluate(input => input === document.activeElement)); + assert.deepEqual(await note.evaluate(input => input.getAttribute("aria-describedby").split(" ") + .map(id => document.getElementById(id).textContent)), ["Describe what should change.", "Enter Review note."]); + await note.fill("x"); + await submit.press("Enter"); + const refusal = panel.getByRole("alert").filter({ hasText: "Check the fields in your answer and try again." }); + await refusal.waitFor(); + await eventually(() => refusal.evaluate(element => element === document.activeElement), "focus on the engine validation error"); + await note.fill("Try a softer palette"); + assert.equal(await note.getAttribute("aria-invalid"), null); + const addItem = panel.getByRole("group", { name: "Scores", exact: true }).getByRole("button", { name: "Add item" }); + await panel.getByRole("button", { name: "Include Tags", exact: true }).click(); + const counters = panel.getByRole("group", { name: "Counters", exact: true }); + await counters.getByRole("button", { name: "Include Counters", exact: true }).click(); + await counters.getByRole("button", { name: "Add field", exact: true }).click(); + await counters.getByRole("textbox", { name: "Field name", exact: true }).fill("count_prints"); + await counters.getByRole("combobox", { name: "Value type", exact: true }).selectOption("number"); + await counters.getByRole("textbox", { name: "Value", exact: true }).fill("4"); + await addItem.press("Enter"); + const item1 = panel.getByRole("textbox", { name: "Item 1", exact: true }); + await eventually(() => item1.evaluate(input => input === document.activeElement), "focus on the new first item"); + await item1.fill("0"); + await addItem.press("Enter"); + const item2 = panel.getByRole("textbox", { name: "Item 2", exact: true }); + await eventually(() => item2.evaluate(input => input === document.activeElement), "focus on the new second item"); + await item2.fill("7"); + await addItem.press("Enter"); + await panel.getByRole("button", { name: "Remove item 3" }).press("Enter"); + await eventually(() => addItem.evaluate(button => button === document.activeElement), "focus after removing the last item"); + assert.equal(await panel.locator("pre,code,textarea").count(), 0); + await page.keyboard.press("Escape"); + await assertPanelClosed(page); + assert.ok(await feedback.review.evaluate(button => button === document.activeElement), "Escape should return focus to the originating card"); + await delivery.review.click(); + await deliveryHeading.waitFor(); + assert.equal(await feedbackHeading.count(), 0); + await page.getByRole("navigation", { name: "Workflow location" }).locator("[aria-current=page]").click(); + await assertPanelClosed(page); + const details = page.getByRole("complementary", { name: "Details", exact: true }); + await details.getByRole("button", { name: "Close details" }).click(); + await feedback.review.click(); + await feedbackHeading.waitFor(); + assert.equal(await panel.getByRole("textbox", { name: "Review note", exact: true }).inputValue(), "Try a softer palette"); + assert.equal(await panel.getByRole("textbox", { name: "Item 2", exact: true }).inputValue(), "7"); + const deliveryRequest = structured.requests.find(request => request.step === "delivery#1"); + assert.ok(deliveryRequest); + json(["respond", "feedback/structured", deliveryRequest.id, "--json", '"png"']); + await delivery.receipt.waitFor(); + // One request remains until a runner opens the follow-up. The tab must count the detached answer. + await waitForReviewTab(page, 1); + runner = spawn(["run", "./feedback.yaml", "--resume", "structured", "--no-view", "--wait-for-answers"]); + await confirmation.review.waitFor(); + await feedbackHeading.waitFor(); + assert.equal(await deliveryHeading.count(), 0); + assert.equal(await panel.getByRole("heading", { name: "Confirm the delivery format", exact: true }).count(), 0); + assert.equal(await panel.getByRole("textbox", { name: "Review note", exact: true }).inputValue(), "Try a softer palette"); + await panel.getByRole("button", { name: "Submit answer" }).click(); + const receipt = panel.getByRole("status").filter({ hasText: "Answered via viewer" }); + await receipt.getByText("Try a softer palette", { exact: true }).waitFor(); + await eventually(() => receipt.evaluate(element => element === document.activeElement), "focus on the answer receipt"); + assert.equal(await receipt.locator("pre,code").count(), 0); + const recorded = () => json(["inspect", "feedback/structured", "--requests", "--json"]).requests; + assert.deepEqual(recorded().find(request => request.step === "review#1").state.answer, + { approved: false, note: "Try a softer palette", scores: [0, 7], metadata: {}, flags: [], tags: [], counters: { count_prints: 4 } }); + assert.equal(await runner.exited, 0, await new Response(runner.stderr).text()); + await feedback.card.getByText("succeeded · Answered", { exact: true }).waitFor(); + await confirmation.card.getByText("succeeded · Expired", { exact: true }).waitFor(); + assert.equal(await confirmation.card.getByRole("timer").count(), 0); + await waitForReviewTab(page, 0); + const expired = recorded().find(request => request.step === "confirmation#1").state; + assert.equal(expired.status, "expired"); + await receipt.getByText("Try a softer palette", { exact: true }).waitFor(); + await panel.getByRole("button", { name: "Close review" }).click(); + await confirmation.card.getByRole("button", { name: /^View outcome(?: |$)/ }).click(); + await panel.getByRole("heading", { name: "Confirm the delivery format", exact: true }).waitFor(); + const expiredReceipt = panel.getByRole("status").filter({ hasText: "Expired" }); + await expiredReceipt.waitFor(); + assert.equal(await panel.getByRole("timer").count(), 0); + assert.equal(await expiredReceipt.locator("time").getAttribute("datetime"), expired.at); + assert.equal(await panel.getByRole("button", { name: "Submit answer" }).count(), 0); + console.log("ok simultaneous reviews: keyboard, draft, and feedback receipt stay with the chosen card through another answer and expiry"); + await page.close(); + + const showcase = "review-showcase/typed-forms"; + runner = spawn(["run", "./showcase.yaml", "--name", "typed-forms", "--max-usd", "0", "--no-view"]); + assert.equal(await runner.exited, 1, await new Response(runner.stderr).text()); + const printRequest = requests => requests.find(request => request.step === "print_settings#1"); + const forms = json(["inspect", showcase, "--requests", "--register", "--json"]); + assert.equal(printRequest(forms.requests)?.state.status, "pending"); + assert.equal(Object.hasOwn(printRequest(forms.requests), "choices"), false); + const formPage = await context.newPage(); + await formPage.goto(forms.viewer_url); + const formPanel = reviewPanel(formPage); + const print = reviewCard(formPage, "print_settings"); + await print.review.waitFor(); + await print.review.press("Enter"); + await formPanel.getByRole("heading", { name: "How should the print edition be produced?", exact: true }).waitFor(); + const finish = formPanel.getByRole("combobox", { name: "Paper finish", exact: true }); + assert.equal(await finish.inputValue(), ""); + await finish.selectOption({ label: "satin" }); + if (process.env.FX_WAITING_ENUM_SCREENSHOT) + await formPage.screenshot({ path: process.env.FX_WAITING_ENUM_SCREENSHOT }); + await formPanel.getByRole("textbox", { name: "Print copies", exact: true }).fill("12"); + await formPanel.getByRole("textbox", { name: "Scale factor", exact: true }).fill("0.95"); + const margins = formPanel.getByRole("group", { name: "Margins", exact: true }); + await margins.getByRole("textbox", { name: "Top margin in mm", exact: true }).fill("3.5"); + const profile = formPanel.getByRole("group", { name: "Color profile override", exact: true }); + await profile.getByRole("checkbox", { name: "No value", exact: true }).check(); + const labels = formPanel.getByRole("group", { name: "Production labels", exact: true }); + await labels.getByRole("button", { name: "Include Production labels", exact: true }).click(); + await labels.getByRole("button", { name: "Add field", exact: true }).click(); + await labels.getByRole("textbox", { name: "Field name", exact: true }).fill("batch"); + await labels.getByRole("textbox", { name: "Value", exact: true }).fill("proof"); + await formPanel.getByRole("button", { name: "Submit answer" }).click(); + const formReceipt = formPanel.getByRole("status").filter({ hasText: "Answered via viewer" }); + await formReceipt.getByText("proof", { exact: true }).waitFor(); + assert.equal(await formReceipt.locator("pre,code").count(), 0); + assert.deepEqual(printRequest(json(["inspect", showcase, "--requests", "--json"]).requests)?.state.answer, { + finish: "satin", copies: 12, scale: 0.95, margins: { top_mm: 3.5 }, profile_override: null, labels: { batch: "proof" }, + }); + await formPage.close(); + console.log("ok showcase print settings: schema enum, typed fields, nested values and explicit null share an answer"); +} finally { + await browser?.close(); + for (const child of [responder, runner, service]) if (child && child.exitCode === null) child.kill(); + await Promise.all([responder, runner, service].filter(Boolean).map(child => child.exited)); + rmSync(directory, { recursive: true, force: true }); +} diff --git a/web/fx-react/src/canvas.tsx b/web/fx-react/src/canvas.tsx index e5370f7b..10aed651 100644 --- a/web/fx-react/src/canvas.tsx +++ b/web/fx-react/src/canvas.tsx @@ -10,7 +10,7 @@ export interface WorkflowCanvasHandle { } /** React only mounts the reusable DOM controller and forwards presentation props. */ -export function WorkflowCanvas({ graph, layout = null, selected, scope = null, onSelect, onOpenScope = () => {}, onBack = () => {}, ref }: { +export function WorkflowCanvas({ graph, layout = null, selected, scope = null, onSelect, onOpenScope = () => {}, onBack = () => {}, onReview, ref }: { graph: CanvasGraph; layout?: LayoutReport | null; selected: string | null; @@ -18,6 +18,7 @@ export function WorkflowCanvas({ graph, layout = null, selected, scope = null, o onSelect: (id: string | null) => void; onOpenScope?: (id: string) => void; onBack?: () => void; + onReview?: (id: string) => void; ref?: Ref; }) { const container = useRef(null); @@ -25,6 +26,7 @@ export function WorkflowCanvas({ graph, layout = null, selected, scope = null, o const select = useRef(onSelect); const openScope = useRef(onOpenScope); const back = useRef(onBack); + const review = useRef(onReview); useImperativeHandle(ref, () => ({ reveal: (id, inset) => controller.current?.reveal(id, inset), present: (graph, layout, selected, scope, focus, inset) => { @@ -35,10 +37,18 @@ export function WorkflowCanvas({ graph, layout = null, selected, scope = null, o else if (focus !== null) controller.current.reveal(focus, inset); }, }), []); - useEffect(() => { select.current = onSelect; openScope.current = onOpenScope; back.current = onBack; }, [onSelect, onOpenScope, onBack]); + useEffect(() => { + select.current = onSelect; + openScope.current = onOpenScope; + back.current = onBack; + review.current = onReview; + }, [onSelect, onOpenScope, onBack, onReview]); useEffect(() => { if (!container.current) return; - controller.current = new CanvasController(container.current, (id) => select.current(id), (id) => openScope.current(id), () => back.current()); + controller.current = new CanvasController( + container.current, (id) => select.current(id), (id) => openScope.current(id), + () => back.current(), (id) => review.current?.(id), + ); return () => { controller.current?.dispose(); controller.current = null; }; }, []); useEffect(() => { controller.current?.setGraph(graph, scope, layout); }, [graph, scope, layout]); diff --git a/web/fx-react/src/index.tsx b/web/fx-react/src/index.tsx index d23ba2af..8d103422 100644 --- a/web/fx-react/src/index.tsx +++ b/web/fx-react/src/index.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useSyncExternalStore } from "react"; +import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from "react"; import { ArtifactController, artifactDownloadName, artifactFileTarget, canPreviewText, jsonShape, jsonSize, parseJson, plainJson, stateIcon, stateIconParts, type Artifact, type CanvasPreview, type ExternalFileController } from "@grida/fx-web"; import { ModelPreview } from "./model-preview"; import { VisualPreview } from "./visual-preview"; @@ -25,7 +25,7 @@ export function StateIcon({ state, size = 12 }: { state: string; size?: number } export function StateLabel({ state }: { state: string }) { return - {state.replaceAll("_", " ")} + {stateLabel(state)} ; } @@ -36,6 +36,7 @@ export function Status({ state }: { state: string }) { cancelling: "bg-amber-50 text-amber-800 ring-amber-200", cancelled: "bg-amber-50 text-amber-800 ring-amber-200", interrupted: "bg-amber-50 text-amber-800 ring-amber-200", + awaiting: "bg-amber-50 text-amber-800 ring-amber-200", planned: "bg-blue-50 text-blue-800 ring-blue-200", maybe: "bg-amber-50 text-amber-800 ring-amber-200", done: "bg-emerald-50 text-emerald-800 ring-emerald-200", @@ -43,15 +44,21 @@ export function Status({ state }: { state: string }) { }; return - {state.replaceAll("_", " ")} + {stateLabel(state)} ; } +function stateLabel(state: string) { + return state === "awaiting" ? "Awaiting answer" : state.replaceAll("_", " "); +} + const imageKinds = ["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]; const jsonKinds = ["json", "application/json", "annotations"]; /** Visual media uses VisualPreview; native players explicitly own their fullscreen control. */ -export function ArtifactPreview({ artifact, poster, externalFiles }: { artifact: Artifact; poster?: Artifact; externalFiles?: ExternalFileController }) { +export function ArtifactPreview({ artifact, poster, externalFiles, renderJson }: { + artifact: Artifact; poster?: Artifact; externalFiles?: ExternalFileController; renderJson?: (value: unknown) => ReactNode; +}) { const controller = useMemo(() => new ArtifactController(), []); const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot); useEffect(() => { void controller.load(artifact); return () => controller.dispose(); }, [controller, artifact]); @@ -84,6 +91,7 @@ export function ArtifactPreview({ artifact, poster, externalFiles }: { artifact: if (canPreviewText(artifact)) { // A JSON file reads as its value does: rows, one line, or folded. const json = jsonKinds.includes(artifact.kind) && state.text !== null ? parseJson(state.text) : undefined; + if (renderJson && jsonKinds.includes(artifact.kind)) return json === undefined ? open : <>{renderJson(json)}; return json !== undefined ? :

{state.text ?? "…"}
; } return open; @@ -108,6 +116,8 @@ export function Value({ value, artifacts, videoPreview, externalFiles }: { value return artifact ? :

File not in this run folder

; } if (typeof value.file === "string" && /^[a-f0-9]{64}$/.test(value.file)) return

file {value.file.slice(0, 12)}

; + if (record(value.object) && Object.keys(value).length === 1) + return ; const json = plainJson(value); if (json !== undefined) return ; // Pictures read best as a grid; anything else, one under another. diff --git a/web/fx-web/src/answer-draft.ts b/web/fx-web/src/answer-draft.ts new file mode 100644 index 00000000..6453bfaf --- /dev/null +++ b/web/fx-web/src/answer-draft.ts @@ -0,0 +1,117 @@ +/** The form keeps incomplete input separate from the answer sent to FX. */ +export type AnswerSchema = boolean | Record; + +export type AnswerKind = "string" | "number" | "integer" | "boolean" | "null" | "array" | "object"; + +export type AnswerDraft = + | { kind: "string" | "number" | "integer"; text: string } + | { kind: "boolean"; value?: boolean } + | { kind: "null" } + | { kind: "array"; items: (AnswerDraft | undefined)[] } + | { kind: "object"; fields: AnswerField[] }; + +export interface AnswerField { + name: string; + value?: AnswerDraft; + editableName?: boolean; +} + +const kinds: readonly AnswerKind[] = ["string", "number", "boolean", "null", "array", "object", "integer"]; +const jsonNumber = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/; + +export function answerSchema(value: unknown): AnswerSchema { + if (typeof value === "boolean") return value; + return value !== null && typeof value === "object" && !Array.isArray(value) + ? value as Record : true; +} + +export function answerKinds(schema: Record): readonly AnswerKind[] { + const declared = Array.isArray(schema.type) ? schema.type : [schema.type]; + const options = kinds.filter(kind => declared.includes(kind)); + return options.length > 0 ? options : kinds.filter(kind => kind !== "integer"); +} + +/** Literal scalar enums can use a picker. Its option values preserve the JSON type. */ +export function scalarEnumOptions(schema: Record) { + if (!Array.isArray(schema.enum) || !schema.enum.length) return undefined; + const options: { label: string; draft: AnswerDraft; encoded: string }[] = []; + for (const value of schema.enum) { + let draft: AnswerDraft; + let label: string; + if (value === null) { + draft = { kind: "null" }; + label = "No value"; + } else if (typeof value === "string") { + draft = { kind: "string", text: value }; + label = value || "Empty text"; + } else if (typeof value === "boolean") { + draft = { kind: "boolean", value }; + label = value ? "Yes" : "No"; + } else if (typeof value === "number") { + draft = { kind: "number", text: String(value) }; + label = String(value); + } else { + return undefined; + } + options.push({ label, draft, encoded: JSON.stringify(value) }); + } + // Distinguish, for example, the text "1" and the number 1 in a mixed enum. + const mixed = options.some(option => option.draft.kind !== options[0].draft.kind); + return mixed ? options.map(option => ({ ...option, label: `${option.label} (${option.draft.kind})` })) : options; +} + +export function emptyAnswer(kind: AnswerKind, schema: Record = {}): AnswerDraft { + switch (kind) { + case "array": return { kind, items: [] }; + case "object": { + const fields: AnswerField[] = []; + const properties = answerSchema(schema.properties); + if (typeof properties === "object" && Array.isArray(schema.required)) { + for (const name of schema.required) { + if (typeof name !== "string" || !Object.hasOwn(properties, name)) continue; + const child = answerSchema(properties[name]); + const value = initialAnswer(child); + if (value !== undefined) fields.push({ name, value }); + } + } + return { kind, fields }; + } + case "boolean": + case "null": return { kind }; + default: return { kind, text: "" }; + } +} + +/** Allow an empty list/object, and require explicit input for scalars. */ +export function initialAnswer(schema: AnswerSchema): AnswerDraft | undefined { + if (typeof schema === "boolean") return undefined; + const [only, second] = answerKinds(schema); + return !second && (only === "object" || only === "array") ? emptyAnswer(only, schema) : undefined; +} + +/** Encode typed controls while preserving the exact spelling of a number for FX's JSON reader. */ +export function encodeAnswer(draft: AnswerDraft | undefined): string | undefined { + switch (draft?.kind) { + case "string": return JSON.stringify(draft.text); + case "number": + case "integer": return jsonNumber.test(draft.text) ? draft.text : undefined; + case "boolean": return draft.value === undefined ? undefined : String(draft.value); + case "null": return "null"; + case "array": { + const members = draft.items.map(encodeAnswer); + return members.includes(undefined) ? undefined : `[${members.join(",")}]`; + } + case "object": { + const members = []; + const names = new Set(); + for (const field of draft.fields) { + const value = encodeAnswer(field.value); + if (value === undefined || names.has(field.name)) return undefined; + names.add(field.name); + members.push(`${JSON.stringify(field.name)}:${value}`); + } + return `{${members.join(",")}}`; + } + case undefined: return undefined; + } +} diff --git a/web/fx-web/src/canvas.css b/web/fx-web/src/canvas.css index 0a3a7958..e3f9d936 100644 --- a/web/fx-web/src/canvas.css +++ b/web/fx-web/src/canvas.css @@ -18,6 +18,24 @@ .fx-canvas-open-workflow text { fill: #2563eb; font: 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } .fx-canvas-open-workflow:hover rect, .fx-canvas-open-workflow:focus-visible rect { fill: #dbeafe; stroke: #2563eb; } .fx-canvas-node-box { fill: #fff; stroke: #d4d4d8; stroke-width: 1.2px; } +.fx-canvas-review-pending .fx-canvas-node-box { stroke: #da9b36; stroke-width: 2px; } +.fx-canvas-node.fx-canvas-review-pending:hover .fx-canvas-node-box { stroke: #ad6c17; } +.fx-canvas-review-header { fill: #ffedca; pointer-events: none; } +.fx-canvas-review-footer { fill: #fff5e1; pointer-events: none; } +.fx-canvas-review-divider { stroke: #e4e4e7; pointer-events: none; } +.fx-canvas-review-pending .fx-canvas-review-divider, .fx-canvas-review-pending .fx-canvas-node-divider { stroke: #e9c789; } +.fx-canvas-review-pending .fx-canvas-node-state { fill: #794612; font-weight: 650; } +.fx-canvas-review-countdown { font-variant-numeric: tabular-nums; } +.fx-canvas-review-pending .fx-state-hands, .fx-canvas-review-pending .fx-state-ring { stroke: #985715; } +.fx-canvas-review-prompt { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #463722; font: 12px/20px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } +.fx-canvas-review-action { cursor: pointer; outline: none; } +.fx-canvas-review-action rect { fill: #fafafa; stroke: #d4d4d8; } +.fx-canvas-review-action text { fill: #3f3f46; font: 600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; pointer-events: none; } +.fx-canvas-review-action:hover rect { fill: #f4f4f5; stroke: #71717a; } +.fx-canvas-review-pending .fx-canvas-review-action rect { fill: #814710; stroke: #814710; } +.fx-canvas-review-pending .fx-canvas-review-action text { fill: white; } +.fx-canvas-review-pending .fx-canvas-review-action:hover rect { fill: #67380c; stroke: #67380c; } +.fx-canvas-node .fx-canvas-review-action:focus-visible rect { stroke: #2563eb; stroke-width: 3px; } .fx-canvas-pending { stroke-dasharray: 6 4; fill: #fafafa; } .fx-canvas-node:hover .fx-canvas-node-box { stroke: #71717a; } .fx-canvas-node.is-selected .fx-canvas-node-box, .fx-canvas-node:focus-visible .fx-canvas-node-box { stroke: #2563eb; stroke-width: 2px; } diff --git a/web/fx-web/src/canvas.ts b/web/fx-web/src/canvas.ts index 2d49f7f1..f66e05cc 100644 --- a/web/fx-web/src/canvas.ts +++ b/web/fx-web/src/canvas.ts @@ -10,10 +10,11 @@ import { element, nodeCard, runningLabel, short } from "./card"; import { CardVideos } from "./video"; import { CardModels } from "./card-models"; import { PortPreview, type InspectedPort } from "./port-preview"; +import { countdownLabel } from "./waiting"; const EXPANDED_GAP = 32; /** A card's labelled controls do what they say (§5.7): a press on one neither pans nor opens its deck. */ -const CARD_CONTROLS = ".fx-canvas-open-workflow, .fx-canvas-play, .fx-canvas-model-open, .fx-canvas-port"; +const CARD_CONTROLS = ".fx-canvas-open-workflow, .fx-canvas-play, .fx-canvas-model-open, .fx-canvas-port, .fx-canvas-review-action"; /** * Whether a key event's target keeps its own keys: a text field, or a card's media player, whose @@ -23,7 +24,7 @@ export function ownsKeys(target: EventTarget | null) { const element = target as Element | null; // Native fullscreen gets Escape before surrounding details, decks or scope navigation. return Boolean(element?.ownerDocument?.fullscreenElement?.contains(element) - || element?.closest?.("input, textarea, select, [contenteditable], .fx-canvas-player, .fx-canvas-model-player, .fx-port-preview")); + || element?.closest?.("input, textarea, select, [contenteditable], [data-fx-owns-keys], .fx-canvas-player, .fx-canvas-model-player, .fx-port-preview")); } /** §5.9: expanded decks fit the viewport down to card titles (13 px) about 11 px on screen. */ const LEGIBLE_ZOOM = 11 / 13; @@ -129,7 +130,8 @@ export class CanvasController { private readonly cameras = new Map; didFit: boolean }>(); constructor(private readonly container: HTMLElement, private readonly onSelect: (id: string | null) => void, - private readonly onOpenScope: (id: string) => void = () => {}, private readonly onBack: () => void = () => {}) { + private readonly onOpenScope: (id: string) => void = () => {}, private readonly onBack: () => void = () => {}, + private readonly onReview?: (sourceId: string) => void) { container.classList.add("fx-canvas"); container.tabIndex = -1; const defs = element("defs"); @@ -236,6 +238,8 @@ export class CanvasController { this.portPreview.dismiss(); const navigating = scope !== this.scope; const restoringFocus = this.content.contains(document.activeElement); + const reviewFocus = restoringFocus && document.activeElement?.matches(".fx-canvas-review-action") + ? document.activeElement.closest("[data-node-id]")?.dataset.nodeId : undefined; const reopen = navigating || !this.open ? null : { id: this.open.deck.placed.id, camera: this.open.camera }; this.cancelDrag(); this.collapse(true, !navigating); @@ -275,7 +279,10 @@ export class CanvasController { // A deck that vanished or dropped below two members stays closed and gives the camera back. else this.animateCamera(() => this.viewport.restore(reopen.camera)); } - if (navigating || restoringFocus) this.container.focus({ preventScroll: true }); + if (navigating || restoringFocus) { + const review = !navigating && reviewFocus ? this.nodes.get(reviewFocus)?.querySelector(".fx-canvas-review-action") : null; + (review && !this.covered(review) ? review : this.container).focus({ preventScroll: true }); + } this.models.redrawn(this.nodes); this.redrawing = false; this.models.recheck(); @@ -335,7 +342,7 @@ export class CanvasController { } } for (const [index, node] of this.layout.nodes.entries()) { - const group = nodeCard(node, this.id, index, signal, (scope) => this.onOpenScope(scope)); + const group = nodeCard(node, this.id, index, signal, this.onOpenScope, this.onReview); for (const socket of group.querySelectorAll(".fx-canvas-port")) { const direction = socket.dataset.portDirection === "input" ? "input" : "output"; const ports = direction === "input" ? node.ports?.inputs : node.ports?.outputs; @@ -394,12 +401,18 @@ export class CanvasController { this.decks = this.layout.decks.map((placed, index) => this.deck(placed, index, layer(placed.frame).cards, items)); this.decks.forEach((_, index) => this.restDeck(index)); this.content.replaceChildren(boundaries, rootEdges, rootCards); - // Running and waiting cards count up together, once a second, until the next redraw. - const clocks = [...this.content.querySelectorAll("text[data-started]")]; + // One timer updates elapsed times and review countdowns until the next redraw. + const clocks = [...this.content.querySelectorAll("[data-started], [data-review-countdown]")]; if (clocks.length) { const timer = window.setInterval(() => { const now = Date.now(); - for (const clock of clocks) clock.textContent = (clock.dataset.prefix ?? "") + runningLabel(Number(clock.dataset.started), now); + for (const clock of clocks) { + const deadline = clock.dataset.reviewCountdown; + const label = deadline === undefined + ? (clock.dataset.prefix ?? "") + runningLabel(Number(clock.dataset.started), now) + : countdownLabel(Number(deadline), now); + if (clock.textContent !== label) clock.textContent = label; + } }, 1000); signal.addEventListener("abort", () => window.clearInterval(timer), { once: true }); } @@ -560,9 +573,9 @@ export class CanvasController { if (this.open && !this.open.deck.cards.some((card) => card.contains(element))) return true; return this.decks.some((deck) => deck !== this.open?.deck && deck.cards.some((card, at) => at !== deck.front && card.contains(element))); } - private syncPortFocus() { - for (const node of this.nodes.values()) for (const port of node.querySelectorAll(".fx-canvas-port")) { - port.setAttribute("tabindex", this.covered(port) ? "-1" : "0"); + private syncControlFocus() { + for (const node of this.nodes.values()) for (const control of node.querySelectorAll(".fx-canvas-port, .fx-canvas-review-action")) { + control.setAttribute("tabindex", this.covered(control) ? "-1" : "0"); } } /** The deck card that is or holds this node's card, or -1. */ @@ -592,7 +605,7 @@ export class CanvasController { this.markFront(deck, front); // One tab stop per closed deck: its front card. deck.cards.forEach((card, at) => { if (card.hasAttribute("tabindex")) card.setAttribute("tabindex", at === front ? "0" : "-1"); }); - this.syncPortFocus(); + this.syncControlFocus(); return deck.cards[front]; } /** @@ -702,7 +715,7 @@ export class CanvasController { veil.style.transition = `opacity ${duration}ms ease`; veil.classList.add("is-shown"); this.open = { deck, veil, camera, grid }; - this.syncPortFocus(); + this.syncControlFocus(); this.videos.recheck(); if (!this.redrawing) this.models.recheck(); this.showScrubber(index); diff --git a/web/fx-web/src/card.ts b/web/fx-web/src/card.ts index 4c7f847a..441cbba2 100644 --- a/web/fx-web/src/card.ts +++ b/web/fx-web/src/card.ts @@ -1,9 +1,10 @@ import { valuePreviewLines, valueStateLabel } from "./value-views"; import { displayPortName } from "./ports"; -import { canvasNodeGeometry, canvasPreviewReserved, PORT_ROW, PORT_TOP, type PositionedNode } from "./layout"; +import { canvasNodeGeometry, canvasPreviewReserved, reviewFooter, PORT_ROW, PORT_TOP, type PositionedNode } from "./layout"; import { stateIcon, stateIconParts } from "./state-icon"; import type { CanvasStep } from "./graph"; import { skipPreviewLines } from "./skip"; +import { countdownLabel } from "./waiting"; import { Box, Braces, CircleSlash, createElement, RotateCw, VideoOff } from "lucide"; const SVG = "http://www.w3.org/2000/svg"; @@ -29,8 +30,14 @@ export function elapsedLabel(ms: number) { * route slots; a waiting one names its route and counts up from when its wait began. `from` is * absent when the record cannot date it; the line is then `text` alone. */ -export function cardStatus(node: Pick, routeLimit = 18): { text: string; from?: number } { +export function cardStatus(node: Pick, routeLimit = 18): { text: string; from?: number } { const time = (value: string | undefined) => value ? Date.parse(value) : NaN; + if (node.review_action === "review") return { text: "Awaiting answer" }; + if (node.state === "awaiting") { + if (node.review_action === "view_answer") return { text: "Answer recorded" }; + if (node.review_action === "view_outcome") return { text: "Expired" }; + return { text: "Awaiting answer" }; + } if (node.state === "running") { const started = time(node.started_at); return Number.isNaN(started) ? { text: node.state } : { text: "", from: started + (node.waited_ms ?? 0) }; @@ -40,7 +47,7 @@ export function cardStatus(node: Pick l * One node card at its absolute position. The caller wires selection and the open-workflow * control; `signal` removes the card's own listeners when the canvas is redrawn. */ -export function nodeCard(node: PositionedNode, canvasId: string, index: number, signal: AbortSignal, onOpen: (scope: string) => void) { +export function nodeCard(node: PositionedNode, canvasId: string, index: number, signal: AbortSignal, onOpen: (scope: string) => void, onReview?: (sourceId: string) => void) { const preview = node.preview; const skippedPreview = !preview && canvasPreviewReserved(node) && node.state === "skipped"; const unavailablePreview = !preview && canvasPreviewReserved(node) && (node.state === "succeeded" || node.value?.state === "known"); const skipMessage = node.state === "skipped" ? node.skip_explanation?.message ?? "Reason not recorded." : null; const { settings_y, preview_y, preview_height } = canvasNodeGeometry(node); + const footer = reviewFooter(node); + const footerTop = footer ? node.height - footer.height : node.height; + const action = onReview && node.review_action; const portsLabel = node.ports ? `, inputs: ${node.ports.inputs.map((port) => `${displayPortName(port.name)} (${port.type}, ${port.kind})`).join(", ") || "none"}, outputs: ${node.ports.outputs.map((port) => `${displayPortName(port.name)} (${port.type}, ${port.kind})`).join(", ") || "none"}` : node.pending ? "" : ", port metadata not recorded"; const scopeLabel = node.kind === "workflow" ? `, imported workflow, ${node.child_count ?? 0} steps, ${node.failure_count ?? 0} failed` : ""; - const state = node.state === "waiting" && node.waiting_for ? `waiting for ${node.waiting_for}` : node.state; + const state = node.state === "waiting" && node.waiting_for ? `waiting for ${node.waiting_for}` : + footer?.pending || node.state === "awaiting" ? cardStatus(node).text : node.state; + const review = node.review_label ? `, ${node.review_label}` : ""; const count = preview ? node.value ? `${preview.count} ${preview.kind}${preview.count === 1 ? "" : "s"}` : `${preview.count} ${preview.kind} ${preview.count === 1 ? "output" : "outputs"}` : ""; - const label = `${node.title}, ${state}${scopeLabel}${portsLabel}${preview ? `, ${preview.label}, ${count}` : skippedPreview ? ", No preview to display." : unavailablePreview ? ", Preview unavailable." : ""}${skipMessage ? ` ${skipMessage}` : ""}`; - const group = element("g", { transform: `translate(${node.x},${node.y})`, class: `fx-canvas-node${node.value ? " fx-canvas-value" : ""}${node.kind === "workflow" ? " fx-canvas-workflow" : node.kind === "boundary" ? " fx-canvas-boundary" : ""}`, role: node.kind === "workflow" ? "group" : "button", tabindex: 0, "data-node-id": node.id, "data-state": node.state, "aria-label": label, ...(node.kind === "workflow" ? { "aria-current": "false" } : { "aria-pressed": "false" }) }); + const label = `${node.title}, ${state}${review}${footer?.pending && node.review_prompt ? `, ${node.review_prompt}` : ""}${scopeLabel}${portsLabel}${preview ? `, ${preview.label}, ${count}` : skippedPreview ? ", No preview to display." : unavailablePreview ? ", Preview unavailable." : ""}${skipMessage ? ` ${skipMessage}` : ""}`; + const containsAction = node.kind === "workflow" || Boolean(action); + const group = element("g", { transform: `translate(${node.x},${node.y})`, class: `fx-canvas-node${node.value ? " fx-canvas-value" : ""}${node.kind === "workflow" ? " fx-canvas-workflow" : node.kind === "boundary" ? " fx-canvas-boundary" : ""}`, role: containsAction ? "group" : "button", tabindex: 0, "data-node-id": node.id, "data-state": node.state, "aria-label": label, ...(containsAction ? { "aria-current": "false" } : { "aria-pressed": "false" }) }); group.append(element("rect", { width: node.width, height: node.height, rx: node.value ? 5 : 11, class: node.pending ? "fx-canvas-node-box fx-canvas-pending" : "fx-canvas-node-box" })); + if (footer?.pending) { + group.classList.add("fx-canvas-review-pending"); + const right = node.width - 1, bottom = node.height - 1; + group.append(element("path", { d: `M1 11Q1 1 11 1H${right - 10}Q${right} 1 ${right} 11V59H1Z`, class: "fx-canvas-review-header", "aria-hidden": "true" })); + group.append(element("path", { d: `M1 ${footerTop}H${right}V${bottom - 10}Q${right} ${bottom} ${right - 10} ${bottom}H11Q1 ${bottom} 1 ${bottom - 10}Z`, class: "fx-canvas-review-footer", "aria-hidden": "true" })); + } + if (footer) group.append(element("line", { x1: 1, x2: node.width - 1, y1: footerTop, y2: footerTop, class: "fx-canvas-review-divider" })); if (node.value) { // A printed binding label belongs to the data sheet, inside its existing footprint. group.append(element("path", { d: `M5 1H${node.width - 5}Q${node.width - 1} 1 ${node.width - 1} 5V59H1V5Q1 1 5 1Z`, class: "fx-canvas-value-label", "aria-hidden": "true" })); @@ -201,7 +221,7 @@ export function nodeCard(node: PositionedNode, canvasId: string, index: number, video.append(border, fallback, play, unavailableIcon); group.append(video); } - group.append(element("text", { x: node.width - 16, y: node.height - 22, "text-anchor": "end", class: "fx-canvas-image-count" }, count)); + group.append(element("text", { x: node.width - 16, y: footer ? footerTop - 7 : node.height - 22, "text-anchor": "end", class: "fx-canvas-image-count" }, count)); } else if (canvasPreviewReserved(node)) { // Only a started step shimmers: the declared file may be on its way. if (node.state === "running") { @@ -231,12 +251,52 @@ export function nodeCard(node: PositionedNode, canvasId: string, index: number, }, node.value ? "File preview unavailable" : "Preview unavailable")); group.append(element("rect", { ...frame, rx: 6, class: "fx-canvas-image-border" })); } - if (!node.value) group.append(stateIconElement(node.state, 15, node.height - 32, 12)); - // A dated running or waiting card carries what it counts from; the canvas recounts it every second. - const status = cardStatus(node, node.ports ? 18 : 12); - if (!node.value) group.append(status.from === undefined - ? element("text", { x: 32, y: node.height - 22, class: "fx-canvas-node-state" }, status.text) - : element("text", { x: 32, y: node.height - 22, class: "fx-canvas-node-state", "data-started": status.from, "data-prefix": status.text }, status.text + runningLabel(status.from, Date.now()))); + const prompt = footer?.pending ? node.review_prompt?.trim() : undefined; + const statusY = footer ? footerTop + (prompt ? 25 : footer.height / 2 + 4) : node.height - 22; + const deadline = footer?.pending && node.review_deadline ? Date.parse(node.review_deadline) : NaN; + const showCountdown = Number.isFinite(deadline); + const showStateIcon = !footer?.pending || showCountdown; + const statusX = showStateIcon ? 32 : 16; + if (!node.value) { + if (showStateIcon) group.append(stateIconElement(showCountdown ? "waiting" : node.state, 15, statusY - 10, 12)); + // The canvas updates only the time text, so the card and its Review button retain focus. + const status = cardStatus(node, node.ports ? 18 : 12); + const label = status.from === undefined + ? element("text", { x: statusX, y: statusY, class: "fx-canvas-node-state" }, status.text) + : element("text", { x: statusX, y: statusY, class: "fx-canvas-node-state", "data-started": status.from, "data-prefix": status.text }, status.text + runningLabel(status.from, Date.now())); + if (showCountdown) label.append( + element("tspan", {}, " · "), + element("tspan", { class: "fx-canvas-review-countdown", "data-review-countdown": deadline, role: "timer" }, countdownLabel(deadline)), + ); + group.append(label); + } + if (footer) { + const width = action === "review" ? 73 : 89; + const x = node.width - 16 - width; + if (prompt) { + const line = element("foreignObject", { x: statusX, y: footerTop + 33, width: (action ? x - 10 : node.width - 16) - statusX, height: 22, "aria-hidden": "true" }); + const text = document.createElement("div"); + text.className = "fx-canvas-review-prompt"; + text.title = prompt; + text.textContent = prompt; + line.append(text); + group.append(line); + } + if (action && onReview) { + const name = action === "review" ? "Review" : action === "view_answer" ? "View answer" : "View outcome"; + const button = element("g", { transform: `translate(${x},${footerTop + (footer.height - 30) / 2})`, class: "fx-canvas-review-action", + role: "button", tabindex: 0, "aria-label": action === "review" ? `Review ${node.title}` : `${name} for ${node.title}`, "aria-controls": "fx-review-panel" }); + button.append(element("rect", { width, height: 30, rx: 6 }), element("text", { x: width / 2, y: 19, "text-anchor": "middle" }, name)); + const activate = (event: Event) => { + event.preventDefault(); + event.stopPropagation(); + if (button.getAttribute("tabindex") === "0") onReview(node.source_id); + }; + button.addEventListener("click", activate, { signal }); + button.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === " ") activate(event); }, { signal }); + group.append(button); + } + } if (node.kind === "workflow" && node.scope_id) { group.append(element("text", { x: 16, y: node.height - 48, class: (node.failure_count ?? 0) > 0 ? "fx-canvas-workflow-failure" : "fx-canvas-workflow-count" }, `${node.child_count ?? 0} steps${node.failure_count ? ` · ${node.failure_count} failed` : ""}`)); const open = element("g", { class: "fx-canvas-open-workflow", role: "button", tabindex: 0, "aria-label": `Open workflow ${node.title}` }); diff --git a/web/fx-web/src/deck.ts b/web/fx-web/src/deck.ts index 4c72dca1..360f5e74 100644 --- a/web/fx-web/src/deck.ts +++ b/web/fx-web/src/deck.ts @@ -31,16 +31,19 @@ export function deckBadge(members: DeckMember[]) { const failures = members.filter((member) => failed.has(member.state)).length; const skipped = members.filter((member) => member.state === "skipped").length; const waiting = members.filter((member) => member.state === "waiting").length; + const awaiting = members.filter((member) => member.state === "awaiting").length; return { text: parts.join(" · "), failed: failures, - detail: [...(failures ? [`${failures} failed`] : []), ...(waiting ? [`${waiting} waiting`] : []), ...(skipped ? [`${skipped} skipped`] : [])], + detail: [...(failures ? [`${failures} failed`] : []), ...(awaiting ? [`${awaiting} awaiting an answer`] : []), + ...(waiting ? [`${waiting} waiting`] : []), ...(skipped ? [`${skipped} skipped`] : [])], }; } /** * The member that rests in front (§5.4): the selected one, else the last failed or blocked, else - * the first running, else the first waiting for its route, else in a take deck the last take read + * the first running, else the first awaiting an answer, else the first waiting for its route. + * In a take deck the next choice is the last take read * from outside it, else the last succeeded, else one with execution evidence, else the first. * Explicit inspection may foreground any member; status alone does not establish consumption. */ @@ -59,6 +62,7 @@ export function restingRow(rows: DeckMember[][], selected: string | null): numbe () => first((member) => member.id === selected), () => last((member) => failed.has(member.state)), () => first((member) => member.state === "running"), + () => first((member) => member.state === "awaiting"), () => first((member) => member.state === "waiting"), () => rows[0]?.some((_, column) => isTakeDeck(rows.map((row) => row[column]))) ? last((member) => member.bound === true) : -1, () => last((member) => succeeded.has(member.state)), @@ -96,7 +100,7 @@ export function deckTicks(members: DeckMember[]): DeckTick[] { const first = Math.floor(at * members.length / count), last = Math.floor((at + 1) * members.length / count) - 1; const states = members.slice(first, last + 1).map((member) => member.state); const tone = states.some((state) => failed.has(state)) ? "failed" - : states.some((state) => state === "running" || state === "waiting") ? "active" + : states.some((state) => ["running", "awaiting", "waiting"].includes(state)) ? "active" : states.some((state) => succeeded.has(state)) ? "done" : "idle"; return { first, last, tone }; }); diff --git a/web/fx-web/src/graph.ts b/web/fx-web/src/graph.ts index 29690881..383f6b1f 100644 --- a/web/fx-web/src/graph.ts +++ b/web/fx-web/src/graph.ts @@ -249,6 +249,12 @@ export interface CanvasModelPreview extends CanvasPreviewBase { export type CanvasPreview = CanvasImagePreview | CanvasVideoPreview | CanvasModelPreview; export interface CanvasStep { id: string; source_id: string; title: string; subtitle: string; state: string; pending: boolean; + /** The recorded review result shown alongside execution state. */ + review_label?: string; + /** Live review affordances supplied by the local request controller. */ + review_action?: "review" | "view_answer" | "view_outcome"; + review_prompt?: string; + review_deadline?: string; /** Recorded evidence that the node executed; status alone does not prove this for skipped nodes. */ executed?: true; /** When the step last started, UTC: a running card counts up from it, less `waited_ms`. */ @@ -364,6 +370,17 @@ function recordedPreview(node: ViewerRun["nodes"][number], artifacts: Map binding.target_port)); @@ -390,6 +408,7 @@ export function flatCanvasGraph(view: GraphDocument | ViewerRun, apiBase = "/api ...(item.take ? { take: item.take } : {}), ...(item.key !== undefined ? { key: item.key } : {}), title: plan ? view.steps?.[(item as GraphInstance).step]?.title || item.path : (item as ViewerRun["nodes"][number]).title || item.path, subtitle: item.uses ?? "Type not recorded", state: item.state, pending: false, + ...(review_label ? { review_label } : {}), ...(run && recordedExecution(run) ? { executed: true as const } : {}), ...(run?.state === "skipped" ? { skip_explanation: skipExplanation(run.skip_reason, (view as ViewerRun).nodes) } : {}), ...(started_at ? { started_at } : {}), diff --git a/web/fx-web/src/index.ts b/web/fx-web/src/index.ts index 064920d2..f94f4da7 100644 --- a/web/fx-web/src/index.ts +++ b/web/fx-web/src/index.ts @@ -6,6 +6,8 @@ import { validateViewerApiBase } from "./route"; import { isSkipReason, type SkipReason } from "./skip"; import { isPrice, type Price } from "./graph"; export { VisualPreviewController } from "./visual-preview"; +export { WaitingReviewController, countdownLabel, parseDraft, withReviewCards, type WaitingRequest } from "./waiting"; +export { answerKinds, answerSchema, emptyAnswer, encodeAnswer, initialAnswer, scalarEnumOptions, type AnswerDraft, type AnswerKind, type AnswerSchema } from "./answer-draft"; export interface Artifact { digest: string; @@ -28,6 +30,8 @@ export interface RunNode { title: string; uses: string | null; state: string; + /** Recorded resolution of this waiting step, independent of its execution state. */ + review_outcome?: "answered" | "expired"; reads: string[]; with: Record; outputs: Record; @@ -138,6 +142,11 @@ function node(value: unknown): value is RunNode { && nullableString(value.error) && (value.diagnostic === undefined || diagnostic(value.diagnostic)) && (value.skip_reason === undefined || value.state === "skipped" && isSkipReason(value.skip_reason)) + && (value.review_outcome === undefined || ( + typeof value.uses === "string" && /^fx\/await@0*1$/.test(value.uses) + && (value.state === "succeeded" && value.review_outcome === "answered" + || (value.state === "succeeded" || value.state === "failed") && value.review_outcome === "expired") + )) && nullableNumber(value.duration_ms) && (value.started_at === undefined || utcTimestamp(value.started_at)) && (value.waiting_for === undefined || typeof value.waiting_for === "string") diff --git a/web/fx-web/src/layout.ts b/web/fx-web/src/layout.ts index 78978228..2cc19e61 100644 --- a/web/fx-web/src/layout.ts +++ b/web/fx-web/src/layout.ts @@ -28,12 +28,20 @@ export function canvasPreviewReserved(node: CanvasStep) { /** A preview frame's height for its width: 16:9, the commonest shape of what steps make. */ const PREVIEW_ASPECT = 9 / 16; +/** A waiting card's footer occupies its own band below ports, settings and any preview. */ +export function reviewFooter(node: CanvasStep) { + const pending = node.review_action === "review" || (node.state === "awaiting" && !node.review_action); + if (node.kind || (!pending && !node.review_action)) return undefined; + return { pending, height: pending ? 66 : 48 }; +} + /** * Geometry depends on declarations, never on media loading or measured DOM text. The preview * frame spans the card less 16 on each side. */ export function canvasNodeGeometry(node: CanvasStep) { - const width = node.ports ? 360 : 250; + const review = reviewFooter(node); + const width = node.ports || review ? 360 : 250; if (node.value) { const lines = valuePreviewLines(valueStateLabel(node.value)).lines.length; const preview_y = 80 + Math.max(1, lines) * 18; @@ -41,13 +49,15 @@ export function canvasNodeGeometry(node: CanvasStep) { return { width, height: preview_y + (canvasPreviewReserved(node) ? preview_height + 14 : 0) + 24, preview_y, preview_height, settings_y: 60 }; } const preview_height = Math.round((width - 32) * PREVIEW_ASPECT); - if (!node.ports) return { width, height: node.preview ? 61 + preview_height + 45 : 106, preview_y: 61, preview_height, settings_y: 0 }; + // The media count sits above a review footer, clear of the message and action. + const footer = review ? review.height + (node.preview ? 20 : 0) : undefined; + if (!node.ports) return { width, height: node.preview ? 61 + preview_height + (footer ?? 45) : 75 + (footer ?? 31), preview_y: 61, preview_height, settings_y: 0 }; const rows = Math.max(node.ports.inputs.length, node.ports.outputs.length); const settings_y = 83 + Math.max(1, rows) * PORT_ROW; const summaryRows = node.summaries?.length ?? 0; const summaryHeight = summaryRows ? 20 + summaryRows * 34 + ((node.summary_count ?? 0) > summaryRows ? 18 : 0) : node.ports.settings.length ? 29 : 5; const preview_y = settings_y + summaryHeight + (node.route_label ? 20 : 0); - return { width, height: preview_y + (canvasPreviewReserved(node) ? preview_height + 16 : 0) + (node.kind === "workflow" ? 70 : 42), preview_y, preview_height, settings_y }; + return { width, height: preview_y + (canvasPreviewReserved(node) ? preview_height + 16 : 0) + (footer ?? (node.kind === "workflow" ? 70 : 42)), preview_y, preview_height, settings_y }; } export function canvasNodeSize(node: CanvasStep) { const { width, height } = canvasNodeGeometry(node); diff --git a/web/fx-web/src/port-values.ts b/web/fx-web/src/port-values.ts index a30363ec..3f68d8af 100644 --- a/web/fx-web/src/port-values.ts +++ b/web/fx-web/src/port-values.ts @@ -28,7 +28,7 @@ function bounded(text: string): string { /** A saved plan can seed success without execution; keep the existing evidence rule. */ export function recordedExecution(node: RunNode): boolean { - return node.state === "running" || node.state === "waiting" || node.interrupted === true + return node.state === "running" || node.state === "waiting" || node.state === "awaiting" || node.interrupted === true || node.started_at !== undefined || typeof node.duration_ms === "number" || typeof node.cache === "string" || Object.keys(node.outputs).length > 0; } @@ -163,7 +163,7 @@ export function projectPortValues(view: GraphDocument | ViewerRun, graph: Canvas const output = run ? (raw as RunNode).outputs : undefined; inspection = output && own(output, port.name) ? inspect(output[port.name], true, artifacts, resolveArtifact) : unavailable(raw.state === "absent" || raw.state === "skipped" || run && executed && raw.state === "succeeded" ? "absent" - : !run || ["pending", "running", "waiting"].includes(raw.state) ? "pending" : "unavailable"); + : !run || ["pending", "running", "waiting", "awaiting"].includes(raw.state) ? "pending" : "unavailable"); } else if (own(raw.with, port.name)) { const value = raw.with[port.name]; const waiting = run ? [...raw.reads, ...(raw.bindings?.map((binding) => binding.source) ?? [])] : (raw as GraphDocument["instances"][number]).waiting_on; diff --git a/web/fx-web/src/ports.ts b/web/fx-web/src/ports.ts index 6b81e73c..7c38f358 100644 --- a/web/fx-web/src/ports.ts +++ b/web/fx-web/src/ports.ts @@ -15,12 +15,14 @@ export interface PortBinding { const record = (value: unknown): value is Record => value !== null && typeof value === "object" && !Array.isArray(value); const name = (value: unknown): value is string => typeof value === "string" && value.length > 0; const portName = (value: unknown): value is string => typeof value === "string" && /^[a-z][a-z0-9_]*$/.test(value); -const notation = /^(?:image|audio|video|model|text|json|annotations|file)(?:\/[a-z0-9.+-]+)?(?:\[\]|\{\})?\??$/; +const filePort = (type: unknown): type is string => typeof type === "string" + && /^(?:image|audio|video|model|text|json|annotations|file)(?:\/[a-z0-9.+-]+)?(?:\[\]|\{\})?\??$/.test(type); export function isNodePorts(value: unknown): value is NodePorts { return record(value) && Object.keys(value).length === 3 && record(value.inputs) && record(value.outputs) && record(value.params) - && [value.inputs, value.outputs].every((ports) => Object.entries(ports).every(([key, type]) => portName(key) && typeof type === "string" && notation.test(type))) + && Object.entries(value.inputs).every(([key, type]) => portName(key) && filePort(type)) + && Object.entries(value.outputs).every(([key, type]) => portName(key) && (filePort(type) || type === "value" || type === "value?")) && Object.entries(value.params).every(([key, schema]) => portName(key) && record(schema)); } diff --git a/web/fx-web/src/scope-state.ts b/web/fx-web/src/scope-state.ts index 5c4f13e3..ebf67c8d 100644 --- a/web/fx-web/src/scope-state.ts +++ b/web/fx-web/src/scope-state.ts @@ -15,6 +15,7 @@ export function scopeState(states: readonly string[], plan: boolean): string { if (has("running")) return "running"; // Work started and none of it runs: every active child waits for a route's slot. if (has("waiting")) return "waiting"; + if (has("awaiting")) return "awaiting"; if (has("failed")) return "failed"; if (has("blocked")) return "blocked"; if (has("cancelled")) return "cancelled"; diff --git a/web/fx-web/src/service.ts b/web/fx-web/src/service.ts index 9e260e48..df05318e 100644 --- a/web/fx-web/src/service.ts +++ b/web/fx-web/src/service.ts @@ -110,7 +110,7 @@ export class ServiceIndexProjection { key, title: primary.title, workflow: primary.workflow, primary, latest_known: (runs.length ? runs : plans).every((entry) => entry.created_at !== undefined), show_source: false, runs, plans, - unfinished_runs: runs.filter((entry) => entry !== primary && ["running", "unfinished"].includes(entry.state)), + unfinished_runs: runs.filter((entry) => entry !== primary && ["running", "unfinished", "awaiting"].includes(entry.state)), }; }); const titles = new Map(), workflowIds = new Map(); diff --git a/web/fx-web/src/waiting.ts b/web/fx-web/src/waiting.ts new file mode 100644 index 00000000..e3ca3865 --- /dev/null +++ b/web/fx-web/src/waiting.ts @@ -0,0 +1,256 @@ +import { validateViewerApiBase } from "./route"; +import type { AnswerDraft } from "./answer-draft"; +import type { CanvasGraph, CanvasStep } from "./graph"; + +export type RequestResolution = + | { status: "pending" } + | { status: "answered"; answer: unknown; channel: string; at: string } + | { status: "expired"; at: string }; + +export interface WaitingRequest { + id: string; + step: string; + message?: string; + schema: boolean | Record; + show?: unknown; + choices?: Record | null; + choice_field?: string | null; + deadline?: string | null; + state: RequestResolution; +} + +function object(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +export function parseWaitingRequest(value: unknown): WaitingRequest { + if (object(value) && typeof value.id === "string" && /^[0-9a-f]{64}$/.test(value.id) + && typeof value.step === "string" && (value.message === undefined || typeof value.message === "string") + && (typeof value.schema === "boolean" || object(value.schema)) + && (value.choices == null || object(value.choices)) + && (value.choice_field == null || typeof value.choice_field === "string") + && (value.deadline == null || typeof value.deadline === "string" && Number.isFinite(Date.parse(value.deadline))) + && object(value.state)) { + const state = value.state; + if (state.status === "pending" || (typeof state.at === "string" + && (state.status === "expired" || state.status === "answered" && "answer" in state && typeof state.channel === "string"))) { + return value as unknown as WaitingRequest; + } + } + throw new Error("The viewer received an invalid workflow request."); +} + +export interface ReviewState { + requests: WaitingRequest[]; + openStep: string | null; + error: string | null; + submitting: ReadonlySet; + drafts: ReadonlyMap; + formDrafts: ReadonlyMap; + notices: ReadonlyMap; +} + +type ReviewCard = { message?: string; status: RequestResolution["status"]; deadline?: string }; + +/** Keep elapsed deadlines at zero until an authoritative request update arrives. */ +export function countdownLabel(deadlineMs: number, now = Date.now()): string { + const remainingSeconds = Math.max(0, Math.ceil((deadlineMs - now) / 1000)); + const hours = Math.floor(remainingSeconds / 3600); + const minutes = Math.floor(remainingSeconds / 60) % 60; + const seconds = String(remainingSeconds % 60).padStart(2, "0"); + const remaining = hours > 0 + ? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}` + : `${minutes}:${seconds}`; + return `${remaining} left`; +} + +/** Add live actions to the exact recorded step. A plan or exported graph has no request controller. */ +export function withReviewCards(graph: CanvasGraph, reviews: ReadonlyMap): CanvasGraph { + let changed = false; + const nodes = graph.nodes.map(node => { + if (node.kind || node.pending) return node; + const request = reviews.get(node.source_id); + if (!request && node.state !== "awaiting") return node; + const review_action = request?.status === "answered" ? "view_answer" + : request?.status === "expired" ? "view_outcome" : "review"; + changed = true; + return { + ...node, review_action, + ...(request?.message ? { review_prompt: request.message } : {}), + ...(request?.status === "pending" && request.deadline ? { review_deadline: request.deadline } : {}), + }; + }); + return changed ? { ...graph, nodes } : graph; +} + +/** Native local run viewer only. All answer validation and arbitration belong to FX. + * Polling continues when execution has exited so a second client can resolve a parked run. */ +export class WaitingReviewController { + private readonly base: string; + private readonly listeners = new Set<() => void>(); + private state: ReviewState = { requests: [], openStep: null, error: null, submitting: new Set(), drafts: new Map(), formDrafts: new Map(), notices: new Map() }; + private cards = new Map(); + private session: AbortController | null = null; + private timer: ReturnType | null = null; + + constructor(apiBase: string, private readonly request: typeof fetch = globalThis.fetch.bind(globalThis)) { + this.base = validateViewerApiBase(apiBase); + } + + readonly getSnapshot = (): ReviewState => this.state; + readonly getCards = (): ReadonlyMap => this.cards; + readonly getPendingCount = (): number => { + let count = 0; + for (const card of this.cards.values()) { + if (card.status === "pending") count++; + } + return count; + }; + readonly getOpenStep = (): string | null => this.state.openStep; + readonly subscribe = (listener: () => void) => { + this.listeners.add(listener); + return () => { this.listeners.delete(listener); }; + }; + + private update(state: Partial) { + if (state.requests) { + const next = new Map(); + for (const request of state.requests) { + next.set(request.step, { + message: request.message, + status: request.state.status, + deadline: request.state.status === "pending" ? request.deadline ?? undefined : undefined, + }); + } + // Repeat polls and form edits must leave camera, deck and keyboard focus in place. + if (next.size !== this.cards.size || [...next].some(([step, card]) => { + const previous = this.cards.get(step); + return previous?.message !== card.message || previous?.status !== card.status || previous?.deadline !== card.deadline; + })) this.cards = next; + } + this.state = { ...this.state, ...state }; + for (const listener of this.listeners) listener(); + } + + readonly open = (step: string): void => { + if (this.state.openStep !== step) this.update({ openStep: step }); + }; + + readonly close = (): void => { + if (this.state.openStep !== null) this.update({ openStep: null }); + }; + + start() { + if (this.session) return; + this.session = new AbortController(); + void this.poll(this.session.signal); + } + + stop() { + this.session?.abort(); + this.session = null; + if (this.timer !== null) clearTimeout(this.timer); + this.timer = null; + this.update({ submitting: new Set() }); + } + + private async poll(signal: AbortSignal) { + const before = this.state.requests; + try { + const response = await this.request(`${this.base}/requests`, { signal, cache: "no-store", mode: "same-origin" }); + if (!response.ok) throw new Error(`Could not read workflow requests (HTTP ${response.status}).`); + const body: unknown = await response.json(); + if (!object(body) || !Array.isArray(body.requests)) throw new Error("The workflow request list is invalid."); + const requests = body.requests.map(parseWaitingRequest); + if (signal.aborted) return; + // Only a POST receipt observed during this read can supersede its snapshot. An expiry + // merely projected by an earlier GET can still become pending if the engine clock moves. + if (before !== this.state.requests) { + const previous = new Set(before); + const receipts = new Map(this.state.requests.filter(r => !previous.has(r) && r.state.status !== "pending").map(r => [r.id, r])); + for (const [index, item] of requests.entries()) requests[index] = receipts.get(item.id) ?? item; + } + this.update({ error: null, requests }); + } catch (error) { + if (signal.aborted) return; + this.update({ error: error instanceof Error ? error.message : "Could not read workflow requests." }); + } + if (!signal.aborted) this.timer = setTimeout(() => void this.poll(signal), this.state.error ? 4000 : 1200); + } + + edit(id: string, text: string) { + const notices = new Map(this.state.notices); + notices.delete(id); + this.update({ drafts: new Map(this.state.drafts).set(id, text), notices }); + } + + editForm(id: string, draft: AnswerDraft | undefined) { + const notices = new Map(this.state.notices); + notices.delete(id); + const formDrafts = new Map(this.state.formDrafts); + if (draft === undefined) formDrafts.delete(id); + else formDrafts.set(id, draft); + this.update({ formDrafts, notices }); + } + + choose(request: WaitingRequest, key: string) { + if (!request.choices || !Object.hasOwn(request.choices, key)) return; + const field = request.choice_field; + if (!field) return this.edit(request.id, JSON.stringify(key)); + const previous = parseDraft(this.state.drafts.get(request.id)); + this.edit(request.id, JSON.stringify({ ...(object(previous) ? previous : {}), [field]: key }, null, 2)); + } + + async submit(id: string, text = this.state.drafts.get(id)) { + const signal = this.session?.signal; + if (!signal || signal.aborted || this.state.submitting.has(id) + || !this.state.requests.some(r => r.id === id && r.state.status === "pending")) return; + const answer = parseDraft(text); + if (answer === undefined) { + this.update({ notices: new Map(this.state.notices).set(id, "Complete your answer before submitting.") }); + return; + } + this.update({ submitting: new Set(this.state.submitting).add(id) }); + try { + const response = await this.request(`${this.base}/requests/${encodeURIComponent(id)}/respond`, { + method: "POST", mode: "same-origin", cache: "no-store", signal, + headers: { "Content-Type": "application/json", "X-FX-Action": "respond" }, + // Retain the authored numeric spelling and duplicate keys for FX's strict JSON reader. + body: `{"answer":${text}}`, + }); + const body: unknown = await response.json(); + if (signal.aborted) return; + const winner = response.ok ? body : object(body) ? body.request : null; + if (winner != null) { + const request = parseWaitingRequest(winner); + if (request.id !== id) throw new Error("The response identified a different workflow request."); + this.update({ requests: this.state.requests.map(r => r.id === id ? request : r) }); + } + if (!response.ok) { + if (object(body) && body.code === "invalid_answer") { + throw new Error("Check the fields in your answer and try again."); + } + throw new Error(object(body) && typeof body.error === "string" + ? body.error : `Could not record the answer (HTTP ${response.status}).`); + } + const notices = new Map(this.state.notices); + notices.delete(id); + this.update({ notices }); + } catch (error) { + if (!signal.aborted) this.update({ notices: new Map(this.state.notices).set(id, + error instanceof Error ? error.message : "Could not confirm the answer. Try submitting it again.") }); + } finally { + if (!signal.aborted) { + const submitting = new Set(this.state.submitting); + submitting.delete(id); + this.update({ submitting }); + } + } + } +} + +/** Undefined distinguishes an empty/invalid editor from a valid JSON null, false or zero. */ +export function parseDraft(text: string | undefined): unknown { + if (!text) return undefined; + try { return JSON.parse(text); } catch { return undefined; } +} diff --git a/web/fx-web/tests/canvas.test.ts b/web/fx-web/tests/canvas.test.ts index 67ec2526..e09b82a8 100644 --- a/web/fx-web/tests/canvas.test.ts +++ b/web/fx-web/tests/canvas.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; -import { BADGE_BAND, DECK_OFFSET, canvasEdgePath, canvasNodeGeometry, canvasPreviewReserved, canvasNodeSize, canvasPortAnchor, deckBadge, layoutGraph, restingFront, type CanvasGraph, type CanvasStep, type LayoutReport } from "../src/index"; +import { BADGE_BAND, DECK_OFFSET, canvasEdgePath, canvasNodeGeometry, canvasPreviewReserved, canvasNodeSize, canvasPortAnchor, deckBadge, flatCanvasGraph, layoutGraph, parseViewerRun, restingFront, type CanvasGraph, type CanvasStep, type LayoutReport, type RunNode } from "../src/index"; import { cardStatus, runningLabel } from "../src/card"; +import { reviewFooter } from "../src/layout"; function node(id: string, preview = false, address = id): CanvasStep { return { @@ -250,3 +251,44 @@ test("a running card counts up from its start, never below zero", () => { expect([0, 8_999, 64_000, 3_599_000, 7_500_000, -5_000].map((elapsed) => runningLabel(start, start + elapsed))) .toEqual(["0s", "8s", "1m 04s", "59m 59s", "2h 05m", "0s"]); }); + +test("the request footer keeps the action, prompt and preview count separate", () => { + const passive = { ...node("choose#2"), state: "awaiting" }; + const open: CanvasStep = { ...passive, review_action: "review", review_prompt: "Which frame?" }; + const answered: CanvasStep = { ...open, state: "succeeded", review_action: "view_answer", review_label: "Selected" }; + const expired: CanvasStep = { ...open, state: "failed", review_action: "view_outcome", review_label: "Expired" }; + expect(cardStatus(passive).text).toBe("Awaiting answer"); + expect(cardStatus({ ...passive, review_action: "view_answer" }).text).toBe("Answer recorded"); + expect(cardStatus({ ...passive, review_action: "view_outcome" }).text).toBe("Expired"); + expect(cardStatus(answered).text).toBe("succeeded · Selected"); + expect(cardStatus(expired).text).toBe("failed · Expired"); + expect(reviewFooter(open)?.pending).toBe(true); + expect(reviewFooter(answered)?.pending).toBe(false); + expect(reviewFooter(expired)?.pending).toBe(false); + expect(reviewFooter(node("draw"))).toBeUndefined(); + // Loading the question leaves the ready-to-review card and its wires in place. + expect(canvasNodeSize(passive)).toEqual(canvasNodeSize(open)); + for (const ports of [undefined, { inputs: [], outputs: [], settings: [] }]) { + const image = { ...answered, ports, preview: node("draw", true).preview }; + const box = canvasNodeGeometry(image); + const footerY = box.height - reviewFooter(image)!.height; + expect(footerY - (box.preview_y + box.preview_height)).toBeGreaterThanOrEqual(20); + } +}); + +test("resolved review cards keep execution state and describe only the disclosed decision", () => { + const gate: RunNode = { id: "review#1", path: "review", title: "Review", uses: "fx/await@1", + state: "succeeded", reads: [], with: {}, outputs: {}, cache: null, error: null, duration_ms: 0 }; + const run = { kind: "fx-viewer-run-v1", workflow: { id: "review", title: "Review" }, + run_name: "test", state: "succeeded", stand_in: false, charged_usd: 0, estimate: null, + inputs: {}, outputs: {}, artifacts: [], warnings: [] }; + const status = (node: RunNode) => cardStatus(flatCanvasGraph(parseViewerRun({ ...run, nodes: [node] })).nodes[0]).text; + const answered = { ...gate, review_outcome: "answered" } as const; + expect(status(gate)).toBe("succeeded"); + expect(status({ ...answered, outputs: { answer: { value: "a" }, selected: { none: true } } })).toBe("succeeded · Selected"); + expect(status({ ...answered, outputs: { answer: { value: true } } })).toBe("succeeded · Answered yes"); + expect(status({ ...answered, outputs: { answer: { value: false } } })).toBe("succeeded · Answered no"); + expect(status({ ...answered, outputs: { answer: { withheld: true }, selected: { none: true } } })).toBe("succeeded · Answered"); + expect(status({ ...gate, state: "failed", review_outcome: "expired" })).toBe("failed · Expired"); + expect(status({ ...gate, review_outcome: "expired" })).toBe("succeeded · Expired"); +}); diff --git a/web/fx-web/tests/ports.test.ts b/web/fx-web/tests/ports.test.ts index b771bc5e..7f9c702e 100644 --- a/web/fx-web/tests/ports.test.ts +++ b/web/fx-web/tests/ports.test.ts @@ -43,6 +43,18 @@ function runFromPlan(plan: GraphDocument): ViewerRun { } describe("named port boundary", () => { + test("accepts polymorphic value declarations only on output ports", () => { + for (const type of ["value", "value?"]) { + const plan = portGraph(); + plan.types!.source.ports = { inputs: {}, outputs: { selected: type }, params: {} }; + expect(parseGraph(plan)).toEqual(plan); + const run = runFromPlan(plan); + expect(parseViewerRun(run)).toEqual(run); + expect(isNodePorts({ ...outputPorts, inputs: { input: type } })).toBeFalse(); + } + for (const type of ["value/png", "value[]", "value{}", "value[]?", "value??"]) + expect(isNodePorts({ ...outputPorts, outputs: { selected: type } })).toBeFalse(); + }); test("accepts complete declarations and rejects invalid names, types, schemas and binding duplicates", () => { expect(isNodePorts(outputPorts)).toBeTrue(); for (const ports of [ diff --git a/web/fx-web/tests/state-icon.test.ts b/web/fx-web/tests/state-icon.test.ts index 2921c71d..ddf4c00b 100644 --- a/web/fx-web/tests/state-icon.test.ts +++ b/web/fx-web/tests/state-icon.test.ts @@ -9,4 +9,5 @@ test("every state takes one glyph in the shared circle slot", () => { // Waiting for a route's slot is still: a clock, never the spinning glyph. expect(stateIcon("waiting")).toBe("waiting"); expect(stateIconParts("waiting").map((part) => part.attributes.class)).toEqual(["fx-state-ring", "fx-state-hands"]); + expect(stateIcon("awaiting")).toBe("pending"); }); diff --git a/web/fx-web/tests/waiting.test.ts b/web/fx-web/tests/waiting.test.ts new file mode 100644 index 00000000..9d78d92d --- /dev/null +++ b/web/fx-web/tests/waiting.test.ts @@ -0,0 +1,143 @@ +import { expect, test } from "bun:test"; +import { WaitingReviewController, countdownLabel, parseWaitingRequest, withReviewCards } from "../src/waiting"; +import type { CanvasGraph } from "../src/graph"; +import { emptyAnswer, encodeAnswer, initialAnswer, scalarEnumOptions } from "../src/answer-draft"; + +const id = "a".repeat(64); +const request = { id, step: "choose#1", message: "Choose", schema: { type: "object" }, choice_field: "variant", + choices: { a: { value: "one" }, b: { value: "two" } }, state: { status: "pending" } }; + +test("a conflict returns the CLI winner and further submissions stop", async () => { + const posted: RequestInit[] = []; + const winner = { ...request, state: { status: "answered", channel: "cli", at: "2026-01-01T01:00:00Z", answer: { variant: "a" } } }; + const controller = new WaitingReviewController("/api", (async (url, init) => { + if (String(url) === "/api/requests") return Response.json({ requests: [request] }); + expect(String(url)).toBe(`/api/requests/${id}/respond`); + posted.push(init!); + return Response.json({ request: winner, code: "answer_conflict", error: "Already answered." }, { status: 409 }); + }) as typeof fetch); + try { + controller.start(); + await new Promise(resolve => setTimeout(resolve, 0)); + const current = controller.getSnapshot().requests[0]; + const cards = controller.getCards(); + expect(controller.getPendingCount()).toBe(1); + controller.open(current.step); + expect(controller.getOpenStep()).toBe(current.step); + controller.edit(id, '{"note":"reviewed"}'); + controller.choose(current, "b"); + controller.close(); + expect(controller.getOpenStep()).toBe(null); + expect(controller.getCards()).toBe(cards); + controller.open(current.step); + await controller.submit(id); + expect(JSON.parse(posted[0].body as string)).toEqual({ answer: { note: "reviewed", variant: "b" } }); + expect(new Headers(posted[0].headers).get("x-fx-action")).toBe("respond"); + expect(controller.getSnapshot().requests).toEqual([winner]); + expect(controller.getPendingCount()).toBe(0); + await controller.submit(id); + expect(posted).toHaveLength(1); + } finally { + controller.stop(); + } +}); + +test("a fresh poll can reverse projected expiry, and an in-flight poll preserves a durable receipt", async () => { + const expired = { ...request, state: { status: "expired", at: "2026-01-01T01:00:00Z" } }; + const answered = { ...request, state: { status: "answered", at: "2026-01-01T00:59:59Z", answer: { variant: "a" }, channel: "viewer" } }; + const stale = Promise.withResolvers(); + const reads = [Promise.resolve(Response.json({ requests: [expired] })), + Promise.resolve(Response.json({ requests: [request] })), stale.promise]; + const controller = new WaitingReviewController("/api", (async (_url, init) => + init?.method === "POST" ? Response.json(answered) : reads.shift()!) as typeof fetch); + const poll = async () => { + controller.stop(); + controller.start(); + await new Promise(resolve => setTimeout(resolve, 0)); + }; + try { + await poll(); + expect(controller.getPendingCount()).toBe(0); + await poll(); + expect(controller.getPendingCount()).toBe(1); + await poll(); + await controller.submit(id, '{"variant":"a"}'); + stale.resolve(Response.json({ requests: [expired] })); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(controller.getSnapshot().requests).toEqual([answered]); + } finally { + controller.stop(); + } +}); + +test("review actions bind only to the matching concrete canvas instance", () => { + const deadline = "2026-01-01T01:00:00Z"; + const graph: CanvasGraph = { + nodes: ["choose['a']#1", "choose['b']#1", "draw#1"].map(source_id => ({ + id: `instance:${source_id}`, source_id, title: source_id, subtitle: "", state: "succeeded", pending: false, + })), + edges: [], + }; + const cards = new Map([ + ["choose['a']#1", { message: "Review A", status: "pending" as const, deadline }], + ["choose['b']#1", { message: "Review B", status: "expired" as const, deadline }], + ]); + const live = withReviewCards(graph, cards); + expect(live.nodes[0]).toMatchObject({ review_action: "review", review_prompt: "Review A", review_deadline: deadline }); + expect(live.nodes[1]).toMatchObject({ review_action: "view_outcome", review_prompt: "Review B" }); + expect(live.nodes[1].review_deadline).toBeUndefined(); + expect(live.nodes[2]).toBe(graph.nodes[2]); + expect(withReviewCards(graph, new Map())).toBe(graph); +}); + +test("countdowns round up a partial second and hold at zero after the deadline", () => { + expect(countdownLabel(60_001, 0)).toBe("1:01 left"); + expect(countdownLabel(3_605_000, 0)).toBe("1:00:05 left"); + expect(countdownLabel(1, 0)).toBe("0:01 left"); + expect(countdownLabel(1, 1)).toBe("0:00 left"); + expect(countdownLabel(1, 1001)).toBe("0:00 left"); +}); + +test("request IDs cannot select another API path and JSON null is a recorded answer", () => { + expect(() => parseWaitingRequest({ ...request, id: "../another" })).toThrow(); + const promptless = { id, step: "revision#1", schema: { type: "string" }, state: { status: "pending" } }; + expect(parseWaitingRequest(promptless)).toEqual(promptless); + expect(() => parseWaitingRequest({ ...promptless, message: null })).toThrow(); + const answered = { ...request, state: { status: "answered", answer: null, channel: "viewer", at: "2026-01-01T00:00:00Z" } }; + expect(parseWaitingRequest(answered)).toEqual(answered); +}); + +test("enum selection preserves literal JSON values without picking a default", () => { + const schema = { enum: [0, "", false, null, "0"] }; + expect(initialAnswer(schema)).toBeUndefined(); + const options = scalarEnumOptions(schema)!; + expect(options.map(option => encodeAnswer(option.draft))).toEqual(["0", '""', "false", "null", '"0"']); + expect(new Set(options.map(option => option.label)).size).toBe(options.length); + expect(scalarEnumOptions({ enum: [{ name: "one" }] })).toBeUndefined(); +}); + +test("answer fields preserve exact numeric input and distinguish empty values from incomplete fields", () => { + const fields = [ + { name: "measure", value: { kind: "number" as const, text: "9007199254740993" } }, + { name: "approved", value: { kind: "boolean" as const, value: false } }, + { name: "note", value: { kind: "string" as const, text: "" } }, + { name: "detail", value: { kind: "null" as const } }, + ]; + expect(encodeAnswer({ kind: "object", fields })).toBe('{"measure":9007199254740993,"approved":false,"note":"","detail":null}'); + expect(encodeAnswer({ kind: "object", fields: [...fields, { name: "detail" }] })).toBeUndefined(); + expect(encodeAnswer({ kind: "array", items: [{ kind: "integer", text: "-" }] })).toBeUndefined(); +}); + +test("an empty required container is an answer, an untouched optional container stays absent", () => { + const schema = { + type: "object", required: ["metadata", "tags", "unknown"], + properties: { + metadata: { type: "object", required: ["nested"], properties: { nested: { type: "object" } } }, + tags: { type: "array" }, unknown: { type: ["object", "null"] }, + optional: { type: "object", required: ["name"], properties: { name: { type: "string" } } }, + }, + }; + const expected = '{"metadata":{"nested":{}},"tags":[]}'; + expect(encodeAnswer(initialAnswer(schema))).toBe(expected); + expect(encodeAnswer(emptyAnswer("object", { ...schema, type: ["object", "string"] }))).toBe(expected); +}); diff --git a/web/viewer/public/favicon-awaiting.svg b/web/viewer/public/favicon-awaiting.svg new file mode 100644 index 00000000..af894fc4 --- /dev/null +++ b/web/viewer/public/favicon-awaiting.svg @@ -0,0 +1,14 @@ + + FX Viewer — Awaiting an answer + + + + + + + + + diff --git a/web/viewer/src/main.tsx b/web/viewer/src/main.tsx index d4a1f254..d2e07c6c 100644 --- a/web/viewer/src/main.tsx +++ b/web/viewer/src/main.tsx @@ -1,10 +1,11 @@ -import { StrictMode, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react"; +import { StrictMode, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react"; import { createRoot } from "react-dom/client"; import { flushSync } from "react-dom"; import { ArrowLeft, ArrowUpRight, Check, ChevronRight, Copy, Download, FileText, List, RefreshCw, Square, Workflow, X } from "lucide-react"; -import { ExternalFileController, FileInventoryController, OutputArchiveController, ServiceIndexProjection, ViewerController, ViewerPage, ViewerPresentation, ViewerPresentationError, elapsedLabel, outputFiles, ownsKeys, priceLabel, readFileInventory, skipExplanation, skipSourceScopes, ViewerEntryController, type Artifact, type CanvasPreview, type CanvasStep, type GraphDocument, type GraphInstance, type PendingRepeat, type ServiceEntry, type ServiceIndex, type ViewerRun, type WorkflowNote, type ValueView, valueArtifacts, valueInspectionData, valueKindLabel, valueStateLabel } from "@grida/fx-web"; +import { ExternalFileController, FileInventoryController, OutputArchiveController, ServiceIndexProjection, ViewerController, ViewerPage, ViewerPresentation, ViewerPresentationError, WaitingReviewController, elapsedLabel, outputFiles, ownsKeys, priceLabel, readFileInventory, skipExplanation, skipSourceScopes, ViewerEntryController, type Artifact, type CanvasPreview, type CanvasStep, type GraphDocument, type GraphInstance, type PendingRepeat, type ServiceEntry, type ServiceIndex, type ViewerRun, type WorkflowNote, type ValueView, valueArtifacts, valueInspectionData, valueKindLabel, valueStateLabel, withReviewCards } from "@grida/fx-web"; import { ExternalFileLink, NoteContent, StateIcon, StateLabel, Status, Value, Values, WorkflowCanvas, money, type WorkflowCanvasHandle } from "@grida/fx-react"; import { RunFavicon } from "./run-favicon"; +import { WaitingReviews } from "./waiting-reviews"; import "./style.css"; const entryController = new ViewerEntryController(window.location.pathname); @@ -196,7 +197,7 @@ function RunDetails({ run, node, canvasNode, onInspectSource }: { run: ViewerRun const [inputs, settings] = split(node.with, canvasNode); const skipped = node.state === "skipped" ? skipExplanation(node.skip_reason, run.nodes) : null; return <> - {skipped ?
@@ -268,11 +269,30 @@ function WorkflowView() { const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot); const external = useSyncExternalStore(externalFiles.subscribe, externalFiles.getSnapshot); const inventory = useSyncExternalStore(fileInventory.subscribe, fileInventory.getSnapshot); + const reviews = useMemo(() => new WaitingReviewController(apiBase), []); + const pendingAnswers = useSyncExternalStore(reviews.subscribe, reviews.getPendingCount); + const reviewStep = useSyncExternalStore(reviews.subscribe, reviews.getOpenStep); useEffect(() => { const favicon = new RunFavicon(document.querySelector('link[rel="icon"]')!); - const unsubscribe = controller.subscribe(() => favicon.setActive(controller.getSnapshot().runActive)); - const hide = () => { controller.dispose(); favicon.setActive(false); }; - const show = (event: PageTransitionEvent) => { if (event.persisted) void controller.refresh(); }; + let pageActive = true; + const syncIcon = () => { + if (!pageActive) favicon.setState("idle"); + else if (reviews.getPendingCount() > 0) favicon.setState("awaiting"); + else favicon.setState(controller.getSnapshot().runActive ? "active" : "idle"); + }; + const unsubscribe = controller.subscribe(syncIcon); + const unsubscribeReviews = reviews.subscribe(syncIcon); + const hide = () => { + pageActive = false; + controller.dispose(); + syncIcon(); + }; + const show = (event: PageTransitionEvent) => { + if (!event.persisted) return; + pageActive = true; + void controller.refresh(); + syncIcon(); + }; window.addEventListener("pagehide", hide); window.addEventListener("pageshow", show); void controller.refresh(); @@ -280,22 +300,38 @@ function WorkflowView() { window.removeEventListener("pagehide", hide); window.removeEventListener("pageshow", show); unsubscribe(); + unsubscribeReviews(); controller.dispose(); favicon.dispose(); }; - }, []); + }, [reviews]); const { view, graph, layout, selected, loading, error, scope, breadcrumbs, scopeNode, cancelling } = state; // The workflow's own details, opened from its name; a selection or another workflow closes them. const [about, setAbout] = useState(false); - useEffect(() => setAbout(false), [scope]); - const select = (id: string | null) => { setAbout(false); controller.select(id); }; + useEffect(() => { setAbout(false); reviews.close(); }, [scope, reviews]); + const select = (id: string | null) => { reviews.close(); setAbout(false); controller.select(id); }; const plan = view && view.kind !== "fx-viewer-run-v1" ? view : null; const run = view?.kind === "fx-viewer-run-v1" ? view : null; + const hasReviews = run?.nodes.some(node => /^fx\/await@0*1$/.test(node.uses ?? "")) ?? false; + const reviewOpen = hasReviews && reviewStep !== null; + const reviewCards = useSyncExternalStore(reviews.subscribe, reviews.getCards); + const liveGraph = useMemo(() => hasReviews ? withReviewCards(graph, reviewCards) : graph, [graph, hasReviews, reviewCards]); + let runStatus = run?.state ?? ""; + if (cancelling) runStatus = "cancelling"; + else if (reviewCards.size > 0 && (runStatus === "unfinished" || runStatus === "awaiting")) { + runStatus = pendingAnswers > 0 ? "awaiting" : "unfinished"; + } + useEffect(() => { + if (!hasReviews) return; + reviews.start(); + return () => reviews.stop(); + }, [hasReviews, reviews]); const workflowTitle = view?.workflow.title.trim() || view?.workflow.id; const description = view?.workflow.description?.trim() || (plan ? `Inspect the execution plan for ${workflowTitle}.` : run ? `Inspect run ${run.run_name} for ${workflowTitle}.` : undefined); - usePageMetadata([run ? "Run" : plan ? "Plan" : undefined, workflowTitle, run?.run_name], description); + const runTitle = pendingAnswers === 1 ? "Awaiting answer" : pendingAnswers > 1 ? `Awaiting ${pendingAnswers} answers` : "Run"; + usePageMetadata([run ? runTitle : plan ? "Plan" : undefined, workflowTitle, run?.run_name], description); const selectedNote = graph.notes?.find((note) => note.id === selected); const selectedNode = graph.nodes.find((node) => node.id === selected); const stepNodes = graph.nodes.filter((node) => node.kind !== "value"); @@ -322,16 +358,32 @@ function WorkflowView() { // A step chosen from the list brings its card into the canvas the open panels leave free. const pane = useRef(null); const canvas = useRef(null); + const closeReview = useCallback(() => { + const step = reviews.getOpenStep(); + reviews.close(); + if (!step || !pane.current) return; + const card = pane.current.querySelector(`[data-node-id="${CSS.escape(`instance:${step}`)}"]`); + const action = card?.querySelector(".fx-canvas-review-action"); + if (action?.getClientRects().length) action.focus({ preventScroll: true }); + else pane.current.querySelector(".fx-canvas")?.focus({ preventScroll: true }); + }, [reviews]); const canvasLoaded = view !== null; useEffect(() => { if (!canvasLoaded) return; return presentation.attachCanvas((next, focus) => { // Commit the controller's selection/scope and its details before measuring the free area. - flushSync(() => { setAbout(false); if (focus !== null) setSteps(false); }); + flushSync(() => { + setAbout(false); + if (focus !== null) { + setSteps(false); + reviews.close(); + } + }); if (!canvas.current || !pane.current) throw new ViewerPresentationError("not_ready", "The workflow canvas is not mounted."); - canvas.current.present(next.graph, next.layout, next.selected, next.scope, focus, canvasInset(pane.current)); + const graph = hasReviews ? withReviewCards(next.graph, reviews.getCards()) : next.graph; + canvas.current.present(graph, next.layout, next.selected, next.scope, focus, canvasInset(pane.current)); }); - }, [canvasLoaded]); + }, [canvasLoaded, hasReviews, reviews]); const [reveal, setReveal] = useState<{ id: string } | null>(null); const inspectSource = (id: string) => { if (!run?.nodes.some((node) => node.id === id)) return; @@ -345,33 +397,36 @@ function WorkflowView() { if (!reveal || !pane.current) return; canvas.current?.reveal(reveal.id, canvasInset(pane.current)); }, [reveal]); - // Esc closes the details, then the step list; an open deck takes it before them, and the canvas's own Esc after. + // Esc closes the right-hand panel before the step list. Interactive content can handle it first. useEffect(() => { - if (!open && !steps) return; + if (!reviewOpen && !open && !steps) return; const close = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented || ownsKeys(event.target)) return; event.preventDefault(); - if (open) { setAbout(false); controller.select(null); } else setSteps(false); + if (reviewOpen) closeReview(); + else if (open) { setAbout(false); controller.select(null); } + else setSteps(false); }; document.addEventListener("keydown", close, { capture: true }); return () => document.removeEventListener("keydown", close, { capture: true }); - }, [open, steps]); + }, [reviewOpen, open, steps, closeReview]); return
{error &&

{error}{view && " Showing the last loaded data."}

} {external.error &&

{external.error}{external.failedReference?.target.kind === "artifact" && external.failedReference.target.artifact.url && <>{" "}Open in browser}{" "}

} {external.available && inventory.error &&

{inventory.error}{" "}

} {!view ?

{loading ? "Opening the workflow…" : "Workflow unavailable"}

{loading ? "Reading the selected graph or run." : "Check that the local viewer server is running."}

{!loading && }
:
- + {steps &&
} - {open &&