Merge media-webui/media-backend into the general shared component/backend system

Extracts a new backend/authproxy package for the AuthGuard-proxy helper
functions (session cookie handling, input normalization, error
translation) that Bitmagnet/GameStream/media-backend/AutoCode/
CollabTable/PubliSafe/SimpleCollection/SyncServer/UnraidMonitor/
OutdoorGames were each independently reimplementing, and repoints all
of them onto it.

Extends packages/web-ui's Button/Badge with the variants media-webui
needed (outline, icon size, primary badge) and promotes EmptyState/
SectionTitle/Metric/StatusWidget/StatusDialog into the shared library,
then migrates media-webui off its own diverged ui/{button,card,badge,
metric} components and local duplicates of the promoted components
onto @gabriel20xx/web-ui, so media-webui is a proper consumer of the
same design system every other project already uses instead of a
parallel fork.

Also removes the dead `desktop`/MediaDesktop service variant from
media-backend and media-webui (MediaDesktop is an Electron client that
never actually runs this stack).
This commit is contained in:
Gabriel20xx committed 2026-09-03 00:14:01 +02:00
1 parent 9589d07baf
commit 7b5a4e6c2c
49 files changed
+872 -726

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
// Package authproxy holds small helpers shared by every Go service in this
// workspace that proxies its own /auth/... (or /api/auth/...) HTTP surface
// to a centralized AuthGuard instance via shared/backend/authclient, instead
// of embedding its own local user table.
//
// Three services independently reimplemented the same handful of pieces
// below before this package existed (Forks/Bitmagnet/backend/internal/auth/service.go,
// Original/GameStream/backend/cmd/gamestreamd/auth.go,
// Central/shared/media-backend/internal/auth/auth.go — read any one of
// their top-of-file doc comments for the fuller AuthGuard-migration
// rationale: session cookie forwarding, the local one-time setup-claim
// flag, "auth disabled" mode, etc.). Those pieces stay project-specific
// (they depend on each project's own storage/framework/response shape) —
// only the pieces below were duplicated near-verbatim everywhere:
//
// - SessionToken / ClearSessionCookies: reading and clearing AuthGuard's
// own session cookie is identical logic in every caller, since none of
// them mint a session token of their own anymore.
// - NormalizeUsername / NormalizeEmail / ValidPassword: the same
// trim+shape checks, just with different max/min lengths and (kept
// deliberately un-touched by this package) different caller-owned
// error messages — see each function's doc comment for why this
// package returns a plain (value, bool) rather than an error.
// - APIErrorResponse: unwrapping an authclient.APIError into the
// (status code, message) pair every caller's own writeError-equivalent
// forwards close to verbatim.
package authproxy
import (
"errors"
"net/http"
"strings"
"unicode/utf8"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// CookieReader is the minimal interface SessionToken needs from an incoming
// request — just *http.Request.Cookie's signature, not the whole request.
// *http.Request satisfies this trivially; a caller (like Bitmagnet's own
// internal/auth.HTTPContext) that deliberately abstracts its request behind
// a narrower interface of its own, e.g. for testability, can pass that
// directly instead of needing a concrete *http.Request.
type CookieReader interface {
Cookie(name string) (*http.Cookie, error)
}
// SessionToken reads AuthGuard's own session cookie
// (authclient.DefaultCookieName) off an incoming request, returning "" if
// it is absent or empty. Every AuthGuard-proxying service in this workspace
// mints no session token of its own — AuthGuard's cookie *is* the session —
// so this same read is duplicated in every one of them.
func SessionToken(r CookieReader) string {
cookie, err := r.Cookie(authclient.DefaultCookieName)
if err != nil || cookie.Value == "" {
return ""
}
return cookie.Value
}
// ClearSessionCookies clears AuthGuard's own session cookie plus one
// legacy, pre-migration cookie name a caller's browser might still be
// holding (each project's own cookie name from before it adopted
// AuthGuard — e.g. "gamestream_session", "bitmagnet_session",
// "mediacollection_session"; pass "" if a given caller has none). Normally
// AuthGuard's own Set-Cookie header, forwarded via authclient.ForwardCookies,
// already clears its cookie on logout — every project's own Logout handler
// also calls this explicitly as a fallback and to clear the legacy cookie,
// which AuthGuard has no way to know about.
func ClearSessionCookies(w http.ResponseWriter, legacyCookieName string, secure bool) {
http.SetCookie(w, &http.Cookie{
Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: secure, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
if legacyCookieName != "" && legacyCookieName != authclient.DefaultCookieName {
http.SetCookie(w, &http.Cookie{
Name: legacyCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: secure, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
}
}
// NormalizeUsername reports whether value, once trimmed, is non-empty and
// no longer than maxLen runes, and returns the trimmed value either way.
//
// This returns (value, bool) rather than (value, error) deliberately: every
// existing caller already owns its own error value/message for this
// failure (e.g. "username is required", "invalid authentication input:
// username must be between 1 and 64 characters") as part of its public API
// response shape, and unifying those messages was not part of what made
// this duplicated — only the trim+shape check was. A caller with "empty
// means leave this field unchanged" update semantics (a partial-update
// endpoint) should special-case an empty value itself before calling this,
// since this function always reports false for one.
func NormalizeUsername(value string, maxLen int) (normalized string, ok bool) {
normalized = strings.TrimSpace(value)
return normalized, normalized != "" && utf8.RuneCountInString(normalized) <= maxLen
}
// NormalizeEmail reports whether value, once lowercased and trimmed, looks
// like a valid email address (exactly one "@", a non-empty local part, and
// a domain part containing at least one ".") and is no longer than maxLen
// runes, and returns the normalized value either way. Same (value, bool)
// shape and rationale as NormalizeUsername.
func NormalizeEmail(value string, maxLen int) (normalized string, ok bool) {
normalized = strings.ToLower(strings.TrimSpace(value))
if normalized == "" || utf8.RuneCountInString(normalized) > maxLen || strings.Count(normalized, "@") != 1 {
return normalized, false
}
local, domain, _ := strings.Cut(normalized, "@")
if local == "" || domain == "" || !strings.Contains(domain, ".") {
return normalized, false
}
return normalized, true
}
// ValidPassword reports whether password is at least minLen runes long.
func ValidPassword(password string, minLen int) bool {
return utf8.RuneCountInString(password) >= minLen
}
// APIErrorResponse extracts the HTTP status code and message an
// authclient.APIError carries, for a caller's own writeError-equivalent to
// forward. ok is false when err is not an *authclient.APIError (a
// transport failure actually reaching AuthGuard, as opposed to AuthGuard
// giving a real answer the caller didn't like) — callers should fall back
// to a generic 500 with their own message in that case, matching every
// existing writeAuthGuardError implementation's behavior.
func APIErrorResponse(err error) (statusCode int, message string, ok bool) {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
return apiErr.StatusCode, apiErr.Message, true
}
return 0, "", false
}
+150
View File
@@ -0,0 +1,150 @@
package authproxy
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
func TestSessionToken(t *testing.T) {
cases := []struct {
name string
cookie *http.Cookie
want string
}{
{name: "no cookie", want: ""},
{name: "present", cookie: &http.Cookie{Name: authclient.DefaultCookieName, Value: "tok123"}, want: "tok123"},
{name: "empty value", cookie: &http.Cookie{Name: authclient.DefaultCookieName, Value: ""}, want: ""},
{name: "wrong cookie name", cookie: &http.Cookie{Name: "other", Value: "tok123"}, want: ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
if tc.cookie != nil {
r.AddCookie(tc.cookie)
}
if got := SessionToken(r); got != tc.want {
t.Fatalf("SessionToken() = %q, want %q", got, tc.want)
}
})
}
}
func TestClearSessionCookies(t *testing.T) {
w := httptest.NewRecorder()
ClearSessionCookies(w, "legacy_session", true)
resp := w.Result()
cookies := resp.Cookies()
if len(cookies) != 2 {
t.Fatalf("got %d Set-Cookie headers, want 2: %+v", len(cookies), cookies)
}
byName := map[string]*http.Cookie{}
for _, c := range cookies {
byName[c.Name] = c
}
for _, name := range []string{authclient.DefaultCookieName, "legacy_session"} {
c, ok := byName[name]
if !ok {
t.Fatalf("missing Set-Cookie for %q", name)
}
if c.Value != "" || c.MaxAge != -1 || !c.HttpOnly || !c.Secure {
t.Fatalf("cookie %q not cleared correctly: %+v", name, c)
}
}
}
func TestClearSessionCookiesNoLegacyName(t *testing.T) {
w := httptest.NewRecorder()
ClearSessionCookies(w, "", false)
if got := len(w.Result().Cookies()); got != 1 {
t.Fatalf("got %d Set-Cookie headers, want 1 (no legacy name given)", got)
}
}
func TestClearSessionCookiesLegacyEqualsDefault(t *testing.T) {
w := httptest.NewRecorder()
ClearSessionCookies(w, authclient.DefaultCookieName, false)
if got := len(w.Result().Cookies()); got != 1 {
t.Fatalf("got %d Set-Cookie headers, want 1 (legacy name equals AuthGuard's own)", got)
}
}
func TestNormalizeUsername(t *testing.T) {
cases := []struct {
name string
input string
want string
ok bool
}{
{name: "valid", input: " gabriel ", want: "gabriel", ok: true},
{name: "empty", input: " ", want: "", ok: false},
{name: "too long", input: string(make([]byte, 65)), want: string(make([]byte, 65)), ok: false},
{name: "exactly max", input: "1234567890", want: "1234567890", ok: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := NormalizeUsername(tc.input, 10)
if got != tc.want || ok != tc.ok {
t.Fatalf("NormalizeUsername(%q, 10) = (%q, %v), want (%q, %v)", tc.input, got, ok, tc.want, tc.ok)
}
})
}
}
func TestNormalizeEmail(t *testing.T) {
cases := []struct {
name string
input string
want string
ok bool
}{
{name: "valid", input: " Gabriel@Example.COM ", want: "gabriel@example.com", ok: true},
{name: "empty", input: "", want: "", ok: false},
{name: "no at", input: "gabriel.example.com", want: "gabriel.example.com", ok: false},
{name: "two ats", input: "a@b@c.com", want: "a@b@c.com", ok: false},
{name: "empty local part", input: "@example.com", want: "@example.com", ok: false},
{name: "empty domain", input: "gabriel@", want: "gabriel@", ok: false},
{name: "domain without dot", input: "gabriel@localhost", want: "gabriel@localhost", ok: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := NormalizeEmail(tc.input, 254)
if got != tc.want || ok != tc.ok {
t.Fatalf("NormalizeEmail(%q, 254) = (%q, %v), want (%q, %v)", tc.input, got, ok, tc.want, tc.ok)
}
})
}
}
func TestValidPassword(t *testing.T) {
if ValidPassword("short", 8) {
t.Fatal("expected 5-char password to fail an 8-char minimum")
}
if !ValidPassword("longenough", 8) {
t.Fatal("expected 10-char password to pass an 8-char minimum")
}
}
func TestAPIErrorResponse(t *testing.T) {
t.Run("api error", func(t *testing.T) {
apiErr := &authclient.APIError{StatusCode: http.StatusConflict, Message: "already exists"}
status, message, ok := APIErrorResponse(apiErr)
if !ok || status != http.StatusConflict || message != "already exists" {
t.Fatalf("APIErrorResponse() = (%d, %q, %v), want (409, %q, true)", status, message, ok, "already exists")
}
})
t.Run("non-api error", func(t *testing.T) {
_, _, ok := APIErrorResponse(errors.New("transport failure"))
if ok {
t.Fatal("expected ok=false for a non-APIError")
}
})
}
+1 -1
View File
@@ -1,6 +1,6 @@
# MediaCollection Go backend
The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, `servant`, or `desktop` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, or `servant` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
From this directory:
+5 -16
View File
@@ -131,6 +131,7 @@ import (
"golang.org/x/crypto/bcrypt"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
)
// User is this service's own /auth/... response shape - UNCHANGED from
@@ -222,25 +223,14 @@ func UserFromContext(ctx context.Context) *User {
// sessionToken reads the AuthGuard session cookie off the incoming request.
// See the top-of-file doc comment's "Session cookie / token model" section.
func (s *Service) sessionToken(r *http.Request) string {
cookie, err := r.Cookie(authclient.DefaultCookieName)
if err != nil || cookie.Value == "" {
return ""
}
return cookie.Value
return authproxy.SessionToken(r)
}
// clearSessionCookies clears both the AuthGuard cookie (as a fallback -
// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies,
// already does this) and the pre-migration cookie name.
func (s *Service) clearSessionCookies(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true,
Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
http.SetCookie(w, &http.Cookie{
Name: s.cookieName, Value: "", Path: "/", HttpOnly: true,
Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1,
})
authproxy.ClearSessionCookies(w, s.cookieName, s.secureCookies)
}
// toUser translates AuthGuard's PublicUser into this service's own User
@@ -1144,9 +1134,8 @@ func (s *Service) SetPassword(ctx context.Context, id int64, password string) er
// non-APIError (a transport failure actually reaching AuthGuard) falls back
// to a generic 500 with fallbackMessage.
func writeAuthGuardError(w http.ResponseWriter, err error, fallbackMessage string) {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
writeError(w, apiErr.StatusCode, apiErr.Message)
if statusCode, message, ok := authproxy.APIErrorResponse(err); ok {
writeError(w, statusCode, message)
return
}
writeError(w, http.StatusInternalServerError, fallbackMessage)
-5
View File
@@ -18,7 +18,6 @@ const (
Moderator Service = "moderator"
Kiosk Service = "kiosk"
Servant Service = "servant"
Desktop Service = "desktop"
)
type Config struct {
@@ -137,8 +136,6 @@ func normalizeService(value string) Service {
return Kiosk
case "servant", "mediaservant":
return Servant
case "desktop", "mediadesktop":
return Desktop
default:
return ""
}
@@ -160,8 +157,6 @@ func serviceName(service Service) string {
return "MediaKiosk"
case Servant:
return "MediaServant"
case Desktop:
return "MediaDesktop"
default:
return "MediaCollection"
}
@@ -1060,12 +1060,6 @@ func (s *Server) kioskStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "latestImage": latest, "queueLength": 0})
}
func (s *Server) mountDesktopRoutes(r chi.Router) {
r.Get("/status", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": "MediaDesktop", "native": true})
})
}
func (s *Server) mountKioskSocket(r chi.Router) {
r.Get("/ws", s.kioskWebsocket)
}
-2
View File
@@ -223,8 +223,6 @@ func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.Desktop:
s.mountDesktopRoutes(r)
}
}
-1
View File
@@ -14,7 +14,6 @@
"build:moderator": "node scripts/build-all.mjs moderator",
"build:kiosk": "node scripts/build-all.mjs kiosk",
"build:servant": "node scripts/build-all.mjs servant",
"build:desktop": "node scripts/build-all.mjs desktop",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"lint": "eslint .",
"format": "prettier --write .",
+1 -2
View File
@@ -5,6 +5,5 @@
"config": { "name": "MediaConfig", "icon": "settings-2" },
"moderator": { "name": "MediaModerator", "icon": "shield-check" },
"kiosk": { "name": "MediaKiosk", "icon": "image" },
"servant": { "name": "MediaServant", "icon": "server" },
"desktop": { "name": "MediaViewer Desktop", "icon": "monitor-play" }
"servant": { "name": "MediaServant", "icon": "server" }
}
-1
View File
@@ -12,7 +12,6 @@ const targets = {
moderator: 'MediaModerator',
kiosk: 'MediaKiosk',
servant: 'MediaServant',
desktop: 'MediaDesktop',
}
const requested = process.argv.slice(2)
-23
View File
@@ -238,29 +238,6 @@ const configs: Record<AppId, AppConfig> = {
},
],
},
desktop: {
id: 'desktop',
name: 'MediaViewer Desktop',
icon: projectIcon('desktop'),
eyebrow: 'Connected player',
description: 'Control playback, funscripts, and connected devices from your desktop.',
nav: [
{
label: 'Player',
panel: 'player',
path: '/',
icon: 'monitor-play',
description: 'Control playback and connected desktop devices.',
},
{
label: 'Devices',
panel: 'devices',
path: '/devices',
icon: 'box',
description: 'Manage connected playback and funscript devices.',
},
],
},
}
export function getAppConfig(id: string): AppConfig {
@@ -1,11 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card, EmptyState, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
@@ -63,14 +59,14 @@
return fallback
}
function statusTone(status: string): 'neutral' | 'primary' | 'success' | 'warning' | 'danger' {
function statusTone(status: string): 'default' | 'primary' | 'success' | 'warning' | 'danger' {
const normalized = status.toLowerCase()
if (normalized.includes('error') || normalized.includes('fail')) return 'danger'
if (normalized.includes('process') || normalized.includes('running')) return 'primary'
if (normalized.includes('queue') || normalized.includes('pending')) return 'warning'
if (normalized.includes('done') || normalized.includes('complete') || normalized.includes('success'))
return 'success'
return 'neutral'
return 'default'
}
async function load({ background = false } = {}) {
@@ -183,7 +179,7 @@
<p class="truncate text-sm font-medium text-fg">{name}</p>
{#if path}<p class="mt-1 truncate text-xs text-muted-fg">{path}</p>{/if}
</div>
<Badge tone={statusTone(status)}>{status}</Badge>
<Badge variant={statusTone(status)}>{status}</Badge>
</div>
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-fg">
{#if entryMediaType}<span>{entryMediaType}</span>{/if}
@@ -1,13 +1,9 @@
<script lang="ts">
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
type Json = Record<string, unknown>
type StatusTone = 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
type StatusTone = 'default' | 'primary' | 'success' | 'warning' | 'danger'
let {
status = {},
@@ -74,7 +70,7 @@
if (running) return paused ? 'warning' : 'primary'
if (label.includes('error') || label.includes('failed')) return 'danger'
if (['idle', 'completed', 'complete', 'done'].includes(label)) return 'success'
return 'neutral'
return 'default'
}
const extractionProgress = $derived(asRecord(status.extractionProgress))
@@ -155,7 +151,7 @@
<div class="flex items-center justify-between gap-3">
<span class="text-sm text-muted-fg">State</span>
<div class="flex items-center gap-2">
<Badge {tone}>{stateLabel}</Badge>
<Badge variant={tone}>{stateLabel}</Badge>
{#if canStop}
<Button variant="danger" size="sm" disabled={stopping} onclick={() => void stopAction()}>
{stopping ? 'Stopping…' : 'Stop'}
@@ -1,6 +1,5 @@
<script lang="ts">
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Card, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
@@ -1,14 +0,0 @@
<script lang="ts">
import { Inbox } from '@lucide/svelte'
let { title, message }: { title: string; message: string } = $props()
</script>
<div
class="flex min-h-40 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface/50 px-5 py-8 text-center"
>
<Inbox class="size-8 text-muted-fg" />
<div>
<p class="text-sm font-medium text-fg">{title}</p>
<p class="mt-1 max-w-sm text-xs text-muted-fg">{message}</p>
</div>
</div>
@@ -1,6 +1,6 @@
<script lang="ts">
import { ArrowDown, ArrowRight, ChevronDown, FileCog, Image as ImageIcon, Search, Sparkles } from '@lucide/svelte'
import Badge from '$lib/components/ui/badge.svelte'
import { Badge } from '@gabriel20xx/web-ui'
import { cn } from '$lib/utils/cn'
type StageStatus = { pending: number; processing: number; processed: number; errors: number; active: boolean }
@@ -220,9 +220,9 @@
<span class="text-sm font-semibold text-fg">Metadata</span>
</div>
{#if metadataStatus.active}
<Badge tone="primary" class="animate-pulse">Active</Badge>
<Badge variant="primary" class="animate-pulse">Active</Badge>
{:else}
<Badge tone="neutral">Idle</Badge>
<Badge>Idle</Badge>
{/if}
</div>
<p class="text-xs text-muted-fg">{metadataDescription}</p>
@@ -249,9 +249,9 @@
<span class="text-sm font-semibold text-fg">Thumbnails</span>
</div>
{#if thumbnailsStatus.active}
<Badge tone="primary" class="animate-pulse">Active</Badge>
<Badge variant="primary" class="animate-pulse">Active</Badge>
{:else}
<Badge tone="neutral">Idle</Badge>
<Badge>Idle</Badge>
{/if}
</div>
<p class="text-xs text-muted-fg">{thumbnailsDescription}</p>
@@ -279,9 +279,9 @@
<span class="text-sm font-semibold text-fg">AI analysis</span>
</div>
{#if analysisStatus.active}
<Badge tone="primary" class="animate-pulse">Active</Badge>
<Badge variant="primary" class="animate-pulse">Active</Badge>
{:else}
<Badge tone="neutral">Idle</Badge>
<Badge>Idle</Badge>
{/if}
</div>
<p class="text-xs text-muted-fg">
@@ -1,10 +0,0 @@
<script lang="ts">
let { title, description = '' }: { title: string; description?: string } = $props()
</script>
<div class="flex items-start justify-between gap-3">
<div>
<h2 class="text-sm font-semibold text-fg">{title}</h2>
{#if description}<p class="mt-1 text-xs text-muted-fg">{description}</p>{/if}
</div>
</div>
@@ -1,6 +1,6 @@
<script lang="ts">
import { Moon, Sun, SunMoon } from '@lucide/svelte'
import Button from '$lib/components/ui/button.svelte'
import { Button, SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/web-ui'
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte'
import { themeState } from '$lib/theme.svelte'
@@ -21,77 +21,62 @@
})
</script>
{#if open}
<div
class="fixed inset-0 z-50 grid place-items-center bg-black/70 p-4 backdrop-blur-sm"
role="presentation"
onclick={(event) => {
if (event.target === event.currentTarget) open = false
}}
>
<div
class="w-full max-w-lg rounded-xl border border-border bg-surface p-6 shadow-xl"
role="dialog"
aria-modal="true"
aria-label="Settings"
tabindex="-1"
>
<div class="flex items-start justify-between gap-4">
<h2 class="text-xl font-semibold">Settings</h2>
<button
class="rounded-md px-2 py-1 text-2xl leading-none text-muted-fg hover:bg-surface-hover hover:text-fg"
<SharedSettingsDialog bind:open title="Settings">
<div class="sc-form">
<div>
<span class="sc-label">Theme</span>
<div class="mediacollection-settings-theme-row">
<Button
type="button"
aria-label="Close"
onclick={() => (open = false)}>×</button
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
size="sm"
fullWidth
onclick={() => themeState.setMode('light')}
>
</div>
<div class="mt-6 space-y-5">
<div>
<span class="mb-2 block text-sm font-medium">Theme</span>
<div class="flex w-full rounded-md border border-border p-1">
<Button
type="button"
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('light')}
>
<Sun class="size-4" />
Light
</Button>
<Button
type="button"
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('dark')}
>
<Moon class="size-4" />
Dark
</Button>
<Button
type="button"
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('system')}
>
<SunMoon class="size-4" />
System
</Button>
</div>
</div>
<label class="block">
<span class="mb-2 block text-sm font-medium">Language</span>
<select class="field" value={currentLanguage()} onchange={(event) => setLanguage(event.currentTarget.value)}>
{#each languageItems as item (item.value)}
<option value={item.value}>{item.label}</option>
{/each}
</select>
</label>
<Sun size={16} />
Light
</Button>
<Button
type="button"
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
size="sm"
fullWidth
onclick={() => themeState.setMode('dark')}
>
<Moon size={16} />
Dark
</Button>
<Button
type="button"
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
size="sm"
fullWidth
onclick={() => themeState.setMode('system')}
>
<SunMoon size={16} />
System
</Button>
</div>
</div>
<label class="sc-field">
<span class="sc-label">Language</span>
<select class="sc-input" value={currentLanguage()} onchange={(event) => setLanguage(event.currentTarget.value)}>
{#each languageItems as item (item.value)}
<option value={item.value}>{item.label}</option>
{/each}
</select>
</label>
</div>
{/if}
</SharedSettingsDialog>
<style>
.mediacollection-settings-theme-row {
display: flex;
width: 100%;
gap: 0.25rem;
padding: 0.25rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
}
</style>
@@ -1,102 +0,0 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle, RefreshCw, X } from '@lucide/svelte'
import Button from '$lib/components/ui/button.svelte'
import type { StatusProbe, StatusSnapshot } from '$lib/status'
let {
open = $bindable(false),
status,
onRefresh,
}: {
open?: boolean
status: StatusSnapshot
onRefresh: () => Promise<void>
} = $props()
const levelLabel = {
checking: 'Checking',
healthy: 'Healthy',
degraded: 'Degraded',
offline: 'Offline',
}
const levelClass = {
checking: 'text-muted-fg',
healthy: 'text-success',
degraded: 'text-warning',
offline: 'text-danger',
}
function probeLabel(probe: StatusProbe | null) {
if (!probe) return 'Not checked'
if (probe.ok) return 'OK'
if (probe.error) return probe.error
return probe.httpStatus ? `HTTP ${probe.httpStatus}` : 'Unavailable'
}
</script>
{#if open}
<div
class="fixed inset-0 z-50 grid place-items-center bg-black/70 px-4"
role="presentation"
onclick={(event) => event.target === event.currentTarget && (open = false)}
>
<div
class="w-full max-w-lg rounded-xl border border-border bg-bg p-6 text-fg shadow-2xl"
role="dialog"
aria-modal="true"
aria-labelledby="status-dialog-title"
>
<div class="mb-5 flex items-start justify-between gap-3">
<div>
<h2 id="status-dialog-title" class="text-xl font-semibold">Service status</h2>
<p class="mt-1 text-sm text-muted-fg">Live liveness and database readiness checks.</p>
</div>
<Button variant="ghost" size="icon" aria-label="Close" onclick={() => (open = false)}>
<X class="size-4" />
</Button>
</div>
<div class="mb-5 flex items-center gap-3 rounded-lg border border-border bg-surface p-3" aria-live="polite">
{#if status.loading && status.level === 'checking'}
<LoaderCircle class="size-5 animate-spin text-muted-fg" />
{:else if status.level === 'healthy'}
<CheckCircle2 class="size-5 text-success" />
{:else if status.level === 'degraded'}
<AlertTriangle class="size-5 text-warning" />
{:else if status.level === 'offline'}
<AlertCircle class="size-5 text-danger" />
{:else}
<CircleHelp class="size-5 text-muted-fg" />
{/if}
<span class={`font-medium ${levelClass[status.level]}`}>{levelLabel[status.level]}</span>
{#if status.checkedAt}
<span class="ml-auto text-xs text-muted-fg">{new Date(status.checkedAt).toLocaleTimeString()}</span>
{/if}
</div>
<div class="space-y-2 text-sm">
{#each [{ label: 'Liveness', probe: status.health }, { label: 'Readiness / database', probe: status.readiness }] as item (item.label)}
<div class="flex items-center justify-between gap-4 rounded-md border border-border px-3 py-2">
<span>{item.label}</span>
<span class={item.probe?.ok ? 'text-success' : 'text-danger'}>{probeLabel(item.probe)}</span>
</div>
{/each}
</div>
{#if status.health?.service || status.readiness?.service}
<p class="mt-4 text-xs text-muted-fg">
Service: {status.health?.service || status.readiness?.service}
</p>
{/if}
<div class="mt-6 flex justify-end gap-2">
<Button variant="outline" disabled={status.loading} onclick={() => void onRefresh()}>
<RefreshCw class={status.loading ? 'animate-spin' : ''} />
Refresh
</Button>
<Button variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
</div>
</div>
</div>
{/if}
@@ -1,97 +0,0 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle } from '@lucide/svelte'
import { onMount } from 'svelte'
import Button from '$lib/components/ui/button.svelte'
import StatusDialog from '$lib/components/StatusDialog.svelte'
import type { StatusProbe, StatusSnapshot } from '$lib/status'
const initialStatus: StatusSnapshot = {
level: 'checking',
health: null,
readiness: null,
checkedAt: null,
loading: false,
}
let status = $state<StatusSnapshot>(initialStatus)
let open = $state(false)
let requestInFlight = false
async function probe(path: string): Promise<StatusProbe> {
try {
const response = await fetch(path, {
credentials: 'include',
headers: { Accept: 'application/json' },
})
const payload = (await response.json().catch(() => null)) as {
ok?: boolean
service?: string
error?: string
} | null
return {
path,
ok: response.ok && payload?.ok !== false,
httpStatus: response.status,
service: payload?.service || null,
error: response.ok ? null : payload?.error || response.statusText || `HTTP ${response.status}`,
}
} catch (error) {
return {
path,
ok: false,
httpStatus: null,
service: null,
error: error instanceof Error ? error.message : 'Unavailable',
}
}
}
async function refresh() {
if (requestInFlight) return
requestInFlight = true
status = { ...status, loading: true, level: status.health || status.readiness ? status.level : 'checking' }
try {
const [health, readiness] = await Promise.all([probe('/healthz'), probe('/ready')])
const level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline'
status = {
level,
health,
readiness,
checkedAt: new Date().toISOString(),
loading: false,
}
} finally {
requestInFlight = false
if (status.loading) status = { ...status, loading: false }
}
}
onMount(() => {
void refresh()
const timer = window.setInterval(() => void refresh(), 15_000)
return () => window.clearInterval(timer)
})
</script>
<Button
variant="ghost"
size="icon"
aria-label="Service status"
title={`Service status: ${status.level}`}
onclick={() => (open = true)}
>
{#if status.loading && status.level === 'checking'}
<LoaderCircle class="size-5 animate-spin text-muted-fg" />
{:else if status.level === 'healthy'}
<CheckCircle2 class="size-5 text-success" />
{:else if status.level === 'degraded'}
<AlertTriangle class="size-5 text-warning" />
{:else if status.level === 'offline'}
<AlertCircle class="size-5 text-danger" />
{:else}
<CircleHelp class="size-5 text-muted-fg" />
{/if}
</Button>
<StatusDialog bind:open {status} onRefresh={refresh} />
@@ -3,7 +3,6 @@
import { getAppConfig, getPanelForPath, getPathForPanel } from '$lib/app-config'
import AnalyzerWorkspace from '$lib/features/AnalyzerWorkspace.svelte'
import ConfigWorkspace from '$lib/features/ConfigWorkspace.svelte'
import DesktopWorkspace from '$lib/features/DesktopWorkspace.svelte'
import FeedWorkspace from '$lib/features/FeedWorkspace.svelte'
import KioskWorkspace from '$lib/features/KioskWorkspace.svelte'
import MediaTypePipeline from '$lib/features/MediaTypePipeline.svelte'
@@ -82,6 +81,4 @@
<KioskWorkspace {panel} />
{:else if app.id === 'servant'}
<ServantWorkspace {panel} />
{:else}
<DesktopWorkspace {panel} />
{/if}
@@ -1,32 +0,0 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements'
import { cn } from '$lib/utils/cn'
let {
class: className,
tone = 'neutral',
children,
...rest
}: HTMLAttributes<HTMLSpanElement> & {
tone?: 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
children?: import('svelte').Snippet
} = $props()
const toneClasses = {
neutral: 'border-border bg-surface-hover text-muted-fg',
primary: 'border-primary/30 bg-primary/15 text-primary',
success: 'border-success/30 bg-success/15 text-success',
warning: 'border-warning/30 bg-warning/15 text-warning',
danger: 'border-danger/30 bg-danger/15 text-danger',
}
</script>
<span
class={cn(
'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
toneClasses[tone],
className,
)}
{...rest}
>
{@render children?.()}
</span>
@@ -1,43 +0,0 @@
<script lang="ts">
import { cva, type VariantProps } from 'class-variance-authority'
import type { HTMLButtonAttributes } from 'svelte/elements'
import { cn } from '$lib/utils/cn'
export const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-primary text-primary-fg hover:opacity-90',
secondary: 'border border-border bg-surface text-fg hover:bg-surface-hover',
outline: 'border border-border bg-transparent text-fg hover:bg-surface-hover',
ghost: 'text-fg hover:bg-surface-hover',
danger: 'bg-danger text-danger-fg hover:opacity-90',
success: 'bg-success text-success-fg hover:opacity-90',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-6',
icon: 'h-9 w-9',
},
},
defaultVariants: { variant: 'default', size: 'default' },
},
)
type Variant = VariantProps<typeof buttonVariants>
let {
class: className,
variant = 'default',
size = 'default',
type = 'button',
children,
...rest
}: HTMLButtonAttributes & Variant & { children?: import('svelte').Snippet } = $props()
</script>
<button {type} class={cn(buttonVariants({ variant, size }), className)} {...rest}>
{@render children?.()}
</button>
@@ -1,14 +0,0 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements'
import { cn } from '$lib/utils/cn'
let {
class: className,
children,
...rest
}: HTMLAttributes<HTMLDivElement> & { children?: import('svelte').Snippet } = $props()
</script>
<div class={cn('rounded-lg border border-border bg-surface p-4 shadow-sm', className)} {...rest}>
{@render children?.()}
</div>
@@ -1,32 +0,0 @@
<script lang="ts">
import { cn } from '$lib/utils/cn'
let {
label,
value,
detail = '',
tone = 'default',
}: {
label: string
value: string | number
detail?: string
tone?: 'default' | 'primary' | 'success' | 'warning' | 'danger'
} = $props()
</script>
<div class="rounded-lg border border-border bg-surface p-4">
<p class="text-xs font-medium uppercase tracking-wider text-muted-fg">{label}</p>
<p
class={cn(
'mt-2 text-2xl font-semibold tracking-tight',
tone === 'primary' && 'text-primary',
tone === 'success' && 'text-success',
tone === 'warning' && 'text-warning',
tone === 'danger' && 'text-danger',
tone === 'default' && 'text-fg',
)}
>
{value}
</p>
{#if detail}<p class="mt-1 text-xs text-muted-fg">{detail}</p>{/if}
</div>
@@ -2,17 +2,11 @@
import { AlertTriangle, Play, Plus, RefreshCw, Trash2 } from '@lucide/svelte'
import { onMount } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { del, get, post } from '$lib/api'
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
import AnalyzerLiveStatus from '$lib/components/AnalyzerLiveStatus.svelte'
import AnalyzerPipelineBreakdown from '$lib/components/AnalyzerPipelineBreakdown.svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
import { cn } from '$lib/utils/cn'
type Json = Record<string, unknown>
@@ -407,18 +401,18 @@
label="Pending"
value={numeric('queued', numeric('queueLength'))}
detail="Waiting for a worker"
tone="warning"
variant="warning"
/><Metric
label="Processing"
value={numeric('processing', numeric('activeJobs'))}
detail="Active jobs"
tone="primary"
variant="primary"
/><Metric
label="Completed"
value={numeric('completed', numeric('processed'))}
detail="Current history window"
tone="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" tone="danger" />
variant="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" variant="danger" />
</div>
<AnalyzerPipelineBreakdown pipeline={asRecord(stats.pipeline)} />
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
@@ -476,18 +470,18 @@
label="Pending"
value={numeric('queued', numeric('queueLength'))}
detail="Waiting for a worker"
tone="warning"
variant="warning"
/><Metric
label="Processing"
value={numeric('processing', numeric('activeJobs'))}
detail="Active jobs"
tone="primary"
variant="primary"
/><Metric
label="Completed"
value={numeric('completed', numeric('processed'))}
detail="Current history window"
tone="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" tone="danger" />
variant="success"
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" variant="danger" />
</div>
<AnalyzerLiveStatus {status} {stats} {loading} description="Current analyzer schedule and worker state." />
<Card class="space-y-5"
@@ -567,7 +561,7 @@
</p>{/if}
</div>
<div class="flex shrink-0 items-center gap-2">
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
<Badge variant={schedule.enabled === false ? 'default' : 'success'}
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
><Button variant="outline" size="sm" onclick={() => void runScheduleNow(String(schedule.id))}
>Run now</Button
@@ -14,17 +14,12 @@
Trash2,
} from '@lucide/svelte'
import { onDestroy, onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import { pageActions } from '$lib/stores/page-actions.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
type Json = Record<string, unknown>
type StatusTone = 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
type StatusTone = 'default' | 'primary' | 'success' | 'warning' | 'danger'
type ConnectionStatus = { label: string; tone: StatusTone; title?: string }
type MountEntry = { type: string; path: string }
type TransferLimit = { uploadKbps: string; downloadKbps: string }
@@ -584,7 +579,7 @@
}
function statusFor(key: string): ConnectionStatus {
return statuses[key] || { label: 'Unknown', tone: 'neutral' }
return statuses[key] || { label: 'Unknown', tone: 'default' }
}
async function checkTarget(key: string, rawUrl: string, project: string | null, id: string) {
@@ -593,7 +588,7 @@
urls = { ...urls, [id]: url }
}
if (!url) {
statuses = { ...statuses, [key]: { label: 'No URL', tone: 'neutral' } }
statuses = { ...statuses, [key]: { label: 'No URL', tone: 'default' } }
return
}
@@ -845,7 +840,7 @@
<p class="mt-1 text-xs text-muted-fg">The image-generation service used by MediaTools.</p>
</div>
<div class="flex items-center gap-2">
<Badge tone={statusFor('comfyui').tone} title={statusFor('comfyui').title}
<Badge variant={statusFor('comfyui').tone} title={statusFor('comfyui').title}
>{statusFor('comfyui').label}</Badge
>
<Button variant="secondary" size="sm" onclick={() => void checkConnection('comfyui')}>Check</Button>
@@ -883,7 +878,7 @@
{connection.label || `External Connection ${index + 1}`}
</p>
<Badge
tone={statusFor(`external:${connection.id}`).tone}
variant={statusFor(`external:${connection.id}`).tone}
title={statusFor(`external:${connection.id}`).title}
>
{statusFor(`external:${connection.id}`).label}
@@ -1007,13 +1002,13 @@
<div class="flex items-center gap-2">
<p class="text-sm font-semibold text-fg">{labels.mediaconfig || 'MediaConfig'}</p>
{#if labels.mediaconfig}<span class="text-xs text-muted-fg">(MediaConfig)</span>{/if}
<Badge tone={statusFor('mediaconfig').tone} title={statusFor('mediaconfig').title}
<Badge variant={statusFor('mediaconfig').tone} title={statusFor('mediaconfig').title}
>{statusFor('mediaconfig').label}</Badge
>
</div>
<div class="flex items-center gap-2">
<Button variant="secondary" size="sm" onclick={() => void checkConnection('mediaconfig')}>Check</Button>
<Badge tone="primary"><Check class="size-3" />Self</Badge>
<Badge variant="primary"><Check class="size-3" />Self</Badge>
</div>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
@@ -1068,7 +1063,7 @@
{#if labels[projectKey(project)]}<span class="text-xs text-muted-fg"
>({getInstanceLabel(project)})</span
>{/if}
<Badge tone={statusFor(projectKey(project)).tone} title={statusFor(projectKey(project)).title}
<Badge variant={statusFor(projectKey(project)).tone} title={statusFor(projectKey(project)).title}
>{statusFor(projectKey(project)).label}</Badge
>
</div>
@@ -1167,7 +1162,7 @@
<div class="flex min-w-0 flex-wrap items-center gap-2">
<p class="truncate text-sm font-semibold text-fg">{labels[key] || getInstanceLabel(project)}</p>
{#if labels[key]}<span class="text-xs text-muted-fg">({getInstanceLabel(project)})</span>{/if}
<Badge tone={statusFor(key).tone} title={statusFor(key).title}>{statusFor(key).label}</Badge>
<Badge variant={statusFor(key).tone} title={statusFor(key).title}>{statusFor(key).label}</Badge>
</div>
</div>
<div class="flex shrink-0 items-center gap-1">
@@ -1,99 +0,0 @@
<script lang="ts">
import { Bluetooth, Cable, CheckCircle2, MonitorPlay, Settings2, SlidersHorizontal } from '@lucide/svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
let { panel = 'player' }: { panel?: string } = $props()
</script>
<div class="space-y-4">
{#if panel === 'devices'}
<div class="grid gap-4 lg:grid-cols-2">
<Card class="space-y-5"
><SectionTitle title="Device connections" description="Connect hardware through the native desktop bridge." />
<div class="space-y-3">
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<Cable class="size-4 text-primary" />
<div class="flex-1">
<p class="text-sm font-medium text-fg">Serial / TCode</p>
<p class="text-xs text-muted-fg">Waiting for a local driver</p>
</div>
<Badge>Offline</Badge>
</div>
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<Bluetooth class="size-4 text-primary" />
<div class="flex-1">
<p class="text-sm font-medium text-fg">Bluetooth devices</p>
<p class="text-xs text-muted-fg">Native discovery is available after launch</p>
</div>
<Badge>Offline</Badge>
</div>
</div></Card
><Card class="space-y-5"
><SectionTitle
title="Safety"
description="The desktop client keeps device output disabled until a connection is explicitly enabled."
/>
<div class="flex items-start gap-3 rounded-md border border-success/25 bg-success/10 p-3">
<CheckCircle2 class="mt-0.5 size-4 text-success" />
<p class="text-sm leading-6 text-fg">
No device is currently receiving output. Connect a driver from the native controls to enable playback
synchronization.
</p>
</div></Card
>
</div>
{:else if panel === 'settings'}
<Card class="space-y-5"
><SectionTitle
title="Application preferences"
description="Native renderer settings remain available from the desktop client bridge."
/>
<div class="grid gap-4 sm:grid-cols-2">
<label class="space-y-2 text-sm"
><span class="font-medium text-fg">Theme</span><select class="field"
><option>System</option><option>Dark</option><option>Light</option></select
></label
><label class="space-y-2 text-sm"
><span class="font-medium text-fg">Control mode</span><select class="field"
><option>Local player</option><option>Remote player</option></select
></label
>
</div>
<Button variant="secondary"><Settings2 class="size-4" />Open native preferences</Button></Card
>
{:else}
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_340px]">
<Card class="space-y-5"
><SectionTitle
title="Embedded player"
description="The desktop shell embeds MediaViewer when a server is connected."
/>
<div class="flex min-h-[420px] items-center justify-center rounded-lg border border-dashed border-border bg-bg">
<EmptyState
title="Connect a MediaViewer server"
message="Enter a server URL in the native desktop panel to load the library and player."
/>
</div></Card
><Card class="space-y-5"
><SectionTitle
title="Playback status"
description="The native bridge reports the active media and sync state here."
/>
<div class="space-y-3">
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
<MonitorPlay class="size-4 text-primary" />
<div>
<p class="text-sm font-medium text-fg">No active media</p>
<p class="text-xs text-muted-fg">Player status will appear after connection.</p>
</div>
</div>
<Button variant="secondary" class="w-full"><SlidersHorizontal class="size-4" />Open player controls</Button>
</div></Card
>
</div>
{/if}
</div>
@@ -2,10 +2,7 @@
import { page } from '$app/state'
import { Film, Music2, Play } from '@lucide/svelte'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card, EmptyState } from '@gabriel20xx/web-ui'
interface FeedItem {
mediaKey?: string
@@ -104,7 +101,7 @@
{item.title || item.name || item.filename || 'Untitled media'}
</p>
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-fg">
{#if item.mediaType}<Badge tone="neutral">{item.mediaType}</Badge>{/if}
{#if item.mediaType}<Badge>{item.mediaType}</Badge>{/if}
{#if item.category}<span>{item.category}</span>{/if}
{#if item.filename}<span class="truncate">{item.filename}</span>{/if}
</div>
@@ -2,11 +2,7 @@
import { Maximize2, Pause, Play, Settings2, Wifi, WifiOff } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import { Badge, Button, Card, Metric, SectionTitle } from '@gabriel20xx/web-ui'
type KioskConfig = {
defaultDisplayDuration?: number
@@ -126,7 +122,7 @@
class="flex flex-wrap justify-end gap-2"
aria-label={panel === 'kiosk' ? 'Kiosk controls' : 'Kiosk display controls'}
>
<Badge tone={connected ? 'success' : 'warning'}
<Badge variant={connected ? 'success' : 'warning'}
>{#if connected}<Wifi class="mr-1 size-3" />Connected{:else}<WifiOff class="mr-1 size-3" />Waiting{/if}</Badge
>
<Button variant="secondary" size="sm" onclick={() => void fullscreen()}
@@ -137,7 +133,7 @@
{error}
</div>{/if}
<div class="grid gap-4 sm:grid-cols-3">
<Metric label="Queue" value={queueLength} detail="Images waiting to display" tone="primary" /><Metric
<Metric label="Queue" value={queueLength} detail="Images waiting to display" variant="primary" /><Metric
label="Display time"
value={durationLabel}
detail="Current server interval"
@@ -2,14 +2,10 @@
import { AlertTriangle, Play, RefreshCw, Trash2 } from '@lucide/svelte'
import { onDestroy, onMount } from 'svelte'
import { SvelteSet } from 'svelte/reactivity'
import { notify } from '@gabriel20xx/web-ui'
import { Button, Card, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
import PipelineFlowDiagram from '$lib/components/PipelineFlowDiagram.svelte'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import { cn } from '$lib/utils/cn'
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
@@ -412,7 +408,7 @@
label="Errors"
value={stageSummaries.reduce((sum, stage) => sum + stage.errors, 0)}
detail="Needs attention"
tone="danger"
variant="danger"
/>
</div>
@@ -1,14 +1,8 @@
<script lang="ts">
import { BarChart3, Check, Pencil, ShieldCheck, Trash2, UserCheck, Users } from '@lucide/svelte'
import { onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post, put } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
interface UserRow {
id: string | number
@@ -183,11 +177,11 @@
<Metric label="Users" value={users.length} detail="Loaded from admin catalog" /><Metric
label="Active users"
value={users.filter((user) => !user.disabled).length}
tone="success"
variant="success"
/><Metric label="Media records" value={media.length} detail="Catalog window" /><Metric
label="Flagged / inactive"
value={media.filter((item) => item.active === false).length}
tone="warning"
variant="warning"
/>
</div>
<div class="grid gap-4 lg:grid-cols-2">
@@ -231,7 +225,7 @@
</div>
</div>
<div class="flex flex-wrap gap-2 border-y border-border py-3">
<Badge tone="primary">{selectedUsers.length} selected</Badge><Button
<Badge variant="primary">{selectedUsers.length} selected</Badge><Button
size="sm"
variant="secondary"
disabled={!selectedUsers.length}
@@ -329,11 +323,11 @@
><p class="text-sm font-medium text-fg">{user.username || user.email || `User ${user.id}`}</p>
<p class="mt-1 text-xs text-muted-fg">{user.email || 'No email'}</p></td
><td class="py-3"
><Badge tone={user.role === 'admin' || user.role === 'superadmin' ? 'primary' : 'neutral'}
><Badge variant={user.role === 'admin' || user.role === 'superadmin' ? 'primary' : 'default'}
>{user.role || 'user'}</Badge
></td
><td class="py-3"
><Badge tone={user.disabled ? 'danger' : 'success'}>{user.disabled ? 'Disabled' : 'Active'}</Badge
><Badge variant={user.disabled ? 'danger' : 'success'}>{user.disabled ? 'Disabled' : 'Active'}</Badge
></td
><td class="py-3 text-xs text-muted-fg">{user.mfaEnabled ? 'MFA enabled' : 'MFA not enabled'}</td><td
class="py-3 text-right"
@@ -445,7 +439,7 @@
</div>
</div>
<div class="flex flex-wrap gap-2 border-y border-border py-3">
<Badge tone="primary">{selectedMedia.length} selected</Badge><Button
<Badge variant="primary">{selectedMedia.length} selected</Badge><Button
size="sm"
variant="secondary"
disabled={!selectedMedia.length}
@@ -489,7 +483,7 @@
><td class="py-3 text-xs text-muted-fg">{item.source || '—'}</td><td
class="py-3 text-xs text-muted-fg">{item.generatorUsername || '—'}</td
><td class="py-3"
><Badge tone={item.active === false ? 'danger' : 'success'}
><Badge variant={item.active === false ? 'danger' : 'success'}
>{item.active === false ? 'Hidden' : 'Visible'}</Badge
></td
></tr
@@ -2,11 +2,7 @@
import { Database, FileClock, FolderOpen, HardDrive, Server, ShieldAlert } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
import { Badge, Card, EmptyState, Metric, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
type FileRow = { rel?: string; name?: string; path?: string; mtime?: number; size?: number; type?: string }
@@ -92,7 +88,7 @@
label="Requests"
value={value(stats, 'requests', 'totalRequests')}
detail="Tracked requests"
tone="primary"
variant="primary"
/><Metric
label="Active mounts"
value={value(mounts, 'count', 'total', 'active')}
@@ -101,7 +97,7 @@
label="Bytes out"
value={formatBytes(bandwidth.bytesOut || bandwidth.egress)}
detail="Current tracker window"
tone="success"
variant="success"
/><Metric label="Updated" value={lastUpdated || '--'} detail={loading ? 'Refreshing' : 'Live snapshot'} />
</div>
@@ -150,7 +146,7 @@
</p>
</div>
</div>
<Badge tone="success">Mapped</Badge>
<Badge variant="success">Mapped</Badge>
</div>{/each}
</div>{/if}</Card
><Card class="space-y-5"
@@ -3,10 +3,7 @@
import { ArrowLeft, ChevronLeft, ChevronRight, Image, Search, Tags as TagsIcon } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card, EmptyState } from '@gabriel20xx/web-ui'
interface TagSummary {
tag: string
@@ -169,7 +166,7 @@
{:else}
<Image class="size-10 text-muted-fg" />
{/if}
{#if media.mediaType}<Badge tone="neutral" class="absolute left-2 top-2">{media.mediaType}</Badge>{/if}
{#if media.mediaType}<Badge class="absolute left-2 top-2">{media.mediaType}</Badge>{/if}
</div>
<div class="p-3">
<p class="truncate text-sm font-medium text-fg">{media.name || media.filename || 'Untitled media'}</p>
@@ -1,14 +1,8 @@
<script lang="ts">
import { Activity, ArrowRight, CheckCircle2, CloudDownload, Film, Upload, WandSparkles, X } from '@lucide/svelte'
import { onMount } from 'svelte'
import { notify } from '@gabriel20xx/web-ui'
import { Badge, Button, Card, EmptyState, Metric, notify, SectionTitle } from '@gabriel20xx/web-ui'
import { get, post } from '$lib/api'
import SectionTitle from '$lib/components/SectionTitle.svelte'
import Card from '$lib/components/ui/card.svelte'
import Button from '$lib/components/ui/button.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import Metric from '$lib/components/ui/metric.svelte'
import EmptyState from '$lib/components/EmptyState.svelte'
type Json = Record<string, unknown>
@@ -258,7 +252,7 @@
label="Active queue"
value={queue.length}
detail="Waiting or running"
tone={queue.length ? 'warning' : 'default'}
variant={queue.length ? 'warning' : 'default'}
/><Metric label="Recent jobs" value={jobs.length} detail="Retained workflow history" /><Metric
label="Schedules"
value={schedules.length}
@@ -286,7 +280,7 @@
<div>
<div class="flex items-center gap-2">
<p class="text-sm font-medium text-fg">{schedule.name || schedule.tool || 'Workflow schedule'}</p>
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
<Badge variant={schedule.enabled === false ? 'default' : 'success'}
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
>
</div>
@@ -456,7 +450,7 @@
<div class="flex items-center justify-between gap-2">
<p class="truncate text-sm font-medium text-fg">{job.tool || 'workflow'}</p>
<Badge
tone={job.status === 'completed' || job.status === 'complete'
variant={job.status === 'completed' || job.status === 'complete'
? 'success'
: job.status === 'error'
? 'danger'
@@ -2,9 +2,7 @@
import { ArrowLeft, Film, Maximize2, Minimize2, Pause, Play, Wifi, WifiOff } from '@lucide/svelte'
import { onMount } from 'svelte'
import { get } from '$lib/api'
import Badge from '$lib/components/ui/badge.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import { Badge, Button, Card } from '@gabriel20xx/web-ui'
type SyncMode = 'none' | 'local' | 'master' | 'slave'
@@ -770,9 +768,9 @@
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT" />
</video>
<div class="absolute left-3 top-3 z-10 flex flex-wrap gap-2">
{#if info.isVr}<Badge tone="primary">VR</Badge>{/if}
{#if hasFunscript}<Badge tone="success">Funscript</Badge>{/if}
{#if syncMode === 'slave'}<Badge tone="warning">Slave</Badge>{/if}
{#if info.isVr}<Badge variant="primary">VR</Badge>{/if}
{#if hasFunscript}<Badge variant="success">Funscript</Badge>{/if}
{#if syncMode === 'slave'}<Badge variant="warning">Slave</Badge>{/if}
</div>
{#if graphPath}
<div
@@ -836,7 +834,7 @@
<h2 class="text-sm font-medium text-fg">Funscript Info</h2>
<p class="mt-1 text-xs text-muted-fg">Action data and playback position for this video.</p>
</div>
{#if hasFunscript}<Badge tone="success">Available</Badge>{:else}<Badge tone="neutral">None</Badge>{/if}
{#if hasFunscript}<Badge variant="success">Available</Badge>{:else}<Badge>None</Badge>{/if}
</div>
{#if hasFunscript}
<div class="grid gap-2 sm:grid-cols-2">
@@ -954,8 +952,8 @@
<h2 class="text-sm font-medium text-fg">Sync Info</h2>
<p class="mt-1 text-xs text-muted-fg">Connect this player to other MediaViewer endpoints.</p>
</div>
{#if syncConnected}<Badge tone="success"><Wifi class="mr-1 size-3" />Connected</Badge>{:else}<Badge
tone="warning"><WifiOff class="mr-1 size-3" />Disconnected</Badge
{#if syncConnected}<Badge variant="success"><Wifi class="mr-1 size-3" />Connected</Badge>{:else}<Badge
variant="warning"><WifiOff class="mr-1 size-3" />Disconnected</Badge
>{/if}
</div>
@@ -5,10 +5,7 @@
import { onMount } from 'svelte'
import { SvelteURLSearchParams } from 'svelte/reactivity'
import { get } from '$lib/api'
import EmptyState from '$lib/components/EmptyState.svelte'
import Button from '$lib/components/ui/button.svelte'
import Card from '$lib/components/ui/card.svelte'
import Badge from '$lib/components/ui/badge.svelte'
import { Badge, Button, Card, EmptyState } from '@gabriel20xx/web-ui'
interface MediaItem {
id: string
@@ -279,7 +276,7 @@
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-fg">Filters</p>
{#if activeFilterCount() > 0}<Badge tone="primary">{activeFilterCount()} active</Badge>{/if}
{#if activeFilterCount() > 0}<Badge variant="primary">{activeFilterCount()} active</Badge>{/if}
</div>
<p class="mt-1 text-xs text-muted-fg">
{activeFilterCount() > 0
@@ -462,8 +459,8 @@
/>{:else}<div class="flex h-full items-center justify-center text-muted-fg">
{#if item.mediaType === 'audio'}<Music2 class="size-10" />{:else}<Film class="size-10" />{/if}
</div>{/if}
<span class="absolute left-2 top-2"><Badge tone="neutral">{item.mediaType}</Badge></span>
{#if item.isVr}<span class="absolute right-2 top-2"><Badge tone="primary">VR</Badge></span>{/if}
<span class="absolute left-2 top-2"><Badge>{item.mediaType}</Badge></span>
{#if item.isVr}<span class="absolute right-2 top-2"><Badge variant="primary">VR</Badge></span>{/if}
<span class="absolute bottom-2 right-2 rounded bg-black/70 px-1.5 py-0.5 text-[11px] text-white"
>{formatDuration(item.durationMs)}</span
>
-17
View File
@@ -1,17 +0,0 @@
export type StatusLevel = 'checking' | 'healthy' | 'degraded' | 'offline'
export interface StatusProbe {
path: string
ok: boolean
httpStatus: number | null
service: string | null
error: string | null
}
export interface StatusSnapshot {
level: StatusLevel
health: StatusProbe | null
readiness: StatusProbe | null
checkedAt: string | null
loading: boolean
}
+1 -1
View File
@@ -1,4 +1,4 @@
export type AppId = 'viewer' | 'tools' | 'analyzer' | 'config' | 'moderator' | 'kiosk' | 'servant' | 'desktop'
export type AppId = 'viewer' | 'tools' | 'analyzer' | 'config' | 'moderator' | 'kiosk' | 'servant'
export type ProjectIconName =
'image' | 'monitor-play' | 'play' | 'scan-search' | 'server' | 'settings-2' | 'shield-check' | 'wand-sparkles'
@@ -1,19 +1,21 @@
<script lang="ts">
import type { HTMLAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte';
type BadgeVariant = 'default' | 'success' | 'warning' | 'danger';
type BadgeVariant = 'default' | 'primary' | 'success' | 'warning' | 'danger';
let {
children,
class: className = '',
variant = 'default'
}: {
variant = 'default',
...rest
}: Omit<HTMLAttributes<HTMLSpanElement>, 'class'> & {
children?: Snippet;
class?: string;
variant?: BadgeVariant;
} = $props();
</script>
<span class={`sc-badge ${className}`} data-variant={variant}>
<span class={`sc-badge ${className}`} data-variant={variant} {...rest}>
{@render children?.()}
</span>
@@ -1,8 +1,9 @@
<script lang="ts">
import type { HTMLButtonAttributes } from 'svelte/elements';
import type { Snippet } from 'svelte';
type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg';
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg' | 'icon';
let {
children,
@@ -12,8 +13,9 @@
onclick,
size = 'md',
type = 'button',
variant = 'primary'
}: {
variant = 'primary',
...rest
}: Omit<HTMLButtonAttributes, 'class' | 'disabled' | 'onclick' | 'type'> & {
children?: Snippet;
class?: string;
disabled?: boolean;
@@ -30,6 +32,7 @@
{disabled}
{onclick}
{type}
{...rest}
>
{@render children?.()}
</button>
@@ -0,0 +1,13 @@
<script lang="ts">
import { Inbox } from '@lucide/svelte';
let { title, message }: { title: string; message: string } = $props();
</script>
<div class="sc-empty-state">
<Inbox aria-hidden="true" class="sc-empty-state-icon" size={32} />
<div>
<p class="sc-empty-state-title">{title}</p>
<p class="sc-empty-state-message">{message}</p>
</div>
</div>
@@ -0,0 +1,21 @@
<script lang="ts">
type MetricVariant = 'default' | 'primary' | 'success' | 'warning' | 'danger';
let {
detail = '',
label,
value,
variant = 'default'
}: {
detail?: string;
label: string;
value: string | number;
variant?: MetricVariant;
} = $props();
</script>
<div class="sc-metric">
<p class="sc-metric-label">{label}</p>
<p class="sc-metric-value" data-variant={variant}>{value}</p>
{#if detail}<p class="sc-metric-detail">{detail}</p>{/if}
</div>
@@ -0,0 +1,8 @@
<script lang="ts">
let { title, description = '' }: { title: string; description?: string } = $props();
</script>
<div class="sc-section-title">
<h2>{title}</h2>
{#if description}<p class="sc-muted">{description}</p>{/if}
</div>
@@ -0,0 +1,71 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle, RefreshCw } from '@lucide/svelte';
import Button from './Button.svelte';
import Dialog from './Dialog.svelte';
import type { StatusProbe, StatusSnapshot } from '../types';
let {
onRefresh,
open = $bindable(false),
status
}: {
onRefresh: () => void | Promise<void>;
open?: boolean;
status: StatusSnapshot;
} = $props();
const levelLabel: Record<StatusSnapshot['level'], string> = {
checking: 'Checking',
healthy: 'Healthy',
degraded: 'Degraded',
offline: 'Offline'
};
function probeLabel(probe: StatusProbe | null): string {
if (!probe) return 'Not checked';
if (probe.ok) return 'OK';
if (probe.error) return probe.error;
return probe.httpStatus ? `HTTP ${probe.httpStatus}` : 'Unavailable';
}
</script>
<Dialog bind:open description="Live liveness and database readiness checks." title="Service status">
<div aria-live="polite" class="sc-status-summary" data-level={status.level}>
{#if status.loading && status.level === 'checking'}
<LoaderCircle aria-hidden="true" class="sc-status-icon sc-status-spin" size={20} />
{:else if status.level === 'healthy'}
<CheckCircle2 aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'degraded'}
<AlertTriangle aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'offline'}
<AlertCircle aria-hidden="true" class="sc-status-icon" size={20} />
{:else}
<CircleHelp aria-hidden="true" class="sc-status-icon" size={20} />
{/if}
<span class="sc-status-summary-label">{levelLabel[status.level]}</span>
{#if status.checkedAt}
<span class="sc-status-summary-time">{new Date(status.checkedAt).toLocaleTimeString()}</span>
{/if}
</div>
<div class="sc-status-probes">
{#each [{ label: 'Liveness', probe: status.health }, { label: 'Readiness / database', probe: status.readiness }] as item (item.label)}
<div class="sc-status-probe">
<span>{item.label}</span>
<span data-ok={item.probe?.ok ?? false}>{probeLabel(item.probe)}</span>
</div>
{/each}
</div>
{#if status.health?.service || status.readiness?.service}
<p class="sc-muted sc-status-service">Service: {status.health?.service || status.readiness?.service}</p>
{/if}
{#snippet footer()}
<Button disabled={status.loading} variant="outline" onclick={() => void onRefresh()}>
<RefreshCw aria-hidden="true" class={status.loading ? 'sc-status-spin' : ''} size={16} />
Refresh
</Button>
<Button variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
{/snippet}
</Dialog>
@@ -0,0 +1,103 @@
<script lang="ts">
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle } from '@lucide/svelte';
import { onMount } from 'svelte';
import Button from './Button.svelte';
import StatusDialog from './StatusDialog.svelte';
import type { StatusProbe, StatusSnapshot } from '../types';
// Polls this service's own /healthz (liveness) and /ready (readiness,
// typically including a database check) endpoints - the convention every
// Go/Node/Python backend in this workspace already serves - and shows the
// combined result as a small header icon that opens StatusDialog for
// detail on click. Both paths are relative, so this widget can drop into
// any app without configuration as long as it follows that convention.
const initialStatus: StatusSnapshot = {
level: 'checking',
health: null,
readiness: null,
checkedAt: null,
loading: false
};
let status = $state<StatusSnapshot>(initialStatus);
let open = $state(false);
let requestInFlight = false;
async function probe(path: string): Promise<StatusProbe> {
try {
const response = await fetch(path, {
credentials: 'include',
headers: { Accept: 'application/json' }
});
const payload = (await response.json().catch(() => null)) as {
ok?: boolean;
service?: string;
error?: string;
} | null;
return {
path,
ok: response.ok && payload?.ok !== false,
httpStatus: response.status,
service: payload?.service || null,
error: response.ok ? null : payload?.error || response.statusText || `HTTP ${response.status}`
};
} catch (error) {
return {
path,
ok: false,
httpStatus: null,
service: null,
error: error instanceof Error ? error.message : 'Unavailable'
};
}
}
async function refresh(): Promise<void> {
if (requestInFlight) return;
requestInFlight = true;
status = { ...status, loading: true, level: status.health || status.readiness ? status.level : 'checking' };
try {
const [health, readiness] = await Promise.all([probe('/healthz'), probe('/ready')]);
const level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline';
status = {
level,
health,
readiness,
checkedAt: new Date().toISOString(),
loading: false
};
} finally {
requestInFlight = false;
if (status.loading) status = { ...status, loading: false };
}
}
onMount(() => {
void refresh();
const timer = window.setInterval(() => void refresh(), 15_000);
return () => window.clearInterval(timer);
});
</script>
<Button
aria-label="Service status"
onclick={() => (open = true)}
size="icon"
title={`Service status: ${status.level}`}
variant="ghost"
>
{#if status.loading && status.level === 'checking'}
<LoaderCircle aria-hidden="true" class="sc-status-icon sc-status-spin" size={20} />
{:else if status.level === 'healthy'}
<CheckCircle2 aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'degraded'}
<AlertTriangle aria-hidden="true" class="sc-status-icon" size={20} />
{:else if status.level === 'offline'}
<AlertCircle aria-hidden="true" class="sc-status-icon" size={20} />
{:else}
<CircleHelp aria-hidden="true" class="sc-status-icon" size={20} />
{/if}
</Button>
<StatusDialog bind:open {status} onRefresh={refresh} />
+8
View File
@@ -6,12 +6,17 @@ export { default as Badge } from './components/Badge.svelte';
export { default as Button } from './components/Button.svelte';
export { default as Card } from './components/Card.svelte';
export { default as Dialog } from './components/Dialog.svelte';
export { default as EmptyState } from './components/EmptyState.svelte';
export { default as Header } from './components/Header.svelte';
export { default as Metric } from './components/Metric.svelte';
export { default as NotificationStack } from './components/NotificationStack.svelte';
export { default as PageHeader } from './components/PageHeader.svelte';
export { default as Pagination } from './components/Pagination.svelte';
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
export { default as SectionTitle } from './components/SectionTitle.svelte';
export { default as SettingsDialog } from './components/SettingsDialog.svelte';
export { default as StatusDialog } from './components/StatusDialog.svelte';
export { default as StatusWidget } from './components/StatusWidget.svelte';
export { default as TotpSettings } from './components/TotpSettings.svelte';
export { default as UserManagement } from './components/UserManagement.svelte';
export { notifications, notify } from './notifications.svelte';
@@ -27,6 +32,9 @@ export type {
NavItem,
ProfileUpdateInput,
ManagedUser,
StatusLevel,
StatusProbe,
StatusSnapshot,
UserCreateInput,
UserCreateRequest,
UserDeleteRequest,
+197
View File
@@ -285,6 +285,12 @@
font-weight: 650;
}
.sc-badge[data-variant="primary"] {
color: var(--sc-primary-fg);
background: var(--sc-primary);
border-color: transparent;
}
.sc-badge[data-variant="success"] {
color: var(--sc-success-fg);
background: var(--sc-success);
@@ -380,6 +386,16 @@
background: var(--sc-danger-hover);
}
.sc-button-outline {
color: var(--sc-fg);
background: transparent;
border-color: var(--sc-border);
}
.sc-button-outline:hover:not(:disabled) {
background: var(--sc-surface-hover);
}
.sc-button-sm {
min-height: 2rem;
padding: 0.45rem 0.75rem;
@@ -391,6 +407,187 @@
padding: 0.75rem 1.25rem;
}
.sc-button-icon {
min-height: 2.5rem;
width: 2.5rem;
padding: 0;
}
.sc-empty-state {
display: flex;
min-height: 10rem;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.75rem;
padding: 2rem 1.25rem;
text-align: center;
border: 1px dashed var(--sc-border);
border-radius: var(--sc-radius-lg);
background: color-mix(in srgb, var(--sc-surface) 50%, transparent);
}
.sc-empty-state-icon {
color: var(--sc-muted-fg);
}
.sc-empty-state-title {
margin: 0;
font-size: 0.9rem;
font-weight: 600;
color: var(--sc-fg);
}
.sc-empty-state-message {
margin: 0.25rem 0 0;
max-width: 24rem;
font-size: 0.8125rem;
color: var(--sc-muted-fg);
}
.sc-section-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
}
.sc-section-title h2 {
margin: 0;
font-size: 0.9rem;
font-weight: 650;
color: var(--sc-fg);
}
.sc-section-title p {
margin: 0.25rem 0 0;
}
.sc-metric {
padding: 1rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-lg);
background: var(--sc-surface);
}
.sc-metric-label {
margin: 0;
font-size: 0.6875rem;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--sc-muted-fg);
}
.sc-metric-value {
margin: 0.5rem 0 0;
font-size: 1.5rem;
font-weight: 650;
letter-spacing: -0.01em;
color: var(--sc-fg);
}
.sc-metric-value[data-variant="primary"] {
color: var(--sc-primary);
}
.sc-metric-value[data-variant="success"] {
color: var(--sc-success);
}
.sc-metric-value[data-variant="warning"] {
color: var(--sc-warning);
}
.sc-metric-value[data-variant="danger"] {
color: var(--sc-danger);
}
.sc-metric-detail {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
color: var(--sc-muted-fg);
}
.sc-status-icon {
color: var(--sc-muted-fg);
}
.sc-status-summary[data-level="healthy"] .sc-status-icon,
.sc-status-summary[data-level="healthy"] .sc-status-summary-label {
color: var(--sc-success);
}
.sc-status-summary[data-level="degraded"] .sc-status-icon,
.sc-status-summary[data-level="degraded"] .sc-status-summary-label {
color: var(--sc-warning);
}
.sc-status-summary[data-level="offline"] .sc-status-icon,
.sc-status-summary[data-level="offline"] .sc-status-summary-label {
color: var(--sc-danger);
}
.sc-status-spin {
animation: sc-spin 900ms linear infinite;
}
@keyframes sc-spin {
to {
transform: rotate(360deg);
}
}
.sc-status-summary {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1.25rem;
padding: 0.75rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-md);
background: var(--sc-surface);
}
.sc-status-summary-label {
font-weight: 650;
}
.sc-status-summary-time {
margin-left: auto;
font-size: 0.75rem;
color: var(--sc-muted-fg);
}
.sc-status-probes {
display: flex;
flex-direction: column;
gap: 0.5rem;
font-size: 0.875rem;
}
.sc-status-probe {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--sc-border);
border-radius: var(--sc-radius-sm);
}
.sc-status-probe span[data-ok="true"] {
color: var(--sc-success);
}
.sc-status-probe span[data-ok="false"] {
color: var(--sc-danger);
}
.sc-status-service {
margin-top: 1rem;
}
.sc-button-full {
width: 100%;
}
+18
View File
@@ -91,3 +91,21 @@ export interface AboutLink {
}
export type ContentSnippet = Snippet;
export type StatusLevel = "checking" | "healthy" | "degraded" | "offline";
export interface StatusProbe {
path: string;
ok: boolean;
httpStatus: number | null;
service: string | null;
error: string | null;
}
export interface StatusSnapshot {
level: StatusLevel;
health: StatusProbe | null;
readiness: StatusProbe | null;
checkedAt: string | null;
loading: boolean;
}