From c96574c2d694e4a301cdc5ea92d07285980bb011 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 00:05:32 -0600 Subject: [PATCH 01/65] Refuse non-positive tee relay retry count and shadow-queue bound RelayConfig now refuses a corepoint_attempts or mefor_queue_max below 1 (or a non-int) in __post_init__, and the tee CLI parses both flags with a positive-integer argparse type, so a bad value fails before any listener binds. Before this, zero attempts would skip the Corepoint forward loop, so the relay would ACK an Epic message and then fail on an assert instead of forwarding or tripping fail-closed; zero or less for the queue bound would make asyncio.Queue unbounded. The assert in _forward_corepoint is now an explicit raise, so it survives python -O. BACKLOG #5829 Proposed PR title: Batch 622: tee relay refuses non-positive corepoint_attempts and mefor_queue_max (BACKLOG #5829) Proposed banner #5829: BUILT in batch 622: RelayConfig __post_init__ and positive-int CLI types refuse corepoint_attempts / mefor_queue_max < 1 before any listener starts; assert replaced by an explicit raise; tests/test_b622_5829_tee_relay_bounds.py. --- tee/__main__.py | 15 ++++- tee/relay.py | 12 +++- tests/test_b622_5829_tee_relay_bounds.py | 76 ++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 tests/test_b622_5829_tee_relay_bounds.py diff --git a/tee/__main__.py b/tee/__main__.py index 9a80b6a944..16a777a1cd 100644 --- a/tee/__main__.py +++ b/tee/__main__.py @@ -145,6 +145,17 @@ def _positive_seconds(value: str) -> float: return seconds +def _positive_int(value: str) -> int: + """A positive integer (refuses 0, negatives and non-integers).""" + try: + number = int(value) + except ValueError: + raise argparse.ArgumentTypeError(f"expected a positive integer, got {value!r}") from None + if number < 1: + raise argparse.ArgumentTypeError(f"expected a positive integer, got {value!r}") + return number + + def _parse_age(spec: str) -> float: """A time cutoff (epoch seconds) for purge/export: a relative age ``Nd``/``Nh``/``Nm`` (days/hours/ minutes ago) or an absolute UTC date ``YYYY-MM-DD``.""" @@ -223,12 +234,12 @@ def _build_parser() -> argparse.ArgumentParser: run.add_argument("--send-timeout", type=float, default=30.0) run.add_argument( "--corepoint-attempts", - type=int, + type=_positive_int, default=3, help="quick retries on the Corepoint leg before tripping fail-closed", ) run.add_argument("--corepoint-retry-delay", type=float, default=1.0) - run.add_argument("--mefor-queue-max", type=int, default=1000) + run.add_argument("--mefor-queue-max", type=_positive_int, default=1000) run.add_argument( "--stop-grace", type=_positive_seconds, diff --git a/tee/relay.py b/tee/relay.py index cc9736a4d8..3f715485e5 100644 --- a/tee/relay.py +++ b/tee/relay.py @@ -74,6 +74,15 @@ class RelayConfig: False ) + def __post_init__(self) -> None: + # Refuse these here, before any listener binds: a zero/negative attempt count would skip the + # Corepoint forward loop, so an ACKed Epic message would never be sent and fail-closed would + # not trip; a zero/negative bound makes asyncio.Queue unbounded. + for name in ("corepoint_attempts", "mefor_queue_max"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + class ForwardError(Exception): """A transport-level failure forwarding to a downstream (connect / I/O / timeout / peer-close).""" @@ -545,7 +554,8 @@ async def _forward_corepoint(self, payload: bytes) -> tuple[str, str | None, str ) if attempt < cfg.corepoint_attempts: await asyncio.sleep(cfg.corepoint_retry_delay) - assert last is not None # corepoint_attempts >= 1, so the loop ran and set `last` + if last is None: # unreachable: RelayConfig refuses corepoint_attempts < 1 + raise ForwardError("no Corepoint forward attempt was made") raise last # -- Listener B: Corepoint copies -> MEFOR ------------------------------- diff --git a/tests/test_b622_5829_tee_relay_bounds.py b/tests/test_b622_5829_tee_relay_bounds.py new file mode 100644 index 0000000000..8db0791242 --- /dev/null +++ b/tests/test_b622_5829_tee_relay_bounds.py @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The tee relay refuses a non-positive retry count or shadow-queue bound (BACKLOG #5829). + +A ``corepoint_attempts`` of zero or less would skip the forward loop, so an ACKed Epic message +would never reach Corepoint and the relay would fail on its "the loop ran" invariant instead of +tripping fail-closed. A ``mefor_queue_max`` of zero or less would make ``asyncio.Queue`` +unbounded. Both must be refused at construction and at the CLI, before any listener starts. +""" + +from __future__ import annotations + +import pytest + +from tee.__main__ import _build_parser +from tee.relay import RelayConfig + +_BASE_ARGV = [ + "run", + "--listen-epic", + "127.0.0.1:6661", + "--corepoint", + "127.0.0.1:6662", + "--mefor", + "127.0.0.1:6663", + "--db", + "relay.db", +] + + +def _config(**overrides: int) -> RelayConfig: + return RelayConfig( + listen_epic=("127.0.0.1", 6661), + corepoint=("127.0.0.1", 6662), + mefor=("127.0.0.1", 6663), + db_path="relay.db", + **overrides, # type: ignore[arg-type] + ) + + +@pytest.mark.parametrize("field", ["corepoint_attempts", "mefor_queue_max"]) +@pytest.mark.parametrize("value", [0, -1]) +def test_config_refuses_non_positive(field: str, value: int) -> None: + with pytest.raises(ValueError, match=field): + _config(**{field: value}) + + +@pytest.mark.parametrize("field", ["corepoint_attempts", "mefor_queue_max"]) +def test_config_refuses_bool(field: str) -> None: + with pytest.raises(ValueError, match=field): + _config(**{field: True}) + + +def test_config_accepts_one() -> None: + cfg = _config(corepoint_attempts=1, mefor_queue_max=1) + assert cfg.corepoint_attempts == 1 + assert cfg.mefor_queue_max == 1 + + +@pytest.mark.parametrize("flag", ["--corepoint-attempts", "--mefor-queue-max"]) +@pytest.mark.parametrize("value", ["0", "-3", "1.5", "x"]) +def test_cli_refuses_non_positive_integer( + flag: str, value: str, capsys: pytest.CaptureFixture[str] +) -> None: + with pytest.raises(SystemExit) as exc: + _build_parser().parse_args([*_BASE_ARGV, f"{flag}={value}"]) + assert exc.value.code == 2 + assert "positive integer" in capsys.readouterr().err + + +def test_cli_accepts_positive_integers() -> None: + args = _build_parser().parse_args( + [*_BASE_ARGV, "--corepoint-attempts", "1", "--mefor-queue-max", "5"] + ) + assert args.corepoint_attempts == 1 + assert args.mefor_queue_max == 5 From 57f4e3f96fa4fe0322b997057b3ec7c85f565464 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 00:06:38 -0600 Subject: [PATCH 02/65] Harness detail panel withdraws Replay while an open loads; a non-ApiError open clears the panel Replay stayed enabled during load() and _on_replay checked only _message_id, so a press while a newer selection was loading would replay the previously shown message. load() now disables Replay with Show body, and _on_replay refuses while a newer load is in flight. The detail submit passed no on_error, so a fetch raising anything but ApiError (a transport error, say) left the previous message on screen with nothing said. It now reports the error and resets the panel, and a late failure from a superseded open is dropped. BACKLOG #5848 --- harness/_console_widgets.py | 37 +++-- ...b622_5848_detail_replay_and_fetch_error.py | 142 ++++++++++++++++++ 2 files changed, 170 insertions(+), 9 deletions(-) create mode 100644 tests/test_b622_5848_detail_replay_and_fetch_error.py diff --git a/harness/_console_widgets.py b/harness/_console_widgets.py index b6415bf569..a8db86e083 100644 --- a/harness/_console_widgets.py +++ b/harness/_console_widgets.py @@ -292,10 +292,16 @@ def load(self, message_id: str) -> None: # an in-flight one (rapid row clicks / replay), so a stale result is dropped in _apply. self._open_seq += 1 self._pending_id = message_id - # No Show body until this open lands: a press now would fetch the previous message's body. + # No Show body or Replay until this open lands: a press now would act on the previous + # message, not the one just selected (BACKLOG #5848). self._show_body.setEnabled(False) + self._replay.setEnabled(False) open_seq = self._open_seq - self._runner.submit(lambda: self._fetch(message_id, open_seq), on_done=self._apply) + self._runner.submit( + lambda: self._fetch(message_id, open_seq), + on_done=self._apply, + on_error=lambda exc: self._open_failed(message_id, open_seq, exc), + ) def stop(self) -> None: """Stop the background runner (call on window close) so a late result can't touch dead widgets.""" @@ -312,14 +318,27 @@ def _fetch(self, message_id: str, open_seq: int) -> _DetailSnapshot: except ApiError as exc: return _DetailSnapshot(message_id, open_seq, None, str(exc)) + def _is_current(self, message_id: str, open_seq: int) -> bool: + """False once a newer load() (or a clear()) has superseded the open that asked.""" + return open_seq == self._open_seq and message_id == self._pending_id + + def _open_failed(self, message_id: str, open_seq: int, exc: BaseException) -> None: + """The open raised something other than ApiError (a transport error, say). Without this + the previous message stayed on screen under the new selection (BACKLOG #5848).""" + if self._is_current(message_id, open_seq): + self._show_open_error(f"the message could not be opened: {type(exc).__name__}") + + def _show_open_error(self, error: str) -> None: + self.error.emit(error) + # Never leave the previous message's metadata and body under the newly selected row. + self._reset("The message could not be opened.") + def _apply(self, snap: _DetailSnapshot) -> None: """Runs on the main thread (result slot) — safe to touch widgets.""" - if snap.open_seq != self._open_seq or snap.message_id != self._pending_id: - return # a newer load() (or a clear()) superseded this result + if not self._is_current(snap.message_id, snap.open_seq): + return if snap.error is not None: - self.error.emit(snap.error) - # Never leave the previous message's metadata and body under the newly selected row. - self._reset("The message could not be opened.") + self._show_open_error(snap.error) return detail = snap.detail assert detail is not None @@ -409,8 +428,8 @@ def _apply_body(self, snap: _BodySnapshot) -> None: self._raw.setPlainText(snap.raw.replace("\r", "\n")) def _on_replay(self) -> None: - if self._message_id is None: - return + if self._message_id is None or self._message_id != self._pending_id: + return # nothing open, or a newer load() is still in flight try: self._client.replay(self._message_id) except ApiError as exc: diff --git a/tests/test_b622_5848_detail_replay_and_fetch_error.py b/tests/test_b622_5848_detail_replay_and_fetch_error.py new file mode 100644 index 0000000000..62e7cdb399 --- /dev/null +++ b/tests/test_b622_5848_detail_replay_and_fetch_error.py @@ -0,0 +1,142 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The harness message detail panel while a newer open is in flight, and when it fails (BACKLOG #5848). + +Two defects at the time this file was written: Replay stayed enabled during a ``load()``, so a press +replayed the previously shown message under the newly selected row; and a fetch that raised +something other than ``ApiError`` had no ``on_error`` callback, so the previous message stayed on +screen with nothing said. Both tests drive the real ``AsyncRunner`` so the submit wiring is covered. +""" + +from __future__ import annotations + +import threading +import time +from types import SimpleNamespace +from typing import Any + +import pytest + +pytest.importorskip("PySide6") + +from harness._console_widgets import MessageDetailPanel # noqa: E402 + + +@pytest.fixture(scope="module") +def qapp() -> Any: + from PySide6.QtWidgets import QApplication + + return QApplication.instance() or QApplication([]) + + +def _detail(message_id: str) -> Any: + return SimpleNamespace( + id=message_id, + message_type="ADT^A01", + control_id=f"CTL-{message_id}", + status="PROCESSED", + received_at=1_780_000_000.0, + error=None, + outbox=[], + events=[], + ) + + +class _FakeClient: + """Opens ``m0`` at once; ``m1`` waits on ``release`` and then returns, or raises an OSError + when ``fails``. A fresh exception per call: a stored one would keep its traceback, and with it + the panel's frame, alive in a Qt reference cycle.""" + + def __init__(self, *, fails: bool = False) -> None: + self.release = threading.Event() + self.replayed: list[str] = [] + self._fails = fails + + def get_message(self, message_id: str) -> Any: + if message_id != "m0": + self.release.wait(5.0) + if self._fails: + raise OSError("connection reset") + return _detail(message_id) + + def replay(self, message_id: str) -> None: + self.replayed.append(message_id) + + +def _pump_until(qapp: Any, predicate: Any, timeout: float = 5.0) -> None: + deadline = time.monotonic() + timeout + while not predicate(): + if time.monotonic() > deadline: + raise AssertionError("condition not reached before the deadline") + qapp.processEvents() + time.sleep(0.01) + + +def test_replay_is_not_offered_while_a_newer_open_is_loading(qapp: Any) -> None: + """m0 open with Replay enabled is the control; selecting m1 must withdraw Replay until m1 + lands, and a press in that window must replay nothing.""" + client = _FakeClient() + panel = MessageDetailPanel(client) # type: ignore[arg-type] + try: + panel.load("m0") + _pump_until(qapp, panel._replay.isEnabled) + assert "CTL-m0" in panel._summary.text() + + panel.load("m1") + assert not panel._replay.isEnabled() + panel._on_replay() # a press that slipped through must not target m0 + assert client.replayed == [] + + client.release.set() + _pump_until(qapp, lambda: "CTL-m1" in panel._summary.text()) + assert panel._replay.isEnabled() + panel._on_replay() + assert client.replayed == ["m1"] + finally: + client.release.set() + panel.stop() + + +def test_a_non_api_error_fetch_clears_the_previous_message_and_reports(qapp: Any) -> None: + """A transport failure (here OSError, not ApiError) while opening m1 must not leave m0 under + the new selection, and must say something. m0 rendered first is the control.""" + client = _FakeClient(fails=True) + panel = MessageDetailPanel(client) # type: ignore[arg-type] + errors: list[str] = [] + panel.error.connect(errors.append) + try: + panel.load("m0") + _pump_until(qapp, lambda: "CTL-m0" in panel._summary.text()) + + panel.load("m1") + client.release.set() + _pump_until(qapp, lambda: bool(errors)) + assert "CTL-m0" not in panel._summary.text() + assert panel._message_id is None + assert not panel._replay.isEnabled() + assert not panel._show_body.isEnabled() + assert "OSError" in errors[0] + finally: + client.release.set() + panel.stop() + + +def test_a_failed_open_superseded_by_a_newer_one_is_dropped(qapp: Any) -> None: + """A late failure from an open the operator has moved past must not clear the newer open.""" + client = _FakeClient(fails=True) + panel = MessageDetailPanel(client) # type: ignore[arg-type] + errors: list[str] = [] + panel.error.connect(errors.append) + try: + panel.load("m1") # blocks, then fails + panel.load("m0") # supersedes it and lands + _pump_until(qapp, lambda: "CTL-m0" in panel._summary.text()) + client.release.set() + panel._runner._pool.waitForDone(5000) + for _ in range(20): + qapp.processEvents() + assert "CTL-m0" in panel._summary.text() + assert errors == [] + finally: + client.release.set() + panel.stop() From 92bca4a66648bb4a8d331b2e2ff3d3565412968c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 00:07:31 -0600 Subject: [PATCH 03/65] IDE Steps view keeps handler roles and message types per panel One StepsEditorProvider serves every open Steps editor, and it kept each element's message type and role in two provider fields that every panel's render() reassigned wholesale. With two Steps editors open, the HL7 picker scope and the Router purity check of one panel would read the projection the other panel rendered last. Both now live on a StepsPanelProjection that each resolved panel owns (new ide/src/stepsPanel.ts, free of vscode so the unit suite loads it); scopeFor takes the panel's handler type rather than reading a provider field. The new suite pins two panels' independence and, by source scan, that the provider holds no provider-wide map (that scan fails on origin/main, which has four this.handlerRoles/this.handlerTypes uses). BACKLOG #5843 --- ide/src/stepsPanel.ts | 41 +++++++++ ide/src/stepsView.ts | 37 +++----- .../suite/b622-5843-steps-panel-maps.test.ts | 91 +++++++++++++++++++ 3 files changed, 144 insertions(+), 25 deletions(-) create mode 100644 ide/src/stepsPanel.ts create mode 100644 ide/src/test/suite/b622-5843-steps-panel-maps.test.ts diff --git a/ide/src/stepsPanel.ts b/ide/src/stepsPanel.ts new file mode 100644 index 0000000000..bc9d4a444e --- /dev/null +++ b/ide/src/stepsPanel.ts @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +// Per-panel projection state for the Steps editor (stepsView.ts). One StepsEditorProvider serves every +// Steps panel, so anything a panel's render() derives from ITS parse must live with that panel, never on +// the provider: two open Steps editors would otherwise read each other's projection (BACKLOG #5843). +// Kept free of `vscode` so the unit suite can load it. +import type { LensParseResult } from "./stepsModel"; + +/** A handler's recognized message type, for the HL7 field picker's scope (ADR 0104 section 2.3 P2). */ +export interface HandlerType { + acceptsTypes?: string[]; + inferredType?: { code?: string; trigger?: string }; +} + +/** + * What ONE panel's last render projected: each element's message type and role. A projection of that + * panel's current parse, never persisted state; `update` replaces all of it wholesale, as render() does. + */ +export class StepsPanelProjection { + private types = new Map(); + private roles = new Map(); + + update(parse: LensParseResult): void { + this.types = new Map( + parse.handlers.map((h) => [ + h.handler, + { acceptsTypes: h.accepts_types, inferredType: h.inferred_type }, + ]), + ); + this.roles = new Map(parse.handlers.map((h) => [h.handler, h.role ?? "handler"])); + } + + typeOf(handler: string): HandlerType | undefined { + return this.types.get(handler); + } + + /** The element's role; an element this projection does not know reads as a Handler, as before. */ + roleOf(handler: string): "handler" | "router" { + return this.roles.get(handler) ?? "handler"; + } +} diff --git a/ide/src/stepsView.ts b/ide/src/stepsView.ts index bfc090dd18..58c92d4379 100644 --- a/ide/src/stepsView.ts +++ b/ide/src/stepsView.ts @@ -106,6 +106,7 @@ import { buildSegmentScope, sampleSegments } from "./hl7scope"; import { pickHl7Path, type PickScope } from "./hl7Picker"; import { nonce } from "./cspNonce"; import { STARTUP_BANNERS } from "./webviewMessaging"; +import { StepsPanelProjection, type HandlerType } from "./stepsPanel"; /** Debounce (ms) before re-parsing after the underlying document changes in a split text view. */ const RERENDER_DEBOUNCE_MS = 250; @@ -183,16 +184,8 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { // undefined if the fetch fails (an older/unavailable engine) -> every param falls back to a text input. private opSchema: OpSchema | undefined; private opSchemaFetched = false; - // ADR 0104 §2.3 P2: handler name -> its recognized message type, stashed by render() from the lens parse - // (a projection of the current parse, never persisted state). Read by scopeFor to rank the picker. - private handlerTypes = new Map< - string, - { acceptsTypes?: string[]; inferredType?: { code?: string; trigger?: string } } - >(); - // ADR 0076 Amendment D: each projected element's ROLE, stashed by render() from the same parse (a - // projection of THIS parse, never persisted state). The webview greys the out-of-role Add items; this - // is the provider-side half of the same rule, because inbound webview data is untrusted. - private handlerRoles = new Map(); + // A panel's handler message types and roles live on that panel's StepsPanelProjection, never here: + // this one provider serves every open Steps editor (BACKLOG #5843). constructor( private readonly version: string, @@ -205,11 +198,10 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { /** The segment ranking/scope for a handler's recognized message type (ADR 0104 §2.3 P2). Undefined when * there is no schema bundle or the type is unresolvable → the picker offers the generic, unscoped * segment list. Reads the (synthetic, PHI-safe) sample so its Z-segments / segments union in. */ - private scopeFor(handler: string): PickScope | undefined { + private scopeFor(t: HandlerType | undefined): PickScope | undefined { if (!this.schema) { return undefined; } - const t = this.handlerTypes.get(handler); let sample: string[] = []; if (this.samplePath) { try { @@ -310,6 +302,9 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { let sawAlive = false; // One edit at a time + the webview↔document update-loop guard (ADR 0076 §5). const guard = new EditLoopGuard(); + // What THIS panel's last render projected (BACKLOG #5843): read by the picker scope and the Router + // role check, so a second open Steps editor can never answer for this one. + const panelState = new StepsPanelProjection(); // The typed rewrites applied since the webview was last projected, so an edit on one of their rows // is sent with the row's current source rather than refused as stale (BACKLOG #5943). render() // tells it which buffer each new webview was projected from. @@ -411,17 +406,9 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { } // parse is non-null here (shouldFallBackToText returned fallback:false only for a real handler set). const handlers = buildHandlerViewModels(parse as LensParseResult, source); - // ADR 0104 §2.3 P2: stash each handler's recognized message type for the field picker's scope (a - // projection of THIS parse — not persisted state). - this.handlerTypes = new Map( - (parse as LensParseResult).handlers.map((h) => [ - h.handler, - { acceptsTypes: h.accepts_types, inferredType: h.inferred_type }, - ]), - ); - this.handlerRoles = new Map( - (parse as LensParseResult).handlers.map((h) => [h.handler, h.role ?? "handler"]), - ); + // ADR 0104 §2.3 P2 and ADR 0076 Amendment D: stash each element's message type (the field picker's + // scope) and role (the Router purity check) for THIS panel (a projection of THIS parse). + panelState.update(parse as LensParseResult); // Live values come from a SECOND `dryrun --trace` that reads the module FROM DISK, but the rows // above are projected from the LIVE buffer. While the buffer is dirty (an unsaved structural edit // shifted rows relative to disk — or any unsaved change made buffer != disk) the disk trace's line @@ -648,7 +635,7 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { } const picked = await pickHl7Path(this.schema, { mode, - scope: this.scopeFor(coords.handler), + scope: this.scopeFor(panelState.typeOf(coords.handler)), verified: this.structures?.verified, seed, }); @@ -924,7 +911,7 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { // A router stays pure destination-selection (ADR 0076 D.6): refuse an item that authors a // transform verb, a lookup, a diagnostic or an outbound send inside one. The engine refuses it // too; this stops the request before it becomes an error toast the user has to read. - if (!itemAllowedInRole(item, this.handlerRoles.get(m.handler) ?? "handler")) { + if (!itemAllowedInRole(item, panelState.roleOf(m.handler))) { void vscode.window.showWarningMessage( `MessageFoundry: "${item.label}" is not available in a Router — a Router selects destinations, it does not transform the message.`, ); diff --git a/ide/src/test/suite/b622-5843-steps-panel-maps.test.ts b/ide/src/test/suite/b622-5843-steps-panel-maps.test.ts new file mode 100644 index 0000000000..3cb909d299 --- /dev/null +++ b/ide/src/test/suite/b622-5843-steps-panel-maps.test.ts @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +import * as assert from "assert"; +import * as fs from "fs"; +import * as path from "path"; + +import { StepsPanelProjection } from "../../stepsPanel"; +import type { LensParseResult } from "../../stepsModel"; + +// BACKLOG #5843. One StepsEditorProvider serves every open Steps editor. It kept each element's message +// type and role in two provider fields that every panel's render() reassigned wholesale, so with two +// Steps editors open the HL7 picker scope and the Router purity check of one panel read the projection +// the OTHER panel rendered last. Both now live on a per-panel StepsPanelProjection. + +const STEPS_VIEW_TS = path.join(__dirname, "..", "..", "..", "src", "stepsView.ts"); + +const routerFile: LensParseResult = { + module: "routers.py", + handlers: [{ handler: "route_adt", module: "routers.py", def_line: 3, rows: [], role: "router" }], +}; + +const handlerFile: LensParseResult = { + module: "handlers.py", + handlers: [ + { + handler: "route_adt", // the same name, a different element in a different file + module: "handlers.py", + def_line: 5, + rows: [], + role: "handler", + accepts_types: ["ORU^R01"], + inferred_type: { code: "ORU", trigger: "R01" }, + }, + ], +}; + +suite("BACKLOG #5843: Steps handler roles and message types are per panel", () => { + test("a second panel's render does not change the first panel's role or message type", () => { + const a = new StepsPanelProjection(); + const b = new StepsPanelProjection(); + a.update(routerFile); + b.update(handlerFile); // the other panel renders last + assert.strictEqual(a.roleOf("route_adt"), "router", "panel A's Router stays a Router"); + assert.strictEqual(a.typeOf("route_adt")?.acceptsTypes, undefined, "panel A has no ORU scope"); + assert.strictEqual(b.roleOf("route_adt"), "handler"); + assert.deepStrictEqual(b.typeOf("route_adt")?.acceptsTypes, ["ORU^R01"]); + }); + + test("an element the projection does not know reads as a Handler, as the provider did", () => { + const p = new StepsPanelProjection(); + assert.strictEqual(p.roleOf("nope"), "handler"); + p.update(routerFile); + assert.strictEqual(p.roleOf("nope"), "handler"); + }); + + test("update replaces the projection wholesale", () => { + const p = new StepsPanelProjection(); + p.update(handlerFile); + p.update(routerFile); + assert.strictEqual(p.roleOf("route_adt"), "router"); + assert.strictEqual(p.typeOf("route_adt")?.inferredType, undefined); + }); + + test("a contract-1 payload with no role reads as a Handler", () => { + const p = new StepsPanelProjection(); + p.update({ + module: "m.py", + handlers: [{ handler: "h", module: "m.py", def_line: 1, rows: [] }], + }); + assert.strictEqual(p.roleOf("h"), "handler"); + }); + + // stepsView.ts imports vscode, so the provider cannot be loaded node-side; pin its wiring by scan. + test("the provider holds no provider-wide role or message-type map", () => { + const src = fs.readFileSync(STEPS_VIEW_TS, "utf8"); + assert.ok( + !/this\.handler(Roles|Types)\b/.test(src), + "stepsView.ts must not read or write a provider-wide handlerRoles/handlerTypes field", + ); + const resolve = src.slice(src.indexOf("resolveCustomTextEditor(")); + assert.ok( + /const panelState = new StepsPanelProjection\(\)/.test(resolve), + "each resolved panel must own its StepsPanelProjection", + ); + assert.ok(/panelState\.roleOf\(m\.handler\)/.test(src), "the Router check reads this panel's role"); + assert.ok( + /scopeFor\(panelState\.typeOf\(coords\.handler\)\)/.test(src), + "the picker scope reads this panel's message type", + ); + }); +}); From cf0feb8e872e9f66f18a1ecb91055d526b403f8b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 00:07:31 -0600 Subject: [PATCH 04/65] IDE: resolve the config dir and fold case only where the filesystem does isUnderConfigDir joined the config dir onto the workspace without resolving dot segments, so a configDir of ./samples/config or . never matched its own files, and it lower-cased both sides on every platform, so a wrong-cased path counted as inside the config dir on a case-sensitive filesystem. It now resolves both sides with the platform's path module, compares by segment, and folds case only on win32 and darwin. A platform parameter, defaulting to the host's, lets the tests pin each rule on any runner. BACKLOG #5832 --- ide/src/configEditorModel.ts | 25 ++++++--- .../b622-5832-config-dir-containment.test.ts | 51 +++++++++++++++++++ .../test/suite/config-editor-model.test.ts | 4 +- 3 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 ide/src/test/suite/b622-5832-config-dir-containment.test.ts diff --git a/ide/src/configEditorModel.ts b/ide/src/configEditorModel.ts index c05af392b3..a2a08792a4 100644 --- a/ide/src/configEditorModel.ts +++ b/ide/src/configEditorModel.ts @@ -4,6 +4,7 @@ // from its file path, deciding whether it opens read-only in the grid, and the small guard that stops // the webview↔document update loop. Separated from configEditors.ts so this mapping is unit-testable // node-side (no Extension Host). No vscode, no I/O. +import * as path from "node:path"; /** * The bare code-set name for a file path — its basename without the .csv/.toml extension. A code set @@ -52,20 +53,28 @@ export function shouldPushDocumentChange(opts: { * shown — and saved — as the config-dir file. When this returns false the provider falls back to the * plain text editor instead of silently editing a different file. * - * `configDir` may be workspace-relative (the default `samples/config`) or absolute; relative is - * resolved against `workspaceDir`. Path comparison is separator- and case-insensitive so it holds for - * Windows (`\\`, case-insensitive) and POSIX paths alike. + * `configDir` may be workspace-relative (the default `samples/config`, or `./samples/config`, `.`) or + * absolute, a root such as `/` included; relative is resolved against `workspaceDir`, and dot segments + * on both sides are resolved before comparing. Case is folded only on `win32` and `darwin`, whose + * default filesystems are case-insensitive; elsewhere a wrong-cased path names a different file, so + * it is outside the config dir (BACKLOG #5832). A case-sensitive volume on `darwin` is the accepted + * miss. `platform` defaults to the host's; it is a parameter so tests pin each rule on any runner. */ export function isUnderConfigDir( documentFsPath: string, workspaceDir: string, configDir: string, + platform: NodeJS.Platform = process.platform, ): boolean { - const norm = (p: string): string => p.replace(/[\\/]+/g, "/").replace(/\/+$/, ""); - const isAbsolute = (p: string): boolean => /^[/\\]/.test(p) || /^[a-zA-Z]:[/\\]/.test(p); - const base = norm(isAbsolute(configDir) ? configDir : `${workspaceDir}/${configDir}`).toLowerCase(); - const file = norm(documentFsPath).toLowerCase(); - return file === base || file.startsWith(`${base}/`); + const p = platform === "win32" ? path.win32 : path.posix; + const caseInsensitive = platform === "win32" || platform === "darwin"; + const fold = (s: string): string => (caseInsensitive ? s.toLowerCase() : s); + const base = fold(p.resolve(workspaceDir, configDir)); + const file = fold(p.resolve(documentFsPath)); + // `relative` is "" for the dir itself, absolute across Windows drives, and starts with a `..` + // SEGMENT when outside -- not merely those characters, so a child dir named "..x" is still inside. + const rel = p.relative(base, file); + return !p.isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${p.sep}`); } /** A connection summary the connections customEditor lists (name/direction/transport) — the fields it diff --git a/ide/src/test/suite/b622-5832-config-dir-containment.test.ts b/ide/src/test/suite/b622-5832-config-dir-containment.test.ts new file mode 100644 index 0000000000..1e4242ff54 --- /dev/null +++ b/ide/src/test/suite/b622-5832-config-dir-containment.test.ts @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +import * as assert from "assert"; +import { isUnderConfigDir } from "../../configEditorModel"; + +// BACKLOG #5832. isUnderConfigDir decides whether connections.toml or a codesets file opens in the +// form or falls back to text. It joined the config dir onto the workspace without resolving dot +// segments, so `./samples/config` and `.` never matched, and it lower-cased both sides on every +// platform, so a wrong-cased path counted as inside the config dir on a case-sensitive filesystem. +suite("configEditorModel: isUnderConfigDir resolves the config dir (BACKLOG #5832)", () => { + test("a ./-prefixed relative config dir matches its own files", () => { + assert.strictEqual(isUnderConfigDir("/ws/samples/config/connections.toml", "/ws", "./samples/config", "linux"), true); + assert.strictEqual(isUnderConfigDir("/ws/other/connections.toml", "/ws", "./samples/config", "linux"), false); + }); + + test("a config dir of '.' is the workspace itself", () => { + assert.strictEqual(isUnderConfigDir("/ws/connections.toml", "/ws", ".", "linux"), true); + assert.strictEqual(isUnderConfigDir("/ws/codesets/diets.csv", "/ws", ".", "linux"), true); + assert.strictEqual(isUnderConfigDir("/elsewhere/connections.toml", "/ws", ".", "linux"), false); + }); + + test("dot segments inside the config dir or the file path are resolved", () => { + assert.strictEqual(isUnderConfigDir("/ws/samples/config/connections.toml", "/ws", "samples/x/../config", "linux"), true); + assert.strictEqual(isUnderConfigDir("/ws/samples/config/../other/connections.toml", "/ws", "samples/config", "linux"), false); + }); + + test("a root config dir contains every absolute path", () => { + assert.strictEqual(isUnderConfigDir("/ws/connections.toml", "/ws", "/", "linux"), true); + assert.strictEqual(isUnderConfigDir("C:\\ws\\connections.toml", "C:\\ws", "C:\\", "win32"), true); + assert.strictEqual(isUnderConfigDir("D:\\ws\\connections.toml", "C:\\ws", "C:\\", "win32"), false); + }); + + test("a wrong-cased path is outside the config dir on a case-sensitive filesystem", () => { + assert.strictEqual(isUnderConfigDir("/ws/Samples/Config/connections.toml", "/ws", "samples/config", "linux"), false); + assert.strictEqual(isUnderConfigDir("/ws/samples/config/connections.toml", "/ws", "samples/config", "linux"), true); + }); + + test("case is folded where the platform filesystem is case-insensitive by default", () => { + assert.strictEqual(isUnderConfigDir("C:\\WS\\Samples\\Config\\connections.toml", "C:\\ws", "samples\\config", "win32"), true); + assert.strictEqual(isUnderConfigDir("/srv/WS/Config/connections.toml", "/srv/ws", "config", "darwin"), true); + }); + + test("a sibling that shares a name prefix, or a dir named like '..x', is judged by segment", () => { + assert.strictEqual(isUnderConfigDir("/ws/samples/config-backup/connections.toml", "/ws", "samples/config", "linux"), false); + assert.strictEqual(isUnderConfigDir("/ws/samples/config/..x/connections.toml", "/ws", "samples/config", "linux"), true); + }); + + test("a file on another Windows drive is outside the config dir", () => { + assert.strictEqual(isUnderConfigDir("D:\\ws\\config\\connections.toml", "C:\\ws", "config", "win32"), false); + }); +}); diff --git a/ide/src/test/suite/config-editor-model.test.ts b/ide/src/test/suite/config-editor-model.test.ts index 3f248b7018..24bc825d07 100644 --- a/ide/src/test/suite/config-editor-model.test.ts +++ b/ide/src/test/suite/config-editor-model.test.ts @@ -82,11 +82,11 @@ suite("configEditorModel — config-dir scope guard (F3)", () => { test("Windows paths + an absolute config dir, case-insensitively", () => { assert.strictEqual( - isUnderConfigDir("C:\\WS\\Config\\connections.toml", "C:\\ws", "C:\\ws\\config"), + isUnderConfigDir("C:\\WS\\Config\\connections.toml", "C:\\ws", "C:\\ws\\config", "win32"), true, ); assert.strictEqual( - isUnderConfigDir("C:\\ws\\elsewhere\\connections.toml", "C:\\ws", "C:\\ws\\config"), + isUnderConfigDir("C:\\ws\\elsewhere\\connections.toml", "C:\\ws", "C:\\ws\\config", "win32"), false, ); }); From dafe9ef51e16d0b4d53a2805eb60ec389e889e81 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 00:12:25 -0600 Subject: [PATCH 05/65] IDE Steps view insert anchors carry the row's fan-out flags The paste, insertToolbar and insertItem handlers built their insert anchor from the row's kind alone, dropping the appended and scaffold flags isReturnRow reads. A request that derives its position would put a new step before a mid-body sends.append(Send(...)) instead of after it, and after the return-sends footer (dead code after the return) instead of before it. The page posts no flags with a paste at all. StepsPanelProjection now also records each projected row's kind and fan-out flags, and anchorFor builds the anchor from the panel's own row when it holds the one the message names (same handler, line range and source), else from the message's fields as addDestination sent them. All four handlers build their anchor through it. A Router route row's position is isReturnRow's to decide (BACKLOG #5838, another branch): the anchor now carries the projected kind "route" for it. BACKLOG #5844 --- ide/src/stepsPanel.ts | 84 +++++++++++- ide/src/stepsView.ts | 67 +++++---- .../b622-5844-steps-insert-anchor.test.ts | 129 ++++++++++++++++++ 3 files changed, 240 insertions(+), 40 deletions(-) create mode 100644 ide/src/test/suite/b622-5844-steps-insert-anchor.test.ts diff --git a/ide/src/stepsPanel.ts b/ide/src/stepsPanel.ts index bc9d4a444e..664c61c65b 100644 --- a/ide/src/stepsPanel.ts +++ b/ide/src/stepsPanel.ts @@ -4,7 +4,7 @@ // Steps panel, so anything a panel's render() derives from ITS parse must live with that panel, never on // the provider: two open Steps editors would otherwise read each other's projection (BACKLOG #5843). // Kept free of `vscode` so the unit suite can load it. -import type { LensParseResult } from "./stepsModel"; +import type { HandlerViewModel, LensParseResult, RowKind } from "./stepsModel"; /** A handler's recognized message type, for the HL7 field picker's scope (ADR 0104 section 2.3 P2). */ export interface HandlerType { @@ -12,15 +12,49 @@ export interface HandlerType { inferredType?: { code?: string; trigger?: string }; } +/** The anchor a structural insert is built from: the row's coordinates plus its fan-out flags. */ +export interface StructuralAnchor { + handler: string; + lineStart: number; + lineEnd: number; + expectSrc?: string; + kind: RowKind; + appended?: boolean; + scaffold?: string; +} + +/** The anchor fields a webview message may carry. Untrusted, so every field is read defensively. */ +export interface AnchorMessage { + handler: string; + lineStart: number; + lineEnd: number; + expectSrc?: unknown; + kind?: unknown; + appended?: unknown; + scaffold?: unknown; +} + +interface ProjectedRow { + kind: RowKind; + expectSrc?: string; + appended?: boolean; + scaffold?: string; +} + +const rowKey = (handler: string, lineStart: number, lineEnd: number): string => + `${handler}\u0000${lineStart}\u0000${lineEnd}`; + /** - * What ONE panel's last render projected: each element's message type and role. A projection of that - * panel's current parse, never persisted state; `update` replaces all of it wholesale, as render() does. + * What ONE panel's last render projected: each element's message type and role, and each row's kind and + * fan-out flags. A projection of that panel's current parse, never persisted state; `update` replaces + * all of it wholesale, as render() does. */ export class StepsPanelProjection { private types = new Map(); private roles = new Map(); + private rows = new Map(); - update(parse: LensParseResult): void { + update(parse: LensParseResult, handlers: readonly HandlerViewModel[] = []): void { this.types = new Map( parse.handlers.map((h) => [ h.handler, @@ -28,6 +62,17 @@ export class StepsPanelProjection { ]), ); this.roles = new Map(parse.handlers.map((h) => [h.handler, h.role ?? "handler"])); + this.rows = new Map(); + for (const h of handlers) { + for (const r of h.rows) { + this.rows.set(rowKey(h.handler, r.lineStart, r.lineEnd), { + kind: r.kind, + expectSrc: r.expectSrc, + appended: r.appended, + scaffold: r.scaffold, + }); + } + } } typeOf(handler: string): HandlerType | undefined { @@ -38,4 +83,35 @@ export class StepsPanelProjection { roleOf(handler: string): "handler" | "router" { return this.roles.get(handler) ?? "handler"; } + + /** + * The anchor for a structural insert at the row a message names (BACKLOG #5844). The insert position + * depends on the row's fan-out flags (stepsModel.isReturnRow: a mid-body append send takes an insert + * after it, a return-collector footer before it), and a message built from `kind` alone carries none. + * So the row's kind and flags come from THIS panel's projection when it holds the row the message + * names (same handler and line range, and the same source when the message carries one); otherwise + * from the message's own fields, as addDestination always sent them. `fallbackKind` is used only when + * neither names a kind. + */ + anchorFor(m: AnchorMessage, fallbackKind: RowKind): StructuralAnchor { + const expectSrc = typeof m.expectSrc === "string" ? m.expectSrc : undefined; + const row = this.rows.get(rowKey(m.handler, m.lineStart, m.lineEnd)); + const anchor: StructuralAnchor = { + handler: m.handler, + lineStart: m.lineStart, + lineEnd: m.lineEnd, + expectSrc, + kind: fallbackKind, + }; + if (row !== undefined && (expectSrc === undefined || row.expectSrc === expectSrc)) { + anchor.kind = row.kind; + anchor.appended = row.appended === true; + anchor.scaffold = row.scaffold; + } else { + anchor.kind = typeof m.kind === "string" ? (m.kind as RowKind) : fallbackKind; + anchor.appended = m.appended === true; + anchor.scaffold = typeof m.scaffold === "string" ? m.scaffold : undefined; + } + return anchor; + } } diff --git a/ide/src/stepsView.ts b/ide/src/stepsView.ts index 58c92d4379..68e826f876 100644 --- a/ide/src/stepsView.ts +++ b/ide/src/stepsView.ts @@ -407,8 +407,9 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { // parse is non-null here (shouldFallBackToText returned fallback:false only for a real handler set). const handlers = buildHandlerViewModels(parse as LensParseResult, source); // ADR 0104 §2.3 P2 and ADR 0076 Amendment D: stash each element's message type (the field picker's - // scope) and role (the Router purity check) for THIS panel (a projection of THIS parse). - panelState.update(parse as LensParseResult); + // scope) and role (the Router purity check), and each row's kind and fan-out flags (the structural + // insert anchor, BACKLOG #5844), for THIS panel (a projection of THIS parse). + panelState.update(parse as LensParseResult, handlers); // Live values come from a SECOND `dryrun --trace` that reads the module FROM DISK, but the rows // above are projected from the LIVE buffer. While the buffer is dirty (an unsaved structural edit // shifted rows relative to disk — or any unsaved change made buffer != disk) the disk trace's line @@ -806,15 +807,10 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { ) { // ADR 0104 fan-out "+ dest": pick a destination, then add_destination via the SAME byte-stable // applyStructural path. The anchor's fan-out flags drive the insert position (isReturnRow). - const anchor = { - handler: m.handler, - lineStart: m.lineStart, - lineEnd: m.lineEnd, - expectSrc: typeof m.expectSrc === "string" ? m.expectSrc : undefined, - kind: (typeof m.kind === "string" ? m.kind : "send") as RowKind, - appended: m.appended === true, - scaffold: typeof m.scaffold === "string" ? m.scaffold : undefined, - }; + const anchor = panelState.anchorFor( + { ...m, handler: m.handler, lineStart: m.lineStart, lineEnd: m.lineEnd }, + "send", + ); void pickDestination("Add destination", "Destination (fan out)").then((dest) => { if (dest !== undefined && dest !== "" && !disposed) { void applyStructural(buildAddDestinationRequest(anchor, dest)); @@ -880,16 +876,14 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { // Insert a DEFAULT-param template at the currently SELECTED row (no InputBox prompts). The // position is either the explicit context-menu choice or derived from the anchor's kind (send → // before the return, else after) inside buildToolbarInsertRequest, which reuses the byte-stable - // `lens rewrite` path via applyStructural. + // `lens rewrite` path via applyStructural. The anchor carries the row's fan-out flags, so a + // derived position puts a mid-body append send before the new step and a footer after it (#5844). void applyStructural( buildToolbarInsertRequest( - { - handler: m.handler, - lineStart: m.lineStart, - lineEnd: m.lineEnd, - expectSrc: m.expectSrc, - kind: m.kind as RowKind, - }, + panelState.anchorFor( + { ...m, handler: m.handler, lineStart: m.lineStart, lineEnd: m.lineEnd }, + m.kind as RowKind, + ), m.action, m.position as "before" | "after" | undefined, ), @@ -917,13 +911,11 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { ); return; } - const anchor = { - handler: m.handler, - lineStart: m.lineStart, - lineEnd: m.lineEnd, - expectSrc: typeof m.expectSrc === "string" ? m.expectSrc : undefined, - kind: m.kind as RowKind, - }; + // The anchor carries the row's fan-out flags, for a request that derives its position (#5844). + const anchor = panelState.anchorFor( + { ...m, handler: m.handler, lineStart: m.lineStart, lineEnd: m.lineEnd }, + m.kind as RowKind, + ); const position = m.position as "before" | "after" | undefined; if (item.prompts.length === 0) { void applyStructural(buildAddMenuRequest(item, anchor, {}, position)); @@ -969,17 +961,20 @@ export class StepsEditorProvider implements vscode.CustomTextEditorProvider { // change; on a real change we show the "Pasted …" toast the webview supplied. const pasteText = typeof m.text === "string" ? m.text : "MessageFoundry: pasted the steps."; + // The page posts no fan-out flags with a paste, so the anchor takes them from this panel's + // projection: a block pasted at a mid-body append send lands after it, at a footer before (#5844). + const anchor = panelState.anchorFor( + { ...m, handler: m.handler, lineStart: m.lineStart, lineEnd: m.lineEnd }, + m.kind as RowKind, + ); void applyStructural( - buildPasteRequest( - { - handler: m.handler, - lineStart: m.lineStart, - lineEnd: m.lineEnd, - expectSrc: m.expectSrc, - kind: m.kind as RowKind, - }, - { source: m.block, nesting: 0, kind: m.kind as RowKind, lineCount: 0, label: "" }, - ), + buildPasteRequest(anchor, { + source: m.block, + nesting: 0, + kind: anchor.kind, + lineCount: 0, + label: "", + }), ).then((ok) => { if (ok && !disposed) { void vscode.window.showInformationMessage(pasteText); diff --git a/ide/src/test/suite/b622-5844-steps-insert-anchor.test.ts b/ide/src/test/suite/b622-5844-steps-insert-anchor.test.ts new file mode 100644 index 0000000000..833543077b --- /dev/null +++ b/ide/src/test/suite/b622-5844-steps-insert-anchor.test.ts @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +import * as assert from "assert"; +import * as fs from "fs"; +import * as path from "path"; + +import { StepsPanelProjection } from "../../stepsPanel"; +import { + ADD_MENU_BY_ID, + buildAddMenuRequest, + buildPasteRequest, + buildToolbarInsertRequest, + type HandlerViewModel, + type LensParseResult, + type RowViewModel, +} from "../../stepsModel"; + +// BACKLOG #5844. The paste, insertToolbar and insertItem handlers built their insert anchor from the +// row's kind alone, dropping the fan-out flags isReturnRow reads. A request that derives its position +// then put a new step BEFORE a mid-body `sends.append(Send(...))` (which takes one after it) and AFTER +// the `return sends` footer (dead code after the return). The page posts no flags with a paste at all, +// so the provider now takes the row's kind and flags from the panel's own projection. + +const STEPS_VIEW_TS = path.join(__dirname, "..", "..", "..", "src", "stepsView.ts"); + +const row = (over: Partial & Pick) => + ({ index: 0, nesting: 0, title: "", params: [], ...over }) as RowViewModel; + +const APPEND = row({ kind: "send", lineStart: 6, lineEnd: 6, appended: true, expectSrc: " sends.append(Send(\"OB\", msg))" }); +const FOOTER = row({ kind: "code", lineStart: 7, lineEnd: 7, scaffold: "return_collector", expectSrc: " return sends" }); +const RETURN = row({ kind: "send", lineStart: 9, lineEnd: 9, expectSrc: " return Send(\"OB\", msg)" }); + +const handlers: HandlerViewModel[] = [{ handler: "h", defLine: 1, role: "handler", rows: [APPEND, FOOTER, RETURN] }]; +const parse: LensParseResult = { + module: "m.py", + handlers: [{ handler: "h", module: "m.py", def_line: 1, rows: [], role: "handler" }], +}; + +/** A webview message naming `r`, as the page posts a paste: coordinates, kind and source, no flags. */ +const pasteMsg = (r: RowViewModel) => ({ + handler: "h", + lineStart: r.lineStart, + lineEnd: r.lineEnd, + kind: r.kind, + expectSrc: r.expectSrc, +}); + +const CLIP = { source: "x = 1", nesting: 0, kind: "code" as const, lineCount: 1, label: "" }; + +suite("BACKLOG #5844: Steps insert anchors carry the row's fan-out flags", () => { + const panel = new StepsPanelProjection(); + panel.update(parse, handlers); + + test("a paste at a mid-body append send lands after it", () => { + const anchor = panel.anchorFor(pasteMsg(APPEND), "send"); + assert.strictEqual(anchor.appended, true); + assert.strictEqual(buildPasteRequest(anchor, CLIP).position, "after"); + }); + + test("a paste at the return-collector footer lands before it", () => { + const anchor = panel.anchorFor(pasteMsg(FOOTER), "code"); + assert.strictEqual(anchor.scaffold, "return_collector"); + assert.strictEqual(buildPasteRequest(anchor, CLIP).position, "before"); + }); + + test("a paste at a terminal return still lands before it", () => { + assert.strictEqual(buildPasteRequest(panel.anchorFor(pasteMsg(RETURN), "send"), CLIP).position, "before"); + }); + + test("a derived toolbar insert and Add-menu insert follow the same flags", () => { + const append = panel.anchorFor(pasteMsg(APPEND), "send"); + const footer = panel.anchorFor(pasteMsg(FOOTER), "code"); + assert.strictEqual(buildToolbarInsertRequest(append, "set_field").position, "after"); + assert.strictEqual(buildToolbarInsertRequest(footer, "set_field").position, "before"); + const item = ADD_MENU_BY_ID.set_field; + assert.strictEqual((buildAddMenuRequest(item, append, {}) as { position?: string }).position, "after"); + assert.strictEqual((buildAddMenuRequest(item, footer, {}) as { position?: string }).position, "before"); + }); + + test("the projection's kind and flags win over what the message claims", () => { + const anchor = panel.anchorFor({ ...pasteMsg(FOOTER), kind: "action", scaffold: 7 }, "code"); + assert.strictEqual(anchor.kind, "code"); + assert.strictEqual(anchor.scaffold, "return_collector"); + }); + + test("a row the projection does not hold falls back to the message's own fields", () => { + const anchor = panel.anchorFor( + { handler: "h", lineStart: 40, lineEnd: 40, kind: "send", appended: true, expectSrc: "y" }, + "send", + ); + assert.deepStrictEqual(anchor, { + handler: "h", + lineStart: 40, + lineEnd: 40, + expectSrc: "y", + kind: "send", + appended: true, + scaffold: undefined, + }); + }); + + test("a message whose source differs from the projected row's does not take the row's flags", () => { + const anchor = panel.anchorFor({ ...pasteMsg(APPEND), expectSrc: "something else" }, "send"); + assert.strictEqual(anchor.appended, false, "a stale message keeps its own (absent) flags"); + assert.strictEqual(anchor.expectSrc, "something else", "the engine's stale check still sees it"); + }); + + test("an untrusted non-string kind or source is never passed through", () => { + const anchor = new StepsPanelProjection().anchorFor( + { handler: "h", lineStart: 1, lineEnd: 1, kind: 3, expectSrc: 4, appended: "true" }, + "send", + ); + assert.strictEqual(anchor.kind, "send"); + assert.strictEqual(anchor.expectSrc, undefined); + assert.strictEqual(anchor.appended, false); + }); + + // stepsView.ts imports vscode, so the provider cannot be loaded node-side; pin its wiring by scan. + test("paste, insertToolbar, insertItem and addDestination build their anchor through anchorFor", () => { + const src = fs.readFileSync(STEPS_VIEW_TS, "utf8"); + for (const command of ["paste", "insertToolbar", "insertItem", "addDestination"]) { + const at = src.indexOf(`m?.command === "${command}"`); + assert.ok(at >= 0, `stepsView.ts has no ${command} handler`); + const next = src.indexOf("m?.command ===", at + 1); + const body = src.slice(at, next < 0 ? undefined : next); + assert.ok(/panelState\.anchorFor\(/.test(body), `the ${command} handler must build its anchor via anchorFor`); + } + }); +}); From 8871ccd7d06fa2dcf64e24ea207c6c6fce98d5b4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 00:12:27 -0600 Subject: [PATCH 06/65] Alert Rules Add refuses values the engine's AlertRule refuses validate() in the Alert Rules webview checked only that each numeric field was a finite number, so a negative min_depth, a fractional min_depth, a negative min_oldest_seconds, and a cooldown_seconds of 0, below 0 or over the engine's cap would post an add the engine then refuses at load. Add now mirrors AlertRule's bounds in messagefoundry/config/settings.py: min_depth an integer of 1 or more, min_oldest_seconds 0 or more, cooldown_seconds above 0 and at most _ALERT_COOLDOWN_MAX_SECONDS. A new jsdom test drives the real page script and pins the cap against settings.py. BACKLOG #5831 --- ide/src/alertEditorWebview.ts | 16 +++ .../test/suite/b622-5831-alert-bounds.test.ts | 122 ++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 ide/src/test/suite/b622-5831-alert-bounds.test.ts diff --git a/ide/src/alertEditorWebview.ts b/ide/src/alertEditorWebview.ts index bf7086f27b..e4086ea087 100644 --- a/ide/src/alertEditorWebview.ts +++ b/ide/src/alertEditorWebview.ts @@ -6,6 +6,10 @@ // source in a jsdom page (webview-receivers.test.ts), so what the tests exercise is what ships. import { SHAPE_HELPERS, WEBVIEW_GUARD_NOTE, SCRIPT_STARTED_MARK, embedJson, guardScript } from "./webviewMessaging"; +/** The largest `cooldown_seconds` the engine loads: `_ALERT_COOLDOWN_MAX_SECONDS` in + * messagefoundry/config/settings.py (BACKLOG #5770). A unit test pins the two together. */ +export const ALERT_COOLDOWN_MAX_SECONDS = 7 * 24 * 60 * 60; + /** The whole inline ` & \"q\""); + assert.ok(!html.includes("