Repository navigation
Architecture
KHost follows a layered architecture. Dependencies only point inward:
UI (KHost.UserInterface, KHost.Screen2)
│
▼
Domain ──► DataAccess
│ │
▼ ▼
Abstractions
│
▼
Plugins.Sdk
-
KHost.Plugins.Sdkis the innermost project — plugin contracts plus the message broker, with no project references of its own, so everything may reference it. -
KHost.Abstractionsdefines every interface and shared model, and references only the SDK.DomainandDataAccessreference it; the UI projects reference all of them. -
KHost.Domainowns business logic and stateful services, registered as singletons in DI. A service with something to report publishes a message onIMessageBroker; components subscribe to the messages they care about and callStateHasChanged(). See Messaging. -
KHost.DataAccessowns EF Core persistence for the song library.
Several Abstractions interfaces are implemented outside Domain by design: ICastService (KHost.Cast), IMediaPlayer (KHost.Screen2), IScreenClient/IScreenServer (KHost.IPC.SignalR), IAnalyticsService (KHost.Telemetry), the repositories and IDatabaseInitializer (KHost.DataAccess), and IInteractionDispatcher/IInteractionHandler<> (KHost.UserInterface).
Browser (Blazor circuit)
│
▼
KHost.UserInterface ── Domain services ──► EF Core / SQLite (song library)
│ ▲ └─► JsonFileCacheService (./cache/*.json)
│ │ (queue, venues, theme, plugins)
│ │ SignalR hub /ipc/screen
commands state
▼ │
KHost.Screen2 (Photino) ── HLS stream served by the host ──► second display
Host ⇄ screen interop. The UI hosts a SignalR hub (KHost.IPC.SignalR) at /ipc/screen. The screen app connects as a SignalR client (--server-uri / --screen-id), receives playback commands, and pushes its ScreenPlaybackState back. LocalScreenProvider (an IScreenProvider) spawns screen processes from the Screens dialog, so a screen is a separate executable remote-controlled by the host console. Protocol details: Screens and Casting.
Why the host transcodes. The host runs one FFmpeg process per song (HlsMediaStreamService in Domain) and serves the result as an HLS playlist via GET /media/{sessionId}/{fileName}. Screens fetch that stream instead of decoding the file, which lets several of them share a decode, keeps them on a common timeline, and allows the same URL to be handed to a Cast receiver that has no access to the library. Pitch shifting (semitone transposition) is applied host-side at transcode time. The /media endpoint pins playlists to song start with #EXT-X-START:TIME-OFFSET=0, serves segments with range support, and sets Access-Control-Allow-Origin: * for Cast.
Reachable, without exposing the console. Kestrel binds every interface so a receiver or an off-machine screen can fetch the stream. LanAccessPolicy — the first middleware in the pipeline — answers only /media and /ipc/screen off-box and returns a bare 404 for everything else; the queue, library, and venue settings stay on the host machine. Cookie authentication (Users and Permissions) layers on top of that for the console itself, but the network boundary never relies on it: off-box requests are refused before authentication runs. The port is declared once, in appsettings.json (Urls); the launch profile intentionally sets no applicationUrl.
Why two persistence strategies? The song library is large, relational, and benefits from SQL indexes. The queue, venue selection, theme choice, and plugin state are small, frequently-mutated session state; serializing them as JSON blobs (ICacheService → ./cache/*.json) is simpler and keeps the host running even if the DB is momentarily unavailable. Details: Data and Persistence.
KHost.UserInterface/Program.cs:
- Single-instance guard — an exclusive lock on
.instance.lockin the app directory; a second launch shows a message box (or stderr when--headless) and exits 1. - Service registration:
AddServiceDefaults(Aspire),AddTelemetry,AddDomain,AddPlugins(plugin discovery/loading — must run before the container is built),AddDataAccess,AddSignalRIPCServer,AddCast, cookie authentication plus one authorization policy perKHostPermission(Users and Permissions), and UI-only services (IThemeService,IDialogService, interaction handlers, startup-redirect providers). - Init-on-startup, each hard-failing the app on error:
IDatabaseInitializer(migrate + seed), thenIVenuesService,ISingerQueueService,IThemeService,IScreenCoordinationService. - Middleware:
LanAccessPolicygate → exception handler (/Error) → status-code re-execute (/not-found) → authentication → console-principal override whenAuth:RequireLoginis off → authorization → antiforgery → startup redirect (first-run/setupwizard,--start-page) → static assets → interactive-server Razor components. - Endpoints: the Blazor app, the SignalR hub at
/ipc/screen,GET /media/{sessionId}/{fileName}, and the native-form auth endpointsPOST /auth/login/POST /auth/logout. - Native shell: unless
--headless, Kestrel is started, the live listening address is resolved (wildcard hosts normalized tolocalhost) and back-filled intoLocalScreen:ServerUriandMediaStream:BaseAddress, and aPhotinoWindow(1440×900) opens on that URL. Window close stops the app and vice versa.
A Release build's native window stops behaving like a browser. SetDevToolsEnabled(false) closes
the developer tools natively on all three platforms — both the "Inspect Element" item in a text
field's own menu and the F12 / Cmd-Opt-I shortcuts, neither of which the page can reach. Deliberately
not SetContextMenuEnabled(false): on Windows and Linux that is all-or-nothing and would take cut,
copy and paste with it, and on macOS it is a documented no-op. wwwroot/js/shell-lockdown.js
suppresses the page context menu everywhere except a field being typed into, and blocks the reload,
back/forward and view-source shortcuts along with the mouse thumb buttons.
The gate is the build configuration, not the environment: a Debug build keeps its tools. It
cannot be the environment, because an unpublished run has to stay in Development to serve its static
web assets at all — start one in Production and the page arrives with no CSS and no
blazor.web.js.
One honest limitation: reload and back navigation cannot be fully closed from application code. The settings that govern them are not exposed by Photino, and blocking their keys from JavaScript is unreliable on every platform — WebView2 in particular handles them before the DOM sees the event. The JavaScript stops casual attempts; it will not stop a determined operator.
All three shutdown tasks hang off ApplicationStopping, so they run on every graceful exit — closing the window (which calls app.StopAsync()), Ctrl+C, or a SIGTERM — but not on a force kill:
-
HLS sessions are swept:
IMediaStreamService.CloseAllAsync()kills the ffmpeg processes and removes the per-session temp directories, which otherwise outlive the process. -
The singer queue is cleared, if the selected venue has
ClearQueueOnCloseset. Failures are logged and swallowed: a queue that will not clear must not block the shutdown. -
Screens the host launched are closed:
IScreenProvider.CloseSpawnedScreens()kills the child processesLocalScreenProviderstarted. Screens the host did not spawn — anything on another machine — keep running and fall back to their lost-host behaviour, so quitting never takes down a display someone else is driving. This is a kill of our own children, deliberately not a message on the hub, which would reach every screen. It has to live here rather than in the provider'sDispose: on macOS closing the window tears the process down inside Photino, so container disposal never runs.
Domain code never references UI types. It sends a typed request through IInteractionDispatcher, which resolves the matching IInteractionHandler<TRequest, TResponse> from DI; handlers bridge dialogs into awaitable calls with TaskCompletionSource. Handlers on master: duplicate-song confirmation, show-lyrics, edit-media.
Routable pages: / (host console: now-playing, singer queue, media search), /setup (first-run wizard), /settings/{media-manager, media-importer, plugins-manager, tips-manager, user-groups-manager, users-manager, venues-manager}, plus /Error and /not-found.
Themes are CSS files in wwwroot/css/themes/ (grape is the default), enumerated by ThemeService at startup; the choice persists via ICacheService and switching is an in-process service call — there is no HTTP API for themes.
KHost
Architecture
- Architecture
- Projects
- Screens and Casting
- Break Music and Ads
- Messaging
- Data and Persistence
- Plugins
Contributing