Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

The plumbing every failing request goes through (#158)

Carterd33ab25d8a7c
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 1d87434..66d7b73 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -2,12 +2,15 @@ import axios, { AxiosInstance } from 'axios'
import * as types from './types'
import { StorageAdapter, STORAGE_KEYS } from './storage'
import { normalizeServerUrl } from './utils/serverUrl'
-import { networkFailureMessage } from './utils/networkError'
+import { networkFailureMessage, type MessageDetail } from './utils/networkError'
import { withLoggedOn, utcOffsetMinutes } from './utils/dateUtils'
// Every API call lives under this versioned path. `origin` is an absolute server
// origin for a cross-origin backend, or '' for the same-origin reverse proxy (web).
const API_BASE_PATH = '/api/v1'
+// Still exported here: web's services/api.ts re-exports it, and un-exporting is part of
+// the web adoption slice, not this one. Keeping the surface additive means this can merge
+// on its own without a web change riding along.
export const apiUrl = (origin = '') => `${origin}${API_BASE_PATH}`
export interface ServerInfo {
@@ -22,21 +25,19 @@ export interface ServerInfo {
demo_mode?: boolean
}
-export interface ClientOptions {
- // Called after a token refresh fails — the session is dead. Web passes a
- // `location.href = '/login'`; mobile passes `router.replace('/login')`.
- onAuthFailure?: () => void
- // Optional hard override of the base URL (web passes import.meta.env.VITE_API_URL).
- // When set, the stored server_url is ignored.
- baseUrlOverride?: string
-}
-
// Turn an axios error into an actionable message. Proxy misconfig (404/405) is
// distinguished from real auth and server errors, so connectivity problems don't
// masquerade as "Registration failed." Response-less failures go to the classifier,
// which separates a blocked-cleartext or untrusted-certificate failure from a genuinely
// unreachable server — they are indistinguishable from the axios error alone.
-export const apiErrorMessage = (err: any, fallback: string): string => {
+// Whether the server answered "that is not here" rather than failing to answer.
+//
+// The difference decides whether a screen may offer Try again. Retrying a row that does
+// not exist fails identically every time, so the button is a promise the app cannot keep;
+// the way out of a 404 is the escape hatch, not the retry. Anything else — a timeout, a
+// 5xx, a dropped connection — may well succeed on a second attempt.
+export const isNotFound = (err: any): boolean => err?.response?.status === 404
+export const apiErrorMessage = (err: any, fallback: string, detail: MessageDetail = 'brief'): string => {
if (err?.response) {
const serverError = err.response.data?.error
if (serverError) return serverError
@@ -44,10 +45,28 @@ export const apiErrorMessage = (err: any, fallback: string): string => {
if (status === 404 || status === 405) {
return "Server URL looks misconfigured — the API endpoint wasn't found. Check Server settings."
}
+ // Ordered ABOVE the HTML sniff on purpose. Every reverse proxy — nginx, Caddy,
+ // Traefik — serves its 502 as an HTML page, so sniffing for a document first
+ // diagnosed a restarting backend as "check Server settings": wrong, and wrong in the
+ // most self-hosted moment there is, when the settings are fine and the stack is
+ // mid-upgrade. Status is the stronger signal when we have one.
+ if (status === 502 || status === 503 || status === 504) {
+ return 'The server is restarting or unreachable. Try again in a moment.'
+ }
+ // A reverse proxy answers with its own HTML page when the app behind it is down,
+ // restarting, or was never there — the body is a document, not our {"error"} envelope.
+ // wger's client models this case explicitly (ErrorType.html) because self-hosted setups
+ // meet it every time the stack is updated. Falling through to the caller's fallback
+ // would report "Couldn't save your workout", hiding an infrastructure problem behind
+ // what reads as an app bug.
+ const body = err.response.data
+ if (typeof body === 'string' && /^\s*<(!doctype|html)/i.test(body)) {
+ return 'That address returned a web page, not the Lyftr API. Check Server settings.'
+ }
if (status >= 500) return 'Server error. Please try again shortly.'
return fallback
}
- return networkFailureMessage(err)
+ return networkFailureMessage(err, detail)
}
// Probe a server's public /info endpoint to confirm it's reachable and is a Lyftr
@@ -63,7 +82,7 @@ export const testServerConnection = async (
}
return { ok: true, info }
} catch (err) {
- return { ok: false, message: apiErrorMessage(err, "Couldn't reach the server.") }
+ return { ok: false, message: apiErrorMessage(err, "Couldn't reach the server.", 'full') }
}
}
@@ -102,7 +121,17 @@ const sessionWasRevoked = (err: any): boolean => {
// Build a fully-wired API client bound to a platform storage adapter. All token
// reads/writes and the base-URL resolution go through `storage`, so the same code
// runs on web (localStorage) and mobile (SecureStore/AsyncStorage).
-export function createClient(storage: StorageAdapter, opts: ClientOptions = {}) {
+export function createClient(
+ storage: StorageAdapter,
+ opts: {
+ // Called after a token refresh fails — the session is dead. Web passes a
+ // `location.href = '/login'`; mobile passes `router.replace('/login')`.
+ onAuthFailure?: () => void
+ // Optional hard override of the base URL (web passes import.meta.env.VITE_API_URL).
+ // When set, the stored server_url is ignored.
+ baseUrlOverride?: string
+ } = {},
+) {
// Resolved per-request so a "Server settings" change takes effect immediately.
const resolveAPIBase = async (): Promise<string> => {
if (opts.baseUrlOverride) return opts.baseUrlOverride
diff --git a/packages/shared/src/hooks/useAsyncAction.ts b/packages/shared/src/hooks/useAsyncAction.ts
new file mode 100644
index 0000000..cc6b3db
--- /dev/null
+++ b/packages/shared/src/hooks/useAsyncAction.ts
@@ -0,0 +1,77 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { apiErrorMessage } from '../client'
+
+export interface AsyncAction<A extends unknown[]> {
+ /** True while the action is in flight. Gate the button on this. */
+ busy: boolean
+ /** '' until the action fails, then the sentence a person should read. */
+ error: string
+ /** Runs the action. Resolves true on success, false if it failed. */
+ run: (...args: A) => Promise<boolean>
+ /** Drop a stale message — on dismiss, or when the form changes underneath it. */
+ reset: () => void
+}
+
+// One way to run a request that can fail.
+//
+// Before this there were forty-odd copies of the same six lines — set a busy flag, try,
+// await, catch, set a message, clear the flag — and they did not agree. Some read
+// `err.response.data.error` directly, which is empty for the failures that matter most
+// (a timeout has no response at all), so the screen fell back to "Failed to save" and
+// told the user nothing. Some caught with a bare `catch {}` and said nothing whatsoever,
+// which made a failed delete look identical to a tap that never registered. Several
+// dismissed the sheet they were in, sending the explanation to a banner at the top of a
+// list the user had scrolled away from.
+//
+// Those were not sloppy call sites; they were forty chances to get one thing right.
+// `apiErrorMessage` lives INSIDE this hook for that reason: the wording is no longer
+// something a call site can bypass, forget, or half-remember.
+//
+// What it deliberately does not do: decide what success means. Navigating, closing a
+// sheet, refetching a list — that stays in the action, where the screen can see it.
+export function useAsyncAction<A extends unknown[] = []>(
+ action: (...args: A) => Promise<unknown>,
+ fallbackMessage: string,
+): AsyncAction<A> {
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ // Latest-callback refs. Screens pass an inline closure that reads current state, so
+ // `action` has a fresh identity every render — capturing it in the useCallback deps
+ // would give `run` a fresh identity too, and `run` is handed to memoized rows and
+ // cards. Reading through a ref keeps `run` permanently stable while still calling the
+ // newest closure, so a per-second tick elsewhere on the screen cannot invalidate it.
+ const latest = useRef(action)
+ latest.current = action
+ const fallback = useRef(fallbackMessage)
+ fallback.current = fallbackMessage
+
+ // A successful action usually navigates away or closes the surface it lives on, so by
+ // the time the promise resolves this component may be gone. Setting state then is a
+ // no-op in React 18+, but the guard keeps that an intention rather than a coincidence.
+ const mounted = useRef(true)
+ useEffect(() => {
+ mounted.current = true
+ return () => { mounted.current = false }
+ }, [])
+
+ const run = useCallback(async (...args: A): Promise<boolean> => {
+ setBusy(true)
+ setError('')
+ try {
+ await latest.current(...args)
+ return true
+ } catch (err) {
+ if (mounted.current) setError(apiErrorMessage(err, fallback.current))
+ return false
+ } finally {
+ // In `finally`, not only on the failure path: a screen that stays put after
+ // succeeding (Settings, a password change) would otherwise read "Saving…" forever.
+ if (mounted.current) setBusy(false)
+ }
+ }, [])
+
+ const reset = useCallback(() => setError(''), [])
+
+ return { busy, error, run, reset }
+}
diff --git a/packages/shared/src/hooks/useServerList.ts b/packages/shared/src/hooks/useServerList.ts
index 2987f51..d19615b 100644
--- a/packages/shared/src/hooks/useServerList.ts
+++ b/packages/shared/src/hooks/useServerList.ts
@@ -19,12 +19,15 @@
// delete. `refreshing` marks the deps-change case so a screen can show a subtle cue over
// the stale results.
import { useState, useEffect, useRef, useCallback } from 'react'
+import { apiErrorMessage } from '../client'
interface Options<T> {
fetcher: (offset: number, limit: number) => Promise<T[]>
pageSize?: number
// Changing any dep resets the list and re-fetches from offset 0 (e.g. search query)
deps?: readonly unknown[]
+ // Shown when the server gives us nothing better to say.
+ errorFallback?: string
}
interface Result<T> {
@@ -43,17 +46,25 @@ interface Result<T> {
// Background revalidate; returns the fetch promise so a caller (e.g. pull-to-refresh)
// can await completion to drive its own spinner.
reload: () => Promise<void>
+ // Why the last fetch failed, or null. A page that never arrived used to just set
+ // hasMore=false, so the list stopped exactly like a list that had reached its end —
+ // the one shape a reader cannot tell from success. Render it, with retry().
+ error: string | null
+ // Resume from wherever we stopped. Keeps whatever already loaded.
+ retry: () => void
}
export function useServerList<T>({
fetcher,
pageSize = 20,
deps = [],
+ errorFallback = "Couldn't load this list.",
}: Options<T>): Result<T> {
const [items, setItems] = useState<T[]>([])
const [hasMore, setHasMore] = useState(true)
const [loading, setLoading] = useState(false)
const [refreshing, setRefreshing] = useState(false)
+ const [error, setError] = useState<string | null>(null)
const offsetRef = useRef(0)
// Tracks whether a fetch is in flight to prevent double-fetches (onEndReached can
// fire repeatedly during momentum scrolling)
@@ -73,13 +84,37 @@ export function useServerList<T>({
try {
const page = await fetcher(currentOffset, pageSize)
if (myId !== reqIdRef.current) return // superseded by a newer fetch — drop it
+ // A response that is not a list takes the whole app down, not just this list:
+ // the spread below throws, React unmounts the tree, and with no error boundary
+ // anywhere the screen goes white — no nav, nothing to click, dead until a manual
+ // reload. Measured with {"data": null} and with {} from a stubbed endpoint, which
+ // is what a half-deployed backend or a proxy in front of the wrong service sends.
+ //
+ // Reported as a failure rather than coerced to []: an empty array here would draw
+ // "No workouts found", which is the same lie about the user's data that the rest
+ // of this work exists to remove.
+ if (!Array.isArray(page)) {
+ if (myId === reqIdRef.current) {
+ setHasMore(false)
+ setError('The server sent something we could not read.')
+ }
+ return
+ }
+ setError(null)
setItems(prev => (replace ? page : [...prev, ...page]))
offsetRef.current = currentOffset + page.length
setHasMore(page.length === pageSize)
- } catch {
+ } catch (err) {
// Web lets rejections escape (harmless in a browser); on RN an unhandled
// rejection is red-box noise — keep what loaded and stop paginating instead.
- if (myId === reqIdRef.current) setHasMore(false)
+ //
+ // Stopping quietly was the whole bug: hasMore=false renders exactly like
+ // reaching the end of the data, so a dropped connection looked like "that is
+ // all there is". Name it and let the screen offer retry().
+ if (myId === reqIdRef.current) {
+ setHasMore(false)
+ setError(apiErrorMessage(err, errorFallback))
+ }
} finally {
// Only the latest fetch owns the shared flags — a stale response bows out without
// flipping loading/fetching out from under the request that superseded it.
@@ -89,7 +124,7 @@ export function useServerList<T>({
setLoading(false)
}
}
- }, [fetcher, pageSize])
+ }, [fetcher, pageSize, errorFallback])
// Deps change (e.g. the search query): reset pagination and refetch page 0, but keep
// the previous results on screen until the fresh page replaces them (stale-while-
@@ -98,6 +133,7 @@ export function useServerList<T>({
useEffect(() => {
offsetRef.current = 0
setHasMore(true)
+ setError(null)
fetchingRef.current = false
setRefreshing(true)
fetchPage(0, true).finally(() => setRefreshing(false))
@@ -114,5 +150,18 @@ export function useServerList<T>({
// the fetch itself on success.
const reload = useCallback(() => fetchPage(0, true), [fetchPage])
- return { items, loadMore, hasMore, loading, initialLoading: loading && !initializedRef.current, refreshing, reload }
+ // Resume, rather than reload: the pages already on screen are fine, it was the next
+ // one that never came. hasMore has to go back up first — loadMore checks it, and the
+ // failure is what set it false.
+ const retry = useCallback(() => {
+ setError(null)
+ setHasMore(true)
+ fetchPage(offsetRef.current, offsetRef.current === 0)
+ }, [fetchPage])
+
+ return {
+ items, loadMore, hasMore, loading,
+ initialLoading: loading && !initializedRef.current,
+ refreshing, reload, error, retry,
+ }
}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index afa7a56..4852b14 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -23,6 +23,7 @@ export * from './utils/dashboard'
export * from './utils/version'
export * from './utils/passwordRules'
export * from './theme/tokens'
+export * from './hooks/useAsyncAction'
export * from './hooks/useCountdown'
export * from './hooks/useNumericText'
export * from './hooks/useElapsedSeconds'
@@ -37,3 +38,4 @@ export * from './stores/server'
export * from './stores/settings'
export * from './stores/theme'
export * from './stores/workoutSession'
+export * from './brand/barbell'
diff --git a/packages/shared/src/stores/auth.ts b/packages/shared/src/stores/auth.ts
index 3ab909c..21839f0 100644
--- a/packages/shared/src/stores/auth.ts
+++ b/packages/shared/src/stores/auth.ts
@@ -47,7 +47,7 @@ export function createAuthStore(client: LyftrClient, storage: StorageAdapter) {
} catch (err: any) {
// Same message logic as the web login page: server-provided error if present,
// else a status-aware hint (network/CORS, 5xx, misconfigured URL) via apiErrorMessage.
- set({ error: apiErrorMessage(err, 'Invalid email or password.'), isLoading: false })
+ set({ error: apiErrorMessage(err, 'Invalid email or password.', 'full'), isLoading: false })
throw err
}
},
@@ -61,7 +61,7 @@ export function createAuthStore(client: LyftrClient, storage: StorageAdapter) {
await storage.set(STORAGE_KEYS.user, JSON.stringify(data.user))
set({ user: data.user, isAuthenticated: true, isLoading: false })
} catch (err: any) {
- set({ error: apiErrorMessage(err, 'Registration failed.'), isLoading: false })
+ set({ error: apiErrorMessage(err, 'Registration failed.', 'full'), isLoading: false })
throw err
}
},
diff --git a/packages/shared/src/stores/settings.test.ts b/packages/shared/src/stores/settings.test.ts
index 4cbb21c..22e2eb9 100644
--- a/packages/shared/src/stores/settings.test.ts
+++ b/packages/shared/src/stores/settings.test.ts
@@ -185,3 +185,88 @@ describe('settings store — reset keeps device prefs', () => {
expect(store.getState().settings.workout_layout).toBe('gym')
})
})
+
+describe('settings store — a write that fails', () => {
+ // The optimistic set is the point of the store, and it was also the bug: on a failed
+ // PUT the app went on showing a unit the server had refused, and the next launch read
+ // the real value back and flipped it, with nothing ever having said why.
+ it('rolls its own optimistic patch back', async () => {
+ const { client } = fakeClient(serverSettings({ weight_unit: 'lbs' }), { fail: true })
+ const store = createSettingsStore(client, createMemoryStorage())
+
+ await store.getState().fetch()
+ expect(store.getState().settings.weight_unit).toBe('lbs')
+
+ await expect(store.getState().update({ weight_unit: 'kg' })).rejects.toThrow('network')
+
+ expect(store.getState().settings.weight_unit).toBe('lbs')
+ })
+
+ it('rethrows, because rolling back is not the same as telling the user', async () => {
+ const { client } = fakeClient(serverSettings(), { fail: true })
+ const store = createSettingsStore(client, createMemoryStorage())
+ await store.getState().fetch()
+
+ await expect(store.getState().update({ calorie_target: 3000 })).rejects.toBeInstanceOf(Error)
+ })
+
+ it('shows the new value while the write is still in flight', async () => {
+ const { client, release } = fakeClient(serverSettings({ weight_unit: 'lbs' }), { fail: true, defer: true })
+ const store = createSettingsStore(client, createMemoryStorage())
+ await store.getState().fetch()
+
+ const pending = store.getState().update({ weight_unit: 'kg' }).catch(() => {})
+ expect(store.getState().settings.weight_unit).toBe('kg')
+
+ release()
+ await pending
+ expect(store.getState().settings.weight_unit).toBe('lbs')
+ })
+
+ it('restores only the keys the failed patch touched', async () => {
+ const { client } = fakeClient(serverSettings({ calorie_target: 2000 }), { fail: true })
+ const store = createSettingsStore(client, createMemoryStorage())
+ await store.getState().fetch()
+
+ await expect(store.getState().update({ calorie_target: 3000 })).rejects.toThrow()
+
+ expect(store.getState().settings.calorie_target).toBe(2000)
+ // Untouched by the patch, so untouched by the rollback.
+ expect(store.getState().settings.protein_target).toBe(150)
+ })
+})
+
+describe('settings store — a read that fails', () => {
+ // Measured in a browser before this flag existed: with the GET failing, the settings
+ // page rendered the DEFAULTS in its target inputs with no error, and pressing Save
+ // sent {calorie_target: 2000, ...} over real targets of 3175. A failed read plus one
+ // ordinary click destroyed them. `loaded` alone cannot express that, because it is
+ // true in both cases.
+ it("flags that the values are substitutes, not the users own", async () => {
+ const failing = {
+ userAPI: {
+ getSettings: async () => { throw new Error('network') },
+ updateSettings: async (p: Partial<UserSettings>) => ({ ...serverSettings(), ...p }),
+ },
+ } as unknown as LyftrClient
+ const store = createSettingsStore(failing, createMemoryStorage())
+
+ await store.getState().fetch()
+
+ // Still usable — blocking every screen on a settings read would be worse...
+ expect(store.getState().loaded).toBe(true)
+ // ...but the app now knows these are not the user's numbers.
+ expect(store.getState().loadFailed).toBe(true)
+ expect(store.getState().settings.calorie_target).toBe(2000)
+ })
+
+ it('is clear when the read succeeds', async () => {
+ const { client } = fakeClient(serverSettings({ calorie_target: 3175 }))
+ const store = createSettingsStore(client, createMemoryStorage())
+
+ await store.getState().fetch()
+
+ expect(store.getState().loadFailed).toBe(false)
+ expect(store.getState().settings.calorie_target).toBe(3175)
+ })
+})
diff --git a/packages/shared/src/stores/settings.ts b/packages/shared/src/stores/settings.ts
index a6db23b..eea393f 100644
--- a/packages/shared/src/stores/settings.ts
+++ b/packages/shared/src/stores/settings.ts
@@ -41,6 +41,11 @@ const BASE_DEFAULTS: types.UserSettings = {
export interface SettingsStore {
settings: types.UserSettings
loaded: boolean
+ // True when `loaded` is standing on DEFAULTS because the read failed, not on the
+ // user's own settings. The distinction is not cosmetic: a screen that offers to
+ // save while this is true will write the defaults over whatever the server still
+ // holds — a failed read plus one ordinary click, and the targets are gone.
+ loadFailed: boolean
// Device-only prefs, no network. Call before first render.
hydratePrefs: () => Promise<void>
fetch: () => Promise<void>
@@ -89,6 +94,7 @@ export function createSettingsStore(
return create<SettingsStore>((set, get) => ({
settings: BASE_DEFAULTS,
loaded: false,
+ loadFailed: false,
// The three client-only prefs, read from device storage with no network call.
//
@@ -103,7 +109,10 @@ export function createSettingsStore(
},
fetch: async () => {
- if (get().loaded) return
+ // `loaded` alone would make this a no-op forever after a failed read, because the
+ // failure path sets it too — so a Retry button would do nothing at all. A load that
+ // fell back to defaults is exactly the one worth attempting again.
+ if (get().loaded && !get().loadFailed) return
const prefs = await clientPrefs(storage)
try {
const s = await client.userAPI.getSettings()
@@ -111,7 +120,7 @@ export function createSettingsStore(
// Awaiting the PATCH would put a write on the critical path of loading
// settings — on a stalled connection every screen that gates on `loaded`
// waits for a socket timeout instead of showing data already in hand.
- set({ settings: { ...s, ...prefs }, loaded: true })
+ set({ settings: { ...s, ...prefs }, loaded: true, loadFailed: false })
void syncTimezone(s).then((synced) => {
// Only the timezone is written back. Splatting the whole response would
// undo anything the user changed while the PATCH was in flight — flipping
@@ -122,15 +131,36 @@ export function createSettingsStore(
}
})
} catch {
- set({ settings: { ...get().settings, ...prefs }, loaded: true })
+ // Still `loaded`, because blocking every screen on a settings read would be
+ // worse — but flagged, so a screen that can WRITE these values knows they are
+ // substitutes rather than the user's.
+ set({ settings: { ...get().settings, ...prefs }, loaded: true, loadFailed: true })
}
},
+ // Optimistic, then reconciled — but the optimism has to be undone when the write
+ // fails, or the app shows kg while the server still holds lbs and the next launch
+ // silently flips it back. Rolling back HERE rather than at each call site is what
+ // makes that true for every caller, including the ones that only toggle.
+ //
+ // Rethrows: the caller still has to say what happened. Rollback answers "what does
+ // the app believe", not "does the user know".
update: async (patch) => {
+ const before = get().settings
set((state) => ({ settings: { ...state.settings, ...patch } }))
- const updated = await client.userAPI.updateSettings(patch)
- const prefs = await clientPrefs(storage)
- set({ settings: { ...updated, ...prefs } })
+ try {
+ const updated = await client.userAPI.updateSettings(patch)
+ const prefs = await clientPrefs(storage)
+ set({ settings: { ...updated, ...prefs } })
+ } catch (err) {
+ // Restore only the keys this patch touched: anything else may have been
+ // changed by another action while the write was in flight.
+ const rollback = Object.fromEntries(
+ Object.keys(patch).map((k) => [k, before[k as keyof types.UserSettings]]),
+ ) as Partial<types.UserSettings>
+ set((state) => ({ settings: { ...state.settings, ...rollback } }))
+ throw err
+ }
},
setWorkoutLayout: async (layout) => {
@@ -167,6 +197,7 @@ export function createSettingsStore(
rest_seconds_default: state.settings.rest_seconds_default,
},
loaded: false,
+ loadFailed: false,
})),
}))
}
diff --git a/packages/shared/src/utils/networkError.test.ts b/packages/shared/src/utils/networkError.test.ts
index 3e93520..bc3fa27 100644
--- a/packages/shared/src/utils/networkError.test.ts
+++ b/packages/shared/src/utils/networkError.test.ts
@@ -119,18 +119,59 @@ describe('networkFailureMessage', () => {
})
it('tells a private-CA user how to install their certificate', () => {
- const msg = networkFailureMessage(rnError('Trust anchor for certification path not found.'))
+ const msg = networkFailureMessage(rnError('Trust anchor for certification path not found.'), 'full')
expect(msg).toMatch(/certificate/i)
expect(msg).toMatch(/Encryption & credentials/)
})
it('appends the raw native reason when it matches nothing, rather than guessing', () => {
- const msg = networkFailureMessage(rnError('brand new platform error'))
+ const msg = networkFailureMessage(rnError('brand new platform error'), 'full')
expect(msg).toContain('brand new platform error')
})
// testEnvironment is 'node', so `document` is undefined — the native wording applies.
it('omits the CORS hint when there is no document (native)', () => {
- expect(networkFailureMessage({ message: 'Network Error', request: {} })).not.toMatch(/CORS/)
+ expect(networkFailureMessage({ message: 'Network Error', request: {} }, 'full')).not.toMatch(/CORS/)
+ })
+})
+
+// The same failure, read in two moments. Configuring a server, you want the fix and will
+// read four lines to get it. Mid-set with a Finish sheet open, you want to know whether to
+// tap again — and the certificate explanation is 313 characters, which is eight lines
+// inside that sheet, about something you cannot change until you are off the gym floor.
+describe('brief vs full', () => {
+ const cert = { request: { _response: 'Trust anchor for certification path not found' } }
+ const timedOut = { code: 'ECONNABORTED' }
+
+ it('defaults to brief, because most call sites are in-flow', () => {
+ expect(networkFailureMessage(cert)).toBe(networkFailureMessage(cert, 'brief'))
+ })
+
+ it('keeps every brief message short enough to sit in a sheet', () => {
+ for (const err of [cert, timedOut, { request: { _response: 'CLEARTEXT communication to 10.0.0.2 not permitted' } },
+ { request: { _response: 'Hostname lyftr.lan not verified' } },
+ { request: { _response: 'Failed to connect to /10.0.0.2:3000' } },
+ { message: 'something we have never seen' }]) {
+ const msg = networkFailureMessage(err, 'brief')
+ expect(msg.length).toBeLessThanOrEqual(90)
+ }
+ })
+
+ it('still points somewhere when the fix is not "try again"', () => {
+ expect(networkFailureMessage(cert, 'brief')).toMatch(/Server settings/)
+ })
+
+ it('keeps the long explanation for the screen where it can be acted on', () => {
+ const full = networkFailureMessage(cert, 'full')
+ expect(full.length).toBeGreaterThan(200)
+ expect(full).toMatch(/reverse proxy/)
+ })
+
+ // In full it is the one thing that saves a self-hoster whose failure we did not classify.
+ // In a sheet it is a raw native string in the middle of a sentence.
+ it('carries the raw native reason only in full', () => {
+ const odd = { request: { _response: 'ENETUNREACH somewhere deep in okhttp' } }
+ expect(networkFailureMessage(odd, 'full')).toMatch(/ENETUNREACH/)
+ expect(networkFailureMessage(odd, 'brief')).not.toMatch(/ENETUNREACH/)
})
})
diff --git a/packages/shared/src/utils/networkError.ts b/packages/shared/src/utils/networkError.ts
index 1654480..734c236 100644
--- a/packages/shared/src/utils/networkError.ts
+++ b/packages/shared/src/utils/networkError.ts
@@ -69,7 +69,36 @@ export const classifyNetworkError = (err: any): NetworkFailure => {
// evaluates it. Mentioning it on mobile sends self-hosters chasing a non-existent problem.
const isWeb = (): boolean => typeof document !== 'undefined'
-export const networkFailureMessage = (err: any): string => {
+// The same failure has to be said two different ways, because it is read in two very
+// different moments.
+//
+// 'full' is for someone who is configuring a server and wants the fix: the sign-in
+// screen and the Server-settings probe. Those explanations are long on purpose - they
+// carry hard-won detail about cleartext policy and CA trust that a self-hoster cannot
+// get anywhere else.
+//
+// 'brief' is for someone who is USING the app and just tapped a button. Mid-set, the
+// certificate explanation is 313 characters - eight lines inside a Finish Workout sheet,
+// pushing the buttons toward the fold - to tell them something they cannot act on until
+// they are off the gym floor anyway. It says what happened and where the fix lives, and
+// stops. NN/g's error guidance and progressive disclosure both land here: the most
+// important information first, the details where they are actionable.
+export type MessageDetail = 'brief' | 'full'
+
+// Each one names the cause and, where the fix is somewhere the user can go, points at it.
+// A short message that offers no way forward is not brief, it is unhelpful.
+const BRIEF: Record<NetworkFailure, string> = {
+ 'cleartext-blocked': 'Blocked because the server URL uses http://. Check Server settings.',
+ 'certificate-untrusted': "The server's certificate isn't trusted by this device. Check Server settings.",
+ 'hostname-mismatch': "The server's certificate doesn't cover this address. Check Server settings.",
+ timeout: "The server didn't respond in time. Try again in a moment.",
+ unreachable: "Couldn't reach the server. Check that it's running.",
+ // No raw native string here: in full it is diagnostic gold, in a sheet it is noise.
+ unknown: "Can't reach the server right now.",
+}
+
+export const networkFailureMessage = (err: any, detail: MessageDetail = 'brief'): string => {
+ if (detail === 'brief') return BRIEF[classifyNetworkError(err)]
switch (classifyNetworkError(err)) {
// Deliberately does NOT say "update the app". This build already permits cleartext, so
// if the OS still blocked it the cause is something an update can't fix — most likely
diff --git a/web/src/services/api.test.ts b/web/src/services/api.test.ts
index 33114e7..5830aaa 100644
--- a/web/src/services/api.test.ts
+++ b/web/src/services/api.test.ts
@@ -25,8 +25,24 @@ describe('apiErrorMessage', () => {
expect(apiErrorMessage({ response: { status: 405, data: {} } }, 'fallback')).toMatch(/misconfigured/i)
})
- it('maps 5xx to a server error', () => {
- expect(apiErrorMessage({ response: { status: 503, data: {} } }, 'fallback')).toMatch(/server error/i)
+ // 502/503/504 are the reverse proxy talking, not the backend: it accepted the
+ // connection and could not reach the app behind it. "Server error" was true but
+ // unhelpful — the answer is to wait, not to change anything.
+ it('reads a gateway status as a restart, not a generic server error', () => {
+ for (const status of [502, 503, 504]) {
+ expect(apiErrorMessage({ response: { status, data: {} } }, 'fallback')).toMatch(/restarting or unreachable/i)
+ }
+ })
+
+ // Every reverse proxy serves its 502 as an HTML page, so a body sniff that ran first
+ // diagnosed a restarting backend as "you typed the wrong address".
+ it('reads an HTML-bodied 502 as a restart, not as a wrong address', () => {
+ const html = '<!DOCTYPE html><html><body>502 Bad Gateway</body></html>'
+ expect(apiErrorMessage({ response: { status: 502, data: html } }, 'fallback')).toMatch(/restarting or unreachable/i)
+ })
+
+ it('still maps a plain 500 to a server error', () => {
+ expect(apiErrorMessage({ response: { status: 500, data: {} } }, 'fallback')).toMatch(/server error/i)
})
it('uses the fallback for other responses without a server error', () => {