Skip to content

Expose dashboard as a mountable starlette app#76

Open
jklaise wants to merge 2 commits into
TkTech:26_uxfrom
jklaise:expose-dashboard-as-starlette-app
Open

Expose dashboard as a mountable starlette app#76
jklaise wants to merge 2 commits into
TkTech:26_uxfrom
jklaise:expose-dashboard-as-starlette-app

Conversation

@jklaise

@jklaise jklaise commented Jan 19, 2026

Copy link
Copy Markdown
Contributor

Adds support for #64.

Full disclosure - I'm not familiar with React development, so for the frontend wiring I have relied on ChatGPT. There are also a bunch of formatting changes made automatically by my IDE - I re-ran npm run lint -- --fix but this didn't change the formatting back.

Basic idea:

  • Ship chancy-config.js and expose it over the API so that the backend server can tell the (statically bundled) frontend under what prefix it is running
  • Provide utilities in config.ts that are used elsewhere to make all route references relative to the base path with the prefix

An example FastAPI app with the dashboard mounted as a subapp:

# app.py
from contextlib import asynccontextmanager

from fastapi import FastAPI

from chancy import Chancy, Worker
from chancy.plugins.api import Api, SimpleAuthBackend

# Configure your Chancy instance as you normally would.
CHANCY_DSN = "postgresql://localhost:5432/dev"

# Auth + path prefix for the mounted dashboard/API
api_plugin = Api(
    authentication_backend=SimpleAuthBackend({"admin": "password"}),
    path_prefix="/chancy",
    allow_origins=["*"],
)

chancy = Chancy(CHANCY_DSN)


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with chancy:
        async with Worker(chancy) as worker:
            # Build the Starlette app once and mount it under the same prefix
            api_app = api_plugin.build_starlette_app(worker, chancy)
            app.mount(api_plugin.path_prefix or "/", api_app)

            yield


app = FastAPI(lifespan=lifespan)


@app.get("/ping")
async def ping():
    return {"pong": True}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)

@codecov

codecov Bot commented Jan 19, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 25 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.76%. Comparing base (31cc61d) to head (4d45dab).
⚠️ Report is 13 commits behind head on 26_ux.

Files with missing lines Patch % Lines
chancy/plugins/api/__init__.py 0.00% 25 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            26_ux      #76      +/-   ##
==========================================
+ Coverage   66.71%   66.76%   +0.05%     
==========================================
  Files          59       59              
  Lines        3506     3563      +57     
==========================================
+ Hits         2339     2379      +40     
- Misses       1167     1184      +17     
Flag Coverage Δ
unittests 66.76% <0.00%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@TkTech TkTech added this to the 0.26.0 milestone Jan 20, 2026
@TkTech TkTech added the enhancement New feature or request label Jan 20, 2026
name=route["name"],
)

async def prefix_config(request):

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems reasonable overall. We should probably pass the port through as well.

@TkTech

TkTech commented Jan 28, 2026

Copy link
Copy Markdown
Owner

Overall I don't see any glaring issues - we should probably pass through the port as well, and we'll need to add a short doc page on mounting under a sub-path.

@jklaise

jklaise commented Mar 24, 2026

Copy link
Copy Markdown
Contributor Author

@TkTech what can I help with to move this and #58 forward? Happy to add a doc page and also pass the mounting port through.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds support for mounting the API + dashboard under an arbitrary URL prefix by exposing the dashboard/API as a reusable Starlette sub-application, and wiring the UI to discover and respect that base path at runtime.

Changes:

  • Add Api.build_starlette_app() and path_prefix support so the dashboard/API can be mounted into an existing ASGI app (and optionally served under a prefix when run standalone).
  • Add a runtime-served chancy-config.js and frontend utilities (config.ts) to make routing and asset URLs base-path aware.
  • Update the UI to use the configured base path for React Router basename, API base URL construction, and static asset references (logo).

Reviewed changes

Copilot reviewed 10 out of 11 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
chancy/plugins/api/init.py Exposes a buildable Starlette app, adds path_prefix, and serves dynamic chancy-config.js.
chancy/plugins/api/ui/vite.config.ts Sets relative base for subpath-friendly asset loading.
chancy/plugins/api/ui/index.html Loads chancy-config.js before the app bootstraps.
chancy/plugins/api/ui/src/config.ts Adds base-path normalization + helpers (getConfiguredBasePath, withBasePath).
chancy/plugins/api/ui/src/main.tsx Configures React Router basename from runtime base path.
chancy/plugins/api/ui/src/hooks/useServerConfiguration.tsx Incorporates base path into the API base URL and persists it in localStorage.
chancy/plugins/api/ui/src/Layout.tsx Adds UI for configuring the base path and updates logo asset URL usage.
chancy/plugins/api/ui/src/pages/Dashboard.tsx Updates logo asset URL usage to be base-path aware.
chancy/plugins/api/ui/src/components/Loading.tsx Updates spinner/logo asset URL usage to be base-path aware.
chancy/plugins/api/ui/public/chancy-config.js Provides a dev default for window.__CHANCY_BASE_PATH__.
chancy/plugins/api/ui/package-lock.json Updates frontend dependencies lockfile (incl. svgr + new deps).
Files not reviewed (1)
  • chancy/plugins/api/ui/package-lock.json: Language not supported
Comments suppressed due to low confidence (1)

chancy/plugins/api/ui/src/Layout.tsx:182

  • The "Connect" action can run while url is invalid (e.g., the port input is cleared and parseInt yields NaN, causing useServerConfiguration() to return url: null). Because login/logout build URLs via template strings, this becomes requests to null/api/... at runtime. Consider disabling the button when url is null/invalid and/or showing a validation error before attempting login.
                <button
                  type="submit"
                  className={"btn btn-primary w-100"}
                  disabled={loginMutation.isPending}
                >
                  {loginMutation.isPending ? <Spinner size={16} /> : "Connect"}
                </button>

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +140 to +146
def build_starlette_app(self, worker: Worker, chancy: Chancy) -> Starlette:
"""
Start the web server.
Build (or return) the Starlette app that powers the API and dashboard.
"""
if self._app is not None:
return self._app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants