Kaleido-Desktop/src/screens/settings/ServerDashboard.tsx
Elijah d9e22dde2e Handle stopped streams, live bandwidth, and rework the upscaling tiers
When the server owner stops a stream, Plex cuts the connection and repeats
the termination in every timeline reply to the client until it reports a
stop. The player now reads those replies (also when playback stalls or
fails), stops mpv, shows the owner's message and acknowledges it; a
termination on a session's first reply is left over from an earlier stream
and is cleared instead of cancelling the new one. Each title also starts
unpaused, as mpv keeps pause across files.

The dashboard's bandwidth graph refreshes every second. Plex's real-time
samples are bytes per second with idle seconds omitted, so they are laid on
a gap-free per-second axis (they were divided by six before).

Upscaling: Balanced is now the strongest shader chain, light nlmeans,
FSRCNNX 16, KrigBilateral and debanding. Measured against 1080p references
shrunk to 480p it beat FSRCNNX 8, two network passes, RAVU and
SSimSuperRes. The denoiser is AN3223's light profile with luma strength at
60%, which keeps texture the default profile smoothed away. Quality is now
NVIDIA RTX Video Super Resolution through mpv's d3d11vpp filter, sized to
the window and re-applied when it changes; it is offered only on Windows
with an NVIDIA RTX GPU (app_info now lists the adapters), runs Balanced for
HDR or at native size, and drops a tier if the driver refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:09:34 -07:00

274 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useMemo } from 'react';
import * as admin from '../../plex/admin';
import * as api from '../../plex/api';
import { useServerQuery } from '../../app/queries';
import { useServer } from '../../app/session';
import { bitrate, clock, episodeLabel, relativeTime } from '../../app/format';
import { Artwork, Button, EmptyState, PageLoader } from '../../ui/primitives';
import { promptDialog, toast, toastError } from '../../ui/overlays';
import { Icon } from '../../ui/Icon';
import { Card, StatTile } from './parts';
function AreaChart({ series, height = 150, max, format }: { series: { values: number[]; color: string; label: string }[]; height?: number; max?: number; format: (v: number) => string }) {
const n = Math.max(...series.map((s) => s.values.length), 2);
const top = Math.max(max ?? 0, ...series.flatMap((s) => s.values), 1);
const W = 920;
const path = (values: number[]) => values.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / (n - 1)) * W).toFixed(1)} ${(height - 6 - (v / top) * (height - 16)).toFixed(1)}`).join(' ');
return (
<div className="chart">
<svg viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="none" className="chart-svg" role="img">
<defs>
{series.map((s, i) => (
<linearGradient key={i} id={`g${i}${s.label}`} x1="0" x2="0" y1="0" y2="1">
<stop stopColor={s.color} stopOpacity=".28" />
<stop offset="1" stopColor={s.color} stopOpacity="0" />
</linearGradient>
))}
</defs>
{[0.25, 0.5, 0.75, 1].map((f) => (
<path key={f} d={`M0 ${(height - 6 - f * (height - 16)).toFixed(1)} H${W}`} stroke="rgba(255,255,255,.08)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
))}
{series.map((s, i) =>
s.values.length > 1 ? (
<g key={i}>
<path d={`${path(s.values)} L${(((s.values.length - 1) / (n - 1)) * W).toFixed(1)} ${height} L0 ${height} Z`} fill={`url(#g${i}${s.label})`} />
<path d={path(s.values)} stroke={s.color} strokeWidth="2" fill="none" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
</g>
) : null,
)}
</svg>
<div className="chart-footer">
<div className="legend">
{series.map((s) => (
<span key={s.label}>
<i style={{ background: s.color }} />
{s.label} {s.values.length ? format(s.values[s.values.length - 1]) : ''}
</span>
))}
</div>
<span>Peak {format(top)}</span>
</div>
</div>
);
}
/** Seconds of bandwidth the chart shows. */
const BANDWIDTH_WINDOW = 120;
/**
* Plex's real-time bandwidth samples are bytes per second, and seconds with
* no traffic are left out; lay them on a gap-free per-second axis in Mbps.
*/
function perSecond(points: admin.BandwidthPoint[]) {
const latest = points.length ? points[points.length - 1].at : 0;
// Ends at the newest sample, or now when nothing has been sent lately.
const end = Math.max(latest, Math.floor(Date.now() / 1000) - 2);
const lan = new Array<number>(BANDWIDTH_WINDOW).fill(0);
const wan = new Array<number>(BANDWIDTH_WINDOW).fill(0);
for (const p of points) {
const i = BANDWIDTH_WINDOW - 1 - (end - p.at);
if (i < 0 || i >= BANDWIDTH_WINDOW) continue;
lan[i] = (p.lan * 8) / 1e6;
wan[i] = (p.wan * 8) / 1e6;
}
return { lan, wan };
}
function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () => void }) {
const server = useServer();
const item = session.item;
const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb;
const pct = item.duration ? (session.viewOffset / item.duration) * 100 : 0;
const d = session.decision;
const mode = !d ? 'Direct play' : d.video === 'transcode' ? 'Transcoding video' : d.audio === 'transcode' ? 'Transcoding audio' : 'Direct stream';
return (
<div className="now-playing">
<div className="np-poster">
<Artwork src={server.image(poster, 90, 135)} />
</div>
<div className="np-body">
<h3>{item.type === 'episode' ? item.grandparentTitle : item.title}</h3>
<p>{item.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : item.year || ''}</p>
<p className="dim">
{session.user.title} · {session.player.title || session.player.product} ({session.player.platform}) · {session.player.local ? 'Local' : 'Remote'} {session.player.address}
</p>
<div className="np-progress">
<span className="progress-bar">
<i style={{ width: `${pct}%` }} />
</span>
<span className="dim">
{session.player.state === 'paused' ? 'Paused · ' : session.player.state === 'buffering' ? 'Buffering · ' : ''}
{clock(session.viewOffset / 1000)} / {clock(item.duration / 1000)}
</span>
</div>
<div className="np-pills">
<span className={`stream-pill${d?.video === 'transcode' ? ' warn' : ''}`}>
<Icon name={d ? 'cpu' : 'check'} size={13} />
{mode}
{d?.transcodeHw ? ' (hw)' : ''}
</span>
{session.bandwidth > 0 && <span className="stream-pill neutral">{bitrate(session.bandwidth)}</span>}
{d && d.speed > 0 && <span className="stream-pill neutral">{d.speed.toFixed(1)}× {d.throttled ? 'throttled' : ''}</span>}
</div>
</div>
<Button variant="ghost" size="sm" icon="x" onClick={onStop}>
Stop
</Button>
</div>
);
}
function Dashboard() {
const server = useServer();
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 1000, staleTime: 0 });
const res = useServerQuery(['resources'], (s) => admin.resources(s, 6), { refetchInterval: 6000, staleTime: 0 });
const info = useServerQuery(['serverInfo'], (s) => api.serverInfo(s), { staleTime: 60_000 });
const sections = useServerQuery(['sections'], (s) => api.sections(s));
const remote = useServerQuery(['remoteAccess'], (s) => admin.remoteAccess(s), { staleTime: 60_000 });
const list = sessions.data ?? [];
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
const { lan, wan } = perSecond(bw.data?.points ?? []);
const r = (res.data ?? []).slice(-40);
const cpu = r[r.length - 1];
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
const stop = async (s: admin.Session) => {
const reason = await promptDialog({
title: 'Stop this stream?',
message: `${s.user.title} will see this message on ${s.player.title || s.player.product}.`,
confirm: 'Stop stream',
danger: true,
input: { label: 'Message', value: 'The server owner has ended this stream.' },
});
if (reason === null) return;
try {
await admin.terminateSession(server, s.sessionId, reason);
toast('Stream stopped', 'success');
sessions.refetch();
} catch (e) {
toastError(e);
}
};
const mc = info.data ?? {};
return (
<>
<div className="stats-grid">
<StatTile label="Active streams" value={list.length} detail={list.length ? `${list.length - transcodes} direct · ${transcodes} transcoding` : 'Nothing playing'} />
<StatTile label="Streaming bandwidth" value={totalBandwidth ? bitrate(totalBandwidth) : '0 Mbps'} detail={`${list.filter((s) => !s.player.local).length} remote`} />
<StatTile label="Server CPU" value={cpu ? `${Math.round(cpu.hostCpu)}%` : '—'} detail={cpu ? `Plex ${cpu.processCpu.toFixed(1)}%` : ''} tone={cpu && cpu.hostCpu > 85 ? 'warn' : undefined} />
<StatTile label="Remote access" value={remote.data?.mappingState === 'mapped' ? 'Online' : 'Limited'} detail={remote.data?.publicAddress ?? ''} tone={remote.data?.mappingState === 'mapped' ? 'good' : 'warn'} />
</div>
<Card title="Now playing" actions={<span className="status-tag"><i className="dot" />{list.length} active</span>}>
{sessions.isLoading && <PageLoader />}
{sessions.data && !list.length && <p className="muted np-empty">No one is watching right now.</p>}
{list.map((s) => (
<NowPlaying key={s.sessionKey} session={s} onStop={() => stop(s)} />
))}
</Card>
<div className="admin-2-col">
<Card title="Bandwidth" actions={<span className="note">Last 2 minutes · live</span>}>
<AreaChart
series={[
{ values: wan, color: '#6797f5', label: 'Remote' },
{ values: lan, color: '#e0ad5d', label: 'Local' },
]}
format={(v) => `${v.toFixed(1)} Mbps`}
/>
</Card>
<Card title="Resources" actions={<span className="note">Host CPU and memory</span>}>
<AreaChart
series={[
{ values: r.map((p) => p.hostCpu), color: '#8fc7a8', label: 'CPU' },
{ values: r.map((p) => p.hostMemory), color: '#b49ae8', label: 'Memory' },
]}
max={100}
format={(v) => `${Math.round(v)}%`}
/>
</Card>
</div>
<Card title="Server">
<div className="server-info">
{[
['Name', mc.friendlyName],
['Version', String(mc.version ?? '').split('-')[0]],
['Platform', [mc.platform, mc.platformVersion].filter(Boolean).join(' ')],
['Libraries', (sections.data ?? []).map((s) => s.title).join(', ')],
['Plex Pass', mc.myPlexSubscription ? 'Active' : 'Not active'],
['Signed in as', mc.myPlexUsername],
['Transcoder', mc.transcoderVideo ? 'Video, audio' : 'Available'],
['Connection', server.uri.replace(/^https?:\/\//, '')],
].map(([k, v]) => (
<div key={k as string}>
<span>{k}</span>
<b>{(v as string) || '—'}</b>
</div>
))}
</div>
</Card>
</>
);
}
function Activity() {
const server = useServer();
const activities = useServerQuery(['activities'], (s) => admin.activities(s), { refetchInterval: 3000, staleTime: 0 });
const history = useServerQuery(['history'], (s) => admin.history(s, 40), { staleTime: 15_000 });
const accounts = useServerQuery(['accounts'], (s) => admin.accounts(s), { staleTime: 10 * 60_000 });
const devices = useServerQuery(['devices'], (s) => admin.devices(s), { staleTime: 10 * 60_000 });
const deviceName = useMemo(() => Object.fromEntries((devices.data ?? []).map((d) => [d.id, d.name])), [devices.data]);
return (
<>
<Card title="Running now" actions={<span className="note">Scans, analysis and maintenance</span>}>
{activities.data && !activities.data.length && <p className="muted np-empty">The server is idle.</p>}
{activities.data?.map((a) => (
<div key={a.uuid} className="activity-row">
<div className="lib-ico">
<Icon name={a.type.includes('library') ? 'refresh' : a.type.includes('media') ? 'film' : 'activity'} size={17} />
</div>
<div className="activity-text">
<strong>{a.title}</strong>
<small>{a.subtitle}</small>
{a.progress > 0 && (
<span className="progress-bar">
<i style={{ width: `${a.progress}%` }} />
</span>
)}
</div>
{a.cancellable && (
<Button variant="ghost" size="sm" onClick={() => admin.cancelActivity(server, a.uuid).then(() => activities.refetch(), toastError)}>
Cancel
</Button>
)}
</div>
))}
</Card>
<Card title="Watch history">
{history.isLoading && <PageLoader />}
{history.data && !history.data.length && <EmptyState icon="clock" title="No history yet" />}
<div className="history-list">
{history.data?.map((h) => (
<div key={h.id + h.viewedAt} className="history-row">
<div className="history-thumb">
<Artwork src={server.image(h.thumb, 60, 90)} />
</div>
<div>
<strong>{h.title}</strong>
<small>{h.subtitle}</small>
</div>
<span className="dim">{accounts.data?.[h.accountId] ?? 'Owner'}</span>
<span className="dim">{deviceName[h.deviceId] ?? ''}</span>
<span className="dim">{relativeTime(h.viewedAt)}</span>
</div>
))}
</div>
</Card>
</>
);
}
export default function ServerDashboard({ tab }: { tab: 'dashboard' | 'activity' }) {
return tab === 'dashboard' ? <Dashboard /> : <Activity />;
}