fix(web): coherent, recoverable Plex authorized-but-no-servers state (#345) #366

Merged
timothy merged 2 commits from fix/345-plex-empty-servers into main 2026-07-16 14:36:52 +02:00
4 changed files with 193 additions and 29 deletions
+23 -8
View File
@@ -25,48 +25,63 @@ describe('initialPinFlowState', () => {
describe('evaluatePinFlow — all transitions with injected state', () => {
it('locked & !authorized => waiting (keep polling)', () => {
const state = evaluatePinFlow({ isLocked: true, isAuthorized: false });
const state = evaluatePinFlow({ isLocked: true, isAuthorized: false, hasServers: false });
expect(state.status).toBe('waiting');
expect(state.done).toBe(false);
expect(state.ok).toBe(false);
});
it('locked & authorized => finalizing (keep polling, discovering servers)', () => {
const state = evaluatePinFlow({ isLocked: true, isAuthorized: true });
const state = evaluatePinFlow({ isLocked: true, isAuthorized: true, hasServers: false });
expect(state.status).toBe('finalizing');
expect(state.done).toBe(false);
expect(state.ok).toBe(false);
});
it('!locked & authorized => success (terminal)', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: true });
it('!locked & authorized & servers => success (terminal)', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: true, hasServers: true });
expect(state.status).toBe('success');
expect(state.done).toBe(true);
expect(state.ok).toBe(true);
});
it('!locked & authorized & NO servers => authorized-no-servers (terminal, recoverable, not ok) — #345', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: true, hasServers: false });
expect(state.status).toBe('authorized-no-servers');
expect(state.done).toBe(true); // terminal: the lock has released, polling stops
expect(state.ok).toBe(false); // authorized, but NOT "Connected to Plex."
expect(state.message).not.toBe('Connected to Plex.');
expect(state.message).toMatch(/no eligible servers/i);
});
it('!locked & !authorized => timeout (terminal, ended without auth)', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: false });
const state = evaluatePinFlow({ isLocked: false, isAuthorized: false, hasServers: false });
expect(state.status).toBe('timeout');
expect(state.done).toBe(true);
expect(state.ok).toBe(false);
});
it('locked & budget exhausted => budget-exhausted (terminal, not a failure)', () => {
const state = evaluatePinFlow({ isLocked: true, isAuthorized: true }, { budgetExhausted: true });
const state = evaluatePinFlow({ isLocked: true, isAuthorized: true, hasServers: false }, { budgetExhausted: true });
expect(state.status).toBe('budget-exhausted');
expect(state.done).toBe(true);
expect(state.ok).toBe(false);
});
it('budget exhaustion is ignored once the lock has released (success still wins)', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: true }, { budgetExhausted: true });
const state = evaluatePinFlow({ isLocked: false, isAuthorized: true, hasServers: true }, { budgetExhausted: true });
expect(state.status).toBe('success');
expect(state.ok).toBe(true);
});
it('budget exhaustion is ignored once the lock has released (authorized-no-servers still wins)', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: true, hasServers: false }, { budgetExhausted: true });
expect(state.status).toBe('authorized-no-servers');
expect(state.ok).toBe(false);
});
it('budget exhaustion is ignored once the lock has released (timeout still wins)', () => {
const state = evaluatePinFlow({ isLocked: false, isAuthorized: false }, { budgetExhausted: true });
const state = evaluatePinFlow({ isLocked: false, isAuthorized: false, hasServers: false }, { budgetExhausted: true });
expect(state.status).toBe('timeout');
});
});
+39 -13
View File
@@ -1,26 +1,40 @@
// The Plex OAuth pin-flow poll STATE MACHINE (design §C1 step 5), as a pure, timer-free module so
// the transitions can be unit-tested with injected state. The Plex screen (slice S6b) drives it:
// after `POST /pin-flow` it opens the auth URL and polls `GET /api/v1/media-sources/plex` every 2s for
// up to 150s, feeding each observation ({ isLocked, isAuthorized }) here to decide what to show and
// whether to keep polling.
// up to 150s, feeding each observation ({ isLocked, isAuthorized, hasServers }) here to decide what to
// show and whether to keep polling.
//
// KEY INSIGHT (finding 5): `isAuthorized` flips true the moment the token is saved, which is BEFORE
// SynchronizePlexMediaSources discovers the servers and releases the Plex lock. So authorization
// alone is NOT success — the terminal success signal is the lock RELEASING while authorized. Poll
// until the lock releases, not until authorized.
//
// isLocked & !isAuthorized -> waiting (keep polling; user hasn't authorized yet)
// isLocked & isAuthorized -> finalizing (keep polling; discovering servers)
// !isLocked & isAuthorized -> success (terminal)
// !isLocked & !isAuthorized -> timeout (terminal; flow ended without auth)
// isLocked (budget spent) -> budget-exhausted (terminal; a large first sync legitimately
// still holds the lock — not a failure)
// AUTHORIZED-BUT-EMPTY (#345): authorization and server discovery are distinct outcomes. A real flow
// reached `isAuthorized: true`, `isLocked: false`, `servers: []` (a Plex account that owns/has been
// granted no eligible servers). That is a coherent, recoverable terminal — NOT "Connected to Plex." —
// so the released-lock success branch further splits on whether any server was actually discovered.
//
// isLocked & !isAuthorized -> waiting (keep polling; user hasn't authorized yet)
// isLocked & isAuthorized -> finalizing (keep polling; discovering servers)
// !isLocked & isAuthorized & servers -> success (terminal; connected to a server)
// !isLocked & isAuthorized & !servers -> authorized-no-servers (terminal; authorized, none discovered)
// !isLocked & !isAuthorized -> timeout (terminal; flow ended without auth)
// isLocked (budget spent) -> budget-exhausted (terminal; a large first sync legitimately
// still holds the lock — not a failure)
export type PinFlowStatus = 'waiting' | 'finalizing' | 'success' | 'timeout' | 'budget-exhausted';
export type PinFlowStatus =
| 'waiting'
| 'finalizing'
| 'success'
| 'authorized-no-servers'
| 'timeout'
| 'budget-exhausted';
export interface PinFlowObservation {
isLocked: boolean;
isAuthorized: boolean;
/** Whether server discovery has surfaced at least one server for this authorization. */
hasServers: boolean;
}
export interface PinFlowState {
@@ -41,14 +55,22 @@ const MESSAGES: Record<PinFlowStatus, string> = {
waiting: 'Waiting for you to authorize in the Plex tab…',
finalizing: 'Authorized — discovering your Plex servers…',
success: 'Connected to Plex.',
'authorized-no-servers': 'Signed in to Plex, but no eligible servers were discovered.',
timeout: 'Plex sign-in timed out — try again.',
'budget-exhausted': 'Still working — this can take a while on a large first sync. Use Refresh to check again.'
};
const TERMINAL: ReadonlySet<PinFlowStatus> = new Set<PinFlowStatus>([
'success',
'authorized-no-servers',
'timeout',
'budget-exhausted'
]);
function stateFor(status: PinFlowStatus): PinFlowState {
return {
status,
done: status === 'success' || status === 'timeout' || status === 'budget-exhausted',
done: TERMINAL.has(status),
ok: status === 'success',
message: MESSAGES[status]
};
@@ -73,11 +95,15 @@ export function evaluatePinFlow(
observation: PinFlowObservation,
options: { budgetExhausted?: boolean } = {}
): PinFlowState {
const { isLocked, isAuthorized } = observation;
const { isLocked, isAuthorized, hasServers } = observation;
// Lock released: terminal either way. Success iff authorized.
// Lock released: terminal. Not authorized at all -> timeout. Authorized -> success only when a
// server was actually discovered; authorized-but-empty is its own recoverable terminal (#345).
if (!isLocked) {
return stateFor(isAuthorized ? 'success' : 'timeout');
if (!isAuthorized) {
return stateFor('timeout');
}
return stateFor(hasServers ? 'success' : 'authorized-no-servers');
}
// Still locked but out of budget: not a failure, just "still working".
+96
View File
@@ -170,4 +170,100 @@ describe('PlexSourceScreen', () => {
expect(fetchSpy.mock.calls.some(([input, init]) => String(input).endsWith('/sign-out') && (init?.method ?? '').toUpperCase() === 'POST')).toBe(true)
);
});
// #345: a real pin flow reached isAuthorized:true, isLocked:false, servers:[] (a Plex account that
// owns no eligible servers). The UI used to claim "Connected to Plex." while the Connection card said
// "Not signed in.", offered Sign in, and hid Sign out — so the stored authorization was unremovable.
it('pin flow ending authorized/unlocked with NO servers is coherent and recoverable', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
installFetch(stateRef, counter);
vi.spyOn(window, 'open').mockReturnValue({} as Window);
vi.useFakeTimers();
render(<PlexSourceScreen />);
await vi.waitFor(() => expect(screen.getByRole('button', { name: 'Sign in to Plex' })).toBeTruthy());
stateRef.current = { isAuthorized: false, isLocked: true, servers: [] };
fireEvent.click(screen.getByRole('button', { name: 'Sign in to Plex' }));
await vi.waitFor(() => expect(screen.getByText(/Waiting for you to authorize/i)).toBeTruthy());
// Authorized but STILL LOCKED = finalizing (discovery in progress). The empty-servers terminal
// messaging must NOT appear here — while locked this is the normal "discovering" window, not
// "no servers were found" (regression guard for the isLocked gate).
stateRef.current = { isAuthorized: true, isLocked: true, servers: [] };
await vi.advanceTimersByTimeAsync(2000);
await vi.waitFor(() => expect(screen.getByText(/discovering your Plex servers/i)).toBeTruthy());
expect(screen.queryByText(/Your Plex account is authorized/i)).toBeNull(); // no "sign out and retry" summary
expect(screen.queryByText(/no eligible servers were discovered/i)).toBeNull();
expect(screen.queryByRole('button', { name: 'Sign in to Plex' })).toBeNull();
// Lock releases while authorized but discovery found nothing: the distinct terminal state.
stateRef.current = { isAuthorized: true, isLocked: false, servers: [] };
await vi.advanceTimersByTimeAsync(2000);
// Pin-flow message distinguishes authorization from server discovery (does not claim connection).
await vi.waitFor(() =>
expect(screen.getByText('Signed in to Plex, but no eligible servers were discovered.')).toBeTruthy()
);
expect(screen.queryByText('Connected to Plex.')).toBeNull();
// The explanatory summary is shown (distinct wording anchors it).
expect(screen.getByText(/Your Plex account is authorized/i)).toBeTruthy();
// No Servers card, and the Connection card + actions agree: Sign out offered, Sign in withheld.
expect(screen.queryByRole('heading', { name: 'Servers' })).toBeNull();
expect(screen.getByRole('button', { name: 'Sign out of Plex' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'Sign in to Plex' })).toBeNull();
// Polling stopped on the terminal state.
const callsAfterTerminal = counter.state;
await vi.advanceTimersByTimeAsync(6000);
expect(counter.state).toBe(callsAfterTerminal);
});
it('authorized/unlocked/empty state loaded fresh (no pin flow) can sign out', async () => {
// The reload path: no pinState, not polling — driven purely by the loaded RemoteMediaSourceState.
const stateRef = { current: { isAuthorized: true, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
const fetchSpy = installFetch(stateRef, counter);
render(<PlexSourceScreen />);
// The explanatory summary and Sign-out action reflect "authorized, no servers" (not "Not signed in.").
await screen.findByText(/Your Plex account is authorized/i);
expect(screen.queryByRole('button', { name: 'Sign in to Plex' })).toBeNull();
expect(screen.queryByText('Not signed in.')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Sign out of Plex' }));
expect(await screen.findByText(/removes all synced Plex servers/i)).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Sign out' }));
await vi.waitFor(() =>
expect(fetchSpy.mock.calls.some(([input, init]) => String(input).endsWith('/sign-out') && (init?.method ?? '').toUpperCase() === 'POST')).toBe(true)
);
});
// #345 (review follow-up): a large first sync legitimately still holds the lock past the poll
// budget (budget-exhausted). The empty-servers "sign out and retry" messaging must NOT show — it
// would contradict the "Still working…" status and urge aborting an in-progress sync.
it('budget-exhausted while locked with no servers does not show the "no servers, sign out" messaging', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
installFetch(stateRef, counter);
vi.spyOn(window, 'open').mockReturnValue({} as Window);
vi.useFakeTimers();
render(<PlexSourceScreen />);
await vi.waitFor(() => expect(screen.getByRole('button', { name: 'Sign in to Plex' })).toBeTruthy());
// Authorized but locked forever (large first sync holds the lock).
stateRef.current = { isAuthorized: true, isLocked: true, servers: [] };
fireEvent.click(screen.getByRole('button', { name: 'Sign in to Plex' }));
await vi.waitFor(() => expect(screen.getByText(/discovering your Plex servers|Waiting/i)).toBeTruthy());
await vi.advanceTimersByTimeAsync(152_000); // consume the whole 150s budget
await vi.waitFor(() => expect(screen.getByText(/Still working/i)).toBeTruthy());
// The lock is still held, so no terminal "no servers were found" messaging.
expect(screen.queryByText(/Your Plex account is authorized/i)).toBeNull();
expect(screen.queryByText(/no eligible servers were discovered/i)).toBeNull();
});
});
+35 -8
View File
@@ -84,7 +84,10 @@ export function PlexSourceScreen() {
}
setBoot({ status: 'ready', state });
const elapsed = Date.now() - startedAtRef.current;
const next = evaluatePinFlow(state, { budgetExhausted: isPinFlowBudgetExhausted(elapsed) });
const next = evaluatePinFlow(
{ isLocked: state.isLocked, isAuthorized: state.isAuthorized, hasServers: (state.servers ?? []).length > 0 },
{ budgetExhausted: isPinFlowBudgetExhausted(elapsed) }
);
setPinState(next);
if (next.done) {
setPolling(false);
@@ -210,8 +213,26 @@ export function PlexSourceScreen() {
const { isAuthorized, isLocked, servers } = boot.state;
const serverList = servers ?? [];
const connected = serverList.length > 0;
const needsFix = connected && !isAuthorized;
const hasServers = serverList.length > 0;
// Authorization (a stored Plex token) and connection (a discovered server) are DISTINCT (#345).
// `hasPlexAccount` is "there is stored Plex state to sign out of" — an authorized token OR
// discovered servers — and it, not the server count, gates Sign in vs Sign out. This makes the
// authorized/unlocked/empty-servers state recoverable: Sign out is offered, Sign in is not.
const hasPlexAccount = isAuthorized || hasServers;
const needsFix = hasServers && !isAuthorized;
// Only a RELEASED lock is terminal: while `isLocked`, an authorized+empty observation is the
// normal `finalizing` (discovery in progress) or `budget-exhausted` (large first sync still
// running) window — NOT "no servers were found". Gating on `!isLocked` keeps the "no eligible
// servers, sign out and retry" messaging from contradicting the in-flight discovery status and
// from urging a sign-out that would abort a legitimately-running sync.
const authorizedNoServers = isAuthorized && !hasServers && !isLocked;
const connectionSubtitle = !hasPlexAccount
? 'Not signed in.'
: needsFix
? 'Signed in, but credentials need attention.'
: authorizedNoServers
? 'Signed in to Plex — no eligible servers were discovered.'
: 'Signed in to Plex.';
return (
<div className="ctv-libraries-screen">
@@ -235,10 +256,10 @@ export function PlexSourceScreen() {
<Card
title={<h3>Connection</h3>}
subtitle={connected ? (isAuthorized ? 'Signed in to Plex.' : 'Signed in, but credentials need attention.') : 'Not signed in.'}
subtitle={connectionSubtitle}
actions={
<div style={{ display: 'flex', gap: 8 }}>
{!connected && (
{!hasPlexAccount && (
<Button disabled={starting || polling} loading={starting} onClick={startPinFlow} startIcon={<LogIn aria-hidden="true" size={14} />}>
Sign in to Plex
</Button>
@@ -248,7 +269,7 @@ export function PlexSourceScreen() {
Fix Plex Credentials
</Button>
)}
{connected && (
{hasPlexAccount && (
<Button disabled={signingOut || polling} onClick={() => setConfirmSignOut(true)} startIcon={<LogOut aria-hidden="true" size={14} />} variant="secondary">
Sign out of Plex
</Button>
@@ -265,12 +286,12 @@ export function PlexSourceScreen() {
)}
</div>
)}
{!polling && !pinState && !connected && (
{!polling && !pinState && !hasPlexAccount && (
<div className="ctv-schedule-empty">Sign in to Plex to connect a server.</div>
)}
</Card>
{connected && (
{hasServers && (
<Card title={<h3>Servers</h3>} subtitle={`${serverList.length} server${serverList.length === 1 ? '' : 's'} discovered.`} padded={false}>
<div className="ctv-library-list" role="list" aria-label="Plex servers">
{serverList.map((server) => (
@@ -300,6 +321,12 @@ export function PlexSourceScreen() {
</div>
)}
{authorizedNoServers && (
<div className="ctv-libraries-summary">
<span><Badge tone="neutral">No servers</Badge> Your Plex account is authorized, but no eligible servers were discovered. Confirm your Plex account owns or has been granted access to a server, then Sign out of Plex and sign in again to retry.</span>
</div>
)}
<ConfirmDialog
open={confirmSignOut}
tone="danger"