diff --git a/CHANGELOG.md b/CHANGELOG.md index 28b0dd8..1bbb9bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. +- Run dialog: a flow input wired only to Decision `model` inputs picks from the decision models + (`provider/model` handles from the `output.decision` route) instead of being a text-model picker + disabled behind "Pick provider…". A model input of a form with no provider input can be picked or + typed on its own; it waits for a provider only when the form has one. +- Run dialog: a run that ends in a fraction of a second showed an invented "On Flow End" step and + the last node's answer as its Final Result. The final result is now the run record's output, and a + flow with an On Flow End never gets an invented end row. +- The "Decision triage" example loads with every wire drawn: its end output `model` (a text, the + provider/model that answered) is now `answered_by`; an end pin named `model` is a model picker + that a text cannot feed. ## [0.13.0] - 2026-11-02 diff --git a/docs/web-editor.md b/docs/web-editor.md index 510fa1c..e55edd6 100644 --- a/docs/web-editor.md +++ b/docs/web-editor.md @@ -940,6 +940,9 @@ text and answers it in a single pass with a decision model (Kev / Lev / Laya loc models (a bare id, sent with `provider`); with no provider the model list is every `provider/model` handle, and a handle can be typed (`typesafe/jev-latest`). Empty: the Gateway `output.decision` default. +- **Run dialog.** A flow input wired only to Decision `model` inputs (the example's On Flow Start + `model`) is a decision-model picker in the Run dialog: every `provider/model` handle on the + `output.decision` route, no provider input needed. Empty: the Gateway `output.decision` default. - The option names and level labels are edited as lists in the panel; they become the `enum` of `choice` / `level` and the keys of `probabilities`, so **Break Object** splits `answer` by name and a **Switch** wired from `choice` or `level` offers **Sync cases from enum**. A wire diff --git a/examples/flows/decision-triage.json b/examples/flows/decision-triage.json index a205532..651022f 100644 --- a/examples/flows/decision-triage.json +++ b/examples/flows/decision-triage.json @@ -741,8 +741,8 @@ "type": "number" }, { - "id": "model", - "label": "model", + "id": "answered_by", + "label": "answered_by", "type": "string" } ], @@ -917,15 +917,15 @@ "animated": false }, { - "id": "e-department-model-end-model", + "id": "e-department-model-end-answered_by", "source": "department", "sourceHandle": "model", "target": "end", - "targetHandle": "model", + "targetHandle": "answered_by", "animated": false } ], "entryNode": "start", - "created_at": "2026-11-02T00:10:18.514134+00:00", - "updated_at": "2026-11-02T00:10:18.514134+00:00" + "created_at": "2026-11-03T02:28:57.989476+00:00", + "updated_at": "2026-11-03T02:28:57.989476+00:00" } diff --git a/llms-full.txt b/llms-full.txt index c7178a2..20fffb5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -1314,6 +1314,9 @@ text and answers it in a single pass with a decision model (Kev / Lev / Laya loc models (a bare id, sent with `provider`); with no provider the model list is every `provider/model` handle, and a handle can be typed (`typesafe/jev-latest`). Empty: the Gateway `output.decision` default. +- **Run dialog.** A flow input wired only to Decision `model` inputs (the example's On Flow Start + `model`) is a decision-model picker in the Run dialog: every `provider/model` handle on the + `output.decision` route, no provider input needed. Empty: the Gateway `output.decision` default. - The option names and level labels are edited as lists in the panel; they become the `enum` of `choice` / `level` and the keys of `probabilities`, so **Break Object** splits `answer` by name and a **Switch** wired from `choice` or `level` offers **Sync cases from enum**. A wire @@ -6641,6 +6644,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. +- Run dialog: a flow input wired only to Decision `model` inputs picks from the decision models + (`provider/model` handles from the `output.decision` route) instead of being a text-model picker + disabled behind "Pick provider…". A model input of a form with no provider input can be picked or + typed on its own; it waits for a provider only when the form has one. +- Run dialog: a run that ends in a fraction of a second showed an invented "On Flow End" step and + the last node's answer as its Final Result. The final result is now the run record's output, and a + flow with an On Flow End never gets an invented end row. +- The "Decision triage" example loads with every wire drawn: its end output `model` (a text, the + provider/model that answered) is now `answered_by`; an end pin named `model` is a model picker + that a text cannot feed. ## [0.13.0] - 2026-11-02 diff --git a/scripts/build_decision_workflow.py b/scripts/build_decision_workflow.py index 5284547..2a2f920 100644 --- a/scripts/build_decision_workflow.py +++ b/scripts/build_decision_workflow.py @@ -143,7 +143,9 @@ def build() -> dict: pin("escalate_probability", "escalate_probability", "number"), pin("frustration", "frustration", "string"), pin("frustration_score", "frustration_score", "number"), - pin("model", "model", "string")]), + # `answered_by`: the provider/model that answered (text). An end pin named + # `model` is a model picker (type `model`) once loaded, which a text cannot feed. + pin("answered_by", "answered_by", "string")]), ] edges = [ edge("start", "exec-out", "department", "exec-in", animated=True), @@ -165,7 +167,7 @@ def build() -> dict: edge("escalate", "noul", "end", "escalate_probability"), edge("frustration", "level", "end", "frustration"), edge("frustration", "score", "end", "frustration_score"), - edge("department", "model", "end", "model"), + edge("department", "model", "end", "answered_by"), ] flow["nodes"] = nodes flow["edges"] = edges diff --git a/scripts/decision_workflow_smoke.py b/scripts/decision_workflow_smoke.py index 1fb657e..89f7271 100644 --- a/scripts/decision_workflow_smoke.py +++ b/scripts/decision_workflow_smoke.py @@ -86,7 +86,7 @@ def decide(run: Any, effect: Any, default_next_node: Any) -> Any: check("escalate probability", out.get("escalate_probability") == 0.73, str(out)) check("frustration level from the legend", out.get("frustration") == "Frustrated", str(out)) check("frustration score", out.get("frustration_score") == 1.29, str(out)) - check("model that answered", out.get("model") == "ggml-org/Kev-4B-GGUF:Q4_K_M", str(out)) + check("model that answered", out.get("answered_by") == "ggml-org/Kev-4B-GGUF:Q4_K_M", str(out)) print("decision-triage smoke: all checks passed") diff --git a/src/components/RunFlowModal.tsx b/src/components/RunFlowModal.tsx index 22e2afd..582d785 100644 --- a/src/components/RunFlowModal.tsx +++ b/src/components/RunFlowModal.tsx @@ -33,7 +33,8 @@ import { useListOpen } from '../utils/listOpen'; import { parseSpeculationInput } from '../utils/speculationControls'; import AfSelect from './inputs/AfSelect'; import AfMultiSelect from './inputs/AfMultiSelect'; -import { useProviders, useModels } from '../hooks/useProviders'; +import { useDecisionCatalog, useProviders, useModels } from '../hooks/useProviders'; +import { decisionModelOptions, decisionModelPinIds } from '../utils/decisionPins'; import { TEXT_OUTPUT_CAPABILITY_ROUTE } from '../utils/capabilityRoutes'; import { thinkingOptionsFromModelCapabilities } from '../utils/thinkingControls'; import { RESEARCH_EFFORT_OPTIONS, isResearchEffortPin, normalizeResearchEffort } from '../utils/researchEffort'; @@ -1776,7 +1777,7 @@ function isWorkspacePinType(type: string | undefined): type is 'workspace_file' return type === 'workspace_file' || type === 'workspace_folder'; } -type ProviderScope = 'text' | 'image' | 'voice' | 'music'; +type ProviderScope = 'text' | 'image' | 'voice' | 'music' | 'decision'; type RunSelectOption = { value: string; label: string }; function providerScopeForPin(pin: Pin): ProviderScope | null { @@ -1810,7 +1811,11 @@ function isMusicProviderInputPin(pin: Pin): boolean { return providerScopeForPin(pin) === 'music'; } -function modelScopeForPin(pin: Pin, pins: Pin[]): ProviderScope { +/** + * The catalog a Run-form model input picks from. `decisionPins` are the entry pins that only feed + * Decision `model` inputs (utils/decisionPins `decisionModelPinIds`): they pick a decision model. + */ +export function modelScopeForPin(pin: Pin, pins: Pin[], decisionPins?: ReadonlySet): ProviderScope { if (pin.type === 'model_image' || pin.id === 'image_model' || pin.id === 'model_image') return 'image'; if ( pin.type === 'model_voice' || @@ -1827,6 +1832,7 @@ function modelScopeForPin(pin: Pin, pins: Pin[]): ProviderScope { // launch form. If a form only exposes an image or voice provider, the model // dropdown must use that catalog rather than the generic LLM model catalog. if (pin.type === 'model' || pin.id === 'model') { + if (decisionPins?.has(pin.id)) return 'decision'; const scopes = new Set(pins.map(providerScopeForPin).filter(Boolean) as ProviderScope[]); if (scopes.size === 1 && scopes.has('image')) return 'image'; if (scopes.size === 1 && scopes.has('voice')) return 'voice'; @@ -1836,6 +1842,27 @@ function modelScopeForPin(pin: Pin, pins: Pin[]): ProviderScope { return 'text'; } +/** + * What a run's `flow_complete` does to the timeline: complete the On Flow End row already + * shown, add an "On Flow End" row for a graph that has none (it ends implicitly), or add + * nothing. A graph WITH an On Flow End never gets an invented row: its own step comes from + * the ledger, and the final result is the run record's output (`flow_complete.result`). + */ +export function flowCompletionRow(hasEndRow: boolean, graphHasFlowEnd: boolean): 'update' | 'implicit' | 'none' { + if (hasEndRow) return 'update'; + return graphHasFlowEnd ? 'none' : 'implicit'; +} + +/** + * Whether a Run-form model picker waits for a provider: only when the form has that provider + * input and it is still empty. A decision model is a `provider/model` handle, and a form with no + * provider input lets the model be picked or typed on its own. + */ +export function modelPickerWaitsForProvider(scope: ProviderScope, hasProviderPin: boolean, provider: string): boolean { + if (scope === 'decision') return false; + return hasProviderPin && !provider.trim(); +} + function isModelInputPin(pin: Pin): boolean { return ( pin.type === 'model' || @@ -2081,6 +2108,8 @@ export function RunFlowModal({ return inputPins.filter((p) => p.id !== 'workspace_root'); }, [inputPins]); + const decisionPinIds = useMemo(() => decisionModelPinIds(entryNode?.id, nodes, edges), [entryNode?.id, edges, nodes]); + // Form state for each input pin const [formValues, setFormValues] = useState>({}); const [toolsValues, setToolsValues] = useState>({}); @@ -2230,7 +2259,7 @@ export function RunFlowModal({ }, [formValues, musicProviderPinId]); const modelPinId = useMemo(() => { - const pin = formInputPins.find((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins) === 'text'); + const pin = formInputPins.find((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins, decisionPinIds) === 'text'); return pin?.id || null; }, [formInputPins]); @@ -2331,10 +2360,13 @@ export function RunFlowModal({ const wantProviderDropdown = Boolean(isOpen && formInputPins.some(isTextProviderInputPin)); const wantModelDropdown = Boolean( - isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins) === 'text') + isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins, decisionPinIds) === 'text') ); const providersQuery = useProviders(wantProviderDropdown); const modelsQuery = useModels(selectedProvider || undefined, wantModelDropdown, TEXT_OUTPUT_CAPABILITY_ROUTE); + const decisionCatalogQuery = useDecisionCatalog( + Boolean(isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins, decisionPinIds) === 'decision')) + ); const providers = Array.isArray(providersQuery.data) ? providersQuery.data : []; const models = Array.isArray(modelsQuery.data) ? modelsQuery.data : []; @@ -2415,7 +2447,7 @@ export function RunFlowModal({ const wantsImageProviderDropdown = Boolean(isOpen && formInputPins.some(isImageProviderInputPin)); const wantsImageModelDropdown = Boolean( - isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins) === 'image') + isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins, decisionPinIds) === 'image') ); const imageProvidersQuery = useQuery({ queryKey: ['run-input', 'image-providers', visionProviderModelsEndpoint], @@ -2446,7 +2478,7 @@ export function RunFlowModal({ const wantsVoiceProviderDropdown = Boolean(isOpen && formInputPins.some(isVoiceProviderInputPin)); const wantsVoiceModelDropdown = Boolean( - isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins) === 'voice') + isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins, decisionPinIds) === 'voice') ); const voiceProvidersQuery = useQuery({ queryKey: ['run-input', 'voice-providers', voiceCatalogEndpoint, ttsModelsEndpoint, sttModelsEndpoint, voiceModelMode], @@ -2507,7 +2539,7 @@ export function RunFlowModal({ const wantsMusicProviderDropdown = Boolean(isOpen && formInputPins.some(isMusicProviderInputPin)); const wantsMusicModelDropdown = Boolean( - isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins) === 'music') + isOpen && formInputPins.some((p) => isModelInputPin(p) && modelScopeForPin(p, formInputPins, decisionPinIds) === 'music') ); const musicProvidersQuery = useQuery({ queryKey: ['run-input', 'music-providers', musicProvidersEndpoint, musicProviderModelsTask], @@ -3151,6 +3183,7 @@ export function RunFlowModal({ ev.execId ? `${getActualRunId(ev)}:exec:${ev.execId}` : `${getActualRunId(ev)}:${nodeId || ''}`; const terminalIndexByNode = new Map(); const all: Step[] = []; + const graphHasFlowEnd = Array.from(nodeById.values()).some((n) => n.data?.nodeType === 'on_flow_end'); const forcedThreadId = typeof threadRootRunId === 'string' ? threadRootRunId.trim() : ''; let threadId: string | null = forcedThreadId || null; @@ -3334,7 +3367,8 @@ export function RunFlowModal({ const completedAt = typeof ev.ts === 'string' ? ev.ts : undefined; const terminalSummary = summarize(ev.result) || 'Workflow completed'; - if (terminalIdx >= 0) { + const completionRow = flowCompletionRow(terminalIdx >= 0, graphHasFlowEnd); + if (completionRow === 'update') { const prior = all[terminalIdx]; all[terminalIdx] = { ...prior, @@ -3346,7 +3380,7 @@ export function RunFlowModal({ runtimeStepId: prior.runtimeStepId ?? evStepId, endedAt: completedAt || prior.endedAt, }; - } else { + } else if (completionRow === 'implicit') { const implicitId = '__implicit_flow_end__'; const meta = resolveNodeMeta(implicitId); all.push({ @@ -8212,7 +8246,7 @@ export function RunFlowModal({ setFormValues((prev) => { const next = { ...prev, [pin.id]: v }; for (const candidate of formInputPins) { - if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins) === 'image') next[candidate.id] = ''; + if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins, decisionPinIds) === 'image') next[candidate.id] = ''; } return next; }) @@ -8241,7 +8275,7 @@ export function RunFlowModal({ setFormValues((prev) => { const next = { ...prev, [pin.id]: v }; for (const candidate of formInputPins) { - if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins) === 'voice') next[candidate.id] = ''; + if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins, decisionPinIds) === 'voice') next[candidate.id] = ''; } return next; }) @@ -8270,7 +8304,7 @@ export function RunFlowModal({ setFormValues((prev) => { const next = { ...prev, [pin.id]: v }; for (const candidate of formInputPins) { - if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins) === 'music') next[candidate.id] = ''; + if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins, decisionPinIds) === 'music') next[candidate.id] = ''; } return next; }) @@ -8299,7 +8333,7 @@ export function RunFlowModal({ setFormValues((prev) => { const next = { ...prev, [pin.id]: v }; for (const candidate of formInputPins) { - if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins) === 'text') next[candidate.id] = ''; + if (isModelInputPin(candidate) && modelScopeForPin(candidate, formInputPins, decisionPinIds) === 'text') next[candidate.id] = ''; } return next; }) @@ -8310,7 +8344,7 @@ export function RunFlowModal({ } if (isModelInputPin(pin)) { - const scope = modelScopeForPin(pin, formInputPins); + const scope = modelScopeForPin(pin, formInputPins, decisionPinIds); const scopeProvider = scope === 'image' ? selectedImageProvider @@ -8319,8 +8353,19 @@ export function RunFlowModal({ : scope === 'music' ? selectedMusicProvider : selectedProvider; - const scopeLoading = + const scopeProviderPinId = scope === 'image' + ? imageProviderPinId + : scope === 'voice' + ? voiceProviderPinId + : scope === 'music' + ? musicProviderPinId + : textProviderPinId; + const waitsForProvider = modelPickerWaitsForProvider(scope, Boolean(scopeProviderPinId), scopeProvider); + const scopeLoading = + scope === 'decision' + ? decisionCatalogQuery.isLoading + : scope === 'image' ? imageModelsQuery.isLoading : scope === 'voice' ? voiceModelsQuery.isLoading @@ -8328,7 +8373,9 @@ export function RunFlowModal({ ? musicModelsQuery.isLoading : modelsQuery.isLoading; const scopeOptions = - scope === 'image' + scope === 'decision' + ? decisionModelOptions(decisionCatalogQuery.data, '') + : scope === 'image' ? imageModelOptions : scope === 'voice' ? voiceModelOptions @@ -8344,10 +8391,16 @@ export function RunFlowModal({ { diff --git a/src/components/nodes/BaseNode.tsx b/src/components/nodes/BaseNode.tsx index b41abab..b8ade69 100644 --- a/src/components/nodes/BaseNode.tsx +++ b/src/components/nodes/BaseNode.tsx @@ -41,7 +41,8 @@ import { COMPARE_DEFAULT_OP, COMPARE_OPS, isCollapsibleOperator } from '../../ut import { HiddenConnectionsBadge } from './HiddenConnectionsBadge'; import { NodeStatusGlyph } from './NodeStatusGlyph'; import { categoryColorVar, colorSectionForCategory, nodeSemanticCategory } from '../../utils/nodeCategoryColors'; -import { useDecisionCatalog, useModels, useProviders, type DecisionCatalog } from '../../hooks/useProviders'; +import { useDecisionCatalog, useModels, useProviders } from '../../hooks/useProviders'; +import { decisionModelOptions } from '../../utils/decisionPins'; import { TEXT_OUTPUT_CAPABILITY_ROUTE } from '../../utils/capabilityRoutes'; import { useGatewayCapabilities, gatewayContractsFromCapabilities } from '../../hooks/useGatewayCapabilities'; import { useVisionAdapterCatalog } from '../../hooks/useVisionAdapterCatalog'; @@ -259,19 +260,6 @@ function withCurrentOption(options: SelectOption[], current: string): SelectOpti return [...options, { value: clean, label: clean }]; } -/** - * The Decision `model` choices: the chosen provider's decision models as bare ids, or, - * with no provider, every `provider/model` handle on the output.decision route. - */ -function decisionModelOptions(catalog: DecisionCatalog | undefined, provider: string): SelectOption[] { - const clean = provider.trim(); - if (!catalog) return []; - if (clean) return (catalog.modelsByProvider[clean] || []).map((model) => ({ value: model, label: model })); - return catalog.providers.flatMap((p) => - (catalog.modelsByProvider[p.name] || []).map((model) => ({ value: `${p.name}/${model}`, label: `${p.name}/${model}` })) - ); -} - /** Why a typed Decision model is refused: with no provider it must be a `provider/model` handle. */ export function decisionModelHandleIssue(value: string, provider: string): string | null { if (provider.trim() || value.includes('/')) return null; diff --git a/src/components/runDecisionModel.test.ts b/src/components/runDecisionModel.test.ts new file mode 100644 index 0000000..4bcb697 --- /dev/null +++ b/src/components/runDecisionModel.test.ts @@ -0,0 +1,104 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { beforeEach, describe, expect, it } from 'vitest'; +import type { Pin, VisualFlow } from '../types/flow'; +import { useFlowStore } from '../hooks/useFlow'; +import { decisionModelOptions, decisionModelPinIds } from '../utils/decisionPins'; +import { flowCompleteEventFromSummary } from '../utils/ledgerEvents'; +import { flowCompletionRow, modelPickerWaitsForProvider, modelScopeForPin } from './RunFlowModal'; + +const EXAMPLE = resolve(__dirname, '../../examples/flows/decision-triage.json'); +const example = (): VisualFlow => JSON.parse(readFileSync(EXAMPLE, 'utf8')) as VisualFlow; + +const node = (id: string, nodeType: string) => ({ id, data: { nodeType } }); +const edge = (source: string, sourceHandle: string, target: string, targetHandle: string) => ({ + source, + sourceHandle, + target, + targetHandle, +}); +const modelPin: Pin = { id: 'model', label: 'model', type: 'model' }; + +describe('Run dialog: a model input that only feeds Decision nodes picks a decision model', () => { + const nodes = [node('start', 'on_flow_start'), node('d1', 'decide'), node('d2', 'decide'), node('llm', 'llm_call')]; + + it('finds the entry pins whose every wire ends on a Decision `model` input', () => { + const ids = decisionModelPinIds('start', nodes, [ + edge('start', 'model', 'd1', 'model'), + edge('start', 'model', 'd2', 'model'), + edge('start', 'text_model', 'llm', 'model'), + edge('start', 'mixed', 'd1', 'model'), + edge('start', 'mixed', 'llm', 'model'), + edge('start', 'ticket', 'd1', 'state'), + ]); + expect([...ids]).toEqual(['model']); + expect(decisionModelPinIds(undefined, nodes, [edge('start', 'model', 'd1', 'model')]).size).toBe(0); + }); + + it('the example flow`s `model` input is a decision model picker that needs no provider input', () => { + const flow = example(); + const ids = decisionModelPinIds(flow.entryNode, flow.nodes as never, flow.edges as never); + expect(ids.has('model')).toBe(true); + const start = flow.nodes.find((n) => n.id === flow.entryNode)!; + const pins = start.data.outputs.filter((p) => p.type !== 'execution'); + expect(pins.some((p) => p.type === 'provider' || p.id === 'provider')).toBe(false); + const scope = modelScopeForPin(modelPin, pins, ids); + expect(scope).toBe('decision'); + expect(modelPickerWaitsForProvider(scope, false, '')).toBe(false); + // Without the graph scope the same pin is a text model. + expect(modelScopeForPin(modelPin, pins)).toBe('text'); + }); + + it('offers `provider/model` handles, so the chosen value carries its provider', () => { + const catalog = { + providers: [{ name: 'mlx' }, { name: 'typesafe' }] as never, + modelsByProvider: { mlx: ['AbstractFramework/kev-0.8b-mlx-8bit'], typesafe: ['jev-latest'] }, + }; + expect(decisionModelOptions(catalog, '').map((o) => o.value)).toEqual([ + 'mlx/AbstractFramework/kev-0.8b-mlx-8bit', + 'typesafe/jev-latest', + ]); + expect(decisionModelOptions(catalog, 'typesafe').map((o) => o.value)).toEqual(['jev-latest']); + }); + + it('a model picker waits for a provider only when the form has that provider input', () => { + expect(modelPickerWaitsForProvider('text', true, '')).toBe(true); + expect(modelPickerWaitsForProvider('text', true, 'ollama')).toBe(false); + expect(modelPickerWaitsForProvider('text', false, '')).toBe(false); + expect(modelPickerWaitsForProvider('image', false, '')).toBe(false); + }); +}); + +describe('decision-triage example', () => { + beforeEach(() => useFlowStore.getState().clearFlow()); + + it('loads with every wire drawn (no connection kept hidden for a type mismatch)', () => { + useFlowStore.getState().loadFlow(example()); + const report = useFlowStore.getState().loadEdgeReport; + expect(report.dropped).toEqual([]); + expect(report.preserved).toEqual([]); + }); +}); + +describe('a completed run`s final result is the run record`s output', () => { + it('never invents an On Flow End row for a graph that has one', () => { + expect(flowCompletionRow(false, true)).toBe('none'); + expect(flowCompletionRow(true, true)).toBe('update'); + expect(flowCompletionRow(false, false)).toBe('implicit'); + }); + + it('flow_complete from the run summary carries summary.output', () => { + const output = { department: 'shipping', escalate: true, answered_by: 'AbstractFramework/kev-0.8b-mlx-8bit' }; + expect(flowCompleteEventFromSummary('r1', { status: 'completed', output }, 't')).toEqual({ + type: 'flow_complete', + runId: 'r1', + ts: 't', + result: output, + }); + expect(flowCompleteEventFromSummary('r1', { status: 'completed', output: null }, 't')).toEqual({ + type: 'flow_complete', + runId: 'r1', + ts: 't', + }); + }); +}); diff --git a/src/hooks/useWebSocket.ts b/src/hooks/useWebSocket.ts index 4bb7970..e8cc510 100644 --- a/src/hooks/useWebSocket.ts +++ b/src/hooks/useWebSocket.ts @@ -9,6 +9,7 @@ import { useFlowStore } from './useFlow'; import { closeOpenNodes, createLedgerMappingState, + flowCompleteEventFromSummary, mapLedgerRecordToEvents, type LedgerRecord, } from '../utils/ledgerEvents'; @@ -690,7 +691,7 @@ export function useWebSocket({ flowId, onEvent, onWaiting }: UseWebSocketOptions const closeEvents = closeOpenNodes({ runId: rid, state: mappingStateRef.current, ts: updatedAt }); closeEvents.forEach(dispatchEvent); terminalEmittedRef.current.set(rid, terminalKey); - dispatchEvent({ type: 'flow_complete', runId: rid, ts: updatedAt }); + dispatchEvent(flowCompleteEventFromSummary(rid, summary, updatedAt)); return; } if (status === 'failed') { diff --git a/src/utils/decisionPins.ts b/src/utils/decisionPins.ts index eef38d3..a040d20 100644 --- a/src/utils/decisionPins.ts +++ b/src/utils/decisionPins.ts @@ -9,6 +9,7 @@ * options or levels change (like Switch cases) and re-derives them on load. * Pure: values in, pins out. */ +import type { DecisionCatalog } from '../hooks/useProviders'; import type { FlowNodeData, Pin } from '../types/flow'; export const DECISION_QUESTION_TYPES = ['choice', 'noul', 'score'] as const; @@ -197,3 +198,43 @@ export function mergeDecisionOptionRows(previous: unknown, rows: string[]): unkn } return rows; } + +/** + * The Decision `model` choices: the chosen provider's decision models as bare ids, or, + * with no provider, every `provider/model` handle on the output.decision route (the + * handle carries its provider, so no separate provider input is needed). + */ +export function decisionModelOptions( + catalog: DecisionCatalog | undefined, + provider: string +): Array<{ value: string; label: string }> { + const clean = provider.trim(); + if (!catalog) return []; + if (clean) return (catalog.modelsByProvider[clean] || []).map((model) => ({ value: model, label: model })); + return catalog.providers.flatMap((p) => + (catalog.modelsByProvider[p.name] || []).map((model) => ({ value: `${p.name}/${model}`, label: `${p.name}/${model}` })) + ); +} + +/** + * The entry node's output pins that pick a decision model: every wire leaving the pin ends on + * the `model` input of a Decision node (and there is at least one). The Run dialog offers those + * pins the decision-model catalog instead of the text-model one. Read from the graph only. + */ +export function decisionModelPinIds( + entryNodeId: string | undefined, + nodes: ReadonlyArray<{ id: string; data: { nodeType?: string } }>, + edges: ReadonlyArray<{ source: string; sourceHandle?: string | null; target: string; targetHandle?: string | null }> +): Set { + const out = new Set(); + if (!entryNodeId) return out; + const typeById = new Map(nodes.map((n) => [n.id, n.data?.nodeType])); + const feedsDecisionOnly = new Map(); + for (const e of edges) { + if (e.source !== entryNodeId || !e.sourceHandle) continue; + const toDecisionModel = typeById.get(e.target) === 'decide' && e.targetHandle === 'model'; + feedsDecisionOnly.set(e.sourceHandle, (feedsDecisionOnly.get(e.sourceHandle) ?? true) && toDecisionModel); + } + for (const [pinId, only] of feedsDecisionOnly) if (only) out.add(pinId); + return out; +} diff --git a/src/utils/ledgerEvents.ts b/src/utils/ledgerEvents.ts index e7d74fb..78f3aa1 100644 --- a/src/utils/ledgerEvents.ts +++ b/src/utils/ledgerEvents.ts @@ -432,3 +432,19 @@ export function closeOpenNodes({ openNodes.clear(); return out; } + +/** + * The `flow_complete` event of a run whose summary reads `completed`. Its `result` is the run + * record's final output (`summary.output`, the On Flow End's values), so the Run dialog's final + * result never depends on which ledger rows the stream delivered before the run ended. + */ +export function flowCompleteEventFromSummary( + runId: string, + summary: Record, + ts: string | undefined +): ExecutionEvent { + const output = summary.output; + return output === undefined || output === null + ? { type: 'flow_complete', runId, ts } + : { type: 'flow_complete', runId, ts, result: output }; +}