From 0f0a0d7fe5b495e5524d1e79a0ade877c72c855c Mon Sep 17 00:00:00 2001 From: Timothy Date: Thu, 16 Jul 2026 14:15:45 +0200 Subject: [PATCH 1/2] fix(web): coherent, recoverable Plex authorized-but-no-servers state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A real Plex pin flow reached isAuthorized:true, isLocked:false, servers:[] (a Plex account that owns/has been granted no eligible servers). The SPA then showed contradictory state: the pin-flow status claimed "Connected to Plex." while the Connection card said "Not signed in.", offered Sign in, and hid Sign out — so the stored authorization could not be removed through the UI. Root cause: PlexSourceScreen conflated authorization (a stored token, isAuthorized) with connection (a discovered server, servers.length > 0) by deriving everything from `connected = servers.length > 0`, and evaluatePinFlow returned `success` ("Connected to Plex.") for any released-lock authorized observation regardless of server count. Fix (pure SPA; sign-out endpoint already works with empty servers): - pinFlowPoll: add a distinct `authorized-no-servers` terminal status and a `hasServers` observation field; the released-lock branch now yields success only when a server was discovered, else authorized-no-servers with an honest message that distinguishes authorization from discovery. - PlexSourceScreen: gate Sign in vs Sign out on `hasPlexAccount` (isAuthorized || hasServers) instead of the server count, so an authorized account can always sign out; add a subtitle + explanatory summary for the authorized/empty state; keep the Servers card gated on actual servers. - Regression tests: the authorized/unlocked/empty transition (pin-flow and fresh-reload paths) and sign-out from that state. fixes #345 --- web/src/mediaSources/pinFlowPoll.test.ts | 31 +++++++++--- web/src/mediaSources/pinFlowPoll.ts | 52 +++++++++++++++----- web/src/screens/PlexSourceScreen.test.tsx | 60 +++++++++++++++++++++++ web/src/screens/PlexSourceScreen.tsx | 38 +++++++++++--- 4 files changed, 152 insertions(+), 29 deletions(-) diff --git a/web/src/mediaSources/pinFlowPoll.test.ts b/web/src/mediaSources/pinFlowPoll.test.ts index d8b2d24da..196e8b0b3 100644 --- a/web/src/mediaSources/pinFlowPoll.test.ts +++ b/web/src/mediaSources/pinFlowPoll.test.ts @@ -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'); }); }); diff --git a/web/src/mediaSources/pinFlowPoll.ts b/web/src/mediaSources/pinFlowPoll.ts index 328cc0337..7a89e9d1d 100644 --- a/web/src/mediaSources/pinFlowPoll.ts +++ b/web/src/mediaSources/pinFlowPoll.ts @@ -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 = { 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 = new Set([ + '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". diff --git a/web/src/screens/PlexSourceScreen.test.tsx b/web/src/screens/PlexSourceScreen.test.tsx index 132383f9e..0790723ee 100644 --- a/web/src/screens/PlexSourceScreen.test.tsx +++ b/web/src/screens/PlexSourceScreen.test.tsx @@ -170,4 +170,64 @@ 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(); + 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()); + + // 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(); + + // 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) + ); + }); }); diff --git a/web/src/screens/PlexSourceScreen.tsx b/web/src/screens/PlexSourceScreen.tsx index 7c896d0be..ea9e4c6ae 100644 --- a/web/src/screens/PlexSourceScreen.tsx +++ b/web/src/screens/PlexSourceScreen.tsx @@ -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,21 @@ 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; + const authorizedNoServers = isAuthorized && !hasServers; + 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 (
@@ -235,10 +251,10 @@ export function PlexSourceScreen() { Connection} - subtitle={connected ? (isAuthorized ? 'Signed in to Plex.' : 'Signed in, but credentials need attention.') : 'Not signed in.'} + subtitle={connectionSubtitle} actions={
- {!connected && ( + {!hasPlexAccount && ( @@ -248,7 +264,7 @@ export function PlexSourceScreen() { Fix Plex Credentials )} - {connected && ( + {hasPlexAccount && ( @@ -265,12 +281,12 @@ export function PlexSourceScreen() { )}
)} - {!polling && !pinState && !connected && ( + {!polling && !pinState && !hasPlexAccount && (
Sign in to Plex to connect a server.
)}
- {connected && ( + {hasServers && ( Servers} subtitle={`${serverList.length} server${serverList.length === 1 ? '' : 's'} discovered.`} padded={false}>
{serverList.map((server) => ( @@ -300,6 +316,12 @@ export function PlexSourceScreen() {
)} + {authorizedNoServers && ( +
+ No servers 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. +
+ )} + Date: Thu, 16 Jul 2026 14:29:47 +0200 Subject: [PATCH 2/2] fix(web): gate Plex authorized-no-servers messaging on released lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adversarial review of the initial fix found that authorizedNoServers = isAuthorized && !hasServers ignored isLocked. Because boot.state updates on every poll observation, the "no eligible servers — sign out and retry" subtitle + summary rendered during the normal `finalizing` window (locked, authorized, no servers yet) alongside the "discovering your Plex servers…" status — and during `budget-exhausted` (large first sync still holding the lock, polling stopped, Sign out enabled) it urged the user to sign out mid-sync. That reintroduced the contradictory-state class the PR fixes. Gate the empty-servers presentation on !isLocked so it only appears at the genuine released-lock terminal. Add regression coverage: the pin-flow test now passes through the finalizing cell asserting the empty-servers messaging is absent while locked, plus a budget-exhausted-while-locked case. Both new guards were confirmed to fail on the ungated code (negative control). Refs #345 --- web/src/screens/PlexSourceScreen.test.tsx | 36 +++++++++++++++++++++++ web/src/screens/PlexSourceScreen.tsx | 7 ++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/web/src/screens/PlexSourceScreen.test.tsx b/web/src/screens/PlexSourceScreen.test.tsx index 0790723ee..1e85a0b94 100644 --- a/web/src/screens/PlexSourceScreen.test.tsx +++ b/web/src/screens/PlexSourceScreen.test.tsx @@ -188,6 +188,16 @@ describe('PlexSourceScreen', () => { 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); @@ -230,4 +240,30 @@ describe('PlexSourceScreen', () => { 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(); + 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(); + }); }); diff --git a/web/src/screens/PlexSourceScreen.tsx b/web/src/screens/PlexSourceScreen.tsx index ea9e4c6ae..81beab971 100644 --- a/web/src/screens/PlexSourceScreen.tsx +++ b/web/src/screens/PlexSourceScreen.tsx @@ -220,7 +220,12 @@ export function PlexSourceScreen() { // authorized/unlocked/empty-servers state recoverable: Sign out is offered, Sign in is not. const hasPlexAccount = isAuthorized || hasServers; const needsFix = hasServers && !isAuthorized; - const authorizedNoServers = isAuthorized && !hasServers; + // 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 -- 2.47.3