🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🔧 chore(alint): add no-inferred-service-types rule (#21410)
Arvin Xu952396b61597
diff --git a/alint.config.toml b/alint.config.tomlindex 56e820513ea..9f0963d1dc6 100644--- a/alint.config.toml+++ b/alint.config.toml@@ -61,6 +61,25 @@ lobehub = "./packages/alint/rules""lobehub/no-mode-flags" = "warn""lobehub/no-unguarded-response-field" = "error"+# Web client data types: payload shapes are declared in @lobechat/types, not+# inferred with Awaited<ReturnType<typeof someService.method>>.+[[config.group]]+files = [ "src/**/*.ts", "src/**/*.tsx" ]+ignores = [ "**/*.test.ts", "**/*.test.tsx", "**/__tests__/**", "**/__mocks__/**", "**/*.stories.tsx" ]++[config.group.plugins]+lobehub = "./packages/alint/rules"++[config.group.rules]+"lobehub/no-inferred-service-types" = "warn"++[[config.group]]+files = [ "packages/alint/fixtures/no-inferred-service-types/**" ]+[config.group.plugins]+lobehub = "./packages/alint/rules"+[config.group.rules]+"lobehub/no-inferred-service-types" = "warn"+# Fixed product images and App-owned resource requests have different namespaces.[[config.group]]files = [ "src/**/*.{ts,tsx,css}", "packages/const/src/**/*.ts", "apps/*/app/**/*.{ts,tsx,css}", "apps/{share,workbench}/src/**/*.{ts,tsx,css}", "apps/desktop/vite.*.config.{ts,mts}", "scripts/**/*.{ts,mts}" ]diff --git a/packages/alint/README.md b/packages/alint/README.mdindex 2892391ccaa..a1e1d4ebb6b 100644--- a/packages/alint/README.md+++ b/packages/alint/README.md@@ -14,6 +14,7 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)| `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-inferred-service-types` | warn | `src/**/*.{ts,tsx}` | payload types live in `@lobechat/types`, not `Awaited<ReturnType<…>>` || `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-benchmark-in-tests` | warn | `**/*.test.ts(x)` except `packages/database` | a unit test asserts on behaviour, not on a wall-clock measurement || `no-unsafe-user-url-fetch` | warn | `apps/server/src` | user-controlled URLs must use SSRF-safe transport (#16601) |diff --git a/packages/alint/fixtures/no-inferred-service-types/bad-action-annotation.ts b/packages/alint/fixtures/no-inferred-service-types/bad-action-annotation.tsnew file mode 100644index 00000000000..a798e6d9f61--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/bad-action-annotation.ts@@ -0,0 +1,17 @@+// Fixture: a store action annotates its result with the service's inferred return type.+import { taskService } from '@/services/task';++export const runTask = async (+ id: string,+ onError: (error: unknown) => void,+): Promise<boolean> => {+ // alint-expect+ let result: Awaited<ReturnType<typeof taskService.run>>;+ try {+ result = await taskService.run(id);+ } catch (error) {+ onError(error);+ return false;+ }+ return result.success;+};diff --git a/packages/alint/fixtures/no-inferred-service-types/bad-procedure-alias.ts b/packages/alint/fixtures/no-inferred-service-types/bad-procedure-alias.tsnew file mode 100644index 00000000000..60bc1f1894e--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/bad-procedure-alias.ts@@ -0,0 +1,14 @@+// Fixture: a local alias of a TRPC procedure is still inference from the router output.+import { lambdaClient } from '@/libs/trpc/client';++export const resolveBySource = async (operationId: string, toolCallId: string) => {+ const mutate = lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate;+ // alint-expect+ let result: Awaited<ReturnType<typeof mutate>>;+ try {+ result = await mutate({ operationId, toolCallId });+ } catch {+ return { resolved: false };+ }+ return { resolved: result.success };+};diff --git a/packages/alint/fixtures/no-inferred-service-types/bad-store-projection.ts b/packages/alint/fixtures/no-inferred-service-types/bad-store-projection.tsnew file mode 100644index 00000000000..92893a3843a--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/bad-store-projection.ts@@ -0,0 +1,20 @@+// Fixture: a store projection that infers its row types from the client service.+import { defineReplica } from '@/libs/replica';+import type { projectService } from '@/services/project';++// alint-expect+type ProjectListResponse = Awaited<ReturnType<typeof projectService.listAll>>;+// alint-expect+type ProjectDetailResponse = Awaited<ReturnType<typeof projectService.detail>>;+type ProjectListRow = ProjectListResponse['data'][number];++export type ProjectListItem = Omit<ProjectListRow, 'coordinatorAgent'> &+ Partial<Pick<ProjectListRow, 'coordinatorAgent'>>;+export type ProjectDetail = ProjectDetailResponse['data'];++export const projectDetailResource = defineReplica<string, ProjectDetail, ProjectDetailResponse>({+ key: (idOrSlug) => idOrSlug,+ name: 'projectDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/packages/alint/fixtures/no-inferred-service-types/bad-trpc-client-inference.ts b/packages/alint/fixtures/no-inferred-service-types/bad-trpc-client-inference.tsnew file mode 100644index 00000000000..c1b623c2eda--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/bad-trpc-client-inference.ts@@ -0,0 +1,11 @@+// Fixture: a client service that exports payload types inferred from the TRPC client.+import { lambdaClient } from '@/libs/trpc/client';++// alint-expect+export type AcceptanceBundle = Awaited<ReturnType<typeof lambdaClient.acceptance.getBundle.query>>;++class VerifyService {+ getBundle = async (id: string) => lambdaClient.acceptance.getBundle.query({ id });+}++export const verifyService = new VerifyService();diff --git a/packages/alint/fixtures/no-inferred-service-types/good-client-and-helper-types.ts b/packages/alint/fixtures/no-inferred-service-types/good-client-and-helper-types.tsnew file mode 100644index 00000000000..e54b9141334--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/good-client-and-helper-types.ts@@ -0,0 +1,21 @@+// Fixture: typing a client object or a pure service-module helper is not payload inference.+import type { ProjectListResponse } from '@lobechat/types';++import { createWorkspaceLambdaClient } from '@/libs/trpc/client';+import { transcriptBucketOf } from '@/services/message/replica';++export type ScopedLambdaClient = ReturnType<typeof createWorkspaceLambdaClient>;++const buckets = new Map<string, ReturnType<typeof transcriptBucketOf>>();++export const bucketFor = (topicId: string) => {+ const cached = buckets.get(topicId);+ if (cached) return cached;+ const bucket = transcriptBucketOf(topicId);+ buckets.set(topicId, bucket);+ return bucket;+};++export const listProjects = async (+ client: ScopedLambdaClient,+): Promise<ProjectListResponse> => client.project.list.query({ limit: 100, offset: 0 });diff --git a/packages/alint/fixtures/no-inferred-service-types/good-declared-types.ts b/packages/alint/fixtures/no-inferred-service-types/good-declared-types.tsnew file mode 100644index 00000000000..6cf6995cefd--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/good-declared-types.ts@@ -0,0 +1,18 @@+// Fixture: the payload shapes are declared in the types package and imported.+import type { ProjectDetail, ProjectListItem, ProjectListResponse } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';++export const projectListResource = defineReplica<+ Record<string, never>,+ ProjectListItem[],+ ProjectListResponse+>({+ key: () => 'all',+ name: 'projectList',+ storage: 'indexedDB',+ version: 1,+});++export const pickActive = (detail: ProjectDetail): ProjectListItem | undefined =>+ detail.status === 'active' ? detail : undefined;diff --git a/packages/alint/fixtures/no-inferred-service-types/good-local-return-types.ts b/packages/alint/fixtures/no-inferred-service-types/good-local-return-types.tsnew file mode 100644index 00000000000..56f32923488--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/good-local-return-types.ts@@ -0,0 +1,32 @@+// Fixture: ReturnType of local functions, timers, store APIs and hooks is not service inference.+import { useForm } from 'antd/es/form/Form';+import { createStore } from 'zustand/vanilla';++import { documentService } from '@/services/document';++type FormInstance = ReturnType<typeof useForm>[0];++const createEditorStore = () => createStore<{ dirty: boolean }>(() => ({ dirty: false }));+type EditorStore = ReturnType<typeof createEditorStore>;++export const createAutosave = (store: EditorStore, form: FormInstance) => {+ let timer: ReturnType<typeof setTimeout> | undefined;++ const requestSave = async (id: string) => {+ const values = form.getFieldsValue();+ return documentService.updateDocument({ id, ...values });+ };++ const flush = async (id: string) => {+ let saved: Awaited<ReturnType<typeof requestSave>> | undefined;+ if (store.getState().dirty) saved = await requestSave(id);+ return saved;+ };++ const schedule = (id: string) => {+ clearTimeout(timer);+ timer = setTimeout(() => void flush(id), 1000);+ };++ return { flush, schedule };+};diff --git a/packages/alint/fixtures/no-inferred-service-types/good-parameters-inference.ts b/packages/alint/fixtures/no-inferred-service-types/good-parameters-inference.tsnew file mode 100644index 00000000000..2d7d2c5eccd--- /dev/null+++ b/packages/alint/fixtures/no-inferred-service-types/good-parameters-inference.ts@@ -0,0 +1,17 @@+// Fixture: input-side inference, injected function types and re-imported aliases are out of scope.+import type { TaskListItem } from '@/store/task/slices/list/initialState';+import { messageService } from '@/services/message';+import { taskService } from '@/services/task';++type CreateTaskParams = Parameters<typeof taskService.create>[0];++export const createFromTemplate = (template: TaskListItem, overrides: Partial<CreateTaskParams>) =>+ taskService.create({ instruction: template.instruction, title: template.title, ...overrides });++export const createMessageWriter = (deps: {+ createMessage: typeof messageService.createMessage;+ updateMessage: typeof messageService.updateMessage;+}) => ({+ create: deps.createMessage,+ update: deps.updateMessage,+});diff --git a/packages/alint/rules/no-inferred-service-types/rule.alint.toml b/packages/alint/rules/no-inferred-service-types/rule.alint.tomlnew file mode 100644index 00000000000..41cfb27241c--- /dev/null+++ b/packages/alint/rules/no-inferred-service-types/rule.alint.toml@@ -0,0 +1,30 @@+name = "no-inferred-service-types"+builtInAgent = "basic-structured"+instruction = """+You are reviewing one TypeScript file from the LobeHub web client (`src/`).++Team rule, from the owner's review rejection of `type ProjectListResponse = Awaited<ReturnType<typeof projectService.listAll>>`: "这类写法是不合理的, 应该都换成写到 types 包里面,然后直接声明,而不是用Await 。"++Why: a type carved out of a service's inferred return value has no name and no home. Every store, component and test re-derives it, the shape silently follows whatever the router happens to return, and a reader has to chase service → TRPC router → model to learn what a project row is. The shape of data the client receives is a contract, so it is declared once in the types package (`packages/types/src/<domain>`, imported as `@lobechat/types`), the server and the client service annotate their return with it, and client code imports that name.++Report every type position in this file whose type is INFERRED from what a client service or the TRPC client returns:+1. `ReturnType<typeof X>` or `Awaited<ReturnType<typeof X>>` — alone or wrapped in `NonNullable<…>`, `Partial<…>`, `Pick<…>`, `Omit<…>`, indexed (`['data']`, `[number]`), or used as a `Promise<…>` argument — where `X` is a method of a client service (`projectService.listAll`, `taskService.list`, `agentEvalService.getRunDetails`, any `<name>Service.<method>`, including one imported with `import type`) or a TRPC client procedure (`lambdaClient.acceptance.getBundle.query`, `edgeClient.*`, `trpc.*`, or a procedure called on a `createWorkspaceLambdaClient(...)` client);+2. `inferRouterOutputs<…>`, `inferProcedureOutput<…>`, or an indexed access into a router-output type (`RouterOutput['project']['list']`).+This covers type aliases, interface fields, variable and parameter annotations (`let result: Awaited<ReturnType<typeof taskService.run>>`), function return annotations and `as` casts.+A local constant that is itself a service method or procedure (`const mutate = lambdaClient.aiAgent.resolve.mutate; let result: Awaited<ReturnType<typeof mutate>>`) counts as that procedure.+Anchor each finding on the line that contains `ReturnType<typeof …>` or the router-output type — one finding per occurrence, never folded into the first one. A multi-line type is anchored on the line where `ReturnType` appears. Only those lines are findings: a later line that merely uses an alias declared above (`defineReplica<…, ProjectListResponse>`) is not another finding.+The message must name the service method or procedure the type is inferred from. The suggestion must name a type to declare in `packages/types/src/<domain>` (e.g. `ProjectListItem` in `packages/types/src/project`), say that the service method (and the router behind it) should annotate its return with that type, and that this file should import it from `@lobechat/types` instead of inferring it. When the inferred type is only indexed into (`['data'][number]`), the declared type is the element, not the envelope.++Do not report — these are not service-response inference:+- types already imported from `@lobechat/types`, `@lobechat/*` packages, or a local declared `interface` / `type` literal, even when they describe a server payload;+- importing or using a type alias that another file inferred (`import type { TaskListItem } from '@/store/task/...'`): the finding belongs to the declaring line in that other file;+- `ReturnType<typeof f>` where `f` is NOT a service method or TRPC procedure: a function or closure this file declares with its own body, even one whose body only returns a service call (`const requestSave = () => documentService.updateDocument(…)`; `Awaited<ReturnType<typeof requestSave>>`) — never follow a local function's body to find a service call inside it, a store action or selector (`typeof store.internal_*`, `typeof useChatStore.getState`), a React hook (`typeof useForm`, `typeof useXxxSWR`), a timer (`typeof setTimeout`, `typeof setInterval`), a factory or third-party function (`typeof createStore`, `typeof dayjs`);+- the type of a client or service OBJECT rather than of data it returns: `ReturnType<typeof createWorkspaceLambdaClient>`, `typeof lambdaClient`, `typeof projectService`;+- plain helper functions exported from a `@/services/*` module that are not methods of a `<name>Service` instance and do not call the server (`transcriptBucketOf`, `buildCursorKey`) — only `<name>Service.<method>` and TRPC procedures count;+- a bare `typeof service.method` used as a FUNCTION type, without `ReturnType` (an injected dependency such as `deps: { createMessage: typeof messageService.createMessage }`);+- `Parameters<typeof service.method>` and other input-side inference — this rule is about returned data only;+- local bridges that are not server responses: anything from `@/services/electron/*`, `window.electron`, `ipcRenderer`;+- test files, stories, fixtures and mocks.++If an exclusion applies, return no finding. If you cannot tell from this file whether `X` is a client service or TRPC procedure, return no finding rather than a low-confidence guess.+"""