diff --git a/docs/system-specs/modules/app-kit-platform.md b/docs/system-specs/modules/app-kit-platform.md index 0dea63161792..923f8c64890b 100644 --- a/docs/system-specs/modules/app-kit-platform.md +++ b/docs/system-specs/modules/app-kit-platform.md @@ -641,8 +641,9 @@ copy of the core file-read endpoint's binary-extension set in its own `tests/`. Every backend app gate runs the same scanner, `test/core_app_independence.py`: `core_app_imports` finds a core import of the app's package in any spelling, and `core_name_strings` finds a core string naming it, minus the reasoned rows the gate -allows. The aws-control and Files gates call it with their own package and names, -and the next app to leave adds a gate that does the same, never another scanner. +allows. The aws-control, Files and Design Critique gates call it with their own +package and names, and the next app to leave adds a gate that does the same, never +another scanner. ## 0. Three-axis classification: origin, resources, lifecycle @@ -4788,6 +4789,40 @@ slot another create path made first (ChatEmbed's own POST) carries neither. Writers: `apps/worker_slots.py`. Tests: `test/test_apps_worker_slots.py`. +## 23a. A built-in's worker slot mode is a seam the built-in fills + +A slot's `mode` is fixed at creation, and the chat sidebar lists only `""` slots, so an +app whose throwaway worker slots must stay off the sidebar creates them under a mode of +its own. `POST /api/chat/slots` and the auto-create on `POST /api/chat` accept only +`chat_handlers._CREATABLE_MODES`, which is `""` followed by `seams.worker_slot_modes()` +(section 30); the core spells no app's mode. + +- **Registration.** A builtin's `seams.py` calls `seams.register_worker_slot_mode(app_id)` + with its own id when it is imported. A non-`str` id is refused with `ValueError`; the + loader logs that module and skips it, like any broken provider. +- **Built-ins only, in practice.** `chat_handlers` reads the seam once, at import, and + that first lookup is what loads the builtin seams modules. An installed app's + `on_startup` runs later, so it reaches no create path, and no manifest field is read. + With no builtin registering one, the create paths accept `""` alone. The mode-switch + (`chat_folders._VALID_MODES`) and fork-override allowlists stay narrower on purpose. +- **Light package.** The lookup imports the app's package `__init__`, so Design + Critique serves `register_routes` from a module `__getattr__` that imports its route + module on first access. That access is the boot route loop's guarded lookup, so an + unreadable route file is skipped like any unreadable app, not fatal. + +Design Critique is held to it by `test/test_core_design_critique_decoupling.py`, which +runs the shared `test/core_app_independence.py` scans: no module under `src/kiro_crew` +outside `apps/builtins/`, and no `scripts/` file, imports the app's package or names +`design_critique` / `design-critique` in a non-docstring string. Its UI is held the +same way by `website/src/apps/design-critique/designCritiqueBoundary.test.ts`: outside that +directory only the `/design-critique` row of `apps/builtinRegistry.ts` imports from it, +and the app's backend and frontend tests live in its own directories. + +Writers: `apps/seams.py`, `apps/builtins/design_critique/seams.py`. +Tests: `test/test_app_seams.py`, +`apps/builtins/design_critique/tests/test_worker_slot_mode.py`, +`apps/builtins/design_critique/tests/test_unreadable_routes_skipped.py`. + ## 24. A backend's principal claim is opt-in and bound to one request `X-KiroCrew-Proxy` proves only that the gateway forwarded a request. An app whose @@ -5151,6 +5186,7 @@ this repository without core changing. | `aws_account_policy` | `AwsAccountPolicy`: `resolve_consent_target()`, `configured_region(p)`, `is_sso_profile(p)` | `dashboard/handlers/aws_consent.py` (`s3` / `ce` cards), `dashboard/handlers/aws_project_profile.py` (the project pill) | the consent card names the CLI default chain; the pill probes in the default region and reports a failed probe as `unavailable` | | `transfer_staging` | `TransferStaging`: `pinned_staging(prefix)` | `cloud/microvm/api.py` `staging_dir` | `RuntimeError`, never the shared temp directory | | `stopped_loop_tombstone` | `StoppedLoopTombstone`: `keeps_stopped_loop(slot_key, app_id)` | `dashboard/session_directive_apply_monitor.py` `_keeps_stopped_loop` (the stop of a legacy autonudge loop) | the loop row is removed, as for every other legacy loop (see `knowledge.md`, "Repository boundary") | +| worker slot modes | `register_worker_slot_mode(app_id)`, one per app | `dashboard/chat_handlers.py` `_CREATABLE_MODES` (section 23a) | the chat create paths accept `""` alone | A builtin app registers from a `seams.py` at its package root. The first lookup of any seam imports every such module once, for each name in `BUILTIN_NAMES`, found by file so @@ -5164,6 +5200,7 @@ an installed app's `on_startup` hook, calls `seams.register` itself. A provider answers whether or not its app is enabled, because the core features above worked with aws-control switched off (its default). One app holds a seam: a second app registering it is refused with `ValueError`, so the answer cannot depend on import order. +Worker slot modes are the exception: each app registers its own id. A broken provider module is logged and skipped. The one-time load holds its own lock, never the registry's, so a provider module registering from another thread cannot deadlock it; a seams module therefore only registers while it is imported, and never diff --git a/src/kiro_crew/apps/builtins/design_critique/__init__.py b/src/kiro_crew/apps/builtins/design_critique/__init__.py index 49a070ffd451..fa326ba6a4f4 100644 --- a/src/kiro_crew/apps/builtins/design_critique/__init__.py +++ b/src/kiro_crew/apps/builtins/design_critique/__init__.py @@ -1,8 +1,35 @@ """Design Critique — builtin app package marker. The startup route loop in ``dashboard/routes/system.py`` imports this package and -checks ``hasattr(module, "register_routes")`` on the package object, so the -handler must be re-exported here. +reads ``register_routes`` off the package object, inside the guard that skips an +app whose files cannot be read. + +The core's ``apps.seams`` imports this package to reach ``seams.py`` while +``dashboard.chat_handlers`` is itself being imported, so the route module (which +imports the dashboard) is not imported here. ``register_routes`` is served by the +module ``__getattr__`` below instead, which imports the route module on first access: +that access is the route loop's guarded lookup, so an unreadable route file is +skipped there like any other unreadable app. """ -from .backend.routes import register_routes # noqa: F401 +from __future__ import annotations + +import importlib +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from kiro_crew.apps.builtins.design_critique.backend.routes import ( # noqa: F401 + register_routes, + ) + +#: Each lazily served name and its owner's dotted name. +_LAZY_OWNERS: dict[str, str] = { + "register_routes": "kiro_crew.apps.builtins.design_critique.backend.routes", +} + + +def __getattr__(name: str) -> Any: + owner = _LAZY_OWNERS.get(name) + if owner is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + return getattr(importlib.import_module(owner), name) diff --git a/src/kiro_crew/apps/builtins/design_critique/seams.py b/src/kiro_crew/apps/builtins/design_critique/seams.py new file mode 100644 index 000000000000..915b2988e359 --- /dev/null +++ b/src/kiro_crew/apps/builtins/design_critique/seams.py @@ -0,0 +1,18 @@ +"""Design Critique's registrations in the core's :mod:`kiro_crew.apps.seams`. + +The core imports this module on its first seam lookup, which ``dashboard.chat_handlers`` +makes while it is itself being imported, so it imports nothing of the app. The page's +``openSlot()`` creates its throwaway ``dc-*`` worker slots under the app's own mode, and +repeats it on every send so a slot recreated after a gateway restart keeps it. A +non-``""`` mode is what keeps those slots off the chat sidebar, which lists only plain +``""`` slots. +""" + +from __future__ import annotations + +from kiro_crew.apps import seams + +#: The manifest name, which is also the worker slot mode. +APP_ID = "design-critique" + +seams.register_worker_slot_mode(APP_ID) diff --git a/test/test_design_critique_capture_site_resolver_rule.py b/src/kiro_crew/apps/builtins/design_critique/tests/test_capture_site_resolver_rule.py similarity index 88% rename from test/test_design_critique_capture_site_resolver_rule.py rename to src/kiro_crew/apps/builtins/design_critique/tests/test_capture_site_resolver_rule.py index c26fb48c321f..a5f31ca11d97 100644 --- a/test/test_design_critique_capture_site_resolver_rule.py +++ b/src/kiro_crew/apps/builtins/design_critique/tests/test_capture_site_resolver_rule.py @@ -7,9 +7,9 @@ script imports cleanly as a module (its entry point runs only when it is the program), so the test calls the shipped function directly under ``node``. -It lives in ``test/`` rather than the app's own ``tests/``: running ``node`` is a -subprocess spawn, and ``test_spawn_audit`` holds every spawn under -``src/kiro_crew`` to the sandbox chokepoint or its allowlist. +Running ``node`` is a subprocess spawn, and ``test_spawn_audit`` holds every spawn +under ``src/kiro_crew`` to the sandbox chokepoint or its allowlist, so ``_rules`` is a +row of ``test/spawn_audit_app_spawns.py``. """ from __future__ import annotations @@ -21,14 +21,9 @@ import pytest -# test/ -> parents[1] is the repo root. +# tests/ -> parents[1] is the app's own directory. CAPTURE_SITE = ( Path(__file__).resolve().parents[1] - / "src" - / "kiro_crew" - / "apps" - / "builtins" - / "design_critique" / "skills" / "design-critique" / "scripts" diff --git a/src/kiro_crew/apps/builtins/design_critique/tests/test_denied_root_parts_owner.py b/src/kiro_crew/apps/builtins/design_critique/tests/test_denied_root_parts_owner.py new file mode 100644 index 000000000000..1b53b582ec60 --- /dev/null +++ b/src/kiro_crew/apps/builtins/design_critique/tests/test_denied_root_parts_owner.py @@ -0,0 +1,17 @@ +"""The local-target guard screens against the core's ONE credential dot-dir denylist. + +``_DENIED_ROOT_PARTS`` must be :data:`kiro_crew.security.DENIED_ROOT_PARTS` itself — +identity, not equality — so a credential directory the core adds for any app is +denied here too. ``test/test_denied_root_parts_shared.py`` pins the owner's own shape. +""" + +from __future__ import annotations + +from kiro_crew.apps.builtins.design_critique.backend import routes +from kiro_crew.security import DENIED_ROOT_PARTS + + +def test_the_local_target_guard_consumes_the_shared_object() -> None: + # `is`, not `==`: a byte-identical local copy would pass equality while + # re-creating exactly the drift the shared owner removes. + assert routes._DENIED_ROOT_PARTS is DENIED_ROOT_PARTS diff --git a/test/test_design_critique_owner_gate.py b/src/kiro_crew/apps/builtins/design_critique/tests/test_owner_gate.py similarity index 100% rename from test/test_design_critique_owner_gate.py rename to src/kiro_crew/apps/builtins/design_critique/tests/test_owner_gate.py diff --git a/test/test_design_critique_ssrf_guard_fail_closed.py b/src/kiro_crew/apps/builtins/design_critique/tests/test_ssrf_guard_fail_closed.py similarity index 97% rename from test/test_design_critique_ssrf_guard_fail_closed.py rename to src/kiro_crew/apps/builtins/design_critique/tests/test_ssrf_guard_fail_closed.py index a2adb542d378..2b5d11158dcd 100644 --- a/test/test_design_critique_ssrf_guard_fail_closed.py +++ b/src/kiro_crew/apps/builtins/design_critique/tests/test_ssrf_guard_fail_closed.py @@ -21,8 +21,9 @@ import pytest -REPO_ROOT = Path(__file__).resolve().parents[1] -SCRIPTS = REPO_ROOT / "src/kiro_crew/apps/builtins/design_critique/skills/design-critique/scripts" +# tests/ -> parents[1] is the app's own directory. +APP_ROOT = Path(__file__).resolve().parents[1] +SCRIPTS = APP_ROOT / "skills/design-critique/scripts" SSRF_GUARD = SCRIPTS / "ssrf-guard.mjs" ENSURE_PW = SCRIPTS / "ensure-playwright.mjs" diff --git a/src/kiro_crew/apps/builtins/design_critique/tests/test_unreadable_routes_skipped.py b/src/kiro_crew/apps/builtins/design_critique/tests/test_unreadable_routes_skipped.py new file mode 100644 index 000000000000..91f06bc35400 --- /dev/null +++ b/src/kiro_crew/apps/builtins/design_critique/tests/test_unreadable_routes_skipped.py @@ -0,0 +1,64 @@ +"""An unreadable Design Critique route module is skipped at boot, not fatal. + +The package keeps its route module out of its ``__init__`` and serves +``register_routes`` from a module ``__getattr__``. That lookup is what the startup +route loop in ``dashboard/routes/system.py`` guards against ``OSError``, so a route +file an endpoint security agent denies is logged and skipped there, and the other +built-ins still register. +""" + +from __future__ import annotations + +import importlib +import logging +from types import SimpleNamespace + +import pytest +from aiohttp import web + +from kiro_crew.dashboard.routes import system + +ROUTES = "kiro_crew.apps.builtins.design_critique.backend.routes" + + +def _app() -> web.Application: + app = web.Application() + app["state"] = SimpleNamespace(owner_id="owner", broadcast_ws=lambda *a, **k: None) + return app + + +def test_the_route_module_is_read_by_the_lookup_not_the_call( + monkeypatch: pytest.MonkeyPatch, +) -> None: + package = importlib.import_module("kiro_crew.apps.builtins.design_critique") + real_import = importlib.import_module + + def _import(name: str, *args, **kwargs): + if name == ROUTES: + raise PermissionError(13, "Permission denied", "backend/routes.py") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(importlib, "import_module", _import) + with pytest.raises(PermissionError): + getattr(package, "register_routes") + + +def test_an_unreadable_route_module_does_not_abort_route_setup( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + real_import = importlib.import_module + + def _import(name: str, *args, **kwargs): + if name == ROUTES: + raise PermissionError(13, "Permission denied", "backend/routes.py") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(importlib, "import_module", _import) + app = _app() + with caplog.at_level(logging.WARNING, logger=system.__name__): + system.register(app) # must not raise + + warned = [r.getMessage() for r in caplog.records if "design_critique" in r.getMessage()] + assert warned and "PermissionError" in warned[0], warned + paths = {getattr(r.resource, "canonical", "") for r in app.router.routes()} + assert not any(p.startswith("/api/apps/design-critique/") for p in paths) diff --git a/src/kiro_crew/apps/builtins/design_critique/tests/test_worker_slot_mode.py b/src/kiro_crew/apps/builtins/design_critique/tests/test_worker_slot_mode.py new file mode 100644 index 000000000000..7a81c934377d --- /dev/null +++ b/src/kiro_crew/apps/builtins/design_critique/tests/test_worker_slot_mode.py @@ -0,0 +1,21 @@ +"""Design Critique's ``dc-*`` worker slots are created under the app's own mode. + +The page's ``openSlot()`` posts ``mode: "design-critique"`` and repeats it on every +send. The core accepts it only because this app registers it from its ``seams.py`` +(through ``kiro_crew.apps.seams``); a slot created without it would be a plain ``""`` +chat and land in the user's chat sidebar. +""" + +from __future__ import annotations + +from kiro_crew.apps import seams +from kiro_crew.dashboard import chat_handlers + + +def test_the_app_registers_its_own_name_as_its_worker_mode() -> None: + assert "design-critique" in seams.worker_slot_modes() + + +def test_the_chat_create_paths_accept_it() -> None: + assert "design-critique" in chat_handlers._CREATABLE_MODES + assert chat_handlers._CREATABLE_MODES[0] == "" diff --git a/src/kiro_crew/apps/seams.py b/src/kiro_crew/apps/seams.py index 4d5b5f6a4cb5..2a0f7ec543c3 100644 --- a/src/kiro_crew/apps/seams.py +++ b/src/kiro_crew/apps/seams.py @@ -5,10 +5,10 @@ paid-service consent cards and the composer's project pill resolve an AWS profile through that app's account policy. The MicroVM control calls stage a secret under the app's sandbox-masked transfer root. A stop of a legacy autonudge loop asks whether -an app reads the stopped row back. Core names each such need as a SEAM here and asks -for its provider when it runs. The app registers the provider, -and core never imports the app, so the app can leave this repository without core -changing. +an app reads the stopped row back. The chat create paths accept the slot mode an app's +throwaway worker slots are born with. Core names each such need as a SEAM here and asks +for its provider when it runs. The app registers the provider, and core never imports +the app, so the app can leave this repository without core changing. Empty by default. A seam that no app filled answers ``None``. Each core caller's own docstring says what it does then: degrade to a fixed answer, or refuse. @@ -29,7 +29,9 @@ what they do. One provider per seam. A second app that registers a seam another app already holds -is refused, because otherwise the answer would depend on import order. +is refused, because otherwise the answer would depend on import order. Worker slot +modes are the one seam every app may fill: each app registers its own, under its own +id, through :func:`register_worker_slot_mode`. """ from __future__ import annotations @@ -118,6 +120,8 @@ def keeps_stopped_loop(self, slot_key: str, app_id: str) -> bool: _lock = threading.Lock() #: seam -> (app id, provider). _providers: dict[str, tuple[str, object]] = {} +#: app id -> the worker slot mode it registered, in registration order. +_worker_slot_modes: dict[str, str] = {} #: Serializes the one-time import of the builtin seams modules. :func:`register` #: never takes it, so a provider module can register while it is held. A seams #: module must therefore only register while it is imported, never look a seam up. @@ -171,6 +175,32 @@ def stopped_loop_tombstone() -> StoppedLoopTombstone | None: return cast("StoppedLoopTombstone | None", provider(SEAM_STOPPED_LOOP_TOMBSTONE)) +def register_worker_slot_mode(app_id: str) -> None: + """Let the chat create paths accept *app_id* as the mode of that app's worker slots. + + A slot's ``mode`` is fixed when it is created, and the chat sidebar lists only + ``""`` slots, so an app whose throwaway worker slots must stay off the sidebar + creates them under a mode of its own. Each builtin passes its own id as that mode. + Registering again is a no-op. + """ + if not isinstance(app_id, str): + raise ValueError(f"a worker slot mode must be a str, not {type(app_id).__name__}") + with _lock: + _worker_slot_modes[app_id] = app_id + + +def worker_slot_modes() -> tuple[str, ...]: + """Every registered worker slot mode, builtins in ``BUILTIN_NAMES`` order. + + ``dashboard.chat_handlers`` reads it once, at import, so only a builtin's seams + module reaches the create paths: it is loaded by the first lookup, before any + installed app runs. Empty when no app registered one. + """ + _load_builtin_seams() + with _lock: + return tuple(_worker_slot_modes.values()) + + def _load_builtin_seams() -> None: """Import each shipped builtin's ``seams`` module, once per process. diff --git a/src/kiro_crew/dashboard/chat_api/chat_send.py b/src/kiro_crew/dashboard/chat_api/chat_send.py index d6761902b89d..e5ceb4c8fe1b 100644 --- a/src/kiro_crew/dashboard/chat_api/chat_send.py +++ b/src/kiro_crew/dashboard/chat_api/chat_send.py @@ -672,13 +672,13 @@ async def _api_chat_send(request: web.Request) -> web.StreamResponse: requested_memory_mode = None # Honor mode from the body when auto-creating a slot, mirroring memory_mode - # above: an app whose worker slot lives only in gateway memory (e.g. Design - # Critique) repeats mode on send(), so a slot recreated here after a - # gateway restart keeps its non-"" surface and stays out of the chat - # sidebar's surface allowlist. Only creation-allowlisted values pass; - # anything else is dropped so get_or_create_slot uses its default. Unlike - # memory_mode there is no mismatch error: get_or_create_slot ignores mode - # for an already-existing slot. + # above: an app whose worker slot lives only in gateway memory repeats mode + # on send(), so a slot recreated here after a gateway restart keeps its + # non-"" surface and stays out of the chat sidebar's surface allowlist. + # Only creation-allowlisted values pass; anything else is dropped so + # get_or_create_slot uses its default. Unlike memory_mode there is no + # mismatch error: get_or_create_slot ignores mode for an already-existing + # slot. requested_mode = body.get("mode") if not isinstance(requested_mode, str) or requested_mode not in _CREATABLE_MODES: requested_mode = "" diff --git a/src/kiro_crew/dashboard/chat_handlers.py b/src/kiro_crew/dashboard/chat_handlers.py index 5d2217587431..44140cddfdf9 100644 --- a/src/kiro_crew/dashboard/chat_handlers.py +++ b/src/kiro_crew/dashboard/chat_handlers.py @@ -34,6 +34,7 @@ from kiro_crew.agent_sdk.capabilities import MODEL_NAMESPACE_ACP, capabilities_of # noqa: F401 from kiro_crew.agent_sdk.provider_identity import is_claude_code # noqa: F401 from kiro_crew.agent_switch_command import switch_announcement # noqa: F401 +from kiro_crew.apps import seams as _app_seams from kiro_crew.atomic_write import atomic_write, read_bytes_with_retry # noqa: F401 from kiro_crew.config.loader import ( # noqa: F401 AUTOCOMPACT_PCT_MAX, @@ -664,13 +665,14 @@ # Modes a slot may be CREATED with. A deliberate superset of the mode-SWITCH # allowlist (chat_folders._VALID_MODES) and the fork override allowlist -# (chat_fork): "design-critique" is an app-worker mode assigned at birth by the -# Design Critique app's openSlot() — the custom mode keeps its throwaway dc-* -# slots off the chat sidebar, which renders only plain "" slots -# (chat/page/pageEnvironment.ts filteredSlots). Switching an existing session INTO an -# app-worker mode, or forking one with it as an override, is not a real flow, so those two -# allowlists deliberately stay narrower — do not "sync" them to this one. -_CREATABLE_MODES = ("", "design-critique") +# (chat_fork): beyond "", each entry is an app-worker mode a shipped built-in app +# registers for itself (apps/seams.py worker_slot_modes) and assigns at birth to the +# throwaway worker slots it opens — the custom mode keeps them off the chat sidebar, +# which renders only plain "" slots (chat/page/pageEnvironment.ts filteredSlots). +# Switching an existing session INTO an app-worker mode, or forking one with it as an +# override, is not a real flow, so those two allowlists deliberately stay narrower — do +# not "sync" them to this one. +_CREATABLE_MODES = ("", *_app_seams.worker_slot_modes()) # Deferral is an optimization, so a request shape added later must stay on the # synchronous path until its publication ordering has been reviewed explicitly. diff --git a/src/kiro_crew/dashboard/state_parts/chat_slot.py b/src/kiro_crew/dashboard/state_parts/chat_slot.py index ce7c977cec23..863fd491b071 100644 --- a/src/kiro_crew/dashboard/state_parts/chat_slot.py +++ b/src/kiro_crew/dashboard/state_parts/chat_slot.py @@ -686,7 +686,7 @@ def __init__( self.agent = agent _slot_session.init_session_fields(self) self.model = model - # "" = default chat; app workers may carry their own mode (design-critique) + # "" = default chat; app workers may carry their own mode (apps/seams.py) self.mode = mode self.workspace = workspace _slot_turns.init_turns_fields(self) diff --git a/test/spawn_audit_app_spawns.py b/test/spawn_audit_app_spawns.py index a83e5a8fe130..f40c857da3b0 100644 --- a/test/spawn_audit_app_spawns.py +++ b/test/spawn_audit_app_spawns.py @@ -587,5 +587,14 @@ # which a scrubbed-env/filesystem-scoped wrapper would move or forbid. "apps/builtins/aws_control/crew/packaging/tests/test_producer.py" "::test_cli_subprocess_leaves_no_pycache_in_the_source_tree", + # TEST-ONLY, and the spawn is the thing under test: Design Critique's capture + # scripts are Node ESM modules, so the only way to call their shipped pure + # functions (``hostResolverRule``, ``installSsrfGuard``, ``getPlaywright``) is + # a ``node --input-type=module -e `` child. Fixed argv, no shell=True; + # the program is a literal built in the test from a ``file://`` URI of the + # app's own script and JSON-encoded fixture inputs, the cwd and environment + # overrides are the test's own ``tmp_path``. Nothing here is agent-derived. + "apps/builtins/design_critique/tests/test_capture_site_resolver_rule.py::_rules", + "apps/builtins/design_critique/tests/test_ssrf_guard_fail_closed.py::_run_node", } ) diff --git a/test/test_app_seams.py b/test/test_app_seams.py index 220f2f258314..a19fc52a2f6a 100644 --- a/test/test_app_seams.py +++ b/test/test_app_seams.py @@ -68,6 +68,43 @@ def register_elsewhere(): assert seams.provider("probe") == 1 +@pytest.fixture() +def slot_modes(monkeypatch): + """The real worker slot modes with the shipped builtins loaded, restored after the test.""" + seams.worker_slot_modes() + monkeypatch.setattr(seams, "_worker_slot_modes", dict(seams._worker_slot_modes)) + return seams._worker_slot_modes + + +class TestWorkerSlotModes: + """The one seam every app may fill: each app registers its own id as a slot mode.""" + + def test_each_app_registers_its_own_mode_in_order(self, slot_modes): + slot_modes.clear() + seams.register_worker_slot_mode("zeta-app") + seams.register_worker_slot_mode("alpha-app") + assert seams.worker_slot_modes() == ("zeta-app", "alpha-app") + + def test_registering_again_is_a_no_op(self, slot_modes): + slot_modes.clear() + seams.register_worker_slot_mode("some-app") + seams.register_worker_slot_mode("some-app") + assert seams.worker_slot_modes() == ("some-app",) + + def test_no_registration_means_no_worker_mode(self, slot_modes): + slot_modes.clear() + assert seams.worker_slot_modes() == () + + def test_a_non_string_id_is_refused(self, slot_modes): + with pytest.raises(ValueError, match="must be a str"): + seams.register_worker_slot_mode(("some-app",)) # type: ignore[arg-type] + + def test_the_chat_create_paths_read_the_seam(self): + from kiro_crew.dashboard import chat_handlers + + assert chat_handlers._CREATABLE_MODES == ("", *seams.worker_slot_modes()) + + class TestTheShippedProviders: def test_aws_control_provides_all_three_seams(self): seams.crew_runtime() diff --git a/test/test_core_design_critique_decoupling.py b/test/test_core_design_critique_decoupling.py new file mode 100644 index 000000000000..3b95b253cfdb --- /dev/null +++ b/test/test_core_design_critique_decoupling.py @@ -0,0 +1,109 @@ +"""GATE: Kiro Crew core does not depend on the Design Critique app's code. + +Design Critique is to leave this repository whole. That is only possible while +nothing outside ``src/kiro_crew/apps/builtins/`` imports it or names it. What the +core needs from the app it reads through a seam that is empty by default: the +worker slot mode the chat create paths accept comes from ``kiro_crew.apps.seams``, +where the app's own ``seams.py`` registers it. + +Two properties are pinned: + +1. **No core module or script imports the app.** Every module under + ``src/kiro_crew`` outside ``apps/builtins/``, and every script under + ``scripts/``, is parsed. ``import``, ``from ... import`` (relative ones + resolved), ``from kiro_crew.apps.builtins import design_critique``, + ``importlib.import_module`` and ``__import__`` with a literal name are all in + scope, and the probes below fail if any of those forms stops being caught. +2. **No core string names the app.** A hard-coded allowlist entry + ``"design-critique"``, or a dynamic import built from ``"design_critique"``, + reaches the app as surely as an import does. Docstrings and comments are prose + and are not read. + +The scans are the shared ones in ``test/core_app_independence.py``. The +dashboard half is ``website/src/apps/design-critique/designCritiqueBoundary.test.ts``. + +If this goes red because core reached for the app, add a generic, app-keyed seam +the app fills instead. Do not add an exemption. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +import core_app_independence as independence +import pytest + +pytestmark = pytest.mark.xdist_group(name="tree_scan_test_core_design_critique_decoupling") + +APP_PACKAGE = "kiro_crew.apps.builtins.design_critique" +#: The package directory name and the app id: every spelling that addresses the app. +APP_NAMES = ("design_critique", "design-critique") + + +@pytest.fixture(scope="module") +def core_trees() -> dict[Path, ast.AST]: + """The parsed core files that mention the app at all.""" + return independence.core_trees(APP_NAMES) + + +def test_no_core_module_or_script_imports_the_app(core_trees): + offenders = independence.core_app_imports(core_trees, APP_PACKAGE) + assert not offenders, ( + "core imports the design-critique app; add a generic seam the app fills instead:\n" + + "\n".join(offenders) + ) + + +def test_no_core_string_names_the_app(core_trees): + found, _allowed = independence.core_name_strings(core_trees, APP_NAMES) + assert not found, "a core string names the design-critique app:\n" + "\n".join(found) + + +@pytest.mark.parametrize( + ("source", "importer", "is_package"), + [ + ("import kiro_crew.apps.builtins.design_critique.backend.routes", "kiro_crew.x", False), + ("from kiro_crew.apps.builtins.design_critique import seams", "kiro_crew.x", False), + ("from kiro_crew.apps.builtins import design_critique", "kiro_crew.x", False), + ("from ..apps.builtins.design_critique import seams", "kiro_crew.dashboard.y", False), + ("from .builtins.design_critique.backend import routes", "kiro_crew.apps.y", False), + ("from .builtins import design_critique", "kiro_crew.apps", True), + ( + "import importlib\n" + "importlib.import_module('kiro_crew.apps.builtins.design_critique')", + "kiro_crew.x", + False, + ), + ("__import__('kiro_crew.apps.builtins.design_critique.backend')", "kiro_crew.x", False), + ], +) +def test_the_scan_catches_every_import_form(source, importer, is_package): + assert independence.app_imports(ast.parse(source), APP_PACKAGE, importer, is_package) + + +@pytest.mark.parametrize( + "source", + [ + "from kiro_crew.apps import seams", + "from kiro_crew.apps.builtins import BUILTIN_NAMES", + "import kiro_crew.apps.builtins.design_tweak", + ], +) +def test_the_scan_leaves_other_imports_alone(source): + assert not independence.app_imports(ast.parse(source), APP_PACKAGE, "kiro_crew.x", False) + + +def test_the_string_scan_skips_docstrings_but_not_allowlists_ids_or_urls(): + tree = ast.parse( + '"""Mentions design-critique in prose."""\n' + "# an app-worker mode (Design Critique's design-critique, for one)\n" + '_MODES = ("", "design-critique")\n' + 'pkg = "kiro_crew.apps.builtins." + "design_critique"\n' + 'url = f"/api/apps/design-critique/{app}"\n' + ) + assert sorted(independence.name_strings(tree, APP_NAMES)) == [ + (3, "design-critique"), + (4, "design_critique"), + (5, "/api/apps/design-critique/"), + ] diff --git a/test/test_dashboard_chat_api_chat.py b/test/test_dashboard_chat_api_chat.py index b744e37cabaf..8128d0d4ba9d 100644 --- a/test/test_dashboard_chat_api_chat.py +++ b/test/test_dashboard_chat_api_chat.py @@ -12,6 +12,9 @@ from kiro_crew.testing.wait import async_wait_until +#: An app-worker slot mode, as a built-in would register it (``apps/seams.py``). +_WORKER_MODE = "some-app" + @pytest.mark.asyncio class TestApiChatDrainOnDisconnect: @@ -213,12 +216,16 @@ async def test_mismatched_memory_mode_on_existing_slot_returns_409(self, tmp_pat class TestApiChatModeForwarding: """api_chat propagates a validated body.mode to the auto-created slot. - The Design Critique app's worker slot (mode="design-critique") lives only - in gateway memory. After a gateway restart the app's next send() recreates - the slot through this auto-create path; without mode forwarding the slot - is reborn with mode="" — it then serializes surface="" and passes the chat - sidebar's surface allowlist, leaking the throwaway worker session into the - user's chat list. Mirrors TestApiChatMemoryModeForwarding above. + An app's worker slot (created under the app-worker mode its built-in registers + through ``apps/seams.py``) lives only in gateway memory. After a + gateway restart the app's next send() recreates the slot through this + auto-create path; without mode forwarding the slot is reborn with mode="" — + it then serializes surface="" and passes the chat sidebar's surface + allowlist, leaking the throwaway worker session into the user's chat list. + Mirrors TestApiChatMemoryModeForwarding above. + + The worker mode here is a fixture registered on the facade for each post, so + these rows hold whichever built-ins ship one. """ async def _post_chat(self, state, body): @@ -230,6 +237,7 @@ async def fake_run_chat( with pytest.MonkeyPatch.context() as mp: mp.setattr("kiro_crew.dashboard.chat_handlers._run_chat", fake_run_chat) + mp.setattr("kiro_crew.dashboard.chat_handlers._CREATABLE_MODES", ("", _WORKER_MODE)) async with TestClient(TestServer(_make_app(state))) as client: resp = await client.post("/api/chat", json=body, timeout=None) assert resp.status == 200 @@ -238,23 +246,23 @@ async def fake_run_chat( resp.close() await asyncio.sleep(0.05) - async def test_design_critique_mode_propagates_to_new_slot(self, tmp_path, monkeypatch): + async def test_app_worker_mode_propagates_to_new_slot(self, tmp_path, monkeypatch): monkeypatch.setattr("kiro_crew.dashboard.state.config_dir", lambda: tmp_path) state = _make_state(tmp_path) await self._post_chat( state, { - "message": "critique this", - "slot": "dc-12345", + "message": "work on this", + "slot": "worker-12345", "memory_mode": "temporary", - "mode": "design-critique", + "mode": _WORKER_MODE, }, ) - slot = state._slots.get("dc-12345") + slot = state._slots.get("worker-12345") assert slot is not None - assert slot.mode == "design-critique" + assert slot.mode == _WORKER_MODE # The leak this guards against: the sidebar allowlist admits the plain # "" surface — the recreated worker must not serialize it. assert slot.mode != "" @@ -307,21 +315,21 @@ async def test_mode_ignored_for_existing_slot(self, tmp_path, monkeypatch): existing slot keeps its stored mode and no error is raised.""" monkeypatch.setattr("kiro_crew.dashboard.state.config_dir", lambda: tmp_path) state = _make_state(tmp_path) - state.get_or_create_slot("dc-alive", mode="design-critique", memory_mode="temporary") + state.get_or_create_slot("worker-alive", mode=_WORKER_MODE, memory_mode="temporary") await self._post_chat( state, { "message": "hello again", - "slot": "dc-alive", + "slot": "worker-alive", "memory_mode": "temporary", - "mode": "design-critique", + "mode": _WORKER_MODE, }, ) - slot = state._slots.get("dc-alive") + slot = state._slots.get("worker-alive") assert slot is not None - assert slot.mode == "design-critique" + assert slot.mode == _WORKER_MODE @pytest.mark.asyncio diff --git a/test/test_denied_root_parts_shared.py b/test/test_denied_root_parts_shared.py index 38f82d35b432..a488f63b2c9b 100644 --- a/test/test_denied_root_parts_shared.py +++ b/test/test_denied_root_parts_shared.py @@ -1,27 +1,23 @@ """Pins the credential dot-dir denylist to ONE shared owner. -`design_critique` (local render target) and `design_tweak` (previewed project -folder) each screen operator-picked paths against a set of credential dot-dirs -that the `is_sensitive_path()` floor does not enumerate. That set is owned by -:data:`kiro_crew.security.DENIED_ROOT_PARTS`; both apps must consume the SAME -object — identity, not equality — so a credential directory added for one app -can never silently miss the other. +Apps that screen operator-picked paths against a set of credential dot-dirs that +the `is_sensitive_path()` floor does not enumerate consume +:data:`kiro_crew.security.DENIED_ROOT_PARTS`, the SAME object — identity, not +equality — so a credential directory added for one app can never silently miss +another. Each consumer pins its own identity, in its own tests where it has them; +`design_tweak` (previewed project folder) does it here. """ from __future__ import annotations -from kiro_crew.apps.builtins.design_critique.backend import routes from kiro_crew.apps.builtins.design_tweak.backend import server from kiro_crew.security import DENIED_ROOT_PARTS class TestDeniedRootPartsSharedOwner: - def test_design_critique_consumes_the_shared_object(self): + def test_design_tweak_consumes_the_shared_object(self): # `is`, not `==`: a byte-identical local copy would pass equality while # re-creating exactly the drift this refactor removes. - assert routes._DENIED_ROOT_PARTS is DENIED_ROOT_PARTS - - def test_design_tweak_consumes_the_shared_object(self): assert server._DENIED_ROOT_PARTS is DENIED_ROOT_PARTS def test_project_secret_dirs_derives_from_the_shared_set(self): diff --git a/website/src/test/DesignCritiqueAskLayerCov80.test.tsx b/website/src/apps/design-critique/DesignCritiqueAskLayerCov80.test.tsx similarity index 98% rename from website/src/test/DesignCritiqueAskLayerCov80.test.tsx rename to website/src/apps/design-critique/DesignCritiqueAskLayerCov80.test.tsx index c592c1a047dc..e8b232ce9c9a 100644 --- a/website/src/test/DesignCritiqueAskLayerCov80.test.tsx +++ b/website/src/apps/design-critique/DesignCritiqueAskLayerCov80.test.tsx @@ -3,8 +3,8 @@ import { fireEvent, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { describe, expect, it, vi } from 'vitest' -import AskLayer from '../apps/design-critique/AskLayer' -import type { Ask, Sel } from '../apps/design-critique/types' +import AskLayer from './AskLayer' +import type { Ask, Sel } from './types' /** * "Ask about this": a floating chip over a text selection, then a popover that diff --git a/website/src/test/DesignCritiqueChrome.i18n.test.tsx b/website/src/apps/design-critique/DesignCritiqueChrome.i18n.test.tsx similarity index 95% rename from website/src/test/DesignCritiqueChrome.i18n.test.tsx rename to website/src/apps/design-critique/DesignCritiqueChrome.i18n.test.tsx index 9a391e8d725c..f730dfff1949 100644 --- a/website/src/test/DesignCritiqueChrome.i18n.test.tsx +++ b/website/src/apps/design-critique/DesignCritiqueChrome.i18n.test.tsx @@ -18,14 +18,14 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import React from 'react' // `/all` registers every authored catalog; `../i18n` registers English only. -import { i18next } from '../i18n/all' -import { HKEY } from '../apps/design-critique/constants' -import { designCritiqueApi } from '../apps/design-critique/api' -import Composer from '../apps/design-critique/Composer' -import FindingRow from '../apps/design-critique/FindingRow' -import type { HistoryEntry, StagedItem } from '../apps/design-critique/types' - -vi.mock('../apps/design-critique/api', () => ({ +import { i18next } from '../../i18n/all' +import { HKEY } from './constants' +import { designCritiqueApi } from './api' +import Composer from './Composer' +import FindingRow from './FindingRow' +import type { HistoryEntry, StagedItem } from './types' + +vi.mock('./api', () => ({ designCritiqueApi: { openSlot: vi.fn(), getSlot: vi.fn(), send: vi.fn(), deleteSlot: vi.fn(), uploadFiles: vi.fn(), discover: vi.fn(), render: vi.fn(), pollDiscover: vi.fn(), pollRender: vi.fn(), @@ -34,7 +34,7 @@ vi.mock('../apps/design-critique/api', () => ({ fileUrl: (p: string) => '/api/file-raw?path=' + encodeURIComponent(p), })) -const DesignCritiquePage = (await import('../apps/design-critique/DesignCritiquePage')).default +const DesignCritiquePage = (await import('./DesignCritiquePage')).default const K = 'apps.designCritique.' diff --git a/website/src/test/DesignCritiqueComposer.i18n.test.tsx b/website/src/apps/design-critique/DesignCritiqueComposer.i18n.test.tsx similarity index 98% rename from website/src/test/DesignCritiqueComposer.i18n.test.tsx rename to website/src/apps/design-critique/DesignCritiqueComposer.i18n.test.tsx index be6e5453c62f..40fcd41ba23f 100644 --- a/website/src/test/DesignCritiqueComposer.i18n.test.tsx +++ b/website/src/apps/design-critique/DesignCritiqueComposer.i18n.test.tsx @@ -18,10 +18,10 @@ import { describe, it, expect, vi, afterAll } from 'vitest' import { render, screen } from '@testing-library/react' import React from 'react' -import Composer from '../apps/design-critique/Composer' +import Composer from './Composer' // `/all` for the 11 authored catalogs this file reads: `../i18n` registers // English only. -import { i18next } from '../i18n/all' +import { i18next } from '../../i18n/all' const noop = () => {} diff --git a/website/src/test/DesignCritiqueComposerCov80.test.tsx b/website/src/apps/design-critique/DesignCritiqueComposerCov80.test.tsx similarity index 98% rename from website/src/test/DesignCritiqueComposerCov80.test.tsx rename to website/src/apps/design-critique/DesignCritiqueComposerCov80.test.tsx index f74adf2d36de..0801866faeab 100644 --- a/website/src/test/DesignCritiqueComposerCov80.test.tsx +++ b/website/src/apps/design-critique/DesignCritiqueComposerCov80.test.tsx @@ -3,8 +3,8 @@ import { fireEvent, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { describe, expect, it, vi } from 'vitest' -import Composer from '../apps/design-critique/Composer' -import type { Blocked, StagedItem } from '../apps/design-critique/types' +import Composer from './Composer' +import type { Blocked, StagedItem } from './types' /** * The composer decides what gets critiqued: staged screenshots (whose ORDER is diff --git a/website/src/test/DesignCritiqueConstantsCov80.test.ts b/website/src/apps/design-critique/DesignCritiqueConstantsCov80.test.ts similarity index 98% rename from website/src/test/DesignCritiqueConstantsCov80.test.ts rename to website/src/apps/design-critique/DesignCritiqueConstantsCov80.test.ts index c1a9b99ed5ee..e8ecd438e985 100644 --- a/website/src/test/DesignCritiqueConstantsCov80.test.ts +++ b/website/src/apps/design-critique/DesignCritiqueConstantsCov80.test.ts @@ -5,8 +5,8 @@ import { SEV, sevOf, KIND_LABEL, KIND_LABEL_KEY, kindLabel, STAGES, WRITING_STAGE, SCAN_STAGES, BLOCKED, blockedFor, KIND_WAIT, SAMPLE_SCREENS, SAMPLE_REPORT, -} from '../apps/design-critique/constants' -import type { SeverityKey } from '../apps/design-critique/types' +} from './constants' +import type { SeverityKey } from './types' /** * Every copy field in this module sits behind a GETTER so `i18nT()` runs on diff --git a/website/src/test/DesignCritiqueDetectKind.test.ts b/website/src/apps/design-critique/DesignCritiqueDetectKind.test.ts similarity index 97% rename from website/src/test/DesignCritiqueDetectKind.test.ts rename to website/src/apps/design-critique/DesignCritiqueDetectKind.test.ts index 05fb83799c71..0ac2dd39ea05 100644 --- a/website/src/test/DesignCritiqueDetectKind.test.ts +++ b/website/src/apps/design-critique/DesignCritiqueDetectKind.test.ts @@ -4,7 +4,7 @@ // was only recognised for two of the four hosts the schemed form accepts. import { describe, expect, it } from 'vitest' -import { detectKind } from '../apps/design-critique/utils' +import { detectKind } from './utils' describe('detectKind', () => { it.each([ diff --git a/website/src/test/DesignCritiquePage.coverage.test.tsx b/website/src/apps/design-critique/DesignCritiquePage.coverage.test.tsx similarity index 99% rename from website/src/test/DesignCritiquePage.coverage.test.tsx rename to website/src/apps/design-critique/DesignCritiquePage.coverage.test.tsx index 960998366993..cedc23c414b4 100644 --- a/website/src/test/DesignCritiquePage.coverage.test.tsx +++ b/website/src/apps/design-critique/DesignCritiquePage.coverage.test.tsx @@ -17,13 +17,13 @@ import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { designCritiqueApi } from '../apps/design-critique/api' -import { HKEY, JOBKEY, LIVEKEY, SLOTSKEY } from '../apps/design-critique/constants' -import type { Ask, HistoryEntry, Report, Scope, SlotData } from '../apps/design-critique/types' +import { designCritiqueApi } from './api' +import { HKEY, JOBKEY, LIVEKEY, SLOTSKEY } from './constants' +import type { Ask, HistoryEntry, Report, Scope, SlotData } from './types' // The single seam between the page and the gateway. `fileUrl` is left real: it is // a pure string builder and the page renders its output as an . -vi.mock('../apps/design-critique/api', () => ({ +vi.mock('./api', () => ({ designCritiqueApi: { openSlot: vi.fn(), getSlot: vi.fn(), @@ -52,7 +52,7 @@ const mockApi = designCritiqueApi as unknown as { method: Mock } -const DesignCritiquePage = (await import('../apps/design-critique/DesignCritiquePage')).default +const DesignCritiquePage = (await import('./DesignCritiquePage')).default /** A finished slot whose last assistant message carries `payload` as JSON. The * fence is deliberate — that is how the model actually replies, and diff --git a/website/src/test/DesignCritiquePromptImages.test.tsx b/website/src/apps/design-critique/DesignCritiquePromptImages.test.tsx similarity index 96% rename from website/src/test/DesignCritiquePromptImages.test.tsx rename to website/src/apps/design-critique/DesignCritiquePromptImages.test.tsx index ce47ba948739..f98bcac49f15 100644 --- a/website/src/test/DesignCritiquePromptImages.test.tsx +++ b/website/src/apps/design-critique/DesignCritiquePromptImages.test.tsx @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest' import { render } from '@testing-library/react' -import MarkdownRenderer from '../components/MarkdownRenderer' -import { IMAGES_PROMPT } from '../apps/design-critique/prompts' +import MarkdownRenderer from '../../components/MarkdownRenderer' +import { IMAGES_PROMPT } from './prompts' /** * Design Critique's prompt is an ordinary chat message — `designCritiqueApi.send` diff --git a/website/src/test/DesignCritiqueReplyParse.test.ts b/website/src/apps/design-critique/DesignCritiqueReplyParse.test.ts similarity index 99% rename from website/src/test/DesignCritiqueReplyParse.test.ts rename to website/src/apps/design-critique/DesignCritiqueReplyParse.test.ts index 4498160859d1..4472b43747f8 100644 --- a/website/src/test/DesignCritiqueReplyParse.test.ts +++ b/website/src/apps/design-critique/DesignCritiqueReplyParse.test.ts @@ -8,8 +8,8 @@ // find. Everything below is the second case, plus the first case still failing. import { describe, expect, it } from 'vitest' -import { extractJson, jsonFromMessages, looksLikeReport } from '../apps/design-critique/utils' -import type { SlotData } from '../apps/design-critique/types' +import { extractJson, jsonFromMessages, looksLikeReport } from './utils' +import type { SlotData } from './types' /** A contract-shaped report, as the schema in `prompts.ts` asks for it. */ const REPORT = { diff --git a/website/src/test/DesignCritiqueResolveScreens.test.ts b/website/src/apps/design-critique/DesignCritiqueResolveScreens.test.ts similarity index 92% rename from website/src/test/DesignCritiqueResolveScreens.test.ts rename to website/src/apps/design-critique/DesignCritiqueResolveScreens.test.ts index 4567ea1fbe3c..d7605970b2cd 100644 --- a/website/src/test/DesignCritiqueResolveScreens.test.ts +++ b/website/src/apps/design-critique/DesignCritiqueResolveScreens.test.ts @@ -7,8 +7,8 @@ // screen and uses the model only for the (nicer) label. import { describe, expect, it } from 'vitest' -import { resolveScreens } from '../apps/design-critique/utils' -import type { Report, Screen } from '../apps/design-critique/types' +import { resolveScreens } from './utils' +import type { Report, Screen } from './types' const url = '/api/file-raw?path=%2FUsers%2Fme%2F.kiro%2Fcrew%2Fuploads%2Fabc_shot.png' const uploaded: Screen[] = [{ step: 1, label: 'Screen 1', url }] diff --git a/website/src/test/DesignCritiqueStartLabel.i18n.test.tsx b/website/src/apps/design-critique/DesignCritiqueStartLabel.i18n.test.tsx similarity index 97% rename from website/src/test/DesignCritiqueStartLabel.i18n.test.tsx rename to website/src/apps/design-critique/DesignCritiqueStartLabel.i18n.test.tsx index 49be89612899..211763fd4c44 100644 --- a/website/src/test/DesignCritiqueStartLabel.i18n.test.tsx +++ b/website/src/apps/design-critique/DesignCritiqueStartLabel.i18n.test.tsx @@ -32,12 +32,12 @@ import React from 'react' import { render, screen, cleanup } from '@testing-library/react' import { describe, it, expect, vi, afterEach, afterAll } from 'vitest' -import Composer from '../apps/design-critique/Composer' -import ScopingPicker from '../apps/design-critique/ScopingPicker' +import Composer from './Composer' +import ScopingPicker from './ScopingPicker' // `/all` for the Chinese catalog `withSentinel` injects into and restores from: // `../i18n` registers English only, which would make the restore a no-op. -import { i18next } from '../i18n/all' -import type { Scope, StagedItem } from '../apps/design-critique/types' +import { i18next } from '../../i18n/all' +import type { Scope, StagedItem } from './types' const noop = () => {} diff --git a/website/src/apps/design-critique/api.typedErrors.test.ts b/website/src/apps/design-critique/api.typedErrors.test.ts new file mode 100644 index 000000000000..6193eb781428 --- /dev/null +++ b/website/src/apps/design-critique/api.typedErrors.test.ts @@ -0,0 +1,58 @@ +/** + * Design Critique's API client surfaces a refusal as the shared typed error. + * + * The app's own row of the per-client contract in `src/test/appApiTypedErrors.test.ts`: + * a refusal body reaches the UI as the human message, not raw wire JSON, and a caller + * can branch on the status. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { ApiError } from '../../api/apiError' +import { designCritiqueApi } from './api' + +/** A refusal whose body is the JSON envelope the backends actually send. */ +const REFUSAL = JSON.stringify({ error: 'path is outside the sandbox' }) + +const refuse = (status = 403, body = REFUSAL) => + vi.fn().mockResolvedValue({ + ok: false, + status, + headers: { get: () => null }, + text: () => Promise.resolve(body), + json: () => Promise.reject(new Error('should not be parsed on a refusal')), + } as unknown as Response) + +describe('designCritiqueApi surfaces refusals as ApiError', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('is typed, status-bearing, and carries the unwrapped message', async () => { + vi.stubGlobal('fetch', refuse()) + const call = () => designCritiqueApi.getSlot('slot-1') + await expect(call()).rejects.toThrow(ApiError) + const e = (await call().catch((err: unknown) => err)) as ApiError + expect(e.status).toBe(403) + // The human message, not the envelope — this is what a toast renders. + expect(e.message).toBe('path is outside the sandbox') + expect(e.message).not.toContain('{"error"') + // The envelope stays reachable for a caller that wants structured fields. + expect(e.body).toBe(REFUSAL) + }) + + it('relabels a 429 with the tunnel-edge message instead of the body', async () => { + vi.stubGlobal('fetch', refuse(429, '{"message":"Rate exceeded","throttlingReasons":null}')) + const e = (await designCritiqueApi.getSlot('slot-1').catch((err: unknown) => err)) as ApiError + expect(e.status).toBe(429) + expect(e.message).toContain('Rate limited') + expect(e.message).not.toContain('throttlingReasons') + expect(e.body).toContain('throttlingReasons') + }) + + it('keeps the HTTP fallback for an empty body', async () => { + vi.stubGlobal('fetch', refuse(500, '')) + const e = (await designCritiqueApi.getSlot('slot-1').catch((err: unknown) => err)) as ApiError + expect(e).toBeInstanceOf(ApiError) + expect(e.message).toBe('HTTP 500') + }) +}) diff --git a/website/src/apps/design-critique/designCritiqueBoundary.test.ts b/website/src/apps/design-critique/designCritiqueBoundary.test.ts new file mode 100644 index 000000000000..999d3c3ecbab --- /dev/null +++ b/website/src/apps/design-critique/designCritiqueBoundary.test.ts @@ -0,0 +1,48 @@ +/** + * Design Critique's UI is one directory the app can leave the repository with. + * + * The core SPA reaches it through exactly one import — the `/design-critique` row of + * `apps/builtinRegistry.ts` — and nothing else outside `src/apps/design-critique/` + * imports a module from it. The app's own tests live in this directory. + */ +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { dirname, isAbsolute, join, relative, resolve } from 'node:path' + +import { describe, expect, it } from 'vitest' + +const APP_DIR = __dirname +const SRC = resolve(APP_DIR, '..', '..') +const SPEC_RE = /(?:from\s+|import\s*\(?\s*|vi\.mock\(\s*)['"]([^'"]+)['"]/g + +// Containment by `relative()`, never a string prefix: it resolves both sides itself, +// so `__dirname`'s separator and the one `resolve()`/`join()` return cannot disagree. +function insideTheApp(p: string): boolean { + const rel = relative(APP_DIR, p) + return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) +} + +function walk(dir: string, out: string[] = []): string[] { + for (const name of readdirSync(dir)) { + const p = join(dir, name) + if (statSync(p).isDirectory()) walk(p, out) + else if (/\.(ts|tsx)$/.test(name)) out.push(p) + } + return out +} + +function importsIntoTheApp(file: string): boolean { + return [...readFileSync(file, 'utf8').matchAll(SPEC_RE)].some(([, spec]) => { + const abs = spec.startsWith('@/') ? join(SRC, spec.slice(2)) : spec.startsWith('.') ? resolve(dirname(file), spec) : null + return abs !== null && insideTheApp(abs) + }) +} + +describe('Design Critique UI boundary', () => { + it('is imported from outside its directory only by the builtin registry', () => { + const outside = walk(SRC) + .filter((p) => !insideTheApp(p)) + .filter(importsIntoTheApp) + .map((p) => relative(SRC, p).split('\\').join('/')) + expect(outside).toEqual(['apps/builtinRegistry.ts']) + }) +}) diff --git a/website/src/test/designCritiqueSendReceipt.test.ts b/website/src/apps/design-critique/designCritiqueSendReceipt.test.ts similarity index 98% rename from website/src/test/designCritiqueSendReceipt.test.ts rename to website/src/apps/design-critique/designCritiqueSendReceipt.test.ts index 028a58235788..622588ebfaae 100644 --- a/website/src/test/designCritiqueSendReceipt.test.ts +++ b/website/src/apps/design-critique/designCritiqueSendReceipt.test.ts @@ -18,7 +18,7 @@ */ import { afterEach, describe, expect, it, vi } from 'vitest' -import { designCritiqueApi } from '../apps/design-critique/api' +import { designCritiqueApi } from './api' const jsonResponse = (body: unknown, status = 200): Response => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) diff --git a/website/src/apps/design-critique/uploads.test.ts b/website/src/apps/design-critique/uploads.test.ts new file mode 100644 index 000000000000..b7b169ccd23e --- /dev/null +++ b/website/src/apps/design-critique/uploads.test.ts @@ -0,0 +1,96 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' + +const prepareHeicImage = vi.fn() +vi.mock('../../utils/heicImage', async importOriginal => ({ + ...(await importOriginal()), + prepareHeicImage: (...args: unknown[]) => prepareHeicImage(...args), +})) +const resizeImageForModel = vi.fn() +vi.mock('../../utils/resizeImage', async importOriginal => ({ + ...(await importOriginal()), + resizeImageForModel: (...args: unknown[]) => resizeImageForModel(...args), +})) + +const { designCritiqueApi } = await import('./api') +const { HeicPrepareError } = await import('../../utils/heicImage') + +/** The Design Critique composer uploads through the same body as the main chat + * composer, so a HEIC photo is converted and an oversized image downscaled + * before the POST, not sent as-is. The same rows as the other apps' in + * `src/test/appComposerUploads.test.ts`. */ + +const heic = () => new File([new Uint8Array(4)], 'IMG_0001.HEIC', { type: 'image/heic' }) +const jpeg = () => new File([new Uint8Array(2)], 'IMG_0001.jpg', { type: 'image/jpeg' }) +const big = () => new File([new Uint8Array(8)], 'big.png', { type: 'image/png' }) +const small = () => new File([new Uint8Array(3)], 'small.png', { type: 'image/png' }) +const shrunk = () => new File([new Uint8Array(1)], 'big.jpg', { type: 'image/jpeg' }) +const resizeInfo = { name: 'big.png', fromW: 6000, fromH: 4000, toW: 1568, toH: 1045, fromBytes: 8, toBytes: 1 } + +type Upload = { name: string; type: string } +let sent: Upload[][] + +function stubUpload(paths: string[]) { + const fetchMock = vi.fn(async (_url: string, init: RequestInit) => { + sent.push(((init.body as FormData).getAll('file') as File[]).map(f => ({ name: f.name, type: f.type }))) + return new Response(JSON.stringify({ paths }), { status: 200 }) + }) + vi.stubGlobal('fetch', fetchMock) + return fetchMock +} + +/** The upload, read as the paths it got or the error it throws. */ +type Outcome = { paths: string[]; error?: string } +const upload = (files: File[]): Promise => designCritiqueApi.uploadFiles(files).then( + r => ({ paths: r.paths }), (e: Error) => ({ paths: [], error: e.message })) + +describe('design critique composer upload', () => { + beforeEach(() => { + sent = [] + prepareHeicImage.mockReset() + resizeImageForModel.mockReset() + prepareHeicImage.mockImplementation(async (f: File) => (f.type === 'image/heic' ? { file: jpeg(), info: null } : null)) + resizeImageForModel.mockImplementation(async (f: File) => (f.name === 'big.png' ? { file: shrunk(), info: resizeInfo } : { file: f, info: null })) + }) + afterEach(() => { vi.unstubAllGlobals() }) + + it('posts the converted JPEG in place of a HEIC photo', async () => { + const fetchMock = stubUpload(['/u/a_IMG_0001.jpg']) + expect(await upload([heic()])).toEqual({ paths: ['/u/a_IMG_0001.jpg'] }) + expect(fetchMock).toHaveBeenCalledWith('/api/upload/file', expect.objectContaining({ method: 'POST' })) + expect(sent).toEqual([[{ name: 'IMG_0001.jpg', type: 'image/jpeg' }]]) + }) + + it('posts the downscaled copy of an oversized image', async () => { + stubUpload(['/u/a_big.jpg']) + expect(await upload([big()])).toEqual({ paths: ['/u/a_big.jpg'] }) + expect(sent).toEqual([[{ name: 'big.jpg', type: 'image/jpeg' }]]) + }) + + it('posts a small PNG unchanged', async () => { + stubUpload(['/u/a_small.png']) + expect(await upload([small()])).toEqual({ paths: ['/u/a_small.png'] }) + expect(sent).toEqual([[{ name: 'small.png', type: 'image/png' }]]) + }) + + it('refuses a HEIC photo it cannot convert with that reason, before any POST', async () => { + prepareHeicImage.mockImplementation(async () => { throw new HeicPrepareError('too_large', 'IMG_0001.HEIC', 'That photo is too large to convert.') }) + const fetchMock = stubUpload([]) + expect(await upload([heic()])).toEqual({ paths: [], error: 'That photo is too large to convert.' }) + expect(fetchMock).not.toHaveBeenCalled() + }) +}) + +describe('design critique upload refusal', () => { + beforeEach(() => { + prepareHeicImage.mockReset() + resizeImageForModel.mockReset() + prepareHeicImage.mockResolvedValue(null) + resizeImageForModel.mockImplementation(async (f: File) => ({ file: f, info: null })) + }) + afterEach(() => { vi.unstubAllGlobals() }) + + it('throws the server\'s error text', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'File type not allowed' }), { status: 415 }))) + await expect(designCritiqueApi.uploadFiles([small()])).rejects.toThrow('File type not allowed') + }) +}) diff --git a/website/src/test/SubagentProgressBar.i18n.test.tsx b/website/src/test/SubagentProgressBar.i18n.test.tsx index 2c8977848451..651a2b91ad19 100644 --- a/website/src/test/SubagentProgressBar.i18n.test.tsx +++ b/website/src/test/SubagentProgressBar.i18n.test.tsx @@ -10,7 +10,8 @@ * of the stalled-row sentence #4020 already converted in this component. * * These tests mount the real component under a non-English language and read - * what the user would read. Same shape as DesignCritiqueComposer.i18n.test.tsx. + * what the user would read. Same shape as + * apps/design-critique/DesignCritiqueComposer.i18n.test.tsx. */ import { describe, it, expect, vi, afterAll } from 'vitest' diff --git a/website/src/test/appApiTypedErrors.test.ts b/website/src/test/appApiTypedErrors.test.ts index 4798308a3c8b..be47d1dce8b4 100644 --- a/website/src/test/appApiTypedErrors.test.ts +++ b/website/src/test/appApiTypedErrors.test.ts @@ -5,11 +5,10 @@ * body reached the UI as raw wire JSON and no caller could branch on the status. * These assertions are per-client on purpose: the bug was four independent * copies of the same mistake, so one shared-helper test would not catch a single - * client drifting back. The Files and Design Tweak clients are pinned the same way - * in their own directories (`apps//api.typedErrors.test.ts`). + * client drifting back. The Files, Design Tweak and Design Critique clients are + * pinned the same way in their own directories (`apps//api.typedErrors.test.ts`). */ import { ApiError } from '../api/apiError' -import { designCritiqueApi } from '../apps/design-critique/api' import { getWatchlist } from '../apps/mochi/api' /** A refusal whose body is the JSON envelope the backends actually send. */ @@ -42,11 +41,6 @@ describe('app API clients surface refusals as ApiError', () => { vi.unstubAllGlobals() }) - it('design-critique', async () => { - vi.stubGlobal('fetch', refuse()) - await expectTypedRefusal(() => designCritiqueApi.getSlot('slot-1')) - }) - it('mochi', async () => { vi.stubGlobal('fetch', refuse()) await expectTypedRefusal(() => getWatchlist()) @@ -60,7 +54,7 @@ describe('app API clients surface refusals as ApiError', () => { // clients now reads as the rate-limit sentence, where before it showed the // raw throttle envelope. vi.stubGlobal('fetch', refuse(429, '{"message":"Rate exceeded","throttlingReasons":null}')) - const e = (await designCritiqueApi.getSlot('slot-1').catch((err: unknown) => err)) as ApiError + const e = (await getWatchlist().catch((err: unknown) => err)) as ApiError expect(e.status).toBe(429) expect(e.message).toContain('Rate limited') expect(e.message).not.toContain('throttlingReasons') @@ -68,17 +62,12 @@ describe('app API clients surface refusals as ApiError', () => { expect(e.body).toContain('throttlingReasons') }) - it('each keeps the HTTP fallback for an empty body', async () => { + it('keeps the HTTP fallback for an empty body', async () => { // The bare-Error calls used `body || HTTP `, so an empty-body refusal // must read exactly as it did before the change. - for (const call of [ - () => designCritiqueApi.getSlot('slot-1'), - () => getWatchlist(), - ]) { - vi.stubGlobal('fetch', refuse(500, '')) - const e = (await call().catch((err: unknown) => err)) as ApiError - expect(e).toBeInstanceOf(ApiError) - expect(e.message).toBe('HTTP 500') - } + vi.stubGlobal('fetch', refuse(500, '')) + const e = (await getWatchlist().catch((err: unknown) => err)) as ApiError + expect(e).toBeInstanceOf(ApiError) + expect(e.message).toBe('HTTP 500') }) }) diff --git a/website/src/test/appComposerUploads.test.ts b/website/src/test/appComposerUploads.test.ts index 4cd646c18b09..42a57e3ea3cb 100644 --- a/website/src/test/appComposerUploads.test.ts +++ b/website/src/test/appComposerUploads.test.ts @@ -11,13 +11,13 @@ vi.mock('../utils/resizeImage', async importOriginal => ({ resizeImageForModel: (...args: unknown[]) => resizeImageForModel(...args), })) -const { designCritiqueApi } = await import('../apps/design-critique/api') const { ingestFiles } = await import('../apps/mochi/panel/composerDrop') const { HeicPrepareError } = await import('../utils/heicImage') -/** The Design Critique and Mochi composers upload through the same body as - * the main chat composer, so a HEIC photo is converted and an oversized image - * downscaled before the POST, not sent as-is. */ +/** The Mochi composer uploads through the same body as the main chat composer, + * so a HEIC photo is converted and an oversized image downscaled before the + * POST, not sent as-is. An app whose tests live in its own directory pins the + * same rows there. */ const heic = () => new File([new Uint8Array(4)], 'IMG_0001.HEIC', { type: 'image/heic' }) const jpeg = () => new File([new Uint8Array(2)], 'IMG_0001.jpg', { type: 'image/jpeg' }) @@ -38,12 +38,10 @@ function stubUpload(paths: string[]) { return fetchMock } -/** Each app's upload, read as the paths it got or the error it shows: Design - * Critique throws its error, Mochi returns it. */ +/** Each app's upload, read as the paths it got or the error it shows: Mochi + * returns its error. */ type Outcome = { paths: string[]; error?: string } const uploaders: Array<[string, (files: File[]) => Promise]> = [ - ['design critique', files => designCritiqueApi.uploadFiles(files).then( - r => ({ paths: r.paths }), (e: Error) => ({ paths: [], error: e.message }))], ['mochi', async files => { const r = await ingestFiles(files) return { paths: [...r.images, ...r.files], ...(r.error !== undefined ? { error: r.error } : {}) } @@ -96,11 +94,6 @@ describe('upload refusals keep each app\'s own message', () => { }) afterEach(() => { vi.unstubAllGlobals() }) - it('design critique throws the server\'s error text', async () => { - vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'File type not allowed' }), { status: 415 }))) - await expect(designCritiqueApi.uploadFiles([small()])).rejects.toThrow('File type not allowed') - }) - it('mochi falls back to the status code when the body names no reason', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 500 }))) expect((await ingestFiles([small()])).error).toBe('Upload failed (500)')