Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(async-boundary): add AsyncBoundary/AsyncError data-fetching framework (#16639)

Arvin Xu63f6abb4e984
diff --git a/.agents/skills/ux/references/feedback.md b/.agents/skills/ux/references/feedback.md
index 8607efae747..cf6329f19c5 100644
--- a/.agents/skills/ux/references/feedback.md
+++ b/.agents/skills/ux/references/feedback.md
@@ -69,6 +69,22 @@ state hands control back and restores certainty. Retry re-runs the _same_ fetch
`mutate` / query refetch), shows loading again while it re-runs, and stays available if it
fails again; keep any already-loaded context rather than blowing the surface away.
+**But not every failure should offer Retry — gate it on whether a retry could plausibly
+succeed.** A `401` (auth expired / invalid) or `403` (no permission) wall will just fail
+again the same way, so a **Reload** button there is a false promise: it invites the user to
+mash a control that can't work. The failed state still renders (reason + status-specific copy
+— "please sign in", "you don't have access"), it just **omits Retry**; `5xx` / timeout /
+network stay retryable. Derive this from the normalized error status, don't hand-code it per
+surface — `normalizeAsyncError` marks `401` / `403` (and anything flagged
+`meta.shouldRetry === false`) non-retryable, and `AsyncError` hides the button accordingly.
+
+> **Decision (2026-07-02): the component-level failed state does _not_ itself redirect on
+> `401`.** We assume session-expiry is caught **globally** (an app-level interceptor routes an
+> expired session to sign-in), so a surface only needs the honest no-retry failure state as a
+> backstop — it should not add a second redirect layer. Revisit only if a future surface turns
+> up where the global redirect doesn't fire and a `401` genuinely strands the user; then wire
+> per-surface handling. Don't pre-build it.
+
> **We under-build this today** — most surfaces only draw loading + success and let a slow
> or failed request spin forever. Treat the failure path as required, not optional: it's a
> large part of what makes the experience feel trustworthy.
@@ -261,6 +277,7 @@ tail, kept distinct from the genuine end-of-list.
- [ ] An error branch isn't **ordered after** a data-presence loading gate — `{error && …}` placed below `if (isLoading) return <Skeleton/>` where `isLoading = !map[id]` is **unreachable on first-load failure** (a failed / not-found fetch never populates the map, so the skeleton short-circuits; it paints only on a **revalidation** failure over already-loaded data), and a resolved-`null` not-found hangs the same permanent skeleton. Check `error` / not-found **before** the loading gate, or flip the gate on settled. _(Certainty)_
- [ ] An awaited write that gates navigation resets its in-progress flag in `finally` and offers retry on `catch` — a failed write never permanently disables the advance / Back control. _(Certainty)_
- [ ] The failed state names the failure and offers a **Reload / Retry** action. _(Meaningful)_
+- [ ] Retry is **gated on retryability**, not shown unconditionally — a `401` / `403` (or `meta.shouldRetry === false`) failure renders the reason but **omits Retry** (a retry there just fails again); derive it from the normalized error status, not per-surface. `401` session-expiry is assumed handled by a **global** redirect to sign-in, so a surface does not add its own redirect layer. _(Certainty・Meaningful)_
- [ ] Retry re-runs the same fetch, shows loading while re-running, and stays available on repeat failure. _(Certainty)_
- [ ] Already-loaded context is preserved on failure — don't wipe the surface. _(Meaningful)_
- [ ] In an auto-dismissing surface (upload dock / progress toast), auto-dismiss fires on **success only** — a failed item persists with a Retry, never cleared by the countdown. _(Certainty・Meaningful)_
diff --git a/locales/en-US/error.json b/locales/en-US/error.json
index 77116ce7dc2..587d69b3529 100644
--- a/locales/en-US/error.json
+++ b/locales/en-US/error.json
@@ -1,4 +1,7 @@
{
+ "asyncState.desc": "Something went wrong while loading. Please try again.",
+ "asyncState.metricLabel": "Failed to load",
+ "asyncState.title": "Failed to load",
"error.backHome": "Back to Home",
"error.desc": "Give it a try later, or go back to the known world.",
"error.retry": "Reload",
diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.json
index e5346ecde9c..7474d0490d4 100644
--- a/locales/zh-CN/error.json
+++ b/locales/zh-CN/error.json
@@ -1,4 +1,7 @@
{
+ "asyncState.desc": "加载时出了点问题,请重试。",
+ "asyncState.metricLabel": "加载失败",
+ "asyncState.title": "加载失败",
"error.backHome": "返回首页",
"error.desc": "页面暂时不可用。你可以返回首页,或稍后重试(你的设置不会因此丢失)",
"error.retry": "重新加载",
diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.ts
index 06a5166872c..b0cd9582690 100644
--- a/packages/locales/src/default/error.ts
+++ b/packages/locales/src/default/error.ts
@@ -1,4 +1,7 @@
export default {
+ 'asyncState.desc': 'Something went wrong while loading. Please try again.',
+ 'asyncState.metricLabel': 'Failed to load',
+ 'asyncState.title': 'Failed to load',
'error.backHome': 'Back to Home',
'error.desc': 'Give it a try later, or go back to the known world.',
'error.stack': 'Error Stack',
diff --git a/src/components/AsyncBoundary/index.test.tsx b/src/components/AsyncBoundary/index.test.tsx
new file mode 100644
index 00000000000..28414417570
--- /dev/null
+++ b/src/components/AsyncBoundary/index.test.tsx
@@ -0,0 +1,130 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import AsyncBoundary from './index';
+
+// Stub the base-ui Button (the failure state's Retry) to a native button — it
+// needs a MotionProvider the app sets up globally but the unit env doesn't; the
+// state-machine assertions only care that a button is/isn't present. vitest
+// hoists this above the imports regardless of position.
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Button: ({ children, onClick }: any) => <button onClick={onClick}>{children}</button>,
+}));
+
+const DATA = <div>DATA_CONTENT</div>;
+const EMPTY = <div>EMPTY_ONBOARDING</div>;
+const LOADING = <div>LOADING_SKELETON</div>;
+
+describe('AsyncBoundary', () => {
+ it('renders children when data is present', () => {
+ render(
+ <AsyncBoundary data={[1]} empty={EMPTY} isEmpty={false}>
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.getByText('DATA_CONTENT')).toBeInTheDocument();
+ expect(screen.queryByText('EMPTY_ONBOARDING')).not.toBeInTheDocument();
+ });
+
+ it('renders the empty state only when there is no error', () => {
+ render(
+ <AsyncBoundary isEmpty data={[]} empty={EMPTY}>
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.getByText('EMPTY_ONBOARDING')).toBeInTheDocument();
+ expect(screen.queryByText('DATA_CONTENT')).not.toBeInTheDocument();
+ });
+
+ it('shows the loading node on first load', () => {
+ render(
+ <AsyncBoundary isEmpty isLoading data={undefined} empty={EMPTY} loading={LOADING}>
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.getByText('LOADING_SKELETON')).toBeInTheDocument();
+ expect(screen.queryByText('EMPTY_ONBOARDING')).not.toBeInTheDocument();
+ });
+
+ // The core regression this framework fixes: a *failed* fetch (isEmpty=true
+ // because data is undefined) must NOT render the onboarding empty. Error wins.
+ it('renders the error state BEFORE the empty branch (no failure-as-empty)', () => {
+ const onRetry = vi.fn();
+ render(
+ <AsyncBoundary
+ isEmpty
+ data={undefined}
+ empty={EMPTY}
+ error={new Error('boom')}
+ loading={LOADING}
+ onRetry={onRetry}
+ >
+ {DATA}
+ </AsyncBoundary>,
+ );
+ // The fake "connect your first device" onboarding is gone…
+ expect(screen.queryByText('EMPTY_ONBOARDING')).not.toBeInTheDocument();
+ // …replaced by a failure state offering Retry.
+ expect(screen.getByRole('button')).toBeInTheDocument();
+ });
+
+ // After a failed first load the user clicks Retry: SWR keeps the previous
+ // error until the revalidation settles, but isLoading is true again. The
+ // boundary must show in-progress feedback, not the stale error + Retry.
+ it('shows loading while a retry is in flight (error still set, isLoading)', () => {
+ render(
+ <AsyncBoundary
+ isEmpty
+ isLoading
+ data={undefined}
+ empty={EMPTY}
+ error={new Error('boom')}
+ loading={LOADING}
+ onRetry={vi.fn()}
+ >
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.getByText('LOADING_SKELETON')).toBeInTheDocument();
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ // A surface that successfully loaded an empty list has settled; a later
+ // focus/reconnect revalidation failure (stale data=[] + error) must not
+ // replace the onboarding empty with the error block. `data={[]}` is the
+ // settled signal — `undefined` means never loaded.
+ it('preserves a loaded empty state when a background revalidation errors', () => {
+ render(
+ <AsyncBoundary isEmpty data={[]} empty={EMPTY} error={new Error('revalidate failed')}>
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.getByText('EMPTY_ONBOARDING')).toBeInTheDocument();
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+
+ it('keeps already-loaded content when a background refresh errors', () => {
+ render(
+ <AsyncBoundary data={[1]} empty={EMPTY} error={new Error('refresh failed')} isEmpty={false}>
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.getByText('DATA_CONTENT')).toBeInTheDocument();
+ });
+
+ it('does not offer Retry for a non-retryable (401) error', () => {
+ render(
+ <AsyncBoundary
+ isEmpty
+ data={undefined}
+ empty={EMPTY}
+ error={{ data: { httpStatus: 401 } }}
+ onRetry={vi.fn()}
+ >
+ {DATA}
+ </AsyncBoundary>,
+ );
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ expect(screen.queryByText('EMPTY_ONBOARDING')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/components/AsyncBoundary/index.tsx b/src/components/AsyncBoundary/index.tsx
new file mode 100644
index 00000000000..a0e43b7b22c
--- /dev/null
+++ b/src/components/AsyncBoundary/index.tsx
@@ -0,0 +1,107 @@
+'use client';
+
+import { Center, Flexbox } from '@lobehub/ui';
+import { memo, type ReactNode } from 'react';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+
+import AsyncError, { type AsyncErrorVariant } from '../AsyncError';
+
+/**
+ * The four-state gate every data surface owes its user: loading / error / empty /
+ * data. It exists because the codebase's fetch conventions only ever modeled
+ * loading + success — the SWR `error` was returned but discarded, so a failed
+ * fetch fell through to a permanent skeleton, a fake onboarding empty, or a
+ * confident `$0`. `AsyncBoundary` reads `error` **before** the empty branch and
+ * renders the right state, once, so no call site hand-rolls the precedence.
+ *
+ * Everything the boundary needs is already in hand at the call site — SWR
+ * returns it. Migrating a surface is mechanical pass-through: capture
+ * `{ data, error, isLoading, mutate }` from the hook and wrap the render in
+ * `<AsyncBoundary data={data} error={error} isLoading={isLoading} onRetry={mutate} …>`.
+ *
+ * Precedence (only before the fetch has ever settled — `data !== undefined` —
+ * so a background revalidate that errors doesn't blow away settled content,
+ * including a settled *empty* list):
+ * loading → error → empty → children
+ *
+ * Loading is read before error so a Retry in flight (SWR keeps the previous
+ * error until the revalidation settles) shows the skeleton instead of a frozen
+ * error block with a still-clickable Retry.
+ */
+export interface AsyncBoundaryProps {
+ children: ReactNode;
+ /**
+ * The fetch result, passed through untouched (SWR's `data`). `undefined`
+ * means the fetch has never settled successfully — the boundary's "nothing
+ * worth keeping on screen" signal. Deliberately not derived from `isEmpty`
+ * (a settled empty list HAS loaded) nor from `isLoading` (a failed first
+ * load is neither loading nor settled). For a merged fetched + static
+ * surface, pass the fetched slice. Required (though `undefined` is a valid
+ * value) so no call site forgets the settled signal and silently regresses
+ * into error-blows-away-content.
+ */
+ data: unknown;
+ /** Node for the empty state (onboarding CTA / no-match). Required to show empty. */
+ empty?: ReactNode;
+ /** The thrown error from SWR / the query. Read before the empty branch. */
+ error?: unknown;
+ /** The `AsyncError` variant to render on failure. Default `block`. */
+ errorVariant?: AsyncErrorVariant;
+ /** No records to show (`length === 0`). Gate it on `!error` at the call site. */
+ isEmpty?: boolean;
+ /** First-load in flight. */
+ isLoading?: boolean;
+ /** Custom loading node (a shape-matched skeleton). Defaults to a centered loader. */
+ loading?: ReactNode;
+ /** Retry the same request (SWR `mutate`). Wired into the error state's Retry. */
+ onRetry?: () => void;
+}
+
+const AsyncBoundary = memo<AsyncBoundaryProps>(
+ ({
+ children,
+ data,
+ error,
+ errorVariant = 'block',
+ empty,
+ isEmpty = false,
+ isLoading = false,
+ loading,
+ onRetry,
+ }) => {
+ // Has the fetch ever settled successfully? A settled result — even an
+ // empty list — is content worth keeping: a background refresh that errors
+ // must not replace it with a full-surface error.
+ const hasSettled = data !== undefined;
+
+ // 1. Request in flight with nothing to show → loading (caller's skeleton,
+ // else a centered loader). Checked before error: after a failed first
+ // load SWR keeps `error` set while a Retry revalidates, and the user
+ // needs in-progress feedback, not the stale error block.
+ if (isLoading && !hasSettled) {
+ return (
+ loading ?? (
+ <Center flex={1} padding={48} width={'100%'}>
+ <NeuralNetworkLoading size={24} />
+ </Center>
+ )
+ );
+ }
+
+ // 2. Failure with nothing to show → the error state (reason + Retry).
+ if (error && !hasSettled) {
+ return <AsyncError error={error} variant={errorVariant} onRetry={onRetry} />;
+ }
+
+ // 3. Genuinely empty (only reached when !error) → the purpose-built empty page.
+ if (isEmpty) return <Flexbox width={'100%'}>{empty}</Flexbox>;
+
+ // 4. Data.
+ return <>{children}</>;
+ },
+);
+
+AsyncBoundary.displayName = 'AsyncBoundary';
+
+export default AsyncBoundary;
diff --git a/src/components/AsyncError/index.tsx b/src/components/AsyncError/index.tsx
new file mode 100644
index 00000000000..5e5cf53b3c6
--- /dev/null
+++ b/src/components/AsyncError/index.tsx
@@ -0,0 +1,155 @@
+'use client';
+
+import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { RotateCwIcon, TriangleAlertIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
+
+/**
+ * The error counterpart to the loading family (`NeuralNetworkLoading`,
+ * `SkeletonLoading`, …). One reusable component, several `variant`s so different
+ * surfaces express failure differently without each re-implementing the
+ * icon + reason + retry plumbing. Pick the variant by where the failure lives;
+ * the judgment (status → copy, retryable → show/hide Retry) stays here.
+ *
+ * - `page` — full detail page / whole surface: centered hero + Reload.
+ * - `block` — a card / settings tab / widget: bordered block + Reload.
+ * - `inline` — a list row / small slot: single line + retry link.
+ * - `metric` — a stat / aggregate slot: a **failed** marker where a number
+ * would sit, so an errored fetch never reads as a confident `$0`.
+ */
+export type AsyncErrorVariant = 'page' | 'block' | 'inline' | 'metric';
+
+export interface AsyncErrorProps {
+ /** Override the auto-derived description (status-based copy otherwise). */
+ description?: ReactNode;
+ /** The thrown error; normalized for status-specific copy + retryable gating. */
+ error?: unknown;
+ /** Retry the same request (SWR `mutate` / query refetch). Hidden if absent. */
+ onRetry?: () => void;
+ /** Override the default title copy. */
+ title?: ReactNode;
+ variant?: AsyncErrorVariant;
+}
+
+const styles = createStaticStyles(({ css }) => ({
+ block: css`
+ width: 100%;
+ min-height: 180px;
+ padding: 32px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ icon: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ inline: css`
+ padding-block: 8px;
+ `,
+ metric: css`
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ page: css`
+ width: 100%;
+ min-height: 320px;
+ padding: 48px;
+ `,
+}));
+
+const AsyncError = memo<AsyncErrorProps>(
+ ({ variant = 'block', error, onRetry, title, description }) => {
+ const { t } = useTranslation('error');
+ const { status, retryable } = normalizeAsyncError(error);
+
+ // Status-specific copy when we recovered a status, else the generic reason.
+ const reason =
+ description ??
+ (status ? t(`response.${status}` as any, t('asyncState.desc')) : t('asyncState.desc'));
+ const heading = title ?? t('asyncState.title');
+ const showRetry = !!onRetry && retryable;
+
+ // ─── metric: a failed marker where a number would render (never a fake $0) ───
+ if (variant === 'metric') {
+ return (
+ <Flexbox horizontal align={'center'} className={styles.metric} gap={6}>
+ <Icon icon={TriangleAlertIcon} size={14} />
+ <Text color={cssVar.colorTextQuaternary} fontSize={13}>
+ {t('asyncState.metricLabel')}
+ </Text>
+ {showRetry && (
+ <Text
+ aria-label={t('error.retry')}
+ role={'button'}
+ style={{ color: cssVar.colorPrimary, cursor: 'pointer' }}
+ tabIndex={0}
+ onClick={onRetry}
+ >
+ {t('error.retry')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ }
+
+ // ─── inline: single-line row failure with a retry link ───
+ if (variant === 'inline') {
+ return (
+ <Flexbox horizontal align={'center'} className={styles.inline} gap={8}>
+ <Icon className={styles.icon} icon={TriangleAlertIcon} size={14} />
+ <Text color={cssVar.colorTextSecondary} fontSize={13}>
+ {heading}
+ </Text>
+ {showRetry && (
+ <Text
+ role={'button'}
+ style={{ color: cssVar.colorPrimary, cursor: 'pointer' }}
+ tabIndex={0}
+ onClick={onRetry}
+ >
+ {t('error.retry')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ }
+
+ // ─── page / block: centered hero, sized by variant ───
+ return (
+ <Center className={variant === 'page' ? styles.page : styles.block} gap={12}>
+ <Icon
+ className={styles.icon}
+ icon={TriangleAlertIcon}
+ size={variant === 'page' ? 32 : 24}
+ />
+ <Flexbox align={'center'} gap={4}>
+ <Text fontSize={variant === 'page' ? 16 : 15} weight={600}>
+ {heading}
+ </Text>
+ <Text
+ align={'center'}
+ color={cssVar.colorTextTertiary}
+ fontSize={13}
+ style={{ maxWidth: 360 }}
+ >
+ {reason}
+ </Text>
+ </Flexbox>
+ {showRetry && (
+ <Button icon={<Icon icon={RotateCwIcon} />} size={'small'} onClick={onRetry}>
+ {t('error.retry')}
+ </Button>
+ )}
+ </Center>
+ );
+ },
+);
+
+AsyncError.displayName = 'AsyncError';
+
+export default AsyncError;
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index ae7bcbf5970..55e486e4376 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -18,6 +18,7 @@ import {
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useClientDataSWR } from '@/libs/swr';
import { lambdaQuery } from '@/libs/trpc/client';
import { deviceService } from '@/services/device';
@@ -47,7 +48,6 @@ const styles = createStaticStyles(({ css }) => ({
padding: 16px;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
-
background: ${cssVar.colorBgContainer};
`,
capabilityIcon: css`
@@ -67,7 +67,6 @@ const styles = createStaticStyles(({ css }) => ({
overflow: hidden;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
-
background: ${cssVar.colorBgContainer};
`,
emptyHero: css`
@@ -94,11 +93,8 @@ const styles = createStaticStyles(({ css }) => ({
`,
option: css`
cursor: pointer;
-
padding: 20px;
-
background: ${cssVar.colorBgContainer};
-
transition: background 0.15s ease;
&:hover {
@@ -118,7 +114,6 @@ const styles = createStaticStyles(({ css }) => ({
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
-
background: ${cssVar.colorBorderSecondary};
`,
optionIcon: css`
@@ -301,7 +296,7 @@ const DeviceManager = memo<DeviceManagerProps>(({ onConnect, scope }) => {
// Devices come from an authed lambda procedure, so only query once signed in
// (desktop always queries — it lists the local device's registered cwd).
const isLogin = useUserStore(authSelectors.isLogin);
- const { data, isLoading } = useClientDataSWR(
+ const { data, isLoading, error, mutate } = useClientDataSWR(
isLogin || isDesktop ? [DEVICE_LIST_SWR_KEY] : null,
() => deviceService.listDevices(),
);
@@ -328,48 +323,47 @@ const DeviceManager = memo<DeviceManagerProps>(({ onConnect, scope }) => {
// Hook must run before any early return so render order stays stable.
const canEditDevice = useCanEditDevice();
- if (isLoading) return <ListSkeleton />;
-
// ─── Empty state: onboarding hero + connect options + capabilities ───
- if (devices.length === 0) {
- return (
- <Flexbox gap={32}>
- <Flexbox className={styles.emptyCard}>
- <Flexbox align={'center'} className={styles.emptyHero} gap={12}>
- <span className={styles.heroIcon}>
- <Icon icon={isWorkspace ? ServerIcon : MonitorDownIcon} size={28} />
- </span>
- <Text fontSize={18} weight={600}>
- {t(isWorkspace ? 'workspaceSetting.devices.heroTitle' : 'devices.empty.title')}
- </Text>
- <Text style={{ maxWidth: 440 }} type={'secondary'}>
- {t(isWorkspace ? 'workspaceSetting.devices.heroDesc' : 'devices.empty.desc')}
- </Text>
- </Flexbox>
+ // Now gated by AsyncBoundary so a *failed* device fetch renders a failure +
+ // Retry instead of this "connect your first device" onboarding (which falsely
+ // told the user they own no devices — ux Read §1.1 error-as-empty trap).
+ const emptyState = (
+ <Flexbox gap={32}>
+ <Flexbox className={styles.emptyCard}>
+ <Flexbox align={'center'} className={styles.emptyHero} gap={12}>
+ <span className={styles.heroIcon}>
+ <Icon icon={isWorkspace ? ServerIcon : MonitorDownIcon} size={28} />
+ </span>
+ <Text fontSize={18} weight={600}>
+ {t(isWorkspace ? 'workspaceSetting.devices.heroTitle' : 'devices.empty.title')}
+ </Text>
+ <Text style={{ maxWidth: 440 }} type={'secondary'}>
+ {t(isWorkspace ? 'workspaceSetting.devices.heroDesc' : 'devices.empty.desc')}
+ </Text>
+ </Flexbox>
- <div className={isWorkspace ? undefined : styles.optionGrid}>
- {!isWorkspace && (
- <ConnectOption
- badge={t('devices.empty.methodDesktop.badge')}
- desc={t('devices.empty.methodDesktop.desc')}
- icon={MonitorDownIcon}
- title={t('devices.empty.methodDesktop.title')}
- onClick={() => onConnect('desktop')}
- />
- )}
+ <div className={isWorkspace ? undefined : styles.optionGrid}>
+ {!isWorkspace && (
<ConnectOption
- desc={t('devices.empty.methodCli.desc')}
- icon={TerminalIcon}
- title={t('devices.empty.methodCli.title')}
- onClick={() => onConnect('cli')}
+ badge={t('devices.empty.methodDesktop.badge')}
+ desc={t('devices.empty.methodDesktop.desc')}
+ icon={MonitorDownIcon}
+ title={t('devices.empty.methodDesktop.title')}
+ onClick={() => onConnect('desktop')}
/>
- </div>
- </Flexbox>
-
- <Capabilities />
+ )}
+ <ConnectOption
+ desc={t('devices.empty.methodCli.desc')}
+ icon={TerminalIcon}
+ title={t('devices.empty.methodCli.title')}
+ onClick={() => onConnect('cli')}
+ />
+ </div>
</Flexbox>
- );
- }
+
+ <Capabilities />
+ </Flexbox>
+ );
const selected = selectedId ? devices.find((d) => d.deviceId === selectedId) : undefined;
const isCurrent = (id: string) => !!currentDeviceId && id === currentDeviceId;
@@ -417,79 +411,92 @@ const DeviceManager = memo<DeviceManagerProps>(({ onConnect, scope }) => {
};
return (
- <Flexbox horizontal align={'flex-start'} gap={16}>
- <Flexbox className={styles.listCol} flex={1}>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.listHeader}
- justify={'space-between'}
- >
+ <AsyncBoundary
+ data={data}
+ empty={emptyState}
+ error={error}
+ errorVariant={'block'}
+ isEmpty={devices.length === 0}
+ isLoading={isLoading}
+ loading={<ListSkeleton />}
+ onRetry={() => mutate()}
+ >
+ <Flexbox horizontal align={'flex-start'} gap={16}>
+ <Flexbox className={styles.listCol} flex={1}>
<Flexbox
horizontal
align={'center'}
- className={editableDevices.length > 0 ? styles.selectAll : undefined}
- gap={8}
- onClick={editableDevices.length > 0 ? toggleAll : undefined}
+ className={styles.listHeader}
+ justify={'space-between'}
>
- {editableDevices.length > 0 && (
- <Checkbox checked={allChecked} indeterminate={someChecked} />
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={editableDevices.length > 0 ? styles.selectAll : undefined}
+ gap={8}
+ onClick={editableDevices.length > 0 ? toggleAll : undefined}
+ >
+ {editableDevices.length > 0 && (
+ <Checkbox checked={allChecked} indeterminate={someChecked} />
+ )}
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {selectionActive
+ ? t('devices.selection.selected', { count: checkedCount })
+ : t('devices.selection.total', { count: devices.length })}
+ </Text>
+ </Flexbox>
+ {selectionActive && (
+ <Button
+ danger
+ icon={<Icon icon={Trash2Icon} />}
+ loading={removeMutation.isPending}
+ size={'small'}
+ onClick={handleBulkRemove}
+ >
+ {t('devices.actions.removeSelected', { count: checkedCount })}
+ </Button>
)}
- <Text fontSize={12} type={'secondary'} weight={500}>
- {selectionActive
- ? t('devices.selection.selected', { count: checkedCount })
- : t('devices.selection.total', { count: devices.length })}
- </Text>
</Flexbox>
- {selectionActive && (
- <Button
- danger
- icon={<Icon icon={Trash2Icon} />}
- loading={removeMutation.isPending}
- size={'small'}
- onClick={handleBulkRemove}
- >
- {t('devices.actions.removeSelected', { count: checkedCount })}
- </Button>
- )}
- </Flexbox>
- <Flexbox className={styles.listScroll} gap={2} padding={4}>
- {devices.map((device) => {
- const editable = canEditDevice(device);
- return (
- <DeviceItem
- checked={checkedIds.has(device.deviceId)}
- device={device}
- isCurrent={isCurrent(device.deviceId)}
- key={device.deviceId}
- selected={device.deviceId === selectedId}
- selectionActive={selectionActive}
- // Withholding the handler also withholds the checkbox; non-
- // editable rows render without a tick so bulk selection only
- // ever includes devices the server would accept.
- onCheckChange={
- editable ? (next) => toggleChecked(device.deviceId, next) : undefined
- }
- onSelect={() =>
- setSelectedId((prev) => (prev === device.deviceId ? undefined : device.deviceId))
- }
- />
- );
- })}
+ <Flexbox className={styles.listScroll} gap={2} padding={4}>
+ {devices.map((device) => {
+ const editable = canEditDevice(device);
+ return (
+ <DeviceItem
+ checked={checkedIds.has(device.deviceId)}
+ device={device}
+ isCurrent={isCurrent(device.deviceId)}
+ key={device.deviceId}
+ selected={device.deviceId === selectedId}
+ selectionActive={selectionActive}
+ // Withholding the handler also withholds the checkbox; non-
+ // editable rows render without a tick so bulk selection only
+ // ever includes devices the server would accept.
+ onCheckChange={
+ editable ? (next) => toggleChecked(device.deviceId, next) : undefined
+ }
+ onSelect={() =>
+ setSelectedId((prev) =>
+ prev === device.deviceId ? undefined : device.deviceId,
+ )
+ }
+ />
+ );
+ })}
+ </Flexbox>
</Flexbox>
+ {selected && (
+ <Flexbox className={styles.detailCol} flex={1}>
+ {/* keyed on deviceId so the form state resets when the selection changes */}
+ <DeviceDetailPanel
+ device={selected}
+ isCurrent={isCurrent(selected.deviceId)}
+ key={selected.deviceId}
+ onClose={() => setSelectedId(undefined)}
+ />
+ </Flexbox>
+ )}
</Flexbox>
- {selected && (
- <Flexbox className={styles.detailCol} flex={1}>
- {/* keyed on deviceId so the form state resets when the selection changes */}
- <DeviceDetailPanel
- device={selected}
- isCurrent={isCurrent(selected.deviceId)}
- key={selected.deviceId}
- onClose={() => setSelectedId(undefined)}
- />
- </Flexbox>
- )}
- </Flexbox>
+ </AsyncBoundary>
);
});
diff --git a/src/libs/swr/normalizeError.test.ts b/src/libs/swr/normalizeError.test.ts
new file mode 100644
index 00000000000..21d5d0532ef
--- /dev/null
+++ b/src/libs/swr/normalizeError.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeAsyncError } from './normalizeError';
+
+describe('normalizeAsyncError', () => {
+ it('treats a missing error as retryable with no status', () => {
+ expect(normalizeAsyncError(undefined)).toEqual({ retryable: true });
+ expect(normalizeAsyncError(null)).toEqual({ retryable: true });
+ });
+
+ it('recovers an HTTP status from a TRPC client error shape', () => {
+ const err = { data: { code: 'INTERNAL_SERVER_ERROR', httpStatus: 500 }, message: 'boom' };
+ const result = normalizeAsyncError(err);
+ expect(result.status).toBe(500);
+ expect(result.code).toBe('INTERNAL_SERVER_ERROR');
+ expect(result.rawMessage).toBe('boom');
+ expect(result.retryable).toBe(true);
+ });
+
+ it('recovers a status from fetch Response-like shapes', () => {
+ expect(normalizeAsyncError({ status: 503 }).status).toBe(503);
+ expect(normalizeAsyncError({ response: { status: 502 } }).status).toBe(502);
+ expect(normalizeAsyncError({ cause: { status: 504 } }).status).toBe(504);
+ });
+
+ it('marks auth / permission failures as non-retryable', () => {
+ expect(normalizeAsyncError({ data: { httpStatus: 401 } }).retryable).toBe(false);
+ expect(normalizeAsyncError({ status: 403 }).retryable).toBe(false);
+ });
+
+ it('honors an explicit non-retryable marker regardless of status', () => {
+ expect(normalizeAsyncError({ meta: { shouldRetry: false }, status: 500 }).retryable).toBe(
+ false,
+ );
+ });
+
+ it('keeps 5xx and other transient failures retryable', () => {
+ expect(normalizeAsyncError({ status: 500 }).retryable).toBe(true);
+ expect(normalizeAsyncError({ status: 408 }).retryable).toBe(true);
+ });
+});
diff --git a/src/libs/swr/normalizeError.ts b/src/libs/swr/normalizeError.ts
new file mode 100644
index 00000000000..dcf90e5997c
--- /dev/null
+++ b/src/libs/swr/normalizeError.ts
@@ -0,0 +1,64 @@
+/**
+ * Canonical async-error shape shared by the whole data layer.
+ *
+ * The read/write conventions used to throw the SWR `error` away (hooks only
+ * registered `onSuccess`, call sites only destructured `{ data, isLoading }`),
+ * so a failed fetch had no way to reach the UI and silently degraded into a
+ * permanent skeleton / a fake empty / a confident `$0`. This module gives every
+ * surface one normalized error to branch on — see `AsyncBoundary` / `AsyncError`
+ * for the UI side.
+ */
+export interface NormalizedAsyncError {
+ /** Machine code when the backend supplies one (TRPC `code`, app error code). */
+ code?: string;
+ /** Raw message from the error, used as a fallback when no status copy exists. */
+ rawMessage?: string;
+ /**
+ * Whether retrying the same request could plausibly succeed. `false` for auth
+ * / permission failures (401 / 403) and anything the backend explicitly marks
+ * non-retryable (`meta.shouldRetry === false`, mirroring the SWR retry gate).
+ */
+ retryable: boolean;
+ /** HTTP-ish status when we can recover one, for status-specific copy. */
+ status?: number;
+}
+
+const NON_RETRYABLE_STATUS = new Set([401, 403]);
+
+/**
+ * Best-effort extraction of an HTTP status from the heterogeneous error shapes
+ * that reach SWR: TRPC client errors (`data.httpStatus`), fetch `Response`
+ * rejections (`status` / `response.status`), and plain objects.
+ */
+const extractStatus = (error: any): number | undefined => {
+ const status =
+ error?.data?.httpStatus ??
+ error?.data?.status ??
+ error?.status ??
+ error?.response?.status ??
+ error?.cause?.status;
+ return typeof status === 'number' ? status : undefined;
+};
+
+/**
+ * Fold any thrown value into a {@link NormalizedAsyncError}. Pure and
+ * i18n-free — the `AsyncError` component maps `status` → localized copy — so it
+ * stays trivially testable and reusable in non-React code (retry policies,
+ * logging).
+ */
+export const normalizeAsyncError = (error: unknown): NormalizedAsyncError => {
+ if (!error) return { retryable: true };
+
+ const err = error as any;
+ const status = extractStatus(err);
+ const code: string | undefined = err?.data?.code ?? err?.code;
+ const rawMessage: string | undefined = typeof err?.message === 'string' ? err.message : undefined;
+
+ // Honor the same non-retryable marker the SWR retry loop checks, and never
+ // invite a retry on an auth / permission wall.
+ const explicitlyNonRetryable = err?.meta?.shouldRetry === false;
+ const retryable =
+ !explicitlyNonRetryable && !(typeof status === 'number' && NON_RETRYABLE_STATUS.has(status));
+
+ return { code, rawMessage, retryable, status };
+};