diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 05a6ec3e..de2885ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,7 +58,7 @@ jobs: mkdir -p "$HOME" for smoke in entity_life_smoke entity_life_loop_smoke multiagent_coding_smoke \ coding_agent_v2_gates_smoke goal_agent_smoke react_coder_smoke \ - ralph_coder_smoke coscientist_smoke decision_workflow_smoke; do + ralph_coder_smoke coscientist_smoke decision_workflow_smoke typed_literals_smoke; do echo "::group::$smoke" python "scripts/$smoke.py" echo "::endgroup::" diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ad4d2ef..28b0dd8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- A value typed on an unwired input takes the input's type (root ADR 0049). A number input stores a number and a + true/false input a boolean; an input that shares its type with others of its node (Compare's `a` and `b`, + Coalesce, the `default` of Get Property, Get Element, Get Random Element and Get Variable, declared as a template + `typeVar`) takes the type wired to them, so `5` typed in Compare `b` next to a wired number is the number 5 and + `a == b` holds. With nothing wired, a typed value is text. A small tag beside the box says the type; a value that + is not of its input's type (including a whole number beyond 2^53, which cannot be stored exactly) is flagged + under its row and refused by the run checks; a rewire converts a value when the conversion is exact. A flow saved by 0.13.0 with such a value stored as text is converted when you open + it, with a notice, and keeps the stored text until you save it. + ## [0.13.0] - 2026-11-02 Needs AbstractRuntime 0.16.0 (the Decision node and the Ask User question policy) and `@abstractframework/ui-kit` ^0.9.12 with `@abstractframework/panel-chat` ^0.7.0. diff --git a/docs/visualflow.md b/docs/visualflow.md index 9916f69d..77ef8292 100644 --- a/docs/visualflow.md +++ b/docs/visualflow.md @@ -143,6 +143,11 @@ The Waits nodes, **Wait Until** (`on_schedule`) and **Wait for Event** (`on_even ## Authoring Rules - Nodes contain editor data and runtime-facing pin defaults. +- A pin default is a JSON value stored with its type (`5`, `"5"`, `true`, `[]`), and the + runtime uses it exactly as stored. The editor stores what is typed on a card as the input's + type, or for an input with a type variable (`typeVar` on the node template, such as Compare's + `a` and `b`) as the type wired to its peers; see + [Web editor > Values typed on a card](web-editor.md#values-typed-on-a-card). - Execution edges connect `exec-out` to `exec-in`. - Data edges connect typed pins. - Provider/model pins should use Gateway-discovered provider ids and models. diff --git a/docs/web-editor.md b/docs/web-editor.md index d9755a21..510fa1c7 100644 --- a/docs/web-editor.md +++ b/docs/web-editor.md @@ -192,6 +192,37 @@ descriptions. The canvas carries no explanatory prose under pins. - **Join** takes its delimiter from a list (Comma, Comma and space, New line, Blank line, Space, Tab) or **Custom…**, a text where `\n` is a new line and `\t` a tab. +### Values typed on a card + +A value you type in an unwired input's box is stored with the input's type, and the runtime +uses it as stored: + +- A **number** input stores a number and a **true/false** input a boolean. A value that is not + one (`abc` on a number input) is outlined, explained under its row ("a: “abc” is not a + number"), and the run checks refuse to run the flow until you fix it. +- An input that takes **any value** but shares its type with other inputs of its node (Compare's + `a` and `b`, Coalesce's inputs and result, the `default` of Get Property, Get Element, Get + Random Element and Get Variable) takes the type of what is wired to them: with `a` wired to a + number, `5` typed in `b` is the number 5, so `a == b` compares 5 with 5. A small tag beside the + box says what you get: **number**, **text**, **true/false**, **JSON** or **list**. +- With nothing wired to give it a type, what you type is **text**. Make Array's elements, Add to + List Variable's `item` and the other inputs that take any value are always text when typed; + the ƒx control is the way to compute a value instead. +- Spaces around a number or a true/false are ignored, and true/false is read in any case + (`True`, `FALSE`). A whole number larger than 9007199254740991 (2^53 − 1) cannot be stored + exactly, so it stays text and is flagged. A number that becomes text is written the way + JavaScript writes it (`1e21` becomes `1e+21`). +- When the wiring changes an input's type, its value follows when the conversion is exact (`5` + and the text "5", `true` and the text "true"); otherwise the value stays as you typed it and is + flagged. A value already stored with a type of its own keeps it while nothing wired says + otherwise. + +A flow saved before this rule may hold such a value as text next to a wired number. Opening it +converts the value, says which values changed ("2 typed values now take the type of their input +… Save to keep them"), and the flow shows unsaved changes until you save it. A flow run without +being opened and saved again keeps the value it stored, and a Compare that meets a number on one +side and text on the other stops the run with "One side is a number and the other is text. Open the flow in the editor and save it to store typed values." + ### If/Else branch order The up/down arrows button at the top right of an If/Else node swaps the order in which its True and diff --git a/docs/workflow-authoring-skill.md b/docs/workflow-authoring-skill.md index 0c5553ae..bd641e06 100644 --- a/docs/workflow-authoring-skill.md +++ b/docs/workflow-authoring-skill.md @@ -116,7 +116,12 @@ Node fields: transcript", not "Variable"). Only On Flow Start / On Flow End may keep defaults. - `pin_defaults`: values for unconnected input pins. Merged per key — omitted - keys keep their current values; emit a key to change it. + keys keep their current values; emit a key to change it. Give each value + the JSON type of its pin: `5` on a `number` pin, and on a `[type T]` pin of + the catalog the type of what is wired to its peers (Compare `b` is `5` + when `a` is wired to a number, `"5"` when it is wired to text). The editor + converts exact text (`"5"` to `5`) and refuses a run on a value that is not + of its pin's type. - `pin_expressions`: sandboxed Python expressions computing input pins at resolution time: `{"condition": "vars.fix_cycles < 3"}`. An expression reads `vars.*` (run variables, read-only) and `value` (the pin's wire value diff --git a/docs/workflow-node-catalog.md b/docs/workflow-node-catalog.md index 73c212f3..9348da67 100644 --- a/docs/workflow-node-catalog.md +++ b/docs/workflow-node-catalog.md @@ -5,6 +5,8 @@ It is the stable AI-readable companion to `docs/workflow-authoring-skill.md`. Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edges": ["node.pin -> node.pin", ...]}`. Each document node uses `type` matching the value shown here; if several visible palette entries share a `type`, set `template` to the exact variant label shown in the document node snippet. +A pin marked `[type T]` shares one type with the other `[type T]` pins of its node (Compare's `a` and `b`): the type comes from what is wired to them. A pin default on such a pin is stored with that type, so give a JSON number (`5`) where the peer carries a number and a JSON string (`"5"`) only where it carries text; with nothing wired, a typed value is text. + ## Visible Authoring Templates ### artifacts / Artifact @@ -129,7 +131,7 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `a` any; `op` string: The operator: ==, !=, >, >=, <, <= (not set: ==).; `b` any +- Inputs: `a` any [type T]; `op` string: The operator: ==, !=, >, >=, <, <= (not set: ==).; `b` any [type T] - Outputs: `result` boolean - Default config: none @@ -545,8 +547,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `a` any; `b` any -- Outputs: `result` any +- Inputs: `a` any [type T]; `b` any [type T] +- Outputs: `result` any [type T] - Default config: none ### data / Concat @@ -609,8 +611,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `array` array: Input array (list/tuple).; `index` number: 0-based index (negative allowed; -1 is last).; `default` any: Fallback value when index is invalid (default null). -- Outputs: `result` any: Element value (or default when not found).; `found` boolean: True when index is valid for the given array. +- Inputs: `array` array: Input array (list/tuple).; `index` number: 0-based index (negative allowed; -1 is last).; `default` any [type T]: Fallback value when index is invalid (default null). +- Outputs: `result` any [type T]: Element value (or default when not found).; `found` boolean: True when index is valid for the given array. - Default config: none ### data / Get Random Element @@ -621,8 +623,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `array` array: Input array (list/tuple).; `default` any: Fallback value when the array is empty (default null). -- Outputs: `result` any: Random element (or default when not found).; `found` boolean: True when an element was selected. +- Inputs: `array` array: Input array (list/tuple).; `default` any [type T]: Fallback value when the array is empty (default null). +- Outputs: `result` any [type T]: Random element (or default when not found).; `found` boolean: True when an element was selected. - Default config: none ### data / Get Property @@ -633,8 +635,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `object` object; `key` string; `default` any -- Outputs: `value` any +- Inputs: `object` object; `key` string; `default` any [type T] +- Outputs: `value` any [type T] - Default config: none ### data / Has Tools @@ -2206,8 +2208,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `name` string; `default` any: Value used when the path is missing. -- Outputs: `value` any +- Inputs: `name` string; `default` any [type T]: Value used when the path is missing. +- Outputs: `value` any [type T] - Default config: none ### variables / Get Variables diff --git a/llms-full.txt b/llms-full.txt index ccd3bc2c..c7178a2f 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -566,6 +566,37 @@ descriptions. The canvas carries no explanatory prose under pins. - **Join** takes its delimiter from a list (Comma, Comma and space, New line, Blank line, Space, Tab) or **Custom…**, a text where `\n` is a new line and `\t` a tab. +### Values typed on a card + +A value you type in an unwired input's box is stored with the input's type, and the runtime +uses it as stored: + +- A **number** input stores a number and a **true/false** input a boolean. A value that is not + one (`abc` on a number input) is outlined, explained under its row ("a: “abc” is not a + number"), and the run checks refuse to run the flow until you fix it. +- An input that takes **any value** but shares its type with other inputs of its node (Compare's + `a` and `b`, Coalesce's inputs and result, the `default` of Get Property, Get Element, Get + Random Element and Get Variable) takes the type of what is wired to them: with `a` wired to a + number, `5` typed in `b` is the number 5, so `a == b` compares 5 with 5. A small tag beside the + box says what you get: **number**, **text**, **true/false**, **JSON** or **list**. +- With nothing wired to give it a type, what you type is **text**. Make Array's elements, Add to + List Variable's `item` and the other inputs that take any value are always text when typed; + the ƒx control is the way to compute a value instead. +- Spaces around a number or a true/false are ignored, and true/false is read in any case + (`True`, `FALSE`). A whole number larger than 9007199254740991 (2^53 − 1) cannot be stored + exactly, so it stays text and is flagged. A number that becomes text is written the way + JavaScript writes it (`1e21` becomes `1e+21`). +- When the wiring changes an input's type, its value follows when the conversion is exact (`5` + and the text "5", `true` and the text "true"); otherwise the value stays as you typed it and is + flagged. A value already stored with a type of its own keeps it while nothing wired says + otherwise. + +A flow saved before this rule may hold such a value as text next to a wired number. Opening it +converts the value, says which values changed ("2 typed values now take the type of their input +… Save to keep them"), and the flow shows unsaved changes until you save it. A flow run without +being opened and saved again keeps the value it stored, and a Compare that meets a number on one +side and text on the other stops the run with "One side is a number and the other is text. Open the flow in the editor and save it to store typed values." + ### If/Else branch order The up/down arrows button at the top right of an If/Else node swaps the order in which its True and @@ -1544,7 +1575,12 @@ Node fields: transcript", not "Variable"). Only On Flow Start / On Flow End may keep defaults. - `pin_defaults`: values for unconnected input pins. Merged per key — omitted - keys keep their current values; emit a key to change it. + keys keep their current values; emit a key to change it. Give each value + the JSON type of its pin: `5` on a `number` pin, and on a `[type T]` pin of + the catalog the type of what is wired to its peers (Compare `b` is `5` + when `a` is wired to a number, `"5"` when it is wired to text). The editor + converts exact text (`"5"` to `5`) and refuses a run on a value that is not + of its pin's type. - `pin_expressions`: sandboxed Python expressions computing input pins at resolution time: `{"condition": "vars.fix_cycles < 3"}`. An expression reads `vars.*` (run variables, read-only) and `value` (the pin's wire value @@ -2423,6 +2459,8 @@ It is the stable AI-readable companion to `docs/workflow-authoring-skill.md`. Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edges": ["node.pin -> node.pin", ...]}`. Each document node uses `type` matching the value shown here; if several visible palette entries share a `type`, set `template` to the exact variant label shown in the document node snippet. +A pin marked `[type T]` shares one type with the other `[type T]` pins of its node (Compare's `a` and `b`): the type comes from what is wired to them. A pin default on such a pin is stored with that type, so give a JSON number (`5`) where the peer carries a number and a JSON string (`"5"`) only where it carries text; with nothing wired, a typed value is text. + ## Visible Authoring Templates ### artifacts / Artifact @@ -2547,7 +2585,7 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `a` any; `op` string: The operator: ==, !=, >, >=, <, <= (not set: ==).; `b` any +- Inputs: `a` any [type T]; `op` string: The operator: ==, !=, >, >=, <, <= (not set: ==).; `b` any [type T] - Outputs: `result` boolean - Default config: none @@ -2963,8 +3001,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `a` any; `b` any -- Outputs: `result` any +- Inputs: `a` any [type T]; `b` any [type T] +- Outputs: `result` any [type T] - Default config: none ### data / Concat @@ -3027,8 +3065,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `array` array: Input array (list/tuple).; `index` number: 0-based index (negative allowed; -1 is last).; `default` any: Fallback value when index is invalid (default null). -- Outputs: `result` any: Element value (or default when not found).; `found` boolean: True when index is valid for the given array. +- Inputs: `array` array: Input array (list/tuple).; `index` number: 0-based index (negative allowed; -1 is last).; `default` any [type T]: Fallback value when index is invalid (default null). +- Outputs: `result` any [type T]: Element value (or default when not found).; `found` boolean: True when index is valid for the given array. - Default config: none ### data / Get Random Element @@ -3039,8 +3077,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `array` array: Input array (list/tuple).; `default` any: Fallback value when the array is empty (default null). -- Outputs: `result` any: Random element (or default when not found).; `found` boolean: True when an element was selected. +- Inputs: `array` array: Input array (list/tuple).; `default` any [type T]: Fallback value when the array is empty (default null). +- Outputs: `result` any [type T]: Random element (or default when not found).; `found` boolean: True when an element was selected. - Default config: none ### data / Get Property @@ -3051,8 +3089,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `object` object; `key` string; `default` any -- Outputs: `value` any +- Inputs: `object` object; `key` string; `default` any [type T] +- Outputs: `value` any [type T] - Default config: none ### data / Has Tools @@ -4624,8 +4662,8 @@ Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edg - Gateway capability: none - Dynamic pin policy: template pins only - Authorable config: input defaults with `pin_defaults` -- Inputs: `name` string; `default` any: Value used when the path is missing. -- Outputs: `value` any +- Inputs: `name` string; `default` any [type T]: Value used when the path is missing. +- Outputs: `value` any [type T] - Default config: none ### variables / Get Variables @@ -5461,6 +5499,11 @@ The Waits nodes, **Wait Until** (`on_schedule`) and **Wait for Event** (`on_even ## Authoring Rules - Nodes contain editor data and runtime-facing pin defaults. +- A pin default is a JSON value stored with its type (`5`, `"5"`, `true`, `[]`), and the + runtime uses it exactly as stored. The editor stores what is typed on a card as the input's + type, or for an input with a type variable (`typeVar` on the node template, such as Compare's + `a` and `b`) as the type wired to its peers; see + [Web editor > Values typed on a card](web-editor.md#values-typed-on-a-card). - Execution edges connect `exec-out` to `exec-in`. - Data edges connect typed pins. - Provider/model pins should use Gateway-discovered provider ids and models. @@ -6589,6 +6632,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- A value typed on an unwired input takes the input's type (root ADR 0049). A number input stores a number and a + true/false input a boolean; an input that shares its type with others of its node (Compare's `a` and `b`, + Coalesce, the `default` of Get Property, Get Element, Get Random Element and Get Variable, declared as a template + `typeVar`) takes the type wired to them, so `5` typed in Compare `b` next to a wired number is the number 5 and + `a == b` holds. With nothing wired, a typed value is text. A small tag beside the box says the type; a value that + is not of its input's type (including a whole number beyond 2^53, which cannot be stored exactly) is flagged + under its row and refused by the run checks; a rewire converts a value when the conversion is exact. A flow saved by 0.13.0 with such a value stored as text is converted when you open + it, with a notice, and keeps the stored text until you save it. + ## [0.13.0] - 2026-11-02 Needs AbstractRuntime 0.16.0 (the Decision node and the Ask User question policy) and `@abstractframework/ui-kit` ^0.9.12 with `@abstractframework/panel-chat` ^0.7.0. diff --git a/scripts/generate-workflow-node-catalog.mjs b/scripts/generate-workflow-node-catalog.mjs index f7eb65a8..daa2d394 100644 --- a/scripts/generate-workflow-node-catalog.mjs +++ b/scripts/generate-workflow-node-catalog.mjs @@ -16,7 +16,8 @@ function json(value) { function pinText(pin) { const label = pin.label && pin.label !== pin.id ? ` (${pin.label})` : ''; const description = pin.description ? `: ${pin.description}` : ''; - return `\`${pin.id}\` ${pin.type}${label}${description}`; + const typeVar = pin.typeVar ? ` [type ${pin.typeVar}]` : ''; + return `\`${pin.id}\` ${pin.type}${typeVar}${label}${description}`; } function defaultConfig(data) { @@ -99,6 +100,8 @@ export async function generateWorkflowNodeCatalog() { '', 'Workflows are authored as one JSON document: `{"flow_name", "nodes": [...], "edges": ["node.pin -> node.pin", ...]}`. Each document node uses `type` matching the value shown here; if several visible palette entries share a `type`, set `template` to the exact variant label shown in the document node snippet.', '', + 'A pin marked `[type T]` shares one type with the other `[type T]` pins of its node (Compare\'s `a` and `b`): the type comes from what is wired to them. A pin default on such a pin is stored with that type, so give a JSON number (`5`) where the peer carries a number and a JSON string (`"5"`) only where it carries text; with nothing wired, a typed value is text.', + '', '## Visible Authoring Templates', '', ]; diff --git a/scripts/typed_literals_smoke.py b/scripts/typed_literals_smoke.py new file mode 100644 index 00000000..da214a12 --- /dev/null +++ b/scripts/typed_literals_smoke.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Run the typed-literals fixtures headlessly through AbstractRuntime (root ADR 0049). + +`src/utils/__fixtures__/typed_literals_flow.json` is what the editor saves for Compare `b` +typed next to a wired number: the JSON numbers 5 and 9. The runtime executes them as stored, +so `5 == 5` and `10 > 9` are true. No model, no network. + +`typed_literals_flow.legacy.json` is the same flow as Flow 0.13.0 saved it (the text "5" and +"9"). The editor converts it when it opens it (src/utils/pinLiterals.test.ts proves the +conversion gives exactly the typed fixture). How the runtime runs it unconverted is the +runtime's contract, tested where it is implemented (AbstractRuntime +tests/test_visual_compare_typed_values.py: a run error naming the Compare node, never a +silent False); this smoke runs against the runtime published on PyPI. +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any, Dict + +from abstractruntime import Runtime, RunStatus +from abstractruntime.storage.in_memory import InMemoryLedgerStore, InMemoryRunStore +from abstractruntime.visualflow_compiler import compile_visualflow + +FIXTURES = Path(__file__).resolve().parents[1] / "src" / "utils" / "__fixtures__" + + +def check(name: str, ok: bool, detail: str = "") -> None: + print(f" [{'PASS' if ok else 'FAIL'}] {name}" + (f" — {detail}" if detail and not ok else "")) + if not ok: + raise SystemExit(f"check failed: {name}: {detail}") + + +def run(path: Path) -> Dict[str, Any]: + spec = compile_visualflow(json.loads(path.read_text(encoding="utf-8"))) + runtime = Runtime(run_store=InMemoryRunStore(), ledger_store=InMemoryLedgerStore()) + run_id = runtime.start(workflow=spec, vars={}) + state = runtime.tick(workflow=spec, run_id=run_id) + check(f"{path.name}: run completed", state.status == RunStatus.COMPLETED, str(state.error)) + return dict(state.output or {}) + + +def main() -> None: + typed = run(FIXTURES / "typed_literals_flow.json") + print(f" typed output: {typed}") + check("typed: 5 == 5 (b stored as the number 5)", typed.get("same") is True, str(typed)) + check("typed: 10 > 9 (b stored as the number 9)", typed.get("above") is True, str(typed)) + + print("typed literals smoke: OK") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/components/Toolbar.tsx b/src/components/Toolbar.tsx index 77c9a091..ecb05356 100644 --- a/src/components/Toolbar.tsx +++ b/src/components/Toolbar.tsx @@ -9,6 +9,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import toast from 'react-hot-toast'; import { copyWithFeedback } from '../lib/copy_feedback'; import { loadEdgeNotice, UNTITLED_FLOW_NAME, useFlowStore } from '../hooks/useFlow'; +import { retypedLiteralsNotice } from '../utils/pinLiterals'; import { NEW_FLOW_EVENT, OPEN_FLOW_EVENT } from '../utils/flowStart'; import { NewFlowDialog, type NewFlowValues } from './NewFlowDialog'; import { useWebSocket } from '../hooks/useWebSocket'; @@ -541,6 +542,9 @@ export function Toolbar() { const showLoadNotices = useCallback(() => { const state = useFlowStore.getState(); if (state.interfacePinsAddedOnLoad > 0) toast(INTERFACE_PINS_ADDED_NOTICE); + // Stored values converted to their inputs' types are said, never converted silently. + const retypedNotice = retypedLiteralsNotice(state.literalsRetypedOnLoad, state.nodes); + if (retypedNotice) toast(retypedNotice, { duration: 10000 }); // Edges the canvas could not draw are never lost silently. const edgeNotice = loadEdgeNotice(state.loadEdgeReport); if (edgeNotice) { diff --git a/src/components/nodes/BaseNode.tsx b/src/components/nodes/BaseNode.tsx index f28fe387..b41abab6 100644 --- a/src/components/nodes/BaseNode.tsx +++ b/src/components/nodes/BaseNode.tsx @@ -20,6 +20,8 @@ import type { FlowNodeData, JsonValue, Pin, PinType, VisualFlow } from '../../ty import { getBundledFlow } from '../../utils/bundledFlows'; import { PIN_COLORS, isEntryNodeType } from '../../types/flow'; import { PinShape } from '../pins/PinShape'; +import { LiteralKindTag, TypedLiteralInput } from '../pins/TypedLiteralInput'; +import { LITERAL_KIND_NOUN, literalKindOfValue, pinLiteralProblem, pinLiteralType } from '../../utils/pinLiterals'; import { PinExpressionChip, PinExpressionEditor, maskStringLiterals } from '../pins/PinExpressionControl'; import { useFoldedReadsForNode } from '../../hooks/foldedGettersContext'; import { IconSwapVertical } from '../ToolbarIcons'; @@ -4479,6 +4481,7 @@ export const BaseNode = memo(function BaseNode({ {(() => { const connected = isPinConnected(pin.id, true); const controls: ReactNode[] = []; + const literalProblem = connected ? null : pinLiteralProblem(id, pin.id, allNodes, edges); // An unwired `any` pin (Make Array's elements, Is Empty's input) keeps a text // field: what you type is the value. The fx control beside it is the explicit @@ -5680,7 +5683,30 @@ export const BaseNode = memo(function BaseNode({ onChange={(v) => setPinDefault(pin.id, v || undefined)} /> ); - } else if (pin.type === 'string' || isAnyTextPin) { + } else if (isAnyTextPin) { + // The value takes the type the graph gives this input (root ADR 0049): + // a type variable resolved from the wires (Compare's b takes a's type), + // else text. The tag says which, so nobody compares 5 with "5" unaware. + const literalType = pinLiteralType(id, pin.id, allNodes, edges); + const resolved = literalType && literalType.from !== 'default' ? literalType.kind : null; + const tagKind = resolved ?? (raw === undefined ? null : literalKindOfValue(raw)) ?? 'string'; + const tagTitle = resolved + ? `Takes the type of what is wired to this node: what you type here is ${LITERAL_KIND_NOUN[resolved]}.` + : literalType + ? 'Nothing wired to this node gives it a type yet: what you type here is text.' + : 'Takes any value: what you type here is text.'; + controls.push( + setPinDefault(pin.id, v)} + />, + + ); + } else if (pin.type === 'string') { controls.push( + {/* A typed value that is not of its input's type (root ADR 0049): said on the card, under its row. */} + {(() => { + const problem = isPinConnected(pin.id, true) ? null : pinLiteralProblem(id, pin.id, allNodes, edges); + return problem ? ( +
+ {pin.label || pin.id}: {problem} +
+ ) : null; + })()} + {/* Inline expression editor: expands below the row it edits. */} {fxEditingPin === pin.id ? ( { + const actual = await importOriginal(); + const live = ((selector?: (s: unknown) => unknown) => (selector ? selector(actual.useFlowStore.getState()) : actual.useFlowStore.getState())) as unknown as typeof actual.useFlowStore; + Object.assign(live, actual.useFlowStore); + return { ...actual, useFlowStore: live }; +}); +const { useFlowStore } = await import('../../hooks/useFlow'); +const { BaseNode } = await import('./BaseNode'); + +function node(id: string, type: NodeType, patch: Partial = {}): Node { + const template = getNodeTemplate(type)!; + return { id, type: 'custom', position: { x: 0, y: 0 }, data: { ...createNodeData(template), ...patch } }; +} + +function renderCard(nodes: Node[], edges: Edge[], id: string): string { + useFlowStore.setState({ nodes, edges }); + const n = useFlowStore.getState().nodes.find((x) => x.id === id)!; + const client = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } }); + const props = { id, data: n.data, selected: false, type: 'custom', zIndex: 0, isConnectable: true, xPos: 0, yPos: 0, dragging: false } as any; + return renderToStaticMarkup( + createElement(QueryClientProvider, { client }, createElement(ReactFlowProvider, null, createElement(BaseNode, props))) + ); +} + +const row = (html: string, pinId: string) => { + const i = html.indexOf(`data-pin-id="${pinId}"`); + expect(i, `row ${pinId}`).toBeGreaterThan(-1); + return html.slice(i, html.indexOf('data-pin-id=', i + 12) > 0 ? html.indexOf('data-pin-id=', i + 12) : undefined); +}; + +describe('typed value tag on the node card', () => { + afterEach(() => useFlowStore.getState().clearFlow()); + const five = () => node('five', 'literal_number', { literalValue: 5 }); + const a = { id: 'e1', source: 'five', sourceHandle: 'value', target: 'cmp', targetHandle: 'a' }; + + it('Compare b next to a wired number: the box shows 5 and the tag says number', () => { + const html = renderCard([five(), node('cmp', 'compare', { pinDefaults: { b: '5' } })], [a], 'cmp'); + const b = row(html, 'b'); + expect(b).toMatch(/]*value="5"/); + expect(b).toMatch(/class="af-pin-type-tag" data-kind="number"[^>]*>number { + const html = renderCard([node('cmp', 'compare', { pinDefaults: { b: '5' } })], [], 'cmp'); + expect(row(html, 'b')).toMatch(/data-kind="string"[^>]*>text { + const html = renderCard([five(), node('cmp', 'compare', { pinDefaults: { b: 'abc' } })], [a], 'cmp'); + expect(row(html, 'b')).toContain('af-pin-input--invalid'); + expect(row(html, 'b')).toContain('af-pin-type-tag--invalid'); + expect(html).toContain('
b: “abc” is not a number
'); + }); +}); diff --git a/src/components/pins/TypedLiteralInput.tsx b/src/components/pins/TypedLiteralInput.tsx new file mode 100644 index 00000000..e0d10aa8 --- /dev/null +++ b/src/components/pins/TypedLiteralInput.tsx @@ -0,0 +1,67 @@ +import { useState } from 'react'; +import { clsx } from 'clsx'; +import type { JsonValue } from '../../types/flow'; +import { type LiteralKind, LITERAL_KIND_LABEL, literalText, parseLiteralText } from '../../utils/pinLiterals'; + +/** + * The box a value is typed in on an unwired input whose type the graph + * decides (root ADR 0049, utils/pinLiterals.ts): what is typed is parsed as + * `kind` and committed as that JSON type; text that is not a value of the + * kind is committed as typed and the card flags it (`problem`). The text + * being typed is kept while the box has focus, so "-" or "1." on the way to + * "-1.5" is not rewritten under the cursor. Empty text is no value. + */ +export function TypedLiteralInput({ + value, + kind, + problem, + ariaLabel, + onCommit, +}: { + value: JsonValue | undefined; + kind: LiteralKind; + problem: string | null; + ariaLabel: string; + onCommit: (value: JsonValue | undefined) => void; +}) { + const [draft, setDraft] = useState(null); + const invalid = draft === null && Boolean(problem); + return ( + e.stopPropagation()} + onClick={(e) => e.stopPropagation()} + onFocus={() => setDraft(literalText(value))} + onBlur={() => setDraft(null)} + onChange={(e) => { + const text = e.target.value; + setDraft(text); + if (text === '') { + onCommit(undefined); + return; + } + // Every keystroke commits, so the flow always holds what the box shows: "-" on the way + // to "-5" is briefly stored as that text (flagged once the box loses focus). + const parsed = parseLiteralText(text, kind); + // Text that is not a value of the kind is kept as typed: the card says why it is wrong. + onCommit(parsed.ok ? parsed.value : text); + }} + /> + ); +} + +/** The small tag beside a typed box that says what the typed value is. */ +export function LiteralKindTag({ kind, title, invalid }: { kind: LiteralKind; title: string; invalid?: boolean }) { + return ( + + {LITERAL_KIND_LABEL[kind]} + + ); +} diff --git a/src/hooks/useFlow.ts b/src/hooks/useFlow.ts index c29bdaed..a52ed1a1 100644 --- a/src/hooks/useFlow.ts +++ b/src/hooks/useFlow.ts @@ -23,6 +23,7 @@ import { computeFoldedGetters } from '../utils/foldedGetters'; import { decisionOutputPinsForData, withDecisionOutputs } from '../utils/decisionPins'; import { withTrailStep } from '../utils/runSpotlight'; import { withLoopItemTypes, withRelayTypes } from '../utils/relays'; +import { typePinLiterals, type RetypedLiteral } from '../utils/pinLiterals'; import { withAgentSchemaOnInput } from '../utils/structuredOutput'; import { withSetVariableRows } from '../utils/setVariables'; import { withoutRedundantTemplateVars } from '../utils/textTemplate'; @@ -179,6 +180,8 @@ interface FlowState { * document excludes them, so such a flow opens with unsaved changes. */ interfacePinsAddedOnLoad: number; + /** Values the last loadFlow converted to their inputs' types (utils/pinLiterals.ts); shown once, saved on the next save. */ + literalsRetypedOnLoad: RetypedLiteral[]; /** * Stored edges the canvas cannot draw because a handle is not a declared * pin (the runtime resolves it by key: code-node dict returns, a subflow's @@ -736,6 +739,7 @@ export const useFlowStore = create((set, get) => ({ flowAutomationDefaults: null, canvasNote: null, interfacePinsAddedOnLoad: 0, + literalsRetypedOnLoad: [], preservedEdges: [], loadEdgeReport: { preserved: [], dropped: [] }, selectedNode: null, @@ -3328,6 +3332,12 @@ export const useFlowStore = create((set, get) => ({ ...(flowAutomationDefaults ? { automation_defaults: deepClone(flowAutomationDefaults) } : {}), }; + // A value stored as text on an input whose type is now known (a flow saved by + // Flow 0.13.0 typed `5` next to a wired number as "5") takes that type here; + // the returned document stays the flow AS STORED, so the flow opens with + // unsaved changes and a notice until it is saved (utils/pinLiterals.ts). + const typedOnLoad = typedGraph(nodes.map(withoutStoredRouteOverrides), displayEdges); + set((state) => ({ flowId: flow.id, draftInstanceId: newDraftInstanceId(), @@ -3335,7 +3345,8 @@ export const useFlowStore = create((set, get) => ({ flowDescription: typeof flow.description === 'string' ? flow.description : '', flowInterfaces: Array.isArray(flow.interfaces) ? flow.interfaces : [], // Per-path values now live only on the drawn per-path wires (displayEdges). - nodes: nodes.map(withoutStoredRouteOverrides), + nodes: typedOnLoad.nodes, + literalsRetypedOnLoad: typedOnLoad.retyped, edges: displayEdges, preservedEdges, loadEdgeReport: edgeReport, @@ -3415,6 +3426,7 @@ export const useFlowStore = create((set, get) => ({ flowAutomationDefaults: null, canvasNote: null, interfacePinsAddedOnLoad: 0, + literalsRetypedOnLoad: [], preservedEdges: [], loadEdgeReport: { preserved: [], dropped: [] }, selectedNode: null, @@ -3469,13 +3481,25 @@ export const useFlowStore = create((set, get) => ({ }, })); +/** Relay and ForEach pin types, then the typed values that follow from them. */ +function typedGraph(nodes: Node[], edges: Edge[]): { nodes: Node[]; retyped: RetypedLiteral[] } { + const relayTyped = withRelayTypes(nodes, edges); + // ForEach over an Email list gives each Email (utils/relays.ts withLoopItemTypes). + return typePinLiterals(withLoopItemTypes(relayTyped, edges), edges); +} + +function withTypedGraph(nodes: Node[], edges: Edge[]): Node[] { + return typedGraph(nodes, edges).nodes; +} + // Relays take the type of the wire that feeds them (utils/relays.ts). One // subscription keeps that true whatever changed the wiring (connect, delete, // undo, the authoring assistant, load); it writes only when a type changes. +// Typed values on unwired inputs follow the same way: a rewire that changes an +// input's type converts its value when exact, else the card flags it +// (utils/pinLiterals.ts, root ADR 0049). useFlowStore.subscribe((state, previous) => { if (state.nodes === previous.nodes && state.edges === previous.edges) return; - const relayTyped = withRelayTypes(state.nodes, state.edges); - // ForEach over an Email list gives each Email (utils/relays.ts withLoopItemTypes). - const typed = withLoopItemTypes(relayTyped, state.edges); + const typed = withTypedGraph(state.nodes, state.edges); if (typed !== state.nodes) useFlowStore.setState({ nodes: typed }); }); diff --git a/src/styles/index.css b/src/styles/index.css index 9cbbefa8..62fb3772 100644 --- a/src/styles/index.css +++ b/src/styles/index.css @@ -1572,6 +1572,37 @@ button.primary:hover:not(:disabled) { box-shadow: 0 0 0 2px rgba(233, 69, 96, 0.18); } +/* Typed pin literals (root ADR 0049): the box of a value whose type the graph + decides carries a small tag saying what the value is; a value that is not + of its input's type is outlined and explained under its row. */ +.af-pin-input--invalid { + border-color: color-mix(in srgb, var(--danger) 70%, transparent); +} + +.af-pin-type-tag { + flex: 0 0 auto; + padding: 0 5px; + border-radius: 6px; + border: 1px solid rgba(255, 255, 255, 0.12); + color: var(--text-secondary); + font-size: 10px; + line-height: 16px; + white-space: nowrap; +} + +.af-pin-type-tag--invalid { + border-color: color-mix(in srgb, var(--danger) 60%, transparent); + color: var(--danger); +} + +.pin-literal-problem { + padding: 0 4px 2px 18px; + color: var(--danger); + font-size: 10px; + line-height: 1.3; + overflow-wrap: anywhere; +} + .node-artifact-upload-input { display: none; } diff --git a/src/types/flow.ts b/src/types/flow.ts index 8ff809aa..73b0f525 100644 --- a/src/types/flow.ts +++ b/src/types/flow.ts @@ -128,6 +128,15 @@ export interface Pin { * This is authoring metadata only; runtime values still flow by pin id. */ schema?: Record; + /** + * A type variable on an `any` pin of a node template: the pins of one node + * that name the same variable carry one type (Compare's `a` and `b`, + * Coalesce's inputs and result). The editor resolves it from the wires, and + * a value typed on an unwired pin of the variable takes that type + * (utils/pinLiterals.ts, root ADR 0049). Read from the template, never + * from a saved pin. + */ + typeVar?: string; } export type PinConnectionFeedback = { diff --git a/src/types/nodes.ts b/src/types/nodes.ts index 99de3bee..ecce74e7 100644 --- a/src/types/nodes.ts +++ b/src/types/nodes.ts @@ -1642,9 +1642,10 @@ const CONTROL_NODES: NodeTemplate[] = [ description: 'Compare a and b using operator op (==, !=, <, <=, >, >=); no operator set compares with ==.', headerColor: '#F39C12', inputs: [ - { id: 'a', label: 'a', type: 'any' }, + // a and b carry one type (T): a value typed on one takes the type wired to the other. + { id: 'a', label: 'a', type: 'any', typeVar: 'T' }, { id: 'op', label: 'op', type: 'string', description: 'The operator: ==, !=, >, >=, <, <= (not set: ==).' }, - { id: 'b', label: 'b', type: 'any' }, + { id: 'b', label: 'b', type: 'any', typeVar: 'T' }, ], outputs: [{ id: 'result', label: 'result', type: 'boolean' }], category: 'control', @@ -1656,8 +1657,8 @@ const CONTROL_NODES: NodeTemplate[] = [ // Data nodes - Pure functions (no execution pins, just data in/out) const DATA_NODES: NodeTemplate[] = [ - { type: 'coalesce', icon: '⇄', label: 'Coalesce', description: 'Return the first non-null value (A, then B, ...).', headerColor: '#3498DB', inputs: [{ id: 'a', label: 'a', type: 'any' }, { id: 'b', label: 'b', type: 'any' }], outputs: [{ id: 'result', label: 'result', type: 'any' }], category: 'data' }, - { type: 'get', icon: '📥', label: 'Get Property', description: 'Safely read a nested path from an object (dot/bracket path) with an optional default.', headerColor: '#3498DB', inputs: [{ id: 'object', label: 'object', type: 'object' }, { id: 'key', label: 'key', type: 'string' }, { id: 'default', label: 'default', type: 'any' }], outputs: [{ id: 'value', label: 'value', type: 'any' }], category: 'data' }, + { type: 'coalesce', icon: '⇄', label: 'Coalesce', description: 'Return the first non-null value (A, then B, ...).', headerColor: '#3498DB', inputs: [{ id: 'a', label: 'a', type: 'any', typeVar: 'T' }, { id: 'b', label: 'b', type: 'any', typeVar: 'T' }], outputs: [{ id: 'result', label: 'result', type: 'any', typeVar: 'T' }], category: 'data' }, + { type: 'get', icon: '📥', label: 'Get Property', description: 'Safely read a nested path from an object (dot/bracket path) with an optional default.', headerColor: '#3498DB', inputs: [{ id: 'object', label: 'object', type: 'object' }, { id: 'key', label: 'key', type: 'string' }, { id: 'default', label: 'default', type: 'any', typeVar: 'T' }], outputs: [{ id: 'value', label: 'value', type: 'any', typeVar: 'T' }], category: 'data' }, { type: 'get_element', icon: '👉', // Pointing hand @@ -1667,10 +1668,10 @@ const DATA_NODES: NodeTemplate[] = [ inputs: [ { id: 'array', label: 'array', type: 'array', description: 'Input array (list/tuple).' }, { id: 'index', label: 'index', type: 'number', description: '0-based index (negative allowed; -1 is last).' }, - { id: 'default', label: 'default', type: 'any', description: 'Fallback value when index is invalid (default null).' }, + { id: 'default', label: 'default', type: 'any', typeVar: 'T', description: 'Fallback value when index is invalid (default null).' }, ], outputs: [ - { id: 'result', label: 'result', type: 'any', description: 'Element value (or default when not found).' }, + { id: 'result', label: 'result', type: 'any', typeVar: 'T', description: 'Element value (or default when not found).' }, { id: 'found', label: 'found', type: 'boolean', description: 'True when index is valid for the given array.' }, ], category: 'data', @@ -1683,10 +1684,10 @@ const DATA_NODES: NodeTemplate[] = [ headerColor: '#3498DB', inputs: [ { id: 'array', label: 'array', type: 'array', description: 'Input array (list/tuple).' }, - { id: 'default', label: 'default', type: 'any', description: 'Fallback value when the array is empty (default null).' }, + { id: 'default', label: 'default', type: 'any', typeVar: 'T', description: 'Fallback value when the array is empty (default null).' }, ], outputs: [ - { id: 'result', label: 'result', type: 'any', description: 'Random element (or default when not found).' }, + { id: 'result', label: 'result', type: 'any', typeVar: 'T', description: 'Random element (or default when not found).' }, { id: 'found', label: 'found', type: 'boolean', description: 'True when an element was selected.' }, ], category: 'data', @@ -1902,9 +1903,10 @@ const VARIABLE_NODES: NodeTemplate[] = [ // `vars.x.get(key, fallback)` and silently resolved to None on a missing path. // On a boolean control pin (`wait_gating`) that flips a gate from shown to // skipped, which is why every trivial-read expression had to stay an expression. - { id: 'default', label: 'default', type: 'any', description: 'Value used when the path is missing.' }, + // default and value carry one type (T): the variable's, once its name is picked. + { id: 'default', label: 'default', type: 'any', typeVar: 'T', description: 'Value used when the path is missing.' }, ], - outputs: [{ id: 'value', label: 'value', type: 'any' }], + outputs: [{ id: 'value', label: 'value', type: 'any', typeVar: 'T' }], category: 'variables', }, { diff --git a/src/utils/__fixtures__/typed_literals_flow.json b/src/utils/__fixtures__/typed_literals_flow.json new file mode 100644 index 00000000..d22180bd --- /dev/null +++ b/src/utils/__fixtures__/typed_literals_flow.json @@ -0,0 +1,223 @@ +{ + "id": "typed-literals", + "name": "Typed literals", + "description": "Compare b typed next to a wired number, saved with its type (root ADR 0049): 5 == 5 and 10 > 9.", + "nodes": [ + { + "id": "start", + "type": "on_flow_start", + "position": { + "x": -520, + "y": 0 + }, + "data": { + "nodeType": "on_flow_start", + "label": "Start", + "icon": "🏁", + "headerColor": "#C0392B", + "inputs": [], + "outputs": [ + { + "id": "exec-out", + "label": "", + "type": "execution" + }, + { + "id": "limit", + "label": "limit", + "type": "number" + } + ], + "pinDefaults": { + "limit": 10 + } + } + }, + { + "id": "five", + "type": "literal_number", + "position": { + "x": -520, + "y": 180 + }, + "data": { + "nodeType": "literal_number", + "label": "Five", + "icon": "#", + "headerColor": "#00FF00", + "inputs": [], + "outputs": [ + { + "id": "value", + "label": "value", + "type": "number" + } + ], + "literalValue": 5 + } + }, + { + "id": "same", + "type": "compare", + "position": { + "x": -200, + "y": 180 + }, + "data": { + "nodeType": "compare", + "label": "Is five", + "icon": "=?", + "headerColor": "#F39C12", + "inputs": [ + { + "id": "a", + "label": "a", + "type": "any", + "typeVar": "T" + }, + { + "id": "op", + "label": "op", + "type": "string" + }, + { + "id": "b", + "label": "b", + "type": "any", + "typeVar": "T" + } + ], + "outputs": [ + { + "id": "result", + "label": "result", + "type": "boolean" + } + ], + "pinDefaults": { + "op": "==", + "b": 5 + } + } + }, + { + "id": "above", + "type": "compare", + "position": { + "x": -200, + "y": 0 + }, + "data": { + "nodeType": "compare", + "label": "Above nine", + "icon": "=?", + "headerColor": "#F39C12", + "inputs": [ + { + "id": "a", + "label": "a", + "type": "any", + "typeVar": "T" + }, + { + "id": "op", + "label": "op", + "type": "string" + }, + { + "id": "b", + "label": "b", + "type": "any", + "typeVar": "T" + } + ], + "outputs": [ + { + "id": "result", + "label": "result", + "type": "boolean" + } + ], + "pinDefaults": { + "op": ">", + "b": 9 + } + } + }, + { + "id": "end", + "type": "on_flow_end", + "position": { + "x": 120, + "y": 0 + }, + "data": { + "nodeType": "on_flow_end", + "label": "End", + "icon": "⏹", + "headerColor": "#C0392B", + "inputs": [ + { + "id": "exec-in", + "label": "", + "type": "execution" + }, + { + "id": "same", + "label": "same", + "type": "boolean" + }, + { + "id": "above", + "label": "above", + "type": "boolean" + } + ], + "outputs": [] + } + } + ], + "edges": [ + { + "id": "e-start-exec-out-end-exec-in", + "source": "start", + "sourceHandle": "exec-out", + "target": "end", + "targetHandle": "exec-in", + "animated": true + }, + { + "id": "e-five-value-same-a", + "source": "five", + "sourceHandle": "value", + "target": "same", + "targetHandle": "a", + "animated": false + }, + { + "id": "e-start-limit-above-a", + "source": "start", + "sourceHandle": "limit", + "target": "above", + "targetHandle": "a", + "animated": false + }, + { + "id": "e-same-result-end-same", + "source": "same", + "sourceHandle": "result", + "target": "end", + "targetHandle": "same", + "animated": false + }, + { + "id": "e-above-result-end-above", + "source": "above", + "sourceHandle": "result", + "target": "end", + "targetHandle": "above", + "animated": false + } + ], + "entryNode": "start" +} diff --git a/src/utils/__fixtures__/typed_literals_flow.legacy.json b/src/utils/__fixtures__/typed_literals_flow.legacy.json new file mode 100644 index 00000000..9a85acad --- /dev/null +++ b/src/utils/__fixtures__/typed_literals_flow.legacy.json @@ -0,0 +1,219 @@ +{ + "id": "typed-literals-legacy", + "name": "Typed literals (Flow 0.13.0 save)", + "description": "The same flow as Flow 0.13.0 saved it: the typed b values stored as text (\"5\", \"9\").", + "nodes": [ + { + "id": "start", + "type": "on_flow_start", + "position": { + "x": -520, + "y": 0 + }, + "data": { + "nodeType": "on_flow_start", + "label": "Start", + "icon": "🏁", + "headerColor": "#C0392B", + "inputs": [], + "outputs": [ + { + "id": "exec-out", + "label": "", + "type": "execution" + }, + { + "id": "limit", + "label": "limit", + "type": "number" + } + ], + "pinDefaults": { + "limit": 10 + } + } + }, + { + "id": "five", + "type": "literal_number", + "position": { + "x": -520, + "y": 180 + }, + "data": { + "nodeType": "literal_number", + "label": "Five", + "icon": "#", + "headerColor": "#00FF00", + "inputs": [], + "outputs": [ + { + "id": "value", + "label": "value", + "type": "number" + } + ], + "literalValue": 5 + } + }, + { + "id": "same", + "type": "compare", + "position": { + "x": -200, + "y": 180 + }, + "data": { + "nodeType": "compare", + "label": "Is five", + "icon": "=?", + "headerColor": "#F39C12", + "inputs": [ + { + "id": "a", + "label": "a", + "type": "any" + }, + { + "id": "op", + "label": "op", + "type": "string" + }, + { + "id": "b", + "label": "b", + "type": "any" + } + ], + "outputs": [ + { + "id": "result", + "label": "result", + "type": "boolean" + } + ], + "pinDefaults": { + "op": "==", + "b": "5" + } + } + }, + { + "id": "above", + "type": "compare", + "position": { + "x": -200, + "y": 0 + }, + "data": { + "nodeType": "compare", + "label": "Above nine", + "icon": "=?", + "headerColor": "#F39C12", + "inputs": [ + { + "id": "a", + "label": "a", + "type": "any" + }, + { + "id": "op", + "label": "op", + "type": "string" + }, + { + "id": "b", + "label": "b", + "type": "any" + } + ], + "outputs": [ + { + "id": "result", + "label": "result", + "type": "boolean" + } + ], + "pinDefaults": { + "op": ">", + "b": "9" + } + } + }, + { + "id": "end", + "type": "on_flow_end", + "position": { + "x": 120, + "y": 0 + }, + "data": { + "nodeType": "on_flow_end", + "label": "End", + "icon": "⏹", + "headerColor": "#C0392B", + "inputs": [ + { + "id": "exec-in", + "label": "", + "type": "execution" + }, + { + "id": "same", + "label": "same", + "type": "boolean" + }, + { + "id": "above", + "label": "above", + "type": "boolean" + } + ], + "outputs": [] + } + } + ], + "edges": [ + { + "id": "e-start-exec-out-end-exec-in", + "source": "start", + "sourceHandle": "exec-out", + "target": "end", + "targetHandle": "exec-in", + "animated": true + }, + { + "id": "e-five-value-same-a", + "source": "five", + "sourceHandle": "value", + "target": "same", + "targetHandle": "a", + "animated": false + }, + { + "id": "e-start-limit-above-a", + "source": "start", + "sourceHandle": "limit", + "target": "above", + "targetHandle": "a", + "animated": false + }, + { + "id": "e-same-result-end-same", + "source": "same", + "sourceHandle": "result", + "target": "end", + "targetHandle": "same", + "animated": false + }, + { + "id": "e-above-result-end-above", + "source": "above", + "sourceHandle": "result", + "target": "end", + "targetHandle": "above", + "animated": false + } + ], + "entryNode": "start" +} diff --git a/src/utils/pinLiterals.test.ts b/src/utils/pinLiterals.test.ts new file mode 100644 index 00000000..76d2c5c3 --- /dev/null +++ b/src/utils/pinLiterals.test.ts @@ -0,0 +1,269 @@ +// Typed pin literals (root ADR 0049): a value typed on an unwired input takes the +// input's type, a type variable resolves from the wires, nothing to resolve from is text. +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { Edge, Node } from 'reactflow'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import type { FlowNodeData, JsonValue, NodeType, VisualFlow } from '../types/flow'; +import { createNodeData, getNodeTemplate } from '../types/nodes'; +import { useFlowStore } from '../hooks/useFlow'; +import { computeRunPreflightIssues } from './preflight'; +import { + convertLiteral, + parseLiteralText, + pinLiteralProblem, + pinLiteralType, + retypedLiteralsNotice, + typePinLiterals, + withTypedPinLiterals, +} from './pinLiterals'; + +function node(id: string, type: NodeType, patch: Partial = {}): Node { + const template = getNodeTemplate(type); + if (!template) throw new Error(`no template for ${type}`); + return { id, type: 'custom', position: { x: 0, y: 0 }, data: { ...createNodeData(template), ...patch } }; +} + +function wire(source: string, sourceHandle: string, target: string, targetHandle: string): Edge { + return { id: `${source}.${sourceHandle}->${target}.${targetHandle}`, source, sourceHandle, target, targetHandle }; +} + +const defaults = (nodes: Node[], id: string) => nodes.find((n) => n.id === id)!.data.pinDefaults || {}; + +/** Compare with `a` wired from `source.handle` and `b` holding `b`. */ +function compareFed(source: Node, handle: string, b: JsonValue) { + const cmp = node('cmp', 'compare', { pinDefaults: { b } }); + return { nodes: [source, cmp], edges: [wire(source.id, handle, 'cmp', 'a')] }; +} + +describe('resolution', () => { + it('Compare: b takes the type wired to a (5 typed next to a wired number is the number 5)', () => { + const { nodes, edges } = compareFed(node('five', 'literal_number', { literalValue: 5 }), 'value', '5'); + expect(pinLiteralType('cmp', 'b', nodes, edges)).toEqual({ kind: 'number', from: 'wire' }); + const typed = withTypedPinLiterals(nodes, edges); + expect(defaults(typed, 'cmp').b).toBe(5); + }); + + it('nothing wired to the type variable: typed text is text ("5" stays "5")', () => { + const nodes = [node('cmp', 'compare', { pinDefaults: { a: '5', b: '5' } })]; + expect(pinLiteralType('cmp', 'b', nodes, [])).toEqual({ kind: 'string', from: 'default' }); + expect(withTypedPinLiterals(nodes, [])).toBe(nodes); + expect(pinLiteralProblem('cmp', 'b', nodes, [])).toBeNull(); + }); + + it('a value stored with its own JSON type keeps it when nothing resolves the variable', () => { + // A generator's Get Property default [] (deep-research.json) is a list, not a wrong text. + const nodes = [node('get', 'get', { pinDefaults: { default: [] } })]; + expect(pinLiteralProblem('get', 'default', nodes, [])).toBeNull(); + expect(withTypedPinLiterals(nodes, [])).toBe(nodes); + }); + + it('an any pin with no type variable takes anything: Make Array keeps "5" as text and 5 as a number', () => { + const nodes = [node('arr', 'make_array', { pinDefaults: { a: '5' } }), node('arr2', 'make_array', { pinDefaults: { a: 5 } })]; + expect(pinLiteralType('arr', 'a', nodes, [])).toBeNull(); + expect(withTypedPinLiterals(nodes, [])).toBe(nodes); + }); + + it("an output's consumer resolves the variable: Coalesce result into Add makes b a number", () => { + const co = node('co', 'coalesce', { pinDefaults: { b: '2' } }); + const add = node('add', 'add'); + const nodes = [co, add]; + const edges = [wire('co', 'result', 'add', 'a')]; + expect(pinLiteralType('co', 'b', nodes, edges)).toEqual({ kind: 'number', from: 'wire' }); + expect(defaults(withTypedPinLiterals(nodes, edges), 'co').b).toBe(2); + }); + + it('through generic nodes: a Coalesce fed a number feeds Compare a, so Compare b is a number', () => { + const five = node('five', 'literal_number', { literalValue: 5 }); + const co = node('co', 'coalesce'); + const cmp = node('cmp', 'compare', { pinDefaults: { b: '5' } }); + const nodes = [five, co, cmp]; + const edges = [wire('five', 'value', 'co', 'a'), wire('co', 'result', 'cmp', 'a')]; + expect(defaults(withTypedPinLiterals(nodes, edges), 'cmp').b).toBe(5); + }); + + it('Get Variable: the default takes the type of the variable the getter reads', () => { + const getter = node('g', 'get_var', { pinDefaults: { name: 'count', default: '3' } }); + getter.data = { ...getter.data, outputs: getter.data.outputs.map((p) => (p.id === 'value' ? { ...p, type: 'number' } : p)) }; + expect(defaults(withTypedPinLiterals([getter], []), 'g').default).toBe(3); + }); + + it('wires that disagree leave the variable unresolved (text)', () => { + const five = node('five', 'literal_number', { literalValue: 5 }); + const word = node('word', 'literal_string', { literalValue: 'x' }); + const co = node('co', 'coalesce', { inputs: [...node('c', 'coalesce').data.inputs, { id: 'c', label: 'c', type: 'any' }] }); + const nodes = [five, word, co]; + const edges = [wire('five', 'value', 'co', 'a'), wire('word', 'value', 'co', 'b')]; + // `c` is a saved pin with no template type variable: it takes anything. + expect(pinLiteralType('co', 'c', nodes, edges)).toBeNull(); + const cmp = node('cmp', 'compare', { pinDefaults: { b: '5' } }); + const all = [...nodes, cmp]; + const allEdges = [...edges, wire('co', 'result', 'cmp', 'a')]; + expect(pinLiteralType('cmp', 'b', all, allEdges)).toEqual({ kind: 'string', from: 'default' }); + }); + + it('a cycle of generic nodes resolves to nothing instead of looping', () => { + const a = node('ca', 'coalesce', { pinDefaults: { b: '1' } }); + const b = node('cb', 'coalesce'); + const nodes = [a, b]; + const edges = [wire('ca', 'result', 'cb', 'a'), wire('cb', 'result', 'ca', 'a')]; + expect(pinLiteralType('ca', 'b', nodes, edges)).toEqual({ kind: 'string', from: 'default' }); + }); + + it('a wired input is not typed or flagged (its value comes from the wire)', () => { + const add = node('add', 'add', { pinDefaults: { a: 'abc' } }); + const five = node('five', 'literal_number', { literalValue: 5 }); + const nodes = [five, add]; + const edges = [wire('five', 'value', 'add', 'a')]; + expect(pinLiteralProblem('add', 'a', nodes, edges)).toBeNull(); + expect(withTypedPinLiterals(nodes, edges)).toBe(nodes); + }); +}); + +describe('declared pin types', () => { + it('a number pin holding "abc" is flagged on the node and refused by the run checks', () => { + const nodes = [node('add', 'add', { pinDefaults: { a: 'abc', b: '2' } })]; + expect(pinLiteralProblem('add', 'a', nodes, [])).toBe('“abc” is not a number'); + const typed = withTypedPinLiterals(nodes, []); + expect(defaults(typed, 'add')).toEqual({ a: 'abc', b: 2 }); + const issues = computeRunPreflightIssues(typed, []); + const issue = issues.find((i) => i.nodeId === 'add'); + expect(issue?.message).toBe('a: “abc” is not a number'); + expect(issue?.severity).toBeUndefined(); // blocking + }); + + it('a boolean pin converts "true"/"false" exactly and flags anything else', () => { + const nodes = [node('and', 'and', { pinDefaults: { a: 'true', b: 'yes' } })]; + const typed = withTypedPinLiterals(nodes, []); + expect(defaults(typed, 'and').a).toBe(true); + expect(pinLiteralProblem('and', 'b', typed, [])).toBe('“yes” is not true or false'); + }); + + it("Wait Until's duration is the timestamp text when the node waits for a timestamp", () => { + const at = '2026-11-03T09:00:00Z'; + const timestamp = node('w', 'wait_until', { pinDefaults: { duration: at }, effectConfig: { durationType: 'timestamp' } }); + expect(pinLiteralProblem('w', 'duration', [timestamp], [])).toBeNull(); + const seconds = node('s', 'wait_until', { pinDefaults: { duration: at } }); + expect(pinLiteralProblem('s', 'duration', [seconds], [])).toBe('“2026-11-03T09:00:00Z” is not a number'); + }); + + it('object and list pins keep their own editors: a stored value is left as it is', () => { + const nodes = [node('m', 'merge', { pinDefaults: { a: '{"x":1}' } })]; + expect(pinLiteralType('m', 'a', nodes, [])).toBeNull(); + expect(withTypedPinLiterals(nodes, [])).toBe(nodes); + }); +}); + +describe('rewiring changes the type', () => { + beforeEach(() => useFlowStore.getState().clearFlow()); + + it('the store converts b when a is wired, rewired to text, and flags what does not convert', () => { + const five = node('five', 'literal_number', { literalValue: 5 }); + const word = node('word', 'literal_string', { literalValue: 'five' }); + const flag = node('flag', 'literal_boolean', { literalValue: true }); + const cmp = node('cmp', 'compare', { pinDefaults: { b: '5' } }); + useFlowStore.setState({ nodes: [five, word, flag, cmp], edges: [] }); + const b = () => defaults(useFlowStore.getState().nodes, 'cmp').b; + expect(b()).toBe('5'); + + useFlowStore.getState().onConnect({ source: 'five', sourceHandle: 'value', target: 'cmp', targetHandle: 'a' }); + expect(b()).toBe(5); + + // Unwired: nothing says otherwise, the number stays a number. + const edgeId = useFlowStore.getState().edges[0].id; + useFlowStore.getState().deleteEdge(edgeId); + expect(b()).toBe(5); + + useFlowStore.getState().onConnect({ source: 'word', sourceHandle: 'value', target: 'cmp', targetHandle: 'a' }); + expect(b()).toBe('5'); + + useFlowStore.getState().deleteEdge(useFlowStore.getState().edges[0].id); + useFlowStore.getState().onConnect({ source: 'flag', sourceHandle: 'value', target: 'cmp', targetHandle: 'a' }); + const { nodes, edges } = useFlowStore.getState(); + expect(b()).toBe('5'); + expect(pinLiteralProblem('cmp', 'b', nodes, edges)).toBe('“5” is not true or false'); + }); +}); + +describe('conversion', () => { + it('parses typed text by kind, never by its look', () => { + expect(parseLiteralText('5', 'number')).toEqual({ ok: true, value: 5 }); + expect(parseLiteralText(' -2.5 ', 'number')).toEqual({ ok: true, value: -2.5 }); + expect(parseLiteralText('.5', 'number')).toEqual({ ok: true, value: 0.5 }); + expect(parseLiteralText('1e3', 'number')).toEqual({ ok: true, value: 1000 }); + expect(parseLiteralText('0x10', 'number').ok).toBe(false); + expect(parseLiteralText('Infinity', 'number').ok).toBe(false); + expect(parseLiteralText('1e999', 'number')).toEqual({ ok: false, problem: '“1e999” is too large a number' }); + expect(parseLiteralText('9007199254740991', 'number')).toEqual({ ok: true, value: 9007199254740991 }); + expect(parseLiteralText('9007199254740993', 'number')).toEqual({ + ok: false, + problem: '“9007199254740993” is too large a number to store exactly', + }); + expect(parseLiteralText('-12345678901234567890', 'number').ok).toBe(false); + expect(parseLiteralText('1e21', 'number')).toEqual({ ok: true, value: 1e21 }); + expect(parseLiteralText('', 'number')).toEqual({ ok: true, value: undefined }); + expect(parseLiteralText('TRUE', 'boolean')).toEqual({ ok: true, value: true }); + expect(parseLiteralText('5', 'string')).toEqual({ ok: true, value: '5' }); + expect(parseLiteralText('{"a":1}', 'object')).toEqual({ ok: true, value: { a: 1 } }); + expect(parseLiteralText('[1]', 'object').ok).toBe(false); + expect(parseLiteralText('[1, 2]', 'array')).toEqual({ ok: true, value: [1, 2] }); + expect(parseLiteralText('{', 'array')).toEqual({ ok: false, problem: '“{” is not valid JSON' }); + }); + + it('converts stored values exactly or says why not', () => { + expect(convertLiteral(5, 'string')).toEqual({ ok: true, value: '5' }); + expect(convertLiteral(true, 'string')).toEqual({ ok: true, value: 'true' }); + expect(convertLiteral(1e21, 'string')).toEqual({ ok: true, value: '1e+21' }); + // A stored text beyond 2^53 is never stored rounded: it stays text and is flagged. + expect(convertLiteral('9007199254740993', 'number').ok).toBe(false); + expect(convertLiteral(5, 'boolean')).toEqual({ ok: false, problem: '5 is a number, not true or false' }); + expect(convertLiteral({ a: 1 }, 'string')).toEqual({ ok: false, problem: '{"a":1} is a JSON object, not text' }); + expect(convertLiteral(null, 'number')).toEqual({ ok: true, value: null }); + }); +}); + +describe('flows saved by Flow 0.13.0 (text on an any input)', () => { + const fixture = (name: string) => + JSON.parse(readFileSync(resolve(__dirname, '__fixtures__', name), 'utf8')) as VisualFlow; + + beforeEach(() => useFlowStore.getState().clearFlow()); + + it('opening one converts the values to their wired types, says so, and keeps the stored document as the baseline', () => { + const legacy = fixture('typed_literals_flow.legacy.json'); + const typed = fixture('typed_literals_flow.json'); + const returned = useFlowStore.getState().loadFlow(legacy); + + // The returned document (the saved baseline) is the flow AS STORED: the flow opens with unsaved changes. + const storedB = (doc: VisualFlow, id: string) => doc.nodes.find((n) => n.id === id)!.data.pinDefaults?.b; + expect(storedB(returned, 'same')).toBe('5'); + + const state = useFlowStore.getState(); + expect(state.literalsRetypedOnLoad).toEqual([ + { nodeId: 'same', pinId: 'b', kind: 'number' }, + { nodeId: 'above', pinId: 'b', kind: 'number' }, + ]); + expect(retypedLiteralsNotice(state.literalsRetypedOnLoad, state.nodes)).toBe( + '2 typed values now take the type of their input (Is five b → number; Above nine b → number). Save to keep them.' + ); + + // Saving gives exactly the values of the typed fixture, which the runtime smoke executes + // (scripts/typed_literals_smoke.py: 5 == 5 and 10 > 9 are true). + const saved = state.getFlow(); + for (const id of ['same', 'above']) { + expect(saved.nodes.find((n) => n.id === id)!.data.pinDefaults).toEqual( + typed.nodes.find((n) => n.id === id)!.data.pinDefaults + ); + } + }); + + it('opening the typed flow changes nothing', () => { + useFlowStore.getState().loadFlow(fixture('typed_literals_flow.json')); + expect(useFlowStore.getState().literalsRetypedOnLoad).toEqual([]); + }); + + it('typePinLiterals reports every conversion it made', () => { + const { nodes, edges } = compareFed(node('five', 'literal_number', { literalValue: 5 }), 'value', '5'); + expect(typePinLiterals(nodes, edges).retyped).toEqual([{ nodeId: 'cmp', pinId: 'b', kind: 'number' }]); + }); +}); diff --git a/src/utils/pinLiterals.ts b/src/utils/pinLiterals.ts new file mode 100644 index 00000000..ce1c8796 --- /dev/null +++ b/src/utils/pinLiterals.ts @@ -0,0 +1,459 @@ +/** + * Typed pin literals (root ADR 0049, operator ruling 2026-11-02). + * + * A value typed on an unwired input takes the type of that input: a number + * pin stores a number, a true/false pin a boolean, a text pin a string. An + * `any` pin that names a type variable (`Pin.typeVar` on the node template: + * Compare's `a`/`b`, Coalesce's inputs and result) takes the type the node's + * wires give that variable, the way a compiler unifies a type variable: + * Compare `a` wired to a number makes the `5` typed on `b` the number 5, never + * the text "5". With nothing to resolve from, a typed value is text. + * + * The type is decided by the graph, never guessed from the text: "5" on an + * unresolved pin stays the text "5". The saved flow stores the JSON value + * with its type (5, "5", true), and the runtime executes it as stored. + * + * One function keeps the stored values true to their types whatever changes + * the wiring (`withTypedPinLiterals`, run by the store subscription and by + * loadFlow): when an input's type is declared or resolved from a wire, a + * value that converts exactly is converted ("5" <-> 5, "true" <-> true), + * anything else stays as typed and is flagged on the node and by the run + * checks (`pinLiteralProblem`), never kept as a silent wrong type. With + * nothing to resolve from, a stored value keeps its own JSON type (a + * generator's `[]` default stays a list; the 5 typed while `a` was wired stays + * 5 once `a` is unwired), and new text typed in the box is text. + */ +import type { Edge, Node } from 'reactflow'; +import type { FlowNodeData, JsonValue, Pin, PinType } from '../types/flow'; +import { getNodeTemplate } from '../types/nodes'; +import { isRouteOverrideEdge } from './multiEntryRoutes'; + +/** The JSON type a typed value is stored as. */ +export type LiteralKind = 'string' | 'number' | 'boolean' | 'object' | 'array'; + +/** What the type tag beside a typed box says. */ +export const LITERAL_KIND_LABEL: Record = { + string: 'text', + number: 'number', + boolean: 'true/false', + object: 'JSON', + array: 'list', +}; + +/** + * Where a pin's literal type comes from: its own declared type (`pin`), the + * wires of its type variable (`wire`), or nothing to resolve from (`default`: + * text typed on a type-variable pin with no wired peer is text, and a value + * already stored keeps its own JSON type: no wire says otherwise). + */ +export type PinLiteralType = { kind: LiteralKind; from: 'pin' | 'wire' | 'default' }; + +const STRING_TYPES: ReadonlySet = new Set([ + 'string', + 'provider', + 'model', + 'provider_text', + 'model_text', + 'provider_image', + 'model_image', + 'provider_video', + 'model_video', + 'provider_voice', + 'model_voice', + 'provider_music', + 'model_music', + 'workspace_file', + 'workspace_folder', +]); +const OBJECT_TYPES: ReadonlySet = new Set([ + 'object', + 'json_schema', + 'memory', + 'assertion', + 'email', + 'artifact', + 'artifact_image', + 'artifact_audio', + 'artifact_text', + 'artifact_video', +]); +const ARRAY_TYPES: ReadonlySet = new Set([ + 'array', + 'tools', + 'assertions', + 'emails', + 'artifacts', + 'artifacts_image', + 'artifacts_audio', + 'artifacts_text', + 'artifacts_video', +]); + +/** The JSON type a value of this pin type is (null: execution, `any`, or a type with no JSON literal). */ +export function literalKindOfType(type: PinType): LiteralKind | null { + if (type === 'number') return 'number'; + if (type === 'boolean') return 'boolean'; + if (STRING_TYPES.has(type)) return 'string'; + if (OBJECT_TYPES.has(type)) return 'object'; + if (ARRAY_TYPES.has(type)) return 'array'; + return null; +} + +/** + * Declared pins whose typed value the editor converts: the scalar ones. A + * declared object/list pin keeps its own JSON editor and is left as stored. + */ +const DECLARED_LITERAL_KINDS: Partial> = { + string: 'string', + number: 'number', + boolean: 'boolean', +}; + +/** The JSON type a stored value has (null for null). */ +export function literalKindOfValue(value: JsonValue): LiteralKind | null { + if (value === null) return null; + if (Array.isArray(value)) return 'array'; + if (typeof value === 'object') return 'object'; + return typeof value as 'string' | 'number' | 'boolean'; +} + +// --------------------------------------------------------------------------- +// The graph index, one per (nodes, edges) pair: a card render or a store +// update asks for many pins of the same graph. + +type Graph = { + nodesById: Map>; + /** `${target}\0${handle}` -> the wire feeding that input. */ + incoming: Map; + /** `${source}\0${handle}` -> the wires leaving that output. */ + outgoing: Map; +}; + +const graphCache = new WeakMap[], WeakMap>(); + +function pinKey(nodeId: string, handle: string | null | undefined): string { + return `${nodeId}\u0000${handle || ''}`; +} + +function graphOf(nodes: Node[], edges: Edge[]): Graph { + let byEdges = graphCache.get(nodes); + if (!byEdges) { + byEdges = new WeakMap(); + graphCache.set(nodes, byEdges); + } + const cached = byEdges.get(edges); + if (cached) return cached; + const incoming = new Map(); + const outgoing = new Map(); + for (const edge of edges) { + // A per-path wire (dashed) replaces the value on one way in only; the pin's + // own value still applies on the others, so it neither wires nor types it. + if (isRouteOverrideEdge(edge)) continue; + incoming.set(pinKey(edge.target, edge.targetHandle), edge); + const out = pinKey(edge.source, edge.sourceHandle); + const list = outgoing.get(out); + if (list) list.push(edge); + else outgoing.set(out, [edge]); + } + const graph: Graph = { nodesById: new Map(nodes.map((n) => [n.id, n])), incoming, outgoing }; + byEdges.set(edges, graph); + return graph; +} + +// --------------------------------------------------------------------------- +// Type variables. + +type Side = 'input' | 'output'; + +/** The type variable the node's TEMPLATE puts on this pin (a saved pin never declares one). */ +function typeVarOf(node: Node, pinId: string, side: Side): string | undefined { + const template = getNodeTemplate(node.data.nodeType); + const pins = side === 'input' ? template?.inputs : template?.outputs; + return pins?.find((p) => p.id === pinId)?.typeVar; +} + +function savedPin(node: Node, pinId: string, side: Side): Pin | undefined { + const pins = side === 'input' ? node.data.inputs : node.data.outputs; + return Array.isArray(pins) ? pins.find((p) => p.id === pinId) : undefined; +} + +/** The one type a set of candidates agrees on, or null (none, or wires that disagree). */ +function agreed(types: PinType[]): PinType | null { + const distinct = new Set(types); + return distinct.size === 1 ? types[0] : null; +} + +/** The type an output carries: its declared type, or its type variable's resolution. */ +function outputType(graph: Graph, nodeId: string, pinId: string, seen: Set): PinType | null { + const node = graph.nodesById.get(nodeId); + const pin = node ? savedPin(node, pinId, 'output') : undefined; + if (!node || !pin || pin.type === 'execution') return null; + if (pin.type !== 'any') return pin.type; + const typeVar = typeVarOf(node, pinId, 'output'); + return typeVar ? resolveTypeVar(graph, node, typeVar, seen) : null; +} + +/** The type an input takes: its declared type, or its type variable's resolution. */ +function inputType(graph: Graph, nodeId: string, pinId: string, seen: Set): PinType | null { + const node = graph.nodesById.get(nodeId); + const pin = node ? savedPin(node, pinId, 'input') : undefined; + if (!node || !pin || pin.type === 'execution') return null; + if (pin.type !== 'any') return pin.type; + const typeVar = typeVarOf(node, pinId, 'input'); + return typeVar ? resolveTypeVar(graph, node, typeVar, seen) : null; +} + +/** + * The concrete type a node's type variable takes, in order: a pin of the + * variable the node already types itself (Get Variable's `value`, typed by the + * variable it reads); else what is wired INTO its pins; else what its outputs + * are wired to. Each step must agree on one type; wires that disagree leave + * the variable unresolved. `seen` stops a cycle of generic nodes. + */ +function resolveTypeVar(graph: Graph, node: Node, typeVar: string, seen: Set): PinType | null { + const key = pinKey(node.id, typeVar); + if (seen.has(key)) return null; + seen.add(key); + const template = getNodeTemplate(node.data.nodeType); + if (!template) return null; + const inputs = template.inputs.filter((p) => p.typeVar === typeVar).map((p) => p.id); + const outputs = template.outputs.filter((p) => p.typeVar === typeVar).map((p) => p.id); + + const own: PinType[] = []; + for (const id of inputs) { + const t = savedPin(node, id, 'input')?.type; + if (t && t !== 'any' && t !== 'execution') own.push(t); + } + for (const id of outputs) { + const t = savedPin(node, id, 'output')?.type; + if (t && t !== 'any' && t !== 'execution') own.push(t); + } + if (own.length > 0) return agreed(own); + + const fed: PinType[] = []; + for (const id of inputs) { + const edge = graph.incoming.get(pinKey(node.id, id)); + if (!edge) continue; + const t = outputType(graph, edge.source, String(edge.sourceHandle || ''), seen); + if (t) fed.push(t); + } + if (fed.length > 0) return agreed(fed); + + const fedTo: PinType[] = []; + for (const id of outputs) { + for (const edge of graph.outgoing.get(pinKey(node.id, id)) || []) { + const t = inputType(graph, edge.target, String(edge.targetHandle || ''), seen); + if (t) fedTo.push(t); + } + } + return fedTo.length > 0 ? agreed(fedTo) : null; +} + +/** + * The type a value typed on this unwired input is stored as, or null when the + * pin takes anything (an `any` pin with no type variable: typed text stays + * text, a value written another way keeps its own JSON type) or has no JSON + * literal (execution, an object/list pin with its own editor). + */ +export function pinLiteralType( + nodeId: string, + pinId: string, + nodes: Node[], + edges: Edge[] +): PinLiteralType | null { + const graph = graphOf(nodes, edges); + const node = graph.nodesById.get(nodeId); + const pin = node ? savedPin(node, pinId, 'input') : undefined; + if (!node || !pin || pin.type === 'execution') return null; + // Wait Until's `duration` is a number of seconds/minutes/hours, or the timestamp to wait + // for when its node says so (the runtime reads it as text then): the node's own setting + // types the pin. + if (node.data.nodeType === 'wait_until' && pinId === 'duration' && node.data.effectConfig?.durationType === 'timestamp') { + return { kind: 'string', from: 'pin' }; + } + if (pin.type !== 'any') { + const kind = DECLARED_LITERAL_KINDS[pin.type]; + return kind ? { kind, from: 'pin' } : null; + } + const typeVar = typeVarOf(node, pinId, 'input'); + if (!typeVar) return null; + const resolved = resolveTypeVar(graph, node, typeVar, new Set()); + if (!resolved) return { kind: 'string', from: 'default' }; + const kind = literalKindOfType(resolved); + return kind ? { kind, from: 'wire' } : null; +} + +/** True when a (non per-path) wire feeds this input. */ +export function isInputWired(nodeId: string, pinId: string, nodes: Node[], edges: Edge[]): boolean { + return graphOf(nodes, edges).incoming.has(pinKey(nodeId, pinId)); +} + +// --------------------------------------------------------------------------- +// Conversion. + +export type LiteralConversion = + | { ok: true; value: JsonValue | undefined } + | { ok: false; problem: string }; + +/** + * Decimal number text, the grammar Python's float() reads (no inf/nan, no + * digit separators): `5`, `-2.5`, `.5`, `1e3`. Hex/octal forms JavaScript's + * Number() would also take are not numbers here. + */ +const DECIMAL_NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; + +function quoted(text: string): string { + const short = text.length > 40 ? `${text.slice(0, 39)}…` : text; + return `“${short}”`; +} + +/** + * Parse what was typed in a box into a value of `kind`. Empty text is no + * value (undefined: the pin has no default). Never guesses: text that is + * not a value of the kind is a problem, reported in plain words. + */ +export function parseLiteralText(text: string, kind: LiteralKind): LiteralConversion { + if (kind === 'string') return { ok: true, value: text }; + const t = text.trim(); + if (t === '') return { ok: true, value: undefined }; + if (kind === 'number') { + if (!DECIMAL_NUMBER.test(t)) return { ok: false, problem: `${quoted(text)} is not a number` }; + const n = Number(t); + if (!Number.isFinite(n)) return { ok: false, problem: `${quoted(text)} is too large a number` }; + // A whole number beyond 2^53 has no exact JSON number in the browser (9007199254740993 would + // be stored as ...992): it stays text and is flagged rather than stored rounded. + const integerText = !t.includes('.') && !t.toLowerCase().includes('e'); + if (integerText && !Number.isSafeInteger(n)) { + return { ok: false, problem: `${quoted(text)} is too large a number to store exactly` }; + } + return { ok: true, value: n }; + } + if (kind === 'boolean') { + const lower = t.toLowerCase(); + if (lower === 'true') return { ok: true, value: true }; + if (lower === 'false') return { ok: true, value: false }; + return { ok: false, problem: `${quoted(text)} is not true or false` }; + } + let parsed: unknown; + try { + parsed = JSON.parse(t); + } catch { + return { ok: false, problem: `${quoted(text)} is not valid JSON` }; + } + if (kind === 'array') { + return Array.isArray(parsed) + ? { ok: true, value: parsed as JsonValue } + : { ok: false, problem: `${quoted(text)} is not a list ([ … ])` }; + } + return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) + ? { ok: true, value: parsed as JsonValue } + : { ok: false, problem: `${quoted(text)} is not a JSON object ({ … })` }; +} + +/** What a value of each kind is, in words ("… is a number"). */ +export const LITERAL_KIND_NOUN: Record = { + string: 'text', + number: 'a number', + boolean: 'true or false', + object: 'a JSON object', + array: 'a list', +}; + +/** + * A stored value as a value of `kind`: unchanged when it already is one, + * converted when the conversion is exact (the text "5" and the number 5, the + * text "true" and true), a problem otherwise. null stays null. + */ +export function convertLiteral(value: JsonValue, kind: LiteralKind): LiteralConversion { + const has = literalKindOfValue(value); + if (has === null || has === kind) return { ok: true, value }; + if (typeof value === 'string') return parseLiteralText(value, kind); + if (kind === 'string' && (has === 'number' || has === 'boolean')) return { ok: true, value: String(value) }; + return { ok: false, problem: `${literalText(value)} is ${LITERAL_KIND_NOUN[has]}, not ${LITERAL_KIND_NOUN[kind]}` }; +} + +/** + * The text a stored value shows in its box, and the text a number becomes when its input turns + * to text: the number as JavaScript writes it (1e21 is "1e+21", as Python writes it too). + */ +export function literalText(value: JsonValue | undefined): string { + if (value === undefined || value === null) return ''; + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'boolean') return String(value); + return JSON.stringify(value); +} + +/** Why the value stored on this unwired input is not of the type it takes, or null. */ +export function pinLiteralProblem( + nodeId: string, + pinId: string, + nodes: Node[], + edges: Edge[] +): string | null { + const defaults = graphOf(nodes, edges).nodesById.get(nodeId)?.data.pinDefaults; + if (!defaults || !Object.prototype.hasOwnProperty.call(defaults, pinId)) return null; + if (isInputWired(nodeId, pinId, nodes, edges)) return null; + const literalType = pinLiteralType(nodeId, pinId, nodes, edges); + if (!literalType || literalType.from === 'default') return null; + const conversion = convertLiteral(defaults[pinId], literalType.kind); + return conversion.ok ? null : conversion.problem; +} + +/** One value loadFlow (or a rewire) converted to its pin's type. */ +export type RetypedLiteral = { nodeId: string; pinId: string; kind: LiteralKind }; + +/** + * The same nodes with every stored value on an unwired, typed input converted + * to that input's type where the conversion is exact (unchanged nodes keep + * their identity; no change returns `nodes` itself). Values that do not + * convert are left as typed: `pinLiteralProblem` flags them. + */ +export function typePinLiterals( + nodes: Node[], + edges: Edge[] +): { nodes: Node[]; retyped: RetypedLiteral[] } { + const retyped: RetypedLiteral[] = []; + let changed = false; + const next = nodes.map((node) => { + const defaults = node.data.pinDefaults; + if (!defaults || !Array.isArray(node.data.inputs)) return node; + let nextDefaults: Record | null = null; + for (const pin of node.data.inputs) { + if (!Object.prototype.hasOwnProperty.call(defaults, pin.id)) continue; + if (isInputWired(node.id, pin.id, nodes, edges)) continue; + const literalType = pinLiteralType(node.id, pin.id, nodes, edges); + if (!literalType || literalType.from === 'default') continue; + const value = defaults[pin.id]; + const conversion = convertLiteral(value, literalType.kind); + if (!conversion.ok || conversion.value === value) continue; + nextDefaults = nextDefaults || { ...defaults }; + if (conversion.value === undefined) delete nextDefaults[pin.id]; + else nextDefaults[pin.id] = conversion.value; + retyped.push({ nodeId: node.id, pinId: pin.id, kind: literalType.kind }); + } + if (!nextDefaults) return node; + changed = true; + return { ...node, data: { ...node.data, pinDefaults: nextDefaults } }; + }); + return { nodes: changed ? next : nodes, retyped }; +} + +/** `typePinLiterals` for callers that only need the nodes. */ +export function withTypedPinLiterals(nodes: Node[], edges: Edge[]): Node[] { + return typePinLiterals(nodes, edges).nodes; +} + +/** The notice after a load that converted stored values to their pins' types, or null. */ +export function retypedLiteralsNotice(retyped: RetypedLiteral[], nodes: Node[], limit = 5): string | null { + if (retyped.length === 0) return null; + const byId = new Map(nodes.map((n) => [n.id, n])); + const shown = retyped.slice(0, limit).map((r) => { + const node = byId.get(r.nodeId); + const label = node?.data.label?.trim() || r.nodeId; + const pinLabel = node?.data.inputs.find((p) => p.id === r.pinId)?.label || r.pinId; + return `${label} ${pinLabel} → ${LITERAL_KIND_LABEL[r.kind]}`; + }); + if (retyped.length > limit) shown.push(`… ${retyped.length - limit} more`); + const n = retyped.length; + return `${n} typed value${n === 1 ? ' now takes' : 's now take'} the type of ${n === 1 ? 'its' : 'their'} input (${shown.join('; ')}). Save to keep ${n === 1 ? 'it' : 'them'}.`; +} diff --git a/src/utils/preflight.ts b/src/utils/preflight.ts index a07f21c6..2aea4ce2 100644 --- a/src/utils/preflight.ts +++ b/src/utils/preflight.ts @@ -11,6 +11,7 @@ import { getArtifactConnectionError, getConfiguredArtifactInputError } from './m import { gatewayCapabilityForNodeType } from './nodeCapabilities'; import { decisionLevels, decisionOptionNames, normalizeDecisionQuestionType } from './decisionPins'; import { loopEndsRunIssues, loopEndsRunMessage } from './loopEndsRun'; +import { pinLiteralProblem } from './pinLiterals'; export type RunPreflightIssue = { id: string; @@ -465,6 +466,16 @@ export function computeRunPreflightIssues( } } + // A value typed on an unwired input that is not of the input's type (a number input, or Compare's + // b next to a wired number, holding "abc"): the run would compare or compute with the wrong + // type, so it is refused with the card's words (utils/pinLiterals.ts, root ADR 0049). + for (const n of nodes) { + for (const pin of n.data.inputs || []) { + const problem = pinLiteralProblem(n.id, pin.id, nodes, edges); + if (problem) push(n, `${pin.label || pin.id}: ${problem}`); + } + } + // A Loop Limit whose `limit reached` goes nowhere: at the limit the path just ends, and at the // top level of the flow that ends the run (review 2026-10-14). for (const n of nodes) {