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.

πŸ”§ chore(alint): add no-unguarded-response-field rule at error (#20474)

Arvin Xu71be00dea609
diff --git a/alint.config.toml b/alint.config.toml
index 7fa6a9b8dbb..1a4cafee7c6 100644
--- a/alint.config.toml
+++ b/alint.config.toml
@@ -59,6 +59,7 @@ lobehub = "./packages/alint/rules"
[config.group.rules]
"lobehub/no-effect-fetching" = "error"
"lobehub/no-mode-flags" = "warn"
+"lobehub/no-unguarded-response-field" = "error"
# Browser code, everywhere: no third-party package that needs Node may be
@@ -208,6 +209,13 @@ lobehub = "./packages/alint/rules"
[config.group.rules]
"lobehub/no-effect-fetching" = "warn"
+[[config.group]]
+files = [ "packages/alint/fixtures/no-unguarded-response-field/**" ]
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+[config.group.rules]
+"lobehub/no-unguarded-response-field" = "warn"
+
[[config.group]]
files = [ "packages/alint/fixtures/no-mode-flags/**" ]
[config.group.plugins]
diff --git a/packages/alint/README.md b/packages/alint/README.md
index 9598ea0a35e..c74a9fce0fd 100644
--- a/packages/alint/README.md
+++ b/packages/alint/README.md
@@ -13,6 +13,7 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)
| `no-effect-fetching` | error | `src/**/*.tsx` | `data-fetching-architecture` skill |
| `no-dynamic-import-in-server` | error | `apps/server/src`, `packages/database` | backend code uses static top-level imports |
| `no-mode-flags` | warn | `src/**/*.tsx` | `compose-atoms` skill |
+| `no-unguarded-response-field` | error | `src/**/*.tsx` | a newer client must survive an older server omitting a response field |
| `no-node-in-browser` | error | browser code in `src/` (not `app/`, `libs/`), package `*.tsx` | no Node-only npm package where the SPA runs it (paths: ESLint) |
| `no-unsafe-user-url-fetch` | warn | `apps/server/src` | user-controlled URLs must use SSRF-safe transport (#16601) |
| `no-unscoped-resource-mutation` | warn | database models/repositories | ownership checks for resource and junction mutations (#13683, #16586) |
diff --git a/packages/alint/fixtures/no-unguarded-response-field/bad-indexed-prop.tsx b/packages/alint/fixtures/no-unguarded-response-field/bad-indexed-prop.tsx
new file mode 100644
index 00000000000..70e26047a7c
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/bad-indexed-prop.tsx
@@ -0,0 +1,26 @@
+// Fixture: the incident β€” a prop typed as a slice of the server bundle, read as an array.
+import { memo } from 'react';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+interface PullRequestLinksProps {
+ pullRequests: AcceptanceBundle['pullRequests'];
+}
+
+const PullRequestLinks = memo<PullRequestLinksProps>(({ pullRequests }) => {
+ // alint-expect
+ if (pullRequests.length === 0) return null;
+
+ return (
+ <>
+ {/* alint-expect */}
+ {pullRequests.map((pullRequest) => (
+ <a href={pullRequest.url} key={pullRequest.url}>
+ #{pullRequest.number}
+ </a>
+ ))}
+ </>
+ );
+});
+
+export default PullRequestLinks;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/bad-swr-data-field.tsx b/packages/alint/fixtures/no-unguarded-response-field/bad-swr-data-field.tsx
new file mode 100644
index 00000000000..b8e85bc1ff2
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/bad-swr-data-field.tsx
@@ -0,0 +1,24 @@
+// Fixture: a field of SWR data iterated after guarding only the payload root.
+import { memo } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { verifyService } from '@/services/verify';
+
+const RoundList = memo<{ acceptanceId: string }>(({ acceptanceId }) => {
+ const { data } = useClientDataSWR(['acceptance-bundle', acceptanceId], () =>
+ verifyService.getAcceptanceBundle(acceptanceId),
+ );
+
+ if (!data) return null;
+
+ return (
+ <ul>
+ {/* alint-expect */}
+ {data.rounds.map((round) => (
+ <li key={round.id}>{round.summary}</li>
+ ))}
+ </ul>
+ );
+});
+
+export default RoundList;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/good-electron-bridge-named.tsx b/packages/alint/fixtures/no-unguarded-response-field/good-electron-bridge-named.tsx
new file mode 100644
index 00000000000..181d4801389
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/good-electron-bridge-named.tsx
@@ -0,0 +1,17 @@
+// Fixture: an Electron IPC bridge whose service name does not say "electron".
+import { memo } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { imessageBridgeService } from '@/services/electron/imessageBridge';
+
+const BridgeStatus = memo<{ applicationId: string }>(({ applicationId }) => {
+ const { data: status } = useClientDataSWR('imessage-bridge-status', () =>
+ imessageBridgeService.getStatus(),
+ );
+
+ const config = status?.configs.find((item) => item.applicationId === applicationId);
+
+ return <span>{config ? config.label : 'β€”'}</span>;
+});
+
+export default BridgeStatus;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/good-electron-ipc.tsx b/packages/alint/fixtures/no-unguarded-response-field/good-electron-ipc.tsx
new file mode 100644
index 00000000000..aab6ed73305
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/good-electron-ipc.tsx
@@ -0,0 +1,20 @@
+// Fixture: a local Electron bridge payload, not a server response.
+import { memo, useEffect, useState } from 'react';
+
+import { electronDevtoolsService } from '@/services/electron/devtools';
+
+type Metrics = Awaited<ReturnType<typeof electronDevtoolsService.getAppProcessMetrics>>;
+
+const ProcessCount = memo(() => {
+ const [metrics, setMetrics] = useState<Metrics | null>(null);
+
+ useEffect(() => {
+ void electronDevtoolsService.getAppProcessMetrics().then(setMetrics);
+ }, []);
+
+ if (!metrics) return null;
+
+ return <span>{metrics.processes.length} processes</span>;
+});
+
+export default ProcessCount;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/good-fallback.tsx b/packages/alint/fixtures/no-unguarded-response-field/good-fallback.tsx
new file mode 100644
index 00000000000..ece578989ae
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/good-fallback.tsx
@@ -0,0 +1,24 @@
+// Fixture: the field is normalized once where it is read.
+import { memo } from 'react';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+interface PullRequestLinksProps {
+ pullRequests?: AcceptanceBundle['pullRequests'];
+}
+
+const PullRequestLinks = memo<PullRequestLinksProps>(({ pullRequests = [] }) => {
+ if (pullRequests.length === 0) return null;
+
+ return (
+ <>
+ {pullRequests.map((pullRequest) => (
+ <a href={pullRequest.url} key={pullRequest.url}>
+ #{pullRequest.number}
+ </a>
+ ))}
+ </>
+ );
+});
+
+export default PullRequestLinks;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/good-response-root-and-passthrough.tsx b/packages/alint/fixtures/no-unguarded-response-field/good-response-root-and-passthrough.tsx
new file mode 100644
index 00000000000..9d3b417f630
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/good-response-root-and-passthrough.tsx
@@ -0,0 +1,30 @@
+// Fixture: a response that is itself the array, and a field handed to an imported helper.
+import { memo } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { agentEvalService } from '@/services/agentEval';
+import { deviceService } from '@/services/device';
+
+import { partitionScan } from './partitionScan';
+
+const ResumeSummary = memo<{ deviceId: string; runId: string }>(({ deviceId, runId }) => {
+ const { data: cases } = useClientDataSWR(['resumable', runId], () =>
+ agentEvalService.getResumableCases(runId),
+ );
+ const { data: scan } = useClientDataSWR(['scan', deviceId], () =>
+ deviceService.scanAgents(deviceId),
+ );
+
+ if (!cases || !scan) return null;
+
+ const resumable = cases.filter((item) => item.canResume);
+ const { installed } = partitionScan(scan.agents);
+
+ return (
+ <span>
+ {resumable.length} / {installed.length}
+ </span>
+ );
+});
+
+export default ResumeSummary;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/good-scalar-fields.tsx b/packages/alint/fixtures/no-unguarded-response-field/good-scalar-fields.tsx
new file mode 100644
index 00000000000..23a2ce6790d
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/good-scalar-fields.tsx
@@ -0,0 +1,22 @@
+// Fixture: scalar response fields rendered and compared β€” undefined renders nothing.
+import { memo } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { verifyService } from '@/services/verify';
+
+const AcceptanceTitle = memo<{ acceptanceId: string }>(({ acceptanceId }) => {
+ const { data } = useClientDataSWR(['acceptance-bundle', acceptanceId], () =>
+ verifyService.getAcceptanceBundle(acceptanceId),
+ );
+
+ if (!data) return null;
+
+ return (
+ <h1>
+ {data.acceptance.title}
+ {data.acceptance.roundCount > 1 && <small> Β· {data.acceptance.roundCount}</small>}
+ </h1>
+ );
+});
+
+export default AcceptanceTitle;
diff --git a/packages/alint/fixtures/no-unguarded-response-field/good-store-and-plain-props.tsx b/packages/alint/fixtures/no-unguarded-response-field/good-store-and-plain-props.tsx
new file mode 100644
index 00000000000..be76f779277
--- /dev/null
+++ b/packages/alint/fixtures/no-unguarded-response-field/good-store-and-plain-props.tsx
@@ -0,0 +1,29 @@
+// Fixture: arrays from a zustand store and from a plain prop interface β€” not raw responses.
+import { memo } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+interface TopicChip {
+ id: string;
+ title: string;
+}
+
+interface TopicChipsProps {
+ pinned: TopicChip[];
+}
+
+const TopicChips = memo<TopicChipsProps>(({ pinned }) => {
+ const topics = useChatStore(topicSelectors.currentTopics);
+
+ return (
+ <>
+ {pinned.map((chip) => (
+ <span key={chip.id}>{chip.title}</span>
+ ))}
+ {topics.length > 0 && topics.map((topic) => <span key={topic.id}>{topic.title}</span>)}
+ </>
+ );
+});
+
+export default TopicChips;
diff --git a/packages/alint/rules/no-unguarded-response-field/rule.alint.toml b/packages/alint/rules/no-unguarded-response-field/rule.alint.toml
new file mode 100644
index 00000000000..52b8bf2bfa9
--- /dev/null
+++ b/packages/alint/rules/no-unguarded-response-field/rule.alint.toml
@@ -0,0 +1,33 @@
+name = "no-unguarded-response-field"
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one React component or hook file from the LobeHub web client.
+
+Why this rule exists: the web client does not ship in lockstep with the server it talks to. The desktop renderer updates on its own channel, a canary client reaches a cloud that has not deployed yet, and a self-hosted server can be months older than the client. Whenever the server adds a field to a response, some live client meets a server that does not send it. The incident behind this rule: an acceptance bundle gained `pullRequests`, the header did `pullRequests.length > 0`, an older server sent no such field, and `Cannot read properties of undefined (reading 'length')` took down the whole route. A client read of a response collection must therefore survive the field being absent.
+
+Report a field of a SERVER RESPONSE that the file dereferences in a way that THROWS when the field is undefined, with no fallback on the path. Throwing dereferences: `.length`, `.map` / `.filter` / `.some` / `.every` / `.find` / `.findIndex` / `.reduce` / `.forEach` / `.flatMap` / `.includes` / `.join` / `.slice` / `.at` / `.sort`, `for … of`, array spread `[...x]`, `Object.keys` / `Object.values` / `Object.entries`, and a property access one level deeper (`data.summary.total`). Object spread `{...x}` and `new Set(x)` accept undefined and do not count. On the CALLER side, handing a field onward as an argument or a prop (`partition(data.agents)`, `setItems(data.items)`, `<List items={data.items} />`) is not a dereference in this file; never guess what an imported function does with it. The RECEIVING side is different: a component or function whose own prop or parameter is typed as a slice of a response type (`pullRequests: AcceptanceBundle['pullRequests']`) and that iterates it IS in scope β€” that is exactly the incident.
+
+First rule out local bridges: a value read through anything imported from `@/services/electron/*` (whatever the service is called, e.g. `imessageBridgeService`), `window.electron`, `ipcRenderer`, or the device gateway is NEVER a server response, even when it flows through `useClientDataSWR`. Stop there for that value.
+
+Otherwise, a value is a server response only when this file shows it:
+- the `data` (or a destructured alias) of `useSWR`, `useClientDataSWR`, `useSWRInfinite`, `useOnlyFetchOnceSWR`, or of a same-repo hook that wraps them and returns a fetched payload (`useAcceptanceBundle`, `useFetch*` returning `data`);
+- the awaited result of a `*Service.*` call, `lambdaClient.*`, `edgeClient.*`, `trpc.*`, or `fetch(...).json()`;
+- a prop, parameter or variable whose declared type is carved out of a response type: an indexed access into a type named like a payload (`AcceptanceBundle['pullRequests']`, `Bundle['rounds'][number]`), `Awaited<ReturnType<typeof someService.method>>[...]`, or `inferRouterOutputs` / `RouterOutput[...]`.
+
+A fallback is anything that makes the dereference safe when the field is missing: `?? []`, `?? {}`, `|| []`, optional chaining on the field itself (`x?.length`, `x?.map`), a destructuring or parameter default (`{ pullRequests = [] }`), or an earlier guard on the same field (`if (!x) return`, `Array.isArray(x)`, `x && x.map(...)`). Guarding only the outer `data` (`if (!data) return null`) is NOT a fallback for its fields.
+
+Report EVERY unguarded throwing dereference as its own finding, anchored on the line of that dereference β€” never fold several sites into one finding on the first of them. Only findings on lines a pull request adds or changes are kept, so a new read of an old field must carry its own anchor, and an untouched old read must not stand in for it. Name the field and where it comes from (hook, service call or type). The suggestion must normalize the field once where it is read (`const pullRequests = data.pullRequests ?? []`, or a destructuring default) rather than sprinkling `?.` at every use.
+
+Do not report β€” these are the places the rule does not apply:
+- the payload root itself: `data.items` before `data` resolves, or a response that IS the array (`service.list().then((data) => data.filter(...))`). Only report a named field INSIDE an object payload β€” a server that lacks the endpoint fails the request, it does not send a partial payload;
+- a field passed as an argument or prop (`partition(data.agents)`, `<List items={data.items} />`). The dereference happens in the callee, which this file cannot see; do not guess what an imported helper does with it;
+- scalar fields that are rendered, compared or formatted (`{data.title}`, `data.count > 0`, `` `#${pr.number}` ``, `formatDate(data.createdAt)`): an undefined scalar renders nothing or compares false; it does not crash;
+- values that come from a zustand store or its selectors, React state, context, URL params, `localStorage`, constants, or something the file built itself β€” even if they were originally fetched; the store owns normalization;
+- props or parameters typed with a plain interface or an element type (`items: Item[]`, `pullRequests: PullRequestLink[]`) rather than a slice of a response type. The file cannot see where those come from;
+- an array the client derived from a response (`data.items.map(...)` is one finding at `.map`; the `.filter` chained after it is not another);
+- local bridges rather than the server: anything imported from `@/services/electron/*` whatever the service is named (`imessageBridgeService`, `electronDevtoolsService`), `window.electron`, `ipcRenderer`, the device gateway, the local file system;
+- fields the server type itself marks optional (`field?:`) when the file already handles them β€” TypeScript forces that path;
+- test files, stories, fixtures and mock data.
+
+If an exclusion applies, return no finding. If you cannot tell from this file whether the value is a server response, return no finding rather than a low-confidence guess.
+"""