feat(orbit): in-app diagnostics popover with copyable event log (#524)

* feat(orbit): in-app diagnostics popover with copyable event log

Multiple users on Discord report Orbit guests stopping after the first
song with no errors anywhere — Settings → Debug → Export Logs is too
buried for non-technical reporters, and the relevant code branches
have no logging at all (silent fail). This adds a one-click "Copy log"
path right inside the Orbit session bar.

The new Activity-icon button next to Help opens a popover with:

- Live mini-display: role, host vs. guest track id + position, drift,
  age of the host's last state write — all updating once a second.
- Scrolling event log textarea fed by an in-memory ring (200 events).
- Copy + Clear buttons. Copy formats `[ISO] [scope] body` lines and
  drops them on the clipboard — paste straight into a Discord report.

Instrumentation lands at the previously-silent decision points:

- Guest pull tick: full snapshot of host vs. guest state on every read.
- Each branch of the divergence detection in `useOrbitGuest.ts` logs
  which path it took and why (initial / track-change-followed /
  track-change-diverged / play-pause-flip), making the
  "stuck after first song" symptom diagnosable from the buffer alone.
- Host pushes log track id, isPlaying, queue length, guest count.

Events are also bridged to the existing `frontend_debug_log` Tauri
command when Settings → Logging is on Debug, so power users still get
the same data in `psysonic-logs-*.log` for offline triage.

i18n: full `orbit.diag.*` namespace in all eight locales. EN + DE are
native; ES / FR / NB / NL / RU / ZH are first-pass and may want a
polish from native speakers later.

* docs(changelog): add orbit diagnostics popover entry
This commit is contained in:
Frank Stellmacher
2026-05-09 21:49:17 +02:00
committed by GitHub
parent acadc1be34
commit a702a5dd5b
15 changed files with 610 additions and 3 deletions
+10
View File
@@ -18,6 +18,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Added
### Orbit — in-app diagnostics popover with copyable event log
**By [@Psychotoxical](https://github.com/Psychotoxical), prompted by reports from nzxl + RavingGrob, PR [#524](https://github.com/Psychotoxical/psysonic/pull/524)**
* New **Activity-icon** button in the Orbit session bar opens a diagnostics popover. Live mini-display (role, host vs. guest track, position, drift, state-age) updates once a second; below it, a scrolling **event log textarea** is fed by a 200-entry in-memory ring buffer.
* **Copy** + **Clear** buttons. Copy drops formatted `[ISO] [scope] body` lines on the clipboard — paste straight into a Discord bug report.
* Instrumentation lands at every previously-silent decision point in the guest tick (`initial-sync`, `track-change` followed / diverged, `play-pause-flip`) plus host state pushes, so the "stopped after the first song" Orbit symptom is now diagnosable from the buffer alone.
* Events are also bridged to the existing `frontend_debug_log` command when **Settings → Logging** is on Debug, so power users still get the same data in `psysonic-logs-*.log` for offline triage.
* i18n: full `orbit.diag.*` namespace across all 8 locales (EN + DE native; ES / FR / NB / NL / RU / ZH first-pass, polish welcome).
### Player Bar — album context menu on song title right-click
**By [@Psychotoxical](https://github.com/Psychotoxical), PR [#512](https://github.com/Psychotoxical/psysonic/pull/512)**
+185
View File
@@ -0,0 +1,185 @@
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import { Copy, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useOrbitStore } from '../store/orbitStore';
import { usePlayerStore } from '../store/playerStore';
import { showToast } from '../utils/toast';
import { computeOrbitDriftMs } from '../utils/orbit';
import {
clearOrbitEvents,
formatOrbitEvents,
getOrbitEvents,
subscribeOrbitEvents,
} from '../utils/orbitDiag';
interface Props {
anchorRef: React.RefObject<HTMLElement | null>;
onClose: () => void;
}
/**
* Live diagnostic popover for the Orbit bar. Renders a mini-summary of the
* host vs guest state plus a scrolling event log captured by `orbitDiag`.
*
* The point is "Discord user can paste a buffer" — so the Copy button is
* the primary action and the textarea is read-only. Clear lets a user wipe
* the buffer before reproducing a specific symptom.
*/
export default function OrbitDiagnosticsPopover({ anchorRef, onClose }: Props) {
const { t } = useTranslation();
const popRef = useRef<HTMLDivElement>(null);
const taRef = useRef<HTMLTextAreaElement>(null);
// Live event buffer subscription via useSyncExternalStore — no extra
// re-render cascade, no flicker.
const events = useSyncExternalStore(subscribeOrbitEvents, getOrbitEvents, getOrbitEvents);
const formatted = formatOrbitEvents(events);
// Tick the mini-display once a second so drift / position read fresh.
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const id = window.setInterval(() => setNowMs(Date.now()), 1000);
return () => window.clearInterval(id);
}, []);
// Auto-scroll the textarea to the bottom whenever a new event lands so
// the most recent line is always visible without manual scrolling.
useEffect(() => {
if (taRef.current) taRef.current.scrollTop = taRef.current.scrollHeight;
}, [formatted]);
useEffect(() => {
const onDown = (e: MouseEvent) => {
const target = e.target as Node | null;
if (popRef.current?.contains(target)) return;
if (anchorRef.current?.contains(target)) return;
onClose();
};
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
};
}, [anchorRef, onClose]);
const anchor = anchorRef.current?.getBoundingClientRect();
const style: React.CSSProperties = anchor
? {
position: 'fixed',
top: anchor.bottom + 12,
right: Math.max(8, window.innerWidth - anchor.right),
zIndex: 9999,
}
: { display: 'none' };
// ── Live mini-display data ────────────────────────────────────────────
const role = useOrbitStore(s => s.role);
const state = useOrbitStore(s => s.state);
const player = usePlayerStore.getState();
const localPosMs = Math.round((player.currentTime ?? 0) * 1000);
const sameTrack = role === 'guest'
&& state?.currentTrack
&& player.currentTrack?.id === state.currentTrack.trackId;
const driftMs = sameTrack && state ? computeOrbitDriftMs(state, localPosMs, nowMs) : null;
const hostStateAgeMs = state ? Math.max(0, nowMs - state.positionAt) : null;
const hostPosSec = state ? Math.round(((state.positionMs ?? 0) + (state.isPlaying ? (nowMs - state.positionAt) : 0)) / 1000) : null;
const guestPosSec = Math.round((player.currentTime ?? 0));
const handleCopy = async () => {
const text = formatted || '(empty)';
try {
await navigator.clipboard.writeText(text);
showToast(t('orbit.diag.copied', { count: events.length }), 2500, 'info');
} catch {
showToast(t('orbit.diag.copyFailed'), 4000, 'error');
}
};
const handleClear = () => {
clearOrbitEvents();
showToast(t('orbit.diag.cleared'), 2000, 'info');
};
return createPortal(
<div ref={popRef} className="orbit-diag-pop" style={style} role="dialog" aria-label={t('orbit.diag.title')}>
<div className="orbit-diag-pop__head">{t('orbit.diag.title')}</div>
<div className="orbit-diag-pop__live">
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.role')}</span>
<span>{role ?? '—'}</span>
</div>
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.hostTrack')}</span>
<span className="orbit-diag-pop__mono">{state?.currentTrack?.trackId ?? '—'}</span>
</div>
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.hostPos')}</span>
<span>{hostPosSec != null ? `${hostPosSec}s · ${state?.isPlaying ? '▶' : '⏸'}` : '—'}</span>
</div>
{role === 'guest' && (
<>
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.guestTrack')}</span>
<span className="orbit-diag-pop__mono">{player.currentTrack?.id ?? '—'}</span>
</div>
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.guestPos')}</span>
<span>{guestPosSec}s · {player.isPlaying ? '▶' : '⏸'}</span>
</div>
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.drift')}</span>
<span>{driftMs != null ? `${(driftMs / 1000).toFixed(1)}s` : '—'}</span>
</div>
</>
)}
{hostStateAgeMs != null && (
<div className="orbit-diag-pop__live-row">
<span className="orbit-diag-pop__live-label">{t('orbit.diag.stateAge')}</span>
<span>{(hostStateAgeMs / 1000).toFixed(1)}s</span>
</div>
)}
</div>
<div className="orbit-diag-pop__log-head">
<span>{t('orbit.diag.eventLog', { count: events.length })}</span>
<div className="orbit-diag-pop__btn-row">
<button
type="button"
className="orbit-diag-pop__btn"
onClick={handleCopy}
data-tooltip={t('orbit.diag.copyTooltip')}
aria-label={t('orbit.diag.copyTooltip')}
>
<Copy size={13} />
<span>{t('orbit.diag.copyLabel')}</span>
</button>
<button
type="button"
className="orbit-diag-pop__btn"
onClick={handleClear}
data-tooltip={t('orbit.diag.clearTooltip')}
aria-label={t('orbit.diag.clearTooltip')}
>
<Trash2 size={13} />
<span>{t('orbit.diag.clearLabel')}</span>
</button>
</div>
</div>
<textarea
ref={taRef}
className="orbit-diag-pop__log"
readOnly
value={formatted}
spellCheck={false}
placeholder={t('orbit.diag.empty')}
/>
<div className="orbit-diag-pop__hint">{t('orbit.diag.hint')}</div>
</div>,
document.body,
);
}
+22 -1
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { X, RefreshCw, Shuffle, Settings2, Share2, HelpCircle } from 'lucide-react';
import { X, RefreshCw, Shuffle, Settings2, Share2, HelpCircle, Activity } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useOrbitStore } from '../store/orbitStore';
import { useHelpModalStore } from '../store/helpModalStore';
@@ -16,6 +16,7 @@ import OrbitParticipantsPopover from './OrbitParticipantsPopover';
import OrbitExitModal from './OrbitExitModal';
import OrbitSettingsPopover from './OrbitSettingsPopover';
import OrbitSharePopover from './OrbitSharePopover';
import OrbitDiagnosticsPopover from './OrbitDiagnosticsPopover';
import ConfirmModal from './ConfirmModal';
/**
@@ -49,10 +50,12 @@ export default function OrbitSessionBar() {
const [peopleOpen, setPeopleOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [shareOpen, setShareOpen] = useState(false);
const [diagOpen, setDiagOpen] = useState(false);
const [confirmLeave, setConfirmLeave] = useState(false);
const peopleBtnRef = useRef<HTMLButtonElement>(null);
const settingsBtnRef = useRef<HTMLButtonElement>(null);
const shareBtnRef = useRef<HTMLButtonElement>(null);
const diagBtnRef = useRef<HTMLButtonElement>(null);
// Second-level tick just for the shuffle countdown + drift readout —
// the store itself only ticks at 2.5 s which is too coarse for a smooth
@@ -209,6 +212,18 @@ export default function OrbitSessionBar() {
<span>{t('orbit.catchUpLabel')}</span>
</button>
)}
<button
ref={diagBtnRef}
type="button"
className="orbit-bar__settings"
onClick={() => setDiagOpen(v => !v)}
data-tooltip={t('orbit.diag.openTooltip')}
aria-haspopup="dialog"
aria-expanded={diagOpen || undefined}
aria-label={t('orbit.diag.openTooltip')}
>
<Activity size={14} />
</button>
<button
type="button"
className="orbit-bar__settings"
@@ -247,6 +262,12 @@ export default function OrbitSessionBar() {
onClose={() => setShareOpen(false)}
/>
)}
{diagOpen && (
<OrbitDiagnosticsPopover
anchorRef={diagBtnRef}
onClose={() => setDiagOpen(false)}
/>
)}
<OrbitExitModal />
<ConfirmModal
open={confirmLeave}
+19 -1
View File
@@ -8,6 +8,7 @@ import {
writeOrbitHeartbeat,
} from '../utils/orbit';
import { orbitOutboxPlaylistName, estimateLivePosition, type OrbitState } from '../api/orbit';
import { pushOrbitEvent } from '../utils/orbitDiag';
/**
* Orbit — guest-side tick hook.
@@ -130,6 +131,7 @@ export function useOrbitGuest(): void {
// explicit `state.ended` branch does; the store still holds the last
// known state so the modal can render the host + session name copy.
// Outbox cleanup runs from the modal's OK handler via leaveOrbitSession.
pushOrbitEvent('pull', 'state read returned null — playlist gone, ending session');
useOrbitStore.getState().setPhase('ended');
return;
}
@@ -203,6 +205,12 @@ export function useOrbitGuest(): void {
const hostPlaying = state.isPlaying;
const last = lastAppliedRef.current;
pushOrbitEvent('pull', JSON.stringify({
host: { track: hostTrackId, playing: hostPlaying, posMs: state.positionMs, posAt: state.positionAt },
guest: { track: player.currentTrack?.id ?? null, playing: player.isPlaying, posSec: Math.round(player.currentTime ?? 0) },
last,
}));
if (!last) {
// Initial sync: only record `last` *after* syncToHost actually
// landed. If the first attempt loses the race (engine not ready,
@@ -211,9 +219,12 @@ export function useOrbitGuest(): void {
// failed sync set `last` anyway and the guest was stuck on their
// pre-join state until they clicked Catch Up.
if (hostTrackId) {
pushOrbitEvent('initial-sync', `attempting initial sync to ${hostTrackId} (hostPlaying=${hostPlaying})`);
const ok = await syncToHost(hostTrackId, state);
pushOrbitEvent('initial-sync', `result: ${ok ? 'success' : 'failed (will retry)'}`);
if (ok) lastAppliedRef.current = { trackId: hostTrackId, isPlaying: hostPlaying };
} else {
pushOrbitEvent('initial-sync', 'host has no current track yet, anchor only');
lastAppliedRef.current = { trackId: null, isPlaying: hostPlaying };
}
} else if (last.trackId !== hostTrackId) {
@@ -222,11 +233,15 @@ export function useOrbitGuest(): void {
// Guest is running their own show (typically: paused while host
// kept going). Do not load/start the host's new track — just
// track the host state so the catch-up prompt stays accurate.
pushOrbitEvent('track-change',
`host: ${last.trackId}${hostTrackId} BUT guest diverged (player.isPlaying=${player.isPlaying} ≠ last.isPlaying=${last.isPlaying}) — NOT loading new track`);
lastAppliedRef.current = { trackId: hostTrackId, isPlaying: hostPlaying };
} else if (hostTrackId) {
pushOrbitEvent('track-change', `host: ${last.trackId}${hostTrackId}, guest in sync, following`);
void syncToHost(hostTrackId, state);
lastAppliedRef.current = { trackId: hostTrackId, isPlaying: hostPlaying };
} else {
pushOrbitEvent('track-change', `host cleared current track, pausing guest`);
if (player.isPlaying) player.pause();
lastAppliedRef.current = { trackId: hostTrackId, isPlaying: hostPlaying };
}
@@ -234,7 +249,10 @@ export function useOrbitGuest(): void {
// Only mirror when the guest hasn't diverged. We compare against the
// *last applied* host state, not the new one — divergence means the
// local player no longer matches what we last pushed in.
if (player.isPlaying === last.isPlaying) {
const localMatchesLast = player.isPlaying === last.isPlaying;
pushOrbitEvent('play-pause-flip',
`host: ${last.isPlaying}${hostPlaying}, guest matches last=${localMatchesLast} (will ${localMatchesLast ? 'mirror' : 'skip'})`);
if (localMatchesLast) {
if (hostPlaying) player.resume();
else player.pause();
}
+12 -1
View File
@@ -19,6 +19,7 @@ import {
} from '../api/orbit';
import { showToast } from '../utils/toast';
import i18n from '../i18n';
import { pushOrbitEvent } from '../utils/orbitDiag';
/**
* Orbit — host-side tick hook.
@@ -137,7 +138,17 @@ export function useOrbitHost(): void {
try {
await writeOrbitState(sessionPlaylistId, next);
lastPushedAtRef.current = Date.now();
} catch { /* best-effort; next tick retries */ }
pushOrbitEvent('host:push', JSON.stringify({
track: next.currentTrack?.trackId ?? null,
playing: next.isPlaying,
posMs: next.positionMs,
queueLen: next.playQueueTotal ?? next.playQueue?.length ?? 0,
guests: next.participants.length,
}));
} catch (e) {
pushOrbitEvent('host:push', `WRITE FAILED: ${String(e)}`);
/* best-effort; next tick retries */
}
};
/**
+21
View File
@@ -1696,6 +1696,27 @@ export const deTranslation = {
endTooltip: 'Session beenden',
leaveTooltip: 'Session verlassen',
helpTooltip: 'Wie Orbit funktioniert',
diag: {
openTooltip: 'Diagnose — kopierbares Ereignis-Log',
title: 'Orbit-Diagnose',
role: 'Rolle',
hostTrack: 'Host-Track-ID',
hostPos: 'Host-Position',
guestTrack: 'Meine Track-ID',
guestPos: 'Meine Position',
drift: 'Versatz',
stateAge: 'Zustand-Alter',
eventLog: 'Ereignis-Log ({{count}})',
copyLabel: 'Kopieren',
copyTooltip: 'Log in Zwischenablage kopieren',
clearLabel: 'Leeren',
clearTooltip: 'Puffer leeren',
empty: 'Noch keine Ereignisse — sie erscheinen sobald Orbit synchronisiert.',
hint: 'Vor dem Reproduzieren des Problems öffnen, dann Kopieren klicken und in den Bug-Report einfügen.',
copied: '{{count}} Zeilen kopiert',
copyFailed: 'Konnte nicht in Zwischenablage kopieren',
cleared: 'Puffer geleert',
},
helpTitle: 'Wie Orbit funktioniert',
helpIntro: 'Orbit macht aus Psysonic einen gemeinsamen Hörraum. Der Host bestimmt die Musik; Gäste hören synchron mit und können Songs vorschlagen.',
helpHostOnly: '(Host)',
+21
View File
@@ -1702,6 +1702,27 @@ export const enTranslation = {
endTooltip: 'End session',
leaveTooltip: 'Leave session',
helpTooltip: 'How Orbit works',
diag: {
openTooltip: 'Diagnostics — copyable event log',
title: 'Orbit diagnostics',
role: 'Role',
hostTrack: 'Host track id',
hostPos: 'Host position',
guestTrack: 'My track id',
guestPos: 'My position',
drift: 'Drift',
stateAge: 'State age',
eventLog: 'Event log ({{count}})',
copyLabel: 'Copy',
copyTooltip: 'Copy log to clipboard',
clearLabel: 'Clear',
clearTooltip: 'Wipe the buffer',
empty: 'No events yet — events appear as Orbit syncs.',
hint: 'Open this before reproducing a problem, then click Copy and paste into the bug report.',
copied: 'Copied {{count}} event lines',
copyFailed: 'Could not copy to clipboard',
cleared: 'Buffer cleared',
},
helpTitle: 'How Orbit works',
helpIntro: 'Orbit turns Psysonic into a shared listening room. A host picks the music; guests listen in sync and can suggest tracks.',
helpHostOnly: '(host)',
+21
View File
@@ -1654,6 +1654,27 @@ export const esTranslation = {
endTooltip: 'Terminar sesión',
leaveTooltip: 'Salir de la sesión',
helpTooltip: 'Cómo funciona Orbit',
diag: {
openTooltip: 'Diagnóstico — registro de eventos copiable',
title: 'Diagnóstico de Orbit',
role: 'Rol',
hostTrack: 'ID de pista del anfitrión',
hostPos: 'Posición del anfitrión',
guestTrack: 'Mi ID de pista',
guestPos: 'Mi posición',
drift: 'Desfase',
stateAge: 'Edad del estado',
eventLog: 'Registro de eventos ({{count}})',
copyLabel: 'Copiar',
copyTooltip: 'Copiar registro al portapapeles',
clearLabel: 'Borrar',
clearTooltip: 'Vaciar el búfer',
empty: 'Aún sin eventos — aparecen cuando Orbit sincroniza.',
hint: 'Abre esto antes de reproducir el problema, luego pulsa Copiar y pega en el reporte.',
copied: '{{count}} líneas copiadas',
copyFailed: 'No se pudo copiar al portapapeles',
cleared: 'Búfer vaciado',
},
helpTitle: 'Cómo funciona Orbit',
helpIntro: 'Orbit convierte Psysonic en una sala de escucha compartida. Un anfitrión elige la música; los invitados escuchan en sincronía y pueden sugerir canciones.',
helpHostOnly: '(anfitrión)',
+21
View File
@@ -1650,6 +1650,27 @@ export const frTranslation = {
endTooltip: 'Terminer la session',
leaveTooltip: 'Quitter la session',
helpTooltip: 'Fonctionnement d\'Orbit',
diag: {
openTooltip: 'Diagnostic — journal d\'événements copiable',
title: 'Diagnostic Orbit',
role: 'Rôle',
hostTrack: 'ID de piste de l\'hôte',
hostPos: 'Position de l\'hôte',
guestTrack: 'Mon ID de piste',
guestPos: 'Ma position',
drift: 'Décalage',
stateAge: 'Âge de l\'état',
eventLog: 'Journal d\'événements ({{count}})',
copyLabel: 'Copier',
copyTooltip: 'Copier le journal dans le presse-papiers',
clearLabel: 'Effacer',
clearTooltip: 'Vider le tampon',
empty: 'Aucun événement — ils apparaissent dès qu\'Orbit synchronise.',
hint: 'Ouvre ceci avant de reproduire le problème, puis clique Copier et colle dans le rapport.',
copied: '{{count}} lignes copiées',
copyFailed: 'Impossible de copier dans le presse-papiers',
cleared: 'Tampon vidé',
},
helpTitle: 'Fonctionnement d\'Orbit',
helpIntro: 'Orbit transforme Psysonic en salle d\'écoute partagée. Un hôte choisit la musique ; les invités écoutent en synchro et peuvent suggérer des morceaux.',
helpHostOnly: '(hôte)',
+21
View File
@@ -1649,6 +1649,27 @@ export const nbTranslation = {
endTooltip: 'Avslutt økt',
leaveTooltip: 'Forlat økt',
helpTooltip: 'Hvordan Orbit fungerer',
diag: {
openTooltip: 'Diagnose — kopierbar hendelseslogg',
title: 'Orbit-diagnose',
role: 'Rolle',
hostTrack: 'Vertens spor-ID',
hostPos: 'Vertens posisjon',
guestTrack: 'Min spor-ID',
guestPos: 'Min posisjon',
drift: 'Avvik',
stateAge: 'Tilstandens alder',
eventLog: 'Hendelseslogg ({{count}})',
copyLabel: 'Kopier',
copyTooltip: 'Kopier loggen til utklippstavlen',
clearLabel: 'Tøm',
clearTooltip: 'Tøm bufferen',
empty: 'Ingen hendelser ennå — de dukker opp når Orbit synkroniserer.',
hint: 'Åpne dette før du reproduserer problemet, klikk Kopier og lim inn i feilrapporten.',
copied: '{{count}} linjer kopiert',
copyFailed: 'Kunne ikke kopiere til utklippstavlen',
cleared: 'Buffer tømt',
},
helpTitle: 'Hvordan Orbit fungerer',
helpIntro: 'Orbit gjør Psysonic til et delt lytterom. En vert velger musikken; gjester lytter synkronisert og kan foreslå spor.',
helpHostOnly: '(vert)',
+21
View File
@@ -1649,6 +1649,27 @@ export const nlTranslation = {
endTooltip: 'Sessie beëindigen',
leaveTooltip: 'Sessie verlaten',
helpTooltip: 'Hoe Orbit werkt',
diag: {
openTooltip: 'Diagnose — kopieerbaar gebeurtenissen-log',
title: 'Orbit-diagnose',
role: 'Rol',
hostTrack: 'Track-ID van host',
hostPos: 'Positie van host',
guestTrack: 'Mijn track-ID',
guestPos: 'Mijn positie',
drift: 'Verschil',
stateAge: 'Leeftijd van staat',
eventLog: 'Gebeurtenissen-log ({{count}})',
copyLabel: 'Kopiëren',
copyTooltip: 'Log naar klembord kopiëren',
clearLabel: 'Wissen',
clearTooltip: 'Buffer leegmaken',
empty: 'Nog geen gebeurtenissen — ze verschijnen zodra Orbit synchroniseert.',
hint: 'Open dit voor je het probleem reproduceert, klik dan Kopiëren en plak in de bugmelding.',
copied: '{{count}} regels gekopieerd',
copyFailed: 'Kon niet naar klembord kopiëren',
cleared: 'Buffer gewist',
},
helpTitle: 'Hoe Orbit werkt',
helpIntro: 'Orbit maakt van Psysonic een gedeelde luisterruimte. Een host kiest de muziek; gasten luisteren synchroon mee en kunnen nummers voorstellen.',
helpHostOnly: '(host)',
+21
View File
@@ -1712,6 +1712,27 @@ export const ruTranslation = {
endTooltip: 'Завершить сессию',
leaveTooltip: 'Покинуть сессию',
helpTooltip: 'Как работает Orbit',
diag: {
openTooltip: 'Диагностика — копируемый журнал событий',
title: 'Диагностика Orbit',
role: 'Роль',
hostTrack: 'ID трека хоста',
hostPos: 'Позиция хоста',
guestTrack: 'Мой ID трека',
guestPos: 'Моя позиция',
drift: 'Расхождение',
stateAge: 'Возраст состояния',
eventLog: 'Журнал событий ({{count}})',
copyLabel: 'Копировать',
copyTooltip: 'Скопировать журнал в буфер обмена',
clearLabel: 'Очистить',
clearTooltip: 'Очистить буфер',
empty: 'Пока нет событий — они появятся когда Orbit начнёт синхронизацию.',
hint: 'Открой это перед воспроизведением проблемы, затем нажми Копировать и вставь в баг-репорт.',
copied: 'Скопировано строк: {{count}}',
copyFailed: 'Не удалось скопировать в буфер обмена',
cleared: 'Буфер очищен',
},
helpTitle: 'Как работает Orbit',
helpIntro: 'Orbit превращает Psysonic в общую комнату прослушивания. Хост выбирает музыку; гости слушают синхронно и могут предлагать треки.',
helpHostOnly: '(хост)',
+21
View File
@@ -1642,6 +1642,27 @@ export const zhTranslation = {
endTooltip: '结束会话',
leaveTooltip: '离开会话',
helpTooltip: 'Orbit 的工作原理',
diag: {
openTooltip: '诊断 — 可复制的事件日志',
title: 'Orbit 诊断',
role: '角色',
hostTrack: '主持人曲目 ID',
hostPos: '主持人位置',
guestTrack: '我的曲目 ID',
guestPos: '我的位置',
drift: '偏差',
stateAge: '状态时长',
eventLog: '事件日志 ({{count}})',
copyLabel: '复制',
copyTooltip: '将日志复制到剪贴板',
clearLabel: '清除',
clearTooltip: '清空缓冲区',
empty: '暂无事件 — Orbit 同步时会显示。',
hint: '在重现问题前打开此面板,然后点击复制并粘贴到错误报告中。',
copied: '已复制 {{count}} 行',
copyFailed: '无法复制到剪贴板',
cleared: '缓冲区已清空',
},
helpTitle: 'Orbit 的工作原理',
helpIntro: 'Orbit 将 Psysonic 变成一个共享的收听空间。主持人选择音乐;访客同步收听并可以推荐曲目。',
helpHostOnly: '(主持人)',
+98
View File
@@ -13323,6 +13323,104 @@ html[data-perf-disable-home-artwork-clip="true"] .home-lite-artwork .song-card-c
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
}
/* ── Diagnostics popover ──────────────────────────────────────────────── */
.orbit-diag-pop {
width: 920px;
max-width: calc(100vw - 24px);
padding: 14px;
background: var(--bg-card);
border: 1px solid color-mix(in srgb, var(--accent) 22%, rgba(255,255,255,0.1));
border-radius: var(--radius-md);
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
display: flex;
flex-direction: column;
gap: 10px;
}
.orbit-diag-pop__head {
padding: 2px 4px 6px;
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
border-bottom: 1px solid color-mix(in srgb, var(--text-primary) 8%, transparent);
}
.orbit-diag-pop__live {
display: grid;
grid-template-columns: max-content 1fr;
gap: 4px 10px;
font-size: 12px;
padding: 0 4px;
}
.orbit-diag-pop__live-row {
display: contents;
}
.orbit-diag-pop__live-label {
color: var(--text-muted);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.orbit-diag-pop__mono {
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 11px;
color: var(--text-secondary);
word-break: break-all;
}
.orbit-diag-pop__log-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 4px 0;
font-size: 11px;
font-weight: 600;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.orbit-diag-pop__btn-row {
display: flex;
gap: 6px;
}
.orbit-diag-pop__btn {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
font-size: 11px;
background: var(--bg-input);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
color: var(--text-primary);
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
.orbit-diag-pop__btn:hover {
background: var(--bg-hover, var(--bg-input));
border-color: var(--accent);
}
.orbit-diag-pop__log {
width: 100%;
height: 220px;
resize: vertical;
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 10.5px;
line-height: 1.45;
background: var(--bg-input);
color: var(--text-secondary);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
padding: 8px;
white-space: pre;
overflow: auto;
}
.orbit-diag-pop__hint {
font-size: 10.5px;
color: var(--text-muted);
padding: 0 4px;
font-style: italic;
}
.orbit-settings-pop__head {
padding: 2px 4px 12px;
font-size: 10.5px;
+96
View File
@@ -0,0 +1,96 @@
/**
* Orbit diagnostics ring buffer.
*
* In-memory log of recent Orbit events for users who can't reach DevTools or
* Settings Debug Export. The Diagnostics popover in the Orbit bar reads
* this buffer live and offers a one-click clipboard copy so a Discord user
* can paste the buffer straight into a bug-report channel.
*
* Events are also bridged to `frontend_debug_log` when the user has Debug
* logging on in Settings, so the same data lands in `psysonic-logs-*.log`
* for power users who want a persistent file.
*/
import { invoke } from '@tauri-apps/api/core';
import { useAuthStore } from '../store/authStore';
/** Hard cap so a long session doesn't spend memory unbounded. ~200 entries. */
const MAX_EVENTS = 200;
export interface OrbitDiagEvent {
/** Wall-clock ms when the event was pushed. */
ts: number;
/** Short tag, e.g. `pull`, `divergence`, `audio:ended`, `host:state`. */
scope: string;
/** Already-stringified message body. Whitespace + line breaks preserved. */
message: string;
}
const buffer: OrbitDiagEvent[] = [];
const subscribers = new Set<() => void>();
/** Frozen snapshot for `useSyncExternalStore`. Replaced on every mutation;
* identical between mutations so React doesn't keep re-rendering. */
let snapshot: readonly OrbitDiagEvent[] = [];
function notify() {
snapshot = buffer.slice();
for (const sub of subscribers) {
try { sub(); } catch { /* never let one bad listener kill the rest */ }
}
}
/**
* Append an event to the ring. Also fires `frontend_debug_log` so the same
* line shows up in the runtime log file when Debug mode is enabled.
*
* Safe to call from anywhere never throws, never blocks.
*/
export function pushOrbitEvent(scope: string, message: string | Record<string, unknown>): void {
const text = typeof message === 'string' ? message : safeStringify(message);
const evt: OrbitDiagEvent = { ts: Date.now(), scope, message: text };
buffer.push(evt);
if (buffer.length > MAX_EVENTS) buffer.splice(0, buffer.length - MAX_EVENTS);
notify();
// Bridge to the existing Rust log buffer when Debug mode is on, so
// Settings → Debug → Export still works for the same data.
if (useAuthStore.getState().loggingMode === 'debug') {
void invoke('frontend_debug_log', {
scope: `orbit:${scope}`,
message: text,
}).catch(() => { /* best-effort */ });
}
}
function safeStringify(obj: Record<string, unknown>): string {
try { return JSON.stringify(obj); }
catch { return '[unserialisable]'; }
}
/** Snapshot of all currently-buffered events, oldest first.
* Returns the SAME reference between mutations so `useSyncExternalStore`
* can detect "nothing changed" and skip the render. */
export function getOrbitEvents(): readonly OrbitDiagEvent[] {
return snapshot;
}
/** Wipe the buffer. Used by the Clear button in the Diagnostics popover. */
export function clearOrbitEvents(): void {
buffer.length = 0;
notify();
}
/** Subscribe to buffer mutations. Returns the unsubscribe function. */
export function subscribeOrbitEvents(listener: () => void): () => void {
subscribers.add(listener);
return () => { subscribers.delete(listener); };
}
/** Format the buffer as a copy-pasteable plain-text block. */
export function formatOrbitEvents(events: readonly OrbitDiagEvent[]): string {
if (events.length === 0) return '';
const lines = events.map(e => {
const stamp = new Date(e.ts).toISOString();
return `[${stamp}] [${e.scope}] ${e.message}`;
});
return lines.join('\n');
}