From 0ef16bb42e7f3eb948bcc93f0dc08cdfd5ba410e Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:34:25 +0100 Subject: [PATCH 1/7] docs: app DX #914-#919 design Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- .../specs/2026-11-11-app-dx-914-919-design.md | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-11-app-dx-914-919-design.md diff --git a/docs/superpowers/specs/2026-11-11-app-dx-914-919-design.md b/docs/superpowers/specs/2026-11-11-app-dx-914-919-design.md new file mode 100644 index 00000000..baa2ef65 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-app-dx-914-919-design.md @@ -0,0 +1,76 @@ +# First-run app fixes from the 0.0.45 field test (#914–#919) + +Six issues filed against a fresh `smpy new` app, shipped as four PRs. + +## PR 1 — `/admin` in every app; quickstart corrections (#914, #919) + +**Problem.** The sidebar "Administration" link and the AdminLayout badge go to +`/admin`, which only this repo's host serves (`host/routes.py` `admin_overview` ++ `host/client_app/pages/Admin.tsx`); a scaffolded app 404s. The quickstart +promises it, documents `curl /api/orders` as `200 []` (it is 401), and names a +test file the scaffold does not write. + +**Approach.** Move the admin overview into `simple_module_hosting`, exactly as +the setup wizard is (#351): `simple_module_hosting/admin_overview/` with the +route (same gating: signed in, and admin or holding any admin-sidebar entry) +and `pages/Overview.tsx`, mounted by `app_builder` and registered by +`gen-pages` like `Setup/Wizard`. Its three strings move from `host/locales` to +the `hosting` namespace (en/de/es). This repo's host drops its copy. +Rejected: copying the route, page and a `host/locales` catalog into the host +template (duplicates the gating per app, forces a host catalog). + +**Docs (#919).** Quickstart step 4: `create-admin` without `--password` (it +prompts) and a passphrase example; step 7: anonymous `curl` returns 401, open +`/orders/` signed in instead; step 8: `modules/orders/tests/web/crud/test_orders_crud.py` +(and `uv run pytest modules/orders`); same password fix in `installation.md`. + +**Tests.** Hosting route tests moved from `host/tests/test_admin_overview_access.py`; +a scaffold test that the app has no admin route of its own and `/admin` +renders for an admin. + +## PR 2 — `uv sync` keeps the app installed; adding a module during `make dev` (#916, #915) + +**#916.** The workspace root template gains a dependency on the host package +through `[tool.uv.sources] = { workspace = true }`, so a plain `uv sync` +installs host and every module instead of uninstalling them. `smpy new` runs +and prints the workspace-correct install (`make install`); `create-module` +inside an app workspace prints the app flow (`smpy add …`, `make install`, +`make migration`, `make test`) instead of `cd module && uv sync --extra dev`. + +**#915.** uvicorn's reloader keeps the `sys.path` it started with, so a module +installed after `make dev` started cannot be imported until a restart. When an +entry point is found but its package cannot be imported, discovery says so: +"installed after this process started — restart `make dev`" instead of the +misleading "No module named '.module'". Rejected: re-reading `.pth` files at +reload (re-implements editable installs); a watcher that restarts the +supervisor (new dev dependency, more moving parts than the problem). + +## PR 3 — SQLite expression-index warning (#917) + +The autogenerate hook warns about every expression index in the metadata, before +the revision has re-emitted them, and points at a make target and doc that only +exist in this repo. Fix: re-emit first, then warn only about expression indexes +on tables the revision touches that it did not emit (so a fresh app's initial +schema and an unrelated module migration print nothing). One advice helper +for the three messages (autogenerate warning, SM026, `migrate` note): this +repo's make target and doc only when they exist, otherwise "verify with +`alembic upgrade heads` against a PostgreSQL `SM_DATABASE_URL`". + +## PR 4 — generated module pages use their locale file (#918) + +The base module templates hardcode English while shipping `locales/en.json`; +the `framework_repo` overlay already has keyed pages (`t(keys..…)`, +`useApiErrorToast`). Make the keyed pages the only pages and delete the +overlay copies. A scaffolded app generates `keys.` with `make gen-i18n` +(also on dev boot); `create-module` / `smpy add` next steps say so. +**Risk:** a module scaffolded outside any app (standalone repo) has no host to +generate keys; if its `tsc` cannot pass, the standalone variant keeps +hardcoded strings and the README says how to switch. + +## Decisions made + +- Four PRs, in the order above (PR 1 also unblocks the quickstart's `/admin`). +- Admin overview strings become `hosting.admin.*`. +- #915 gets a precise error message, not automatic reloading. +- #917 keeps SM026 and the `migrate` note (SQLite really cannot verify), only + their advice changes. From 0a0c5a20d5afbc21958272228377b5b23950227f Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:42:13 +0100 Subject: [PATCH 2/7] fix(hosting): serve /admin from simple_module_hosting in every app; fix quickstart (#914, #919) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- CHANGELOG.md | 5 ++ CLAUDE.md | 4 +- README.md | 2 +- biome.json | 1 + docs/guide/installation.md | 4 +- docs/guide/quickstart.md | 17 ++++-- docs/modules/users.md | 2 +- docs/reference/make-commands.md | 2 +- .../test_scaffolded_host_admin_overview.py | 38 ++++++++++++ .../admin_overview/__init__.py | 42 ++++++++++++++ .../admin_overview/pages/Overview.tsx | 9 ++- .../admin_overview/routes.py | 55 ++++++++++++++++++ .../simple_module_hosting/app_builder.py | 2 + .../hosting/simple_module_hosting/assets.py | 38 +++++++----- .../simple_module_hosting/locales/de.json | 5 ++ .../simple_module_hosting/locales/en.json | 5 ++ .../simple_module_hosting/locales/es.json | 5 ++ .../hosting/simple_module_hosting/manifest.py | 14 +++-- .../tests-js/hosting_AdminOverview.test.tsx | 41 +++++++++++++ framework/hosting/tsconfig.json | 4 +- host/locales/de.json | 6 -- host/locales/en.json | 6 -- host/locales/es.json | 6 -- host/routes.py | 58 ++----------------- host/tests/test_admin_overview_access.py | 42 ++++++-------- packages/i18n/src/generated-resources.ts | 7 +-- packages/i18n/src/keys.generated.ts | 11 ++-- scripts/check_no_raw_fetch.py | 1 + 28 files changed, 287 insertions(+), 145 deletions(-) create mode 100644 framework/cli/tests/test_scaffolded_host_admin_overview.py create mode 100644 framework/hosting/simple_module_hosting/admin_overview/__init__.py rename host/client_app/pages/Admin.tsx => framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx (93%) create mode 100644 framework/hosting/simple_module_hosting/admin_overview/routes.py create mode 100644 framework/hosting/tests-js/hosting_AdminOverview.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index cbb4bc30..1298012f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,11 @@ All notable changes to this project are documented in this file. The format is b - `users`: Microsoft sign-in is OpenID Connect. It runs authorization-code + PKCE (S256) + nonce on the tenant's v2.0 endpoints and takes the identity from the validated ID token (RS256 against Entra's JWKS, exact issuer, `aud`/`azp`, `exp`/`iat`, nonce) instead of Graph `/me`. A tenant GUID also requires the token's `tid` to match, `organizations` refuses personal accounts and `consumers` accepts only them. The linked account id keeps the value Graph returned, so existing links keep matching; the email is the optional `upn` claim when present, else `preferred_username` (the UPN for members; add the `upn` optional claim if email is an alternate login ID). The trusted-tenant policy (#873) now also treats an `idp` claim naming another issuer as a guest, besides `#EXT#`. The OAuth callback passes the whole token response to `OAuthProvider.get_identity(token, login)` and keeps a per-login PKCE verifier and nonce in the session for providers that use them. **Behaviour change:** the Entra app registration needs the `openid`, `profile` and `email` delegated permissions (usually present by default); Graph `User.Read` is no longer requested. Code that calls `OAuthProvider.get_identity` with an access-token string must pass the token response dict (#876). +### Fixed + +- `/admin` works in every app. The admin overview that the sidebar's "Administration" link and the AdminLayout badge open lived only in this repository's host, so an app made by `smpy new` answered 404 there. It now ships with `simple_module_hosting` (`simple_module_hosting.admin_overview`), mounted by `create_app` and registered by `gen-pages` as the `Admin/Overview` page, exactly like the `/setup` wizard; admission is unchanged (an admin, or anyone with an admin sidebar entry). Its strings moved from the `host` namespace to `hosting.admin.*`. An existing app needs nothing beyond upgrading and running `smpy gen-pages` (a dev boot does it) (#914). +- The quickstart matches what a new app does: an anonymous `curl /api/orders` answers 401 (the scaffold guards the API with `orders.*` permissions), the single-file test example names `tests/web/crud/test_orders_crud.py`, and `smpy users create-admin` is shown without `--password`, so it prompts instead of putting a weak password in shell history (#919). + ## [0.0.45] — 2026-11-11 ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index f056c204..aa8775df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -248,8 +248,8 @@ Per-middleware detail: `docs/framework/middleware.md`, `SidebarLayout` renders the menu its `menuKey` names, so a page left on `AuthenticatedLayout` after its item moved shows a sidebar without it. `group=` sub-clusters inside a sidebar (`Access`, `Appearance`, `System`). -`/admin` itself is a host route (`host/routes.py`) rendered from the -`adminSidebar` shared prop; old URLs 301 from `host/routes_legacy.py`. +`/admin` itself ships with `simple_module_hosting` (`admin_overview/`, mounted +by `create_app` like `/setup`) and renders the `adminSidebar` shared prop; old URLs 301 from `host/routes_legacy.py`. `/api/*` paths never move. **Inertia.** `inertia.render("/")` maps to diff --git a/README.md b/README.md index 26ab644e..031bd923 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ of them: a host that ships only `keycloak` (or only `oidc`) keeps it regardless Either use the CLI: ```bash -uv run smpy users create-admin --email admin@example.com --password changeme +uv run smpy users create-admin --email admin@example.com ``` Or let the app bootstrap it automatically on first boot by setting env vars **before** running `make migrate && make dev`: diff --git a/biome.json b/biome.json index 3ac435e8..b2bde162 100644 --- a/biome.json +++ b/biome.json @@ -9,6 +9,7 @@ "modules/*/*/**/components/**", "modules/*/tests-js/**", "framework/hosting/simple_module_hosting/setup_wizard/**", + "framework/hosting/simple_module_hosting/admin_overview/**", "framework/hosting/tsconfig.json", "!.claude", "!**/*.md", diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 63f01a8a..ca5686ad 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -107,9 +107,11 @@ Or run the whole stack in containers — `make docker-up` builds the image (`doc If you included the `users` module: ```bash -uv run smpy users create-admin --email admin@example.com --password changeme +uv run smpy users create-admin --email admin@example.com ``` +It prompts for the password; `--password` is for scripts and ends up in your shell history. + Or set bootstrap env vars so the admin is auto-created on first boot: ```bash diff --git a/docs/guide/quickstart.md b/docs/guide/quickstart.md index 74b87a07..759fbe7a 100644 --- a/docs/guide/quickstart.md +++ b/docs/guide/quickstart.md @@ -40,9 +40,11 @@ The API and Vite dev servers start side by side. Visit: Until an administrator exists, every page redirects to the `/setup` wizard, which asks for one. To create it from a terminal instead (from inside `myapp`): ```bash -uv run smpy users create-admin --email admin@example.com --password changeme +uv run smpy users create-admin --email admin@example.com ``` +It prompts for the password without echoing it. Pick a real one (a passphrase such as `correct-horse-battery-staple` is fine locally); `--password` exists for scripts, but it lands in your shell history. + Sign in at `/users/login` and you land on the dashboard. ## 5. Scaffold a new module @@ -81,11 +83,11 @@ make migrate Restart `make dev` (modules are discovered at boot). Then: ```bash -curl http://localhost:8000/api/orders -# → [] (200) +curl -i http://localhost:8000/api/orders +# → 401 {"detail":"Not authenticated"} ``` -Visit `http://localhost:8000/orders` — you see the `Browse` page with an empty list and a "Create" button. The sidebar menu now includes an **Orders** entry (registered via `register_menu_items`). +The scaffold guards every route with the module's `orders.*` permissions, so an anonymous request is refused. Sign in as the admin and visit `http://localhost:8000/orders/` — you see the `Browse` page with an empty list and a "Create" button. The sidebar menu now includes an **Orders** entry (registered via `register_menu_items`). ## 8. Run the tests @@ -93,12 +95,15 @@ Visit `http://localhost:8000/orders` — you see the `Browse` page with an empty uv run pytest ``` -Single file: +Just the new module, or a single file: ```bash -uv run pytest modules/orders/tests/test_orders.py -v +uv run pytest modules/orders +uv run pytest modules/orders/tests/web/crud/test_orders_crud.py -v ``` +The scaffold writes `modules/orders/tests/web/crud/test_orders_crud.py` (REST and page endpoints), `modules/orders/tests/core/module/test_orders_module.py` and `modules/orders/tests/core/contracts/test_orders_schemas.py`. + ## What just happened - **Discovery** — the `simple_module` entry point pointed Python's installer at `orders.module:OrdersModule`. `discover_modules()` loaded it, topologically sorted against every other installed module, and invoked `register_*` hooks in order. diff --git a/docs/modules/users.md b/docs/modules/users.md index 5332e5e6..68b7324d 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -331,7 +331,7 @@ undo the committed account; these callbacks do not retry mail delivery. - `smpy users create-admin --email --password

[--full-name ] [--force]` — creates (or, with `--force`, updates) an admin user. Idempotent: re-running with the same email is a no-op without `--force`. ```bash -uv run smpy users create-admin --email admin@example.com --password changeme +uv run smpy users create-admin --email admin@example.com ``` Programmatically: diff --git a/docs/reference/make-commands.md b/docs/reference/make-commands.md index 22e18517..fd2791b8 100644 --- a/docs/reference/make-commands.md +++ b/docs/reference/make-commands.md @@ -71,7 +71,7 @@ When a module declares a `simple_module_cli.cli_plugins` entry point, the CLI mo `smpy users create-admin` is contributed by the `users` module as a `smpy users` subcommand: ```bash -uv run smpy users create-admin --email admin@example.com --password changeme +uv run smpy users create-admin --email admin@example.com ``` ## Scaffolded-app Makefile diff --git a/framework/cli/tests/test_scaffolded_host_admin_overview.py b/framework/cli/tests/test_scaffolded_host_admin_overview.py new file mode 100644 index 00000000..2203abd2 --- /dev/null +++ b/framework/cli/tests/test_scaffolded_host_admin_overview.py @@ -0,0 +1,38 @@ +"""A freshly scaffolded host serves ``/admin`` with no files of its own. + +GH #914: the sidebar's "Administration" link and the AdminLayout badge point +at ``/admin``, but the route and page lived only in this repository's host, so +an app made by ``smpy new`` answered 404. The overview now ships with +``simple_module_hosting`` like the setup wizard: ``create_app`` mounts the +route and ``gen-pages`` registers the page. +""" + +from __future__ import annotations + +import json + +from simple_module_hosting.admin_overview import PAGE_OVERVIEW, PAGES_NAME, pages_dir +from simple_module_hosting.manifest import write_module_pages_manifest + + +def test_scaffold_carries_no_admin_code_and_resolves_the_overview(tmp_path) -> None: + from simple_module_cli.scaffolding import create_host + + dest = tmp_path / "demo" + create_host(dest, name="demo-host", modules=[]) + client_app = dest / "client_app" + + assert "/admin" not in (dest / "routes.py").read_text(encoding="utf-8") + assert not list((client_app / "pages").rglob("Admin*")) + + write_module_pages_manifest([], client_app, repo_root=dest) + + manifest = json.loads((client_app / "modules.manifest.json").read_text(encoding="utf-8")) + assert manifest[PAGES_NAME] == pages_dir().as_posix() + assert (pages_dir() / "Overview.tsx").is_file() + assert f"{PAGES_NAME}/Overview" == PAGE_OVERVIEW + + generated = (client_app / "modules.generated.ts").read_text(encoding="utf-8") + assert f'"{PAGES_NAME}": import.meta.glob' in generated + css = (client_app / "modules.generated.css").read_text(encoding="utf-8") + assert f'@source "{pages_dir().as_posix()}/**/*.{{ts,tsx}}";' in css diff --git a/framework/hosting/simple_module_hosting/admin_overview/__init__.py b/framework/hosting/simple_module_hosting/admin_overview/__init__.py new file mode 100644 index 00000000..113544eb --- /dev/null +++ b/framework/hosting/simple_module_hosting/admin_overview/__init__.py @@ -0,0 +1,42 @@ +"""The ``/admin`` overview, shipped with the framework. + +The sidebar's "Administration" link and the AdminLayout badge point every app +at ``/admin``. The page used to live in this repository's own host, so an app +made by ``smpy new`` answered 404 there (GH #914). ``create_app`` now mounts +it for every host, the way it mounts the setup wizard (GH #351). + +No module owns the admin section as a whole — it is assembled from whatever +modules happen to be installed — so the framework serves it rather than one +plugin claiming ``/admin`` as its ``view_prefix``. + +The page is registered in ``modules.generated.ts`` under :data:`PAGES_NAME`, +like a module's ``pages/``, so a host's Vite build picks it up from the wheel. +""" + +from __future__ import annotations + +from pathlib import Path + +#: The ``modules.generated.ts`` key the overview's pages are registered under. +PAGES_NAME = "Admin" + +#: ``pages/Overview.tsx`` as an Inertia page key. +PAGE_OVERVIEW = f"{PAGES_NAME}/Overview" + +_PACKAGE_DIR = Path(__file__).resolve().parent + + +def package_dir() -> Path: + """The overview's frontend root.""" + return _PACKAGE_DIR + + +def pages_dir() -> Path: + return _PACKAGE_DIR / "pages" + + +def mount_admin_overview(app) -> None: + """Mount ``/admin``; every other ``/admin/*`` path belongs to a module.""" + from simple_module_hosting.admin_overview.routes import router + + app.include_router(router) diff --git a/host/client_app/pages/Admin.tsx b/framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx similarity index 93% rename from host/client_app/pages/Admin.tsx rename to framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx index 2a8d99eb..5d3a99f4 100644 --- a/host/client_app/pages/Admin.tsx +++ b/framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx @@ -58,10 +58,13 @@ function AdminPage() { return ( <> - - + + {items.length === 0 ? ( -

{t(keys.host.admin.empty)}

+

{t(keys.hosting.admin.empty)}

) : (
{grouped.map(([group, groupItems_]) => ( diff --git a/framework/hosting/simple_module_hosting/admin_overview/routes.py b/framework/hosting/simple_module_hosting/admin_overview/routes.py new file mode 100644 index 00000000..5c1ab54a --- /dev/null +++ b/framework/hosting/simple_module_hosting/admin_overview/routes.py @@ -0,0 +1,55 @@ +"""``GET /admin`` — the landing page of the admin section.""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Request +from simple_module_core.permissions import is_admin_principal +from simple_module_inertia import InertiaResponse + +from simple_module_hosting.admin_overview import PAGE_OVERVIEW +from simple_module_hosting.inertia_deps import InertiaDep + +router = APIRouter() + + +@router.get("/admin", response_model=None, include_in_schema=False) +@router.get("/admin/", response_model=None, include_in_schema=False) +async def admin_overview(request: Request, inertia: InertiaDep) -> InertiaResponse: + """Landing page for the admin section. + + Renders no list of its own — the page reads the ``adminSidebar`` shared + prop, which is already filtered by the viewer's roles and permissions. A + second hand-maintained list here would drift from the sidebar the moment + a module was added. + + AuthMiddleware has already rejected anonymous visitors by this point; the + check below is the authorisation half, which it does not do. + + Admission mirrors what the page renders: anyone with at least one entry in + the admin sidebar can open it. Gating on the ``admin`` role alone was + inconsistent — the sidebar is filtered by roles *and* permissions, so a + custom role holding, say, ``settings.view`` reaches ``/admin/settings/``, + sees the AdminLayout badge pointing here, and would be met with a 403 for + a page that would have listed the one tool they can use. + + Admins are admitted regardless, so an install with no admin modules still + reaches the page's own empty state rather than a 403. + """ + user = getattr(request.state, "user", None) + if user is None: + raise HTTPException(status_code=403, detail="Administrator access required") + if not (is_admin_principal(user) or _has_admin_entries(request)): + raise HTTPException(status_code=403, detail="Administrator access required") + return await inertia.render(PAGE_OVERVIEW, {}) + + +def _has_admin_entries(request: Request) -> bool: + """Whether the viewer has any admin sidebar entry. + + Read from the shared props ``InertiaLayoutDataMiddleware`` already built + for this request, so admission and rendering cannot disagree — recomputing + the filter here is how the two drift apart. + """ + shared = getattr(request.state, "inertia_shared", None) or {} + menus = shared.get("menus") or {} + return bool(menus.get("adminSidebar")) diff --git a/framework/hosting/simple_module_hosting/app_builder.py b/framework/hosting/simple_module_hosting/app_builder.py index 59947a80..94259579 100644 --- a/framework/hosting/simple_module_hosting/app_builder.py +++ b/framework/hosting/simple_module_hosting/app_builder.py @@ -48,6 +48,7 @@ check_settings_registration, register_host_settings, ) +from simple_module_hosting.admin_overview import mount_admin_overview from simple_module_hosting.health import router as health_router from simple_module_hosting.i18n_manifest import build_i18n_registry from simple_module_hosting.i18n_routes import router as i18n_router @@ -217,6 +218,7 @@ def create_app(settings: Settings | None = None) -> FastAPI: app.include_router(health_router) app.include_router(i18n_router) # /i18n/set-locale — LocaleSwitcher posts here mount_setup_wizard(app, setup_registry) # /setup — what SetupMiddleware redirects to + mount_admin_overview(app) # /admin — where the sidebar and AdminLayout badge link mount_host_static(app, _PROJECT_ROOT) diff --git a/framework/hosting/simple_module_hosting/assets.py b/framework/hosting/simple_module_hosting/assets.py index 4a8238d4..f9406c4c 100644 --- a/framework/hosting/simple_module_hosting/assets.py +++ b/framework/hosting/simple_module_hosting/assets.py @@ -143,26 +143,32 @@ def compute_module_assets(modules: Sequence[ModuleBase]) -> list[ModuleAssets]: return result -def framework_assets() -> ModuleAssets: - """The frontend the framework itself ships: the ``/setup`` wizard. +def framework_assets() -> list[ModuleAssets]: + """The frontends the framework itself ships: ``/setup`` and ``/admin``. Emitted through the same records as a module's assets so a host's - ``vite.config.ts`` treats it identically — allowed in ``server.fs``, its - bare imports resolved against the host's ``node_modules``, its classes + ``vite.config.ts`` treats them identically — allowed in ``server.fs``, their + bare imports resolved against the host's ``node_modules``, their classes scanned by Tailwind — with nothing for the host to add by hand. """ - from simple_module_hosting.setup_wizard import PAGES_NAME, package_dir, pages_dir - - root = package_dir() - return ModuleAssets( - name=PAGES_NAME, - package_name="simple_module_hosting.setup_wizard", - package_dir=root, - pages_dir=pages_dir(), - theme_css=None, - styles_css=None, - components_dir=root / COMPONENTS_DIR, - ) + from simple_module_hosting import admin_overview, setup_wizard + + result = [] + for package in (setup_wizard, admin_overview): + root = package.package_dir() + components = root / COMPONENTS_DIR + result.append( + ModuleAssets( + name=package.PAGES_NAME, + package_name=package.__name__, + package_dir=root, + pages_dir=package.pages_dir(), + theme_css=None, + styles_css=None, + components_dir=components if components.is_dir() else None, + ) + ) + return result _CSS_HEADER = """\ diff --git a/framework/hosting/simple_module_hosting/locales/de.json b/framework/hosting/simple_module_hosting/locales/de.json index 5cf7d5dd..a978f1d5 100644 --- a/framework/hosting/simple_module_hosting/locales/de.json +++ b/framework/hosting/simple_module_hosting/locales/de.json @@ -24,5 +24,10 @@ }, "errors": { "token_not_allowed": "API-Tokens können auf dieser Route nicht verwendet werden. Verwenden Sie eine angemeldete Sitzung oder eine Route, deren Berechtigung zum Geltungsbereich des Tokens gehört." + }, + "admin": { + "title": "Administration", + "description": "Benutzer, Zugriff, Darstellung und Systemeinstellungen verwalten.", + "empty": "Für Ihr Konto sind keine Administrationswerkzeuge verfügbar." } } diff --git a/framework/hosting/simple_module_hosting/locales/en.json b/framework/hosting/simple_module_hosting/locales/en.json index 836d5b3b..983cb17d 100644 --- a/framework/hosting/simple_module_hosting/locales/en.json +++ b/framework/hosting/simple_module_hosting/locales/en.json @@ -24,5 +24,10 @@ }, "errors": { "token_not_allowed": "API tokens cannot be used on this route. Use a signed-in session, or a route gated by a permission the token is scoped to." + }, + "admin": { + "title": "Administration", + "description": "Manage users, access, appearance and system configuration.", + "empty": "No admin tools are available to your account." } } diff --git a/framework/hosting/simple_module_hosting/locales/es.json b/framework/hosting/simple_module_hosting/locales/es.json index 37dd98c3..8db895f3 100644 --- a/framework/hosting/simple_module_hosting/locales/es.json +++ b/framework/hosting/simple_module_hosting/locales/es.json @@ -24,5 +24,10 @@ }, "errors": { "token_not_allowed": "Los tokens de API no se pueden usar en esta ruta. Usa una sesión iniciada o una ruta protegida por un permiso incluido en el token." + }, + "admin": { + "title": "Administración", + "description": "Gestiona usuarios, accesos, apariencia y configuración del sistema.", + "empty": "No hay herramientas de administración disponibles para tu cuenta." } } diff --git a/framework/hosting/simple_module_hosting/manifest.py b/framework/hosting/simple_module_hosting/manifest.py index 91a3623a..8037d6b9 100644 --- a/framework/hosting/simple_module_hosting/manifest.py +++ b/framework/hosting/simple_module_hosting/manifest.py @@ -160,13 +160,15 @@ def write_module_pages_manifest( if repo_root is None: repo_root = repo_root_from_client_app(output_dir) - # The framework's own frontend (the setup wizard) is emitted alongside the - # modules', so every host's resolver finds ``Setup/Wizard`` and its Vite - # config serves it from the wheel — with no host-side file to add. + # The framework's own frontends (the setup wizard, the admin overview) are + # emitted alongside the modules', so every host's resolver finds + # ``Setup/Wizard`` and ``Admin/Overview`` and its Vite config serves them + # from the wheel — with no host-side file to add. framework = framework_assets() pages_map = dict(compute_module_pages(modules)) - if framework.pages_dir is not None: - pages_map[framework.name] = framework.pages_dir + for entry in framework: + if entry.pages_dir is not None: + pages_map[entry.name] = entry.pages_dir manifest_path = output_dir / "modules.manifest.json" manifest_payload = {name: path.as_posix() for name, path in pages_map.items()} @@ -193,7 +195,7 @@ def write_module_pages_manifest( # Rendered from the richer asset record rather than pages_map, so that a # module shipping CSS but no pages/ still contributes its stylesheets. - assets = [*compute_module_assets(modules), framework] + assets = [*compute_module_assets(modules), *framework] css_path = output_dir / "modules.generated.css" css_text = render_modules_css(assets, in_repo=lambda p: _is_in_repo_module(p, repo_root)) diff --git a/framework/hosting/tests-js/hosting_AdminOverview.test.tsx b/framework/hosting/tests-js/hosting_AdminOverview.test.tsx new file mode 100644 index 00000000..1a124e7f --- /dev/null +++ b/framework/hosting/tests-js/hosting_AdminOverview.test.tsx @@ -0,0 +1,41 @@ +import '@testing-library/jest-dom/vitest'; +import { configureI18n, keys } from '@simple-module-py/i18n'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +configureI18n({ locale: 'en', messages: {} }); + +const props = vi.hoisted(() => ({ menus: { adminSidebar: [] as unknown[] } })); + +vi.mock('@inertiajs/react', async (importOriginal) => ({ + ...(await importOriginal()), + usePage: () => ({ props, url: '/admin' }), + Head: () => null, + Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => ( + + {children} + + ), +})); +vi.mock('@simple-module-py/ui/hooks/usePageProps', () => ({ usePageProps: () => props })); + +import Overview from '../simple_module_hosting/admin_overview/pages/Overview'; + +describe('Admin overview', () => { + it('shows the empty state when the viewer has no admin tools', () => { + props.menus.adminSidebar = []; + render(); + expect(screen.getByText(keys.hosting.admin.empty)).toBeInTheDocument(); + }); + + it('renders one card per admin sidebar entry, grouped', () => { + props.menus.adminSidebar = [ + { label: 'Users', url: '/admin/users', icon: 'users', group: 'Access' }, + { label: 'Settings', url: '/admin/settings', icon: 'settings', group: 'System' }, + ]; + render(); + expect(screen.getByRole('link', { name: /Users/ })).toHaveAttribute('href', '/admin/users'); + expect(screen.getByText('Access')).toBeInTheDocument(); + expect(screen.getByText('System')).toBeInTheDocument(); + }); +}); diff --git a/framework/hosting/tsconfig.json b/framework/hosting/tsconfig.json index a08b2975..f165467f 100644 --- a/framework/hosting/tsconfig.json +++ b/framework/hosting/tsconfig.json @@ -1,7 +1,7 @@ { // Type-checks the pages simple_module_hosting ships itself (the /setup - // wizard). They are bundled by each host's Vite build from the installed - // wheel, so nothing else in the repo would compile them. + // wizard and the /admin overview). They are bundled by each host's Vite + // build from the installed wheel, so nothing else in the repo would compile them. "extends": "@simple-module-py/tsconfig/base.json", "compilerOptions": { "paths": { diff --git a/host/locales/de.json b/host/locales/de.json index 09b2dbbc..fedae218 100644 --- a/host/locales/de.json +++ b/host/locales/de.json @@ -1,10 +1,4 @@ { - "admin": { - "title": "Administration", - "description": "Benutzer, Zugriff, Darstellung und Systemeinstellungen verwalten.", - "empty": "Für Ihr Konto sind keine Administrationswerkzeuge verfügbar.", - "overview": "Übersicht" - }, "landing": { "badge": "✦ FastAPI + Inertia als Komplettpaket", "hero_title_line1": "Modulare Python-Apps,", diff --git a/host/locales/en.json b/host/locales/en.json index 2b2eb987..6061457c 100644 --- a/host/locales/en.json +++ b/host/locales/en.json @@ -1,10 +1,4 @@ { - "admin": { - "title": "Administration", - "description": "Manage users, access, appearance and system configuration.", - "empty": "No admin tools are available to your account.", - "overview": "Overview" - }, "landing": { "badge": "✦ Batteries-included FastAPI + Inertia starter", "hero_title_line1": "Modular Python apps,", diff --git a/host/locales/es.json b/host/locales/es.json index 520dea0a..bf8716ef 100644 --- a/host/locales/es.json +++ b/host/locales/es.json @@ -1,10 +1,4 @@ { - "admin": { - "title": "Administración", - "description": "Gestiona usuarios, accesos, apariencia y configuración del sistema.", - "empty": "No hay herramientas de administración disponibles para tu cuenta.", - "overview": "Resumen" - }, "landing": { "badge": "✦ Plantilla FastAPI + Inertia con todo incluido", "hero_title_line1": "Aplicaciones Python modulares,", diff --git a/host/routes.py b/host/routes.py index 4b1c61c8..c74b7458 100644 --- a/host/routes.py +++ b/host/routes.py @@ -1,20 +1,13 @@ """Host-level routes that don't belong to any module. -The public landing page at ``/``, and the admin overview at ``/admin``. -Keeping these here means "landing" isn't coupled to the dashboard (or any -other plugin) and can evolve independently. - -The admin overview lives at the host rather than in a module because no -module owns the admin section as a whole — it is assembled from whatever -modules happen to be installed. A module could only serve it by claiming -``/admin`` as its own ``view_prefix``, which would make one plugin the -landlord of a space all of them share. +The public landing page at ``/``. Keeping it here means "landing" isn't +coupled to the dashboard (or any other plugin) and can evolve independently. +The admin overview at ``/admin`` ships with ``simple_module_hosting``. """ from __future__ import annotations -from fastapi import APIRouter, HTTPException, Request -from simple_module_core.permissions import is_admin_principal +from fastapi import APIRouter, Request from simple_module_hosting.inertia_deps import InertiaDep from simple_module_inertia import InertiaResponse @@ -31,46 +24,3 @@ async def landing(request: Request, inertia: InertiaDep) -> InertiaResponse: "isAuthenticated": is_authenticated, }, ) - - -@router.get("/admin", response_model=None, include_in_schema=False) -@router.get("/admin/", response_model=None, include_in_schema=False) -async def admin_overview(request: Request, inertia: InertiaDep) -> InertiaResponse: - """Landing page for the admin section. - - Renders no list of its own — the page reads the ``adminSidebar`` shared - prop, which is already filtered by the viewer's roles and permissions. A - second hand-maintained list here would drift from the sidebar the moment - a module was added. - - AuthMiddleware has already rejected anonymous visitors by this point; the - check below is the authorisation half, which it does not do. - - Admission mirrors what the page renders: anyone with at least one entry in - the admin sidebar can open it. Gating on the ``admin`` role alone was - inconsistent — the sidebar is filtered by roles *and* permissions, so a - custom role holding, say, ``settings.view`` reaches ``/admin/settings/``, - sees the AdminLayout badge pointing here, and would be met with a 403 for - a page that would have listed the one tool they can use. - - Admins are admitted regardless, so an install with no admin modules still - reaches the page's own empty state rather than a 403. - """ - user = getattr(request.state, "user", None) - if user is None: - raise HTTPException(status_code=403, detail="Administrator access required") - if not (is_admin_principal(user) or _has_admin_entries(request)): - raise HTTPException(status_code=403, detail="Administrator access required") - return await inertia.render("Admin", {}) - - -def _has_admin_entries(request: Request) -> bool: - """Whether the viewer has any admin sidebar entry. - - Read from the shared props ``InertiaLayoutDataMiddleware`` already built - for this request, so admission and rendering cannot disagree — recomputing - the filter here is how the two drift apart. - """ - shared = getattr(request.state, "inertia_shared", None) or {} - menus = shared.get("menus") or {} - return bool(menus.get("adminSidebar")) diff --git a/host/tests/test_admin_overview_access.py b/host/tests/test_admin_overview_access.py index 2247e9ae..894d0064 100644 --- a/host/tests/test_admin_overview_access.py +++ b/host/tests/test_admin_overview_access.py @@ -6,28 +6,21 @@ admin permission could reach the screen that permission unlocks, see the AdminLayout badge pointing at ``/admin``, and get a 403 from a page that would have listed exactly the one tool they can use. + +The route ships with ``simple_module_hosting`` (GH #914), so the plain +``app`` fixture serves it; these tests live here because they sign in through +the ``users`` module. """ from __future__ import annotations import httpx import pytest +from simple_module_hosting.admin_overview import PAGE_OVERVIEW +from simple_module_test import inertia_page from simple_module_test.fixtures import forge_session_cookie -@pytest.fixture -def host_app(app): - """The framework fixture builds ``create_app()`` only — host-level routes - live in ``host/main.py`` and are otherwise absent from tests, so ``/admin`` - would 404 rather than exercise its guard. Mounting here keeps the real - middleware stack (auth, shared props) around the route. The ``app`` fixture - is function-scoped, so this does not leak into other tests.""" - from host.routes import router as host_router - - app.include_router(host_router) - return app - - async def _client_for(app, *, email: str, roles: list[str], permissions: list[str]): """Sign in an account holding exactly these roles and permissions.""" from sqlalchemy import select @@ -66,24 +59,25 @@ async def _client_for(app, *, email: str, roles: list[str], permissions: list[st @pytest.mark.anyio -async def test_admin_reaches_the_overview(host_app) -> None: - client = await _client_for(host_app, email="root@example.com", roles=["admin"], permissions=[]) +async def test_admin_reaches_the_overview(app) -> None: + client = await _client_for(app, email="root@example.com", roles=["admin"], permissions=[]) async with client: resp = await client.get("/admin", follow_redirects=False) assert resp.status_code == 200, resp.text + assert inertia_page(resp).component == PAGE_OVERVIEW @pytest.mark.anyio -async def test_admin_reaches_it_even_with_an_empty_sidebar(host_app) -> None: +async def test_admin_reaches_it_even_with_an_empty_sidebar(app) -> None: """An install with no admin modules must still reach the page's own empty state — 403'ing there would make that copy unreachable.""" from simple_module_core.menu import MenuSection - registry = host_app.state.sm.menu_registry + registry = app.state.sm.menu_registry registry._items = [i for i in registry._items if i.section != MenuSection.ADMIN_SIDEBAR] registry._sorted = None client = await _client_for( - host_app, email="lonely-admin@example.com", roles=["admin"], permissions=[] + app, email="lonely-admin@example.com", roles=["admin"], permissions=[] ) async with client: resp = await client.get("/admin", follow_redirects=False) @@ -91,16 +85,16 @@ async def test_admin_reaches_it_even_with_an_empty_sidebar(host_app) -> None: @pytest.mark.anyio -async def test_account_with_no_admin_entries_is_refused(host_app) -> None: +async def test_account_with_no_admin_entries_is_refused(app) -> None: """A plain signed-in user has an empty admin sidebar — nothing to show.""" - client = await _client_for(host_app, email="plain@example.com", roles=[], permissions=[]) + client = await _client_for(app, email="plain@example.com", roles=[], permissions=[]) async with client: resp = await client.get("/admin", follow_redirects=False) assert resp.status_code == 403 @pytest.mark.anyio -async def test_permission_holder_without_the_admin_role_is_admitted(host_app) -> None: +async def test_permission_holder_without_the_admin_role_is_admitted(app) -> None: """The case the role-only gate got wrong. This account can open ``/admin/settings/`` on its ``settings.view`` grant, @@ -109,7 +103,7 @@ async def test_permission_holder_without_the_admin_role_is_admitted(host_app) -> from settings.core.constants import PERM_VIEW client = await _client_for( - host_app, + app, email="settings-only@example.com", roles=["settings-reader"], permissions=[PERM_VIEW], @@ -120,9 +114,9 @@ async def test_permission_holder_without_the_admin_role_is_admitted(host_app) -> @pytest.mark.anyio -async def test_anonymous_is_bounced_to_login(host_app) -> None: +async def test_anonymous_is_bounced_to_login(app) -> None: """AuthMiddleware owns this half — a 403 here would leak that /admin exists.""" - transport = httpx.ASGITransport(app=host_app) + transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c: resp = await c.get("/admin", follow_redirects=False) assert resp.status_code == 302 diff --git a/packages/i18n/src/generated-resources.ts b/packages/i18n/src/generated-resources.ts index aacb8348..9bfec6ee 100644 --- a/packages/i18n/src/generated-resources.ts +++ b/packages/i18n/src/generated-resources.ts @@ -598,10 +598,6 @@ export default { 'file_storage.upload.resume_prompt': '', 'file_storage.upload.retry': '', 'file_storage.upload.start_over': '', - 'host.admin.description': '', - 'host.admin.empty': '', - 'host.admin.overview': '', - 'host.admin.title': '', 'host.landing.badge': '', 'host.landing.command_copied': '', 'host.landing.copied_label': '', @@ -643,6 +639,9 @@ export default { 'host.offline.description': '', 'host.offline.restored': '', 'host.offline.title': '', + 'hosting.admin.description': '', + 'hosting.admin.empty': '', + 'hosting.admin.title': '', 'hosting.errors.token_not_allowed': '', 'hosting.setup.connections.description': '', 'hosting.setup.connections.heading': '', diff --git a/packages/i18n/src/keys.generated.ts b/packages/i18n/src/keys.generated.ts index e5bb3c5a..f77cd4a9 100644 --- a/packages/i18n/src/keys.generated.ts +++ b/packages/i18n/src/keys.generated.ts @@ -761,12 +761,6 @@ export const keys = { }, }, host: { - admin: { - description: 'host.admin.description', - empty: 'host.admin.empty', - overview: 'host.admin.overview', - title: 'host.admin.title', - }, landing: { badge: 'host.landing.badge', command_copied: 'host.landing.command_copied', @@ -816,6 +810,11 @@ export const keys = { }, }, hosting: { + admin: { + description: 'hosting.admin.description', + empty: 'hosting.admin.empty', + title: 'hosting.admin.title', + }, errors: { token_not_allowed: 'hosting.errors.token_not_allowed', }, diff --git a/scripts/check_no_raw_fetch.py b/scripts/check_no_raw_fetch.py index a3cd241b..f31cf8f2 100644 --- a/scripts/check_no_raw_fetch.py +++ b/scripts/check_no_raw_fetch.py @@ -31,6 +31,7 @@ ("packages", "ui", "src"), ("host", "client_app"), ("framework", "hosting", "simple_module_hosting", "setup_wizard"), + ("framework", "hosting", "simple_module_hosting", "admin_overview"), ) _CLIENT_ROOT = ("packages", "ui", "src", "lib") From 6fa68b3a02c14ea1b42e8dfea59531c71e01ecae Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:46:56 +0100 Subject: [PATCH 3/7] docs: app DX #914-#919 plan Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- .../plans/2026-11-11-app-dx-914-919.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-11-app-dx-914-919.md diff --git a/docs/superpowers/plans/2026-11-11-app-dx-914-919.md b/docs/superpowers/plans/2026-11-11-app-dx-914-919.md new file mode 100644 index 00000000..d85d6063 --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-app-dx-914-919.md @@ -0,0 +1,23 @@ +# Plan: first-run app fixes #914–#919 + +Design: `docs/superpowers/specs/2026-11-11-app-dx-914-919-design.md`. Four PRs, in order; each in its own worktree off `origin/main`, TDD, then `/ship`. + +## PR 1 — #914, #919 +1. Test: a scaffolded host has no `/admin` code and `gen-pages` registers `Admin/Overview` (`framework/cli/tests/test_scaffolded_host_admin_overview.py`). +2. `simple_module_hosting/admin_overview/` (`PAGES_NAME`, `PAGE_OVERVIEW`, `routes.py`, `pages/Overview.tsx`); `framework_assets()` returns both framework frontends; `create_app` mounts it. +3. Strings `host.admin.*` → `hosting.admin.*` (en/de/es); `make gen-i18n`. +4. Drop the host copy; keep the access tests in `host/tests` (they sign in through `users`) on the plain `app` fixture; vitest for the page. +5. Lint configs (biome include, raw-fetch roots, hosting tsconfig comment); quickstart/installation/README password and path fixes; CHANGELOG; CLAUDE.md. + +## PR 2 — #916, #915 +1. Test: the scaffolded workspace root depends on the host through a workspace source; `smpy new` next steps say `make install`. +2. Test: `create-module` inside an app workspace prints the app flow. +3. Test: discovery reports a module installed after start as "restart `make dev`". + +## PR 3 — #917 +1. Tests: a fresh initial schema and an unrelated revision print no warning; a revision touching a table with an un-emitted expression index warns. +2. Re-emit before warning; one advice helper for the hook, SM026 and the `migrate` note. + +## PR 4 — #918 +1. Test: a scaffolded module's pages use `t(keys..…)` and pass the app's `tsc`. +2. Make the keyed pages the base templates; delete the `framework_repo` overlay copies; next-step text mentions `make gen-i18n`. From 9852f5b0618728a78532d3814963d6ca8021bb7d Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:49:47 +0100 Subject: [PATCH 4/7] fix: address code review findings (round 1, pass 1) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- CHANGELOG.md | 2 +- docs/modules/users.md | 2 +- framework/core/simple_module_core/__main__.py | 2 +- .../simple_module_hosting/_i18n_build.py | 4 ++-- .../admin_overview/pages/Overview.tsx | 4 ++-- .../hosting/simple_module_hosting/manifest.py | 11 ++++++++-- .../tests-js/hosting_AdminOverview.test.tsx | 14 +++++++++++-- .../test_hosting_framework_pages_reserved.py | 21 +++++++++++++++++++ skills/simple-module-cli/SKILL.md | 1 + 9 files changed, 50 insertions(+), 11 deletions(-) create mode 100644 framework/hosting/tests/test_hosting_framework_pages_reserved.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1298012f..5068c8d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed -- `/admin` works in every app. The admin overview that the sidebar's "Administration" link and the AdminLayout badge open lived only in this repository's host, so an app made by `smpy new` answered 404 there. It now ships with `simple_module_hosting` (`simple_module_hosting.admin_overview`), mounted by `create_app` and registered by `gen-pages` as the `Admin/Overview` page, exactly like the `/setup` wizard; admission is unchanged (an admin, or anyone with an admin sidebar entry). Its strings moved from the `host` namespace to `hosting.admin.*`. An existing app needs nothing beyond upgrading and running `smpy gen-pages` (a dev boot does it) (#914). +- `/admin` works in every app. The admin overview that the sidebar's "Administration" link and the AdminLayout badge open lived only in this repository's host, so an app made by `smpy new` answered 404 there. It now ships with `simple_module_hosting` (`simple_module_hosting.admin_overview`), mounted by `create_app` and registered by `gen-pages` as the `Admin/Overview` page, exactly like the `/setup` wizard; admission is unchanged (an admin, or anyone with an admin sidebar entry). Its strings moved from the `host` namespace to `hosting.admin.*`. An existing app needs nothing beyond upgrading and running `smpy gen-pages` (a dev boot does it); a host that copied this repository's `/admin` route and `pages/Admin.tsx` can delete both, since `create_app`'s route is matched first. `simple_module_hosting.assets.framework_assets()` now returns a list, and `gen-pages` refuses a module whose `ModuleMeta.name` is `Admin` or `Setup`, which would have hidden that module's pages (#914). - The quickstart matches what a new app does: an anonymous `curl /api/orders` answers 401 (the scaffold guards the API with `orders.*` permissions), the single-file test example names `tests/web/crud/test_orders_crud.py`, and `smpy users create-admin` is shown without `--password`, so it prompts instead of putting a weak password in shell history (#919). ## [0.0.45] — 2026-11-11 diff --git a/docs/modules/users.md b/docs/modules/users.md index 68b7324d..60b387cf 100644 --- a/docs/modules/users.md +++ b/docs/modules/users.md @@ -328,7 +328,7 @@ undo the committed account; these callbacks do not retry mail delivery. ## CLI -- `smpy users create-admin --email --password

[--full-name ] [--force]` — creates (or, with `--force`, updates) an admin user. Idempotent: re-running with the same email is a no-op without `--force`. +- `smpy users create-admin --email [--password

] [--full-name ] [--force]` — creates (or, with `--force`, updates) an admin user. `--password` is prompted for (hidden) when omitted. Idempotent: re-running with the same email is a no-op without `--force`. ```bash uv run smpy users create-admin --email admin@example.com diff --git a/framework/core/simple_module_core/__main__.py b/framework/core/simple_module_core/__main__.py index 94e008b5..fcd7776a 100644 --- a/framework/core/simple_module_core/__main__.py +++ b/framework/core/simple_module_core/__main__.py @@ -98,7 +98,7 @@ def _database_dialect() -> str: def _hosting_locales() -> Path | None: - """The framework's own ``hosting`` catalog (setup wizard), found without importing it. + """The framework's own ``hosting`` catalog (setup wizard, admin overview), found without importing it. The running app's ``build_i18n_registry`` always adds it, so doctor must too, or every ``hosting.*`` host override reads as unknown (SM027). Core diff --git a/framework/hosting/simple_module_hosting/_i18n_build.py b/framework/hosting/simple_module_hosting/_i18n_build.py index c2cacec0..860e0e65 100644 --- a/framework/hosting/simple_module_hosting/_i18n_build.py +++ b/framework/hosting/simple_module_hosting/_i18n_build.py @@ -32,8 +32,8 @@ def build_i18n_registry( for namespace, locale_dir in mod.locale_dirs().items(): registry.add_source(namespace, locale_dir, audience=audience) - # The framework's own catalog — the setup wizard ships with this package, - # so its strings must too, whatever host is serving it. + # The framework's own catalog — the setup wizard and the admin overview ship + # with this package, so their strings must too, whatever host is serving it. hosting_locales = Path(__file__).resolve().parent / "locales" registry.add_source("hosting", hosting_locales) extra_sources.append(("simple_module_hosting", "hosting", hosting_locales)) diff --git a/framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx b/framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx index 5d3a99f4..e3c472ee 100644 --- a/framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx +++ b/framework/hosting/simple_module_hosting/admin_overview/pages/Overview.tsx @@ -67,7 +67,7 @@ function AdminPage() {

{t(keys.hosting.admin.empty)}

) : (
- {grouped.map(([group, groupItems_]) => ( + {grouped.map(([group, cards]) => (
{group && (

@@ -75,7 +75,7 @@ function AdminPage() {

)}
- {groupItems_.map((item) => ( + {cards.map((item) => ( ))}
diff --git a/framework/hosting/simple_module_hosting/manifest.py b/framework/hosting/simple_module_hosting/manifest.py index 8037d6b9..d54d5f3e 100644 --- a/framework/hosting/simple_module_hosting/manifest.py +++ b/framework/hosting/simple_module_hosting/manifest.py @@ -167,8 +167,15 @@ def write_module_pages_manifest( framework = framework_assets() pages_map = dict(compute_module_pages(modules)) for entry in framework: - if entry.pages_dir is not None: - pages_map[entry.name] = entry.pages_dir + if entry.pages_dir is None: + continue + if entry.name in pages_map: + # Overwriting would silently unregister the module's pages. + raise ValueError( + f"Module name {entry.name!r} is reserved for the framework's own pages " + f"({entry.package_name}); rename the module's ModuleMeta.name." + ) + pages_map[entry.name] = entry.pages_dir manifest_path = output_dir / "modules.manifest.json" manifest_payload = {name: path.as_posix() for name, path in pages_map.items()} diff --git a/framework/hosting/tests-js/hosting_AdminOverview.test.tsx b/framework/hosting/tests-js/hosting_AdminOverview.test.tsx index 1a124e7f..2b4e9679 100644 --- a/framework/hosting/tests-js/hosting_AdminOverview.test.tsx +++ b/framework/hosting/tests-js/hosting_AdminOverview.test.tsx @@ -3,7 +3,16 @@ import { configureI18n, keys } from '@simple-module-py/i18n'; import { render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -configureI18n({ locale: 'en', messages: {} }); +import en from '../simple_module_hosting/locales/en.json'; + +// The real catalog, so a missing or misspelt string fails here rather than +// rendering its key. +configureI18n({ + locale: 'en', + messages: Object.fromEntries( + Object.entries(en.admin).map(([key, value]) => [`hosting.admin.${key}`, value]), + ), +}); const props = vi.hoisted(() => ({ menus: { adminSidebar: [] as unknown[] } })); @@ -25,7 +34,8 @@ describe('Admin overview', () => { it('shows the empty state when the viewer has no admin tools', () => { props.menus.adminSidebar = []; render(); - expect(screen.getByText(keys.hosting.admin.empty)).toBeInTheDocument(); + expect(screen.getByText(en.admin.empty)).toBeInTheDocument(); + expect(screen.queryByText(keys.hosting.admin.empty)).not.toBeInTheDocument(); }); it('renders one card per admin sidebar entry, grouped', () => { diff --git a/framework/hosting/tests/test_hosting_framework_pages_reserved.py b/framework/hosting/tests/test_hosting_framework_pages_reserved.py new file mode 100644 index 00000000..bdbcff70 --- /dev/null +++ b/framework/hosting/tests/test_hosting_framework_pages_reserved.py @@ -0,0 +1,21 @@ +"""The framework's own page names cannot be taken by a module. + +``gen-pages`` registers the setup wizard and the admin overview next to the +modules' pages, keyed by name. A module named ``Admin`` or ``Setup`` would +otherwise have its entry overwritten and its pages stop resolving, silently. +""" + +from __future__ import annotations + +import pytest +from simple_module_hosting import manifest +from simple_module_hosting.admin_overview import PAGES_NAME + + +def test_a_module_named_like_framework_pages_is_refused(tmp_path, monkeypatch) -> None: + pages = tmp_path / "pages" + pages.mkdir() + monkeypatch.setattr(manifest, "compute_module_pages", lambda modules: {PAGES_NAME: pages}) + + with pytest.raises(ValueError, match="reserved"): + manifest.write_module_pages_manifest([], tmp_path / "client_app", repo_root=tmp_path) diff --git a/skills/simple-module-cli/SKILL.md b/skills/simple-module-cli/SKILL.md index 43a85a74..c5c3a427 100644 --- a/skills/simple-module-cli/SKILL.md +++ b/skills/simple-module-cli/SKILL.md @@ -193,6 +193,7 @@ smpy settings import-from-env Bootstraps the first admin user, or rotates an existing admin's password. ```bash +smpy users create-admin -e admin@example.com # prompts for the password smpy users create-admin -e admin@example.com -p hunter2 smpy users create-admin -e admin@example.com -p new-password --force # rotate smpy users create-admin -e admin@example.com -p hunter2 --full-name "Admin" From db60e64a8811561526e1d6a3939430cfb6004e60 Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:49:57 +0100 Subject: [PATCH 5/7] style: wrap hosting catalog docstring Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- framework/core/simple_module_core/__main__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/framework/core/simple_module_core/__main__.py b/framework/core/simple_module_core/__main__.py index fcd7776a..dc02c9fd 100644 --- a/framework/core/simple_module_core/__main__.py +++ b/framework/core/simple_module_core/__main__.py @@ -98,7 +98,9 @@ def _database_dialect() -> str: def _hosting_locales() -> Path | None: - """The framework's own ``hosting`` catalog (setup wizard, admin overview), found without importing it. + """The framework's own ``hosting`` catalog, found without importing it. + + It holds the setup wizard's and the admin overview's strings. The running app's ``build_i18n_registry`` always adds it, so doctor must too, or every ``hosting.*`` host override reads as unknown (SM027). Core From aa8161c5d381530ef6902da2a69f0e982baa4d7c Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:54:20 +0100 Subject: [PATCH 6/7] fix: address code review findings (round 1, pass 2) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- framework/hosting/simple_module_hosting/host_cli.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/framework/hosting/simple_module_hosting/host_cli.py b/framework/hosting/simple_module_hosting/host_cli.py index 10681ca2..ac346da7 100644 --- a/framework/hosting/simple_module_hosting/host_cli.py +++ b/framework/hosting/simple_module_hosting/host_cli.py @@ -45,7 +45,11 @@ def gen_pages( # Skip the auth provider the host won't boot — its pages would otherwise # ship in the bundle with no view endpoint able to render them. modules = select_auth_provider(discover_modules(), resolve_auth_provider()) - written = write_module_pages_manifest(modules, host_dir) + try: + written = write_module_pages_manifest(modules, host_dir) + except ValueError as exc: + typer.echo(f"ERROR: {exc}", err=True) + raise typer.Exit(code=1) from exc typer.echo( f"Module pages manifest: {len(modules)} module(s) " f"→ {written['manifest'].name}, {written['generated'].name}, " From bcc1a051dcb229af3e0f4ccdad235fc31ad52e3c Mon Sep 17 00:00:00 2001 From: Anto Subash Date: Thu, 12 Nov 2026 15:55:34 +0100 Subject: [PATCH 7/7] test: pin gen-pages reserved-name error (round 1, pass 3) Claude-Session: https://claude.ai/code/session_01M9neheZZEe3sVpDi2S3zT4 --- framework/hosting/tests/test_host_cli.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/framework/hosting/tests/test_host_cli.py b/framework/hosting/tests/test_host_cli.py index 984ac25e..459ab139 100644 --- a/framework/hosting/tests/test_host_cli.py +++ b/framework/hosting/tests/test_host_cli.py @@ -31,6 +31,19 @@ def test_gen_pages_errors_on_missing_client_app(tmp_path: Path) -> None: assert "not found" in result.output.lower() or "not found" in (result.stderr or "").lower() +def test_gen_pages_reports_manifest_error_without_traceback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def _boom(*_args: object, **_kwargs: object) -> None: + raise ValueError("duplicate page 'X'") + + monkeypatch.setattr("simple_module_hosting.host_cli.write_module_pages_manifest", _boom) + result = CliRunner().invoke(app, ["gen-pages", "--host-dir", str(tmp_path)]) + assert result.exit_code == 1 + assert "ERROR: duplicate page 'X'" in result.output + assert not isinstance(result.exception, ValueError) + + @pytest.mark.parametrize( "module_target", ["simple_module_hosting", "simple_module_hosting.host_cli"],