🤯 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
📝 docs(skills): frontmatter cleanup + argument-hint (#14683)
YuTengjing83b2a0031401
diff --git a/.agents/skills/add-provider-doc/SKILL.md b/.agents/skills/add-provider-doc/SKILL.mdindex 490e8f7a386..d5a9a14dad4 100644--- a/.agents/skills/add-provider-doc/SKILL.md+++ b/.agents/skills/add-provider-doc/SKILL.md@@ -1,6 +1,8 @@---name: add-provider-docdescription: Guide for adding new AI provider documentation. Use when adding documentation for a new AI provider (like OpenAI, Anthropic, etc.), including usage docs, environment variables, Docker config, and image resources. Triggers on provider documentation tasks.+disable-model-invocation: true+argument-hint: '[provider-name]'---# Adding New AI Provider Documentationdiff --git a/.agents/skills/add-setting-env/SKILL.md b/.agents/skills/add-setting-env/SKILL.mdindex d3e4de3a644..5b61b2db98b 100644--- a/.agents/skills/add-setting-env/SKILL.md+++ b/.agents/skills/add-setting-env/SKILL.md@@ -1,6 +1,8 @@---name: add-setting-envdescription: Guide for adding environment variables to configure user settings. Use when implementing server-side environment variables that control default values for user settings. Triggers on env var configuration or setting default value tasks.+disable-model-invocation: true+argument-hint: '[setting-name]'---# Adding Environment Variable for User Settingsdiff --git a/.agents/skills/builtin-tool/SKILL.md b/.agents/skills/builtin-tool/SKILL.mdindex 6b35a749664..74adc0b74c7 100644--- a/.agents/skills/builtin-tool/SKILL.md+++ b/.agents/skills/builtin-tool/SKILL.md@@ -19,11 +19,11 @@ A builtin tool is a package the agent runtime can call. It ships **five faces**:## Read These First-| Question | Doc |-| ------------------------------------------------------------------------------------ | ---------------------------------- |-| Where do files live? What does each face do? Wiring? | [architecture.md](architecture.md) |-| How do I name the tool, design APIs, write the manifest, executor, ExecutionRuntime? | [tool-design.md](tool-design.md) |-| How do I build Inspector / Render / Placeholder / Streaming / Intervention / Portal? | [ui.md](ui.md) |+| Question | Doc |+| ------------------------------------------------------------------------------------ | --------------------------------------------- |+| Where do files live? What does each face do? Wiring? | [architecture.md](references/architecture.md) |+| How do I name the tool, design APIs, write the manifest, executor, ExecutionRuntime? | [tool-design.md](references/tool-design.md) |+| How do I build Inspector / Render / Placeholder / Streaming / Intervention / Portal? | [ui.md](references/ui.md) |---@@ -109,7 +109,7 @@ Before opening the PR:- [ ] Placeholder added if the API has a perceivable execution lag (search, list, crawl).- [ ] Streaming added for APIs that emit incremental output (run command, write file, code execution).- [ ] Intervention added if `humanIntervention` is set in the manifest.-- [ ] All registry files updated (see [architecture.md → Registry wiring](architecture.md#registry-wiring)).+- [ ] All registry files updated (see [architecture.md → Registry wiring](references/architecture.md#registry-wiring)).- [ ] i18n keys in `src/locales/default/plugin.ts` plus dev seeds in `en-US`/`zh-CN`.- [ ] `bunx vitest run --silent='passed-only' 'packages/builtin-tool-<name>'` passes.- [ ] `bun run type-check` passes.diff --git a/.agents/skills/builtin-tool/architecture.md b/.agents/skills/builtin-tool/references/architecture.mdsimilarity index 100%rename from .agents/skills/builtin-tool/architecture.mdrename to .agents/skills/builtin-tool/references/architecture.mddiff --git a/.agents/skills/builtin-tool/tool-design.md b/.agents/skills/builtin-tool/references/tool-design.mdsimilarity index 100%rename from .agents/skills/builtin-tool/tool-design.mdrename to .agents/skills/builtin-tool/references/tool-design.mddiff --git a/.agents/skills/builtin-tool/ui.md b/.agents/skills/builtin-tool/references/ui.mdsimilarity index 100%rename from .agents/skills/builtin-tool/ui.mdrename to .agents/skills/builtin-tool/references/ui.mddiff --git a/.agents/skills/chat-sdk/SKILL.md b/.agents/skills/chat-sdk/SKILL.mdindex ca315c920a5..4d10647059c 100644--- a/.agents/skills/chat-sdk/SKILL.md+++ b/.agents/skills/chat-sdk/SKILL.md@@ -8,6 +8,7 @@ description: >(4) Send interactive cards or stream AI responses to chat platforms.Triggers on "chat sdk", "chat bot", "slack bot", "teams bot", "discord bot", "@chat-adapter",building bots that work across multiple chat platforms.+user-invocable: false---# Chat SDKdiff --git a/.agents/skills/data-fetching/SKILL.md b/.agents/skills/data-fetching/SKILL.mdindex 00cc439fa41..baf38f92dfe 100644--- a/.agents/skills/data-fetching/SKILL.md+++ b/.agents/skills/data-fetching/SKILL.md@@ -1,17 +1,16 @@---name: data-fetchingdescription: Data fetching architecture guide using Service layer + Zustand Store + SWR. Use when implementing data fetching, creating services, working with store hooks, or migrating from useEffect. Triggers on data loading, API calls, service creation, or store data fetching tasks.+user-invocable: false---# LobeHub Data Fetching Architecture-> **Related Skills:**->-> - `store-data-structures` - How to structure List and Detail data in stores (Map vs Array patterns)+> **Related:** `store-data-structures` covers List vs Detail data shape rationale (Map vs Array).## Architecture Overview-```+```text┌─────────────┐│ Component │└──────┬──────┘@@ -41,18 +40,17 @@ description: Data fetching architecture guide using Service layer + Zustand Stor1. **Use Service Layer** for all API calls2. **Use Store SWR Hooks** for data fetching (not useEffect)-3. **Use proper data structures** - See `store-data-structures` skill for List vs Detail patterns+3. **Use proper data structures** — see `store-data-structures` skill for List vs Detail patterns4. **Use lambdaClient.mutate** for write operations (create/update/delete)5. **Use lambdaClient.query** only inside service methods+6. **Naming convention** — read hooks are `useFetchXxx`, cache invalidation helpers are `refreshXxx` (e.g. `useFetchBenchmarks` / `refreshBenchmarks`). Mutations then chain `refreshXxx()` after the service call.### ❌ DON'T1. **Never use useEffect** for data fetching2. **Never call lambdaClient** directly in components or stores3. **Never use useState** for server data-4. **Never mix data structure patterns** - Follow `store-data-structures` skill--> **Note:** For data structure patterns (Map vs Array, List vs Detail), see the `store-data-structures` skill.+4. **Never mix data structure patterns** — follow `store-data-structures` skill---@@ -68,8 +66,6 @@ description: Data fetching architecture guide using Service layer + Zustand Stor```typescript// src/services/agentEval.ts-import { lambdaClient } from '@/libs/trpc/client';-class AgentEvalService {// Query methods - READ operationsasync listBenchmarks() {@@ -114,20 +110,16 @@ export const agentEvalService = new AgentEvalService();- Provide SWR hooks for data fetching- Handle cache invalidation-> **Data Structure:** See `store-data-structures` skill for how to structure List and Detail data.--### Store Structure Overview+### State Structure```typescript// src/store/eval/slices/benchmark/initialState.ts-import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';-export interface BenchmarkSliceState {- // List data - simple array (see store-data-structures skill)+ // List data - simple arraybenchmarkList: AgentEvalBenchmarkListItem[];benchmarkListInit: boolean;- // Detail data - map for caching (see store-data-structures skill)+ // Detail data - map for cachingbenchmarkDetailMap: Record<string, AgentEvalBenchmark>;loadingBenchmarkDetailIds: string[];@@ -140,19 +132,10 @@ export interface BenchmarkSliceState {> For complete initialState, reducer, and internal dispatch patterns, see the `store-data-structures` skill.-### Create Actions+### Actions```typescript// src/store/eval/slices/benchmark/action.ts-import type { SWRResponse } from 'swr';-import type { StateCreator } from 'zustand/vanilla';-import isEqual from 'fast-deep-equal';--import { mutate, useClientDataSWR } from '@/libs/swr';-import { agentEvalService } from '@/services/agentEval';-import type { EvalStore } from '@/store/eval/store';-import { benchmarkDetailReducer, type BenchmarkDetailDispatch } from './reducer';-const FETCH_BENCHMARKS_KEY = 'FETCH_BENCHMARKS';const FETCH_BENCHMARK_DETAIL_KEY = 'FETCH_BENCHMARK_DETAIL';@@ -165,7 +148,7 @@ export interface BenchmarkAction {refreshBenchmarks: () => Promise<void>;refreshBenchmarkDetail: (id: string) => Promise<void>;- // Mutation actions - for write operations+ // Mutation actionscreateBenchmark: (params: CreateParams) => Promise<any>;updateBenchmark: (params: UpdateParams) => Promise<void>;deleteBenchmark: (id: string) => Promise<void>;@@ -175,35 +158,25 @@ export interface BenchmarkAction {internal_updateBenchmarkDetailLoading: (id: string, loading: boolean) => void;}-export const createBenchmarkSlice: StateCreator<- EvalStore,- [['zustand/devtools', never]],- [],- BenchmarkAction-> = (set, get) => ({- // Fetch list - Simple array- useFetchBenchmarks: () => {- return useClientDataSWR(FETCH_BENCHMARKS_KEY, () => agentEvalService.listBenchmarks(), {- onSuccess: (data: any) => {- set(- {- benchmarkList: data,- benchmarkListInit: true,- },- false,- 'useFetchBenchmarks/success',- );+export const createBenchmarkSlice: StateCreator<EvalStore, any, [], BenchmarkAction> = (+ set,+ get,+) => ({+ // Fetch list — simple array stored in benchmarkList+ useFetchBenchmarks: () =>+ useClientDataSWR(FETCH_BENCHMARKS_KEY, () => agentEvalService.listBenchmarks(), {+ onSuccess: (data) => {+ set({ benchmarkList: data, benchmarkListInit: true }, false, 'useFetchBenchmarks/success');},- });- },+ }),- // Fetch detail - Map with dispatch- useFetchBenchmarkDetail: (id) => {- return useClientDataSWR(+ // Fetch detail — null key disables the request when id is missing+ useFetchBenchmarkDetail: (id) =>+ useClientDataSWR(id ? [FETCH_BENCHMARK_DETAIL_KEY, id] : null,() => agentEvalService.getBenchmark(id!),{- onSuccess: (data: any) => {+ onSuccess: (data) => {get().internal_dispatchBenchmarkDetail({type: 'setBenchmarkDetail',id: id!,@@ -212,19 +185,13 @@ export const createBenchmarkSlice: StateCreator<get().internal_updateBenchmarkDetailLoading(id!, false);},},- );- },+ ),// Refresh methods- refreshBenchmarks: async () => {- await mutate(FETCH_BENCHMARKS_KEY);- },+ refreshBenchmarks: () => mutate(FETCH_BENCHMARKS_KEY),+ refreshBenchmarkDetail: (id) => mutate([FETCH_BENCHMARK_DETAIL_KEY, id]),- refreshBenchmarkDetail: async (id) => {- await mutate([FETCH_BENCHMARK_DETAIL_KEY, id]);- },-- // CREATE - Refresh list after creation+ // CREATE — refresh list after creationcreateBenchmark: async (params) => {set({ isCreatingBenchmark: true }, false, 'createBenchmark/start');try {@@ -236,7 +203,7 @@ export const createBenchmarkSlice: StateCreator<}},- // UPDATE - With optimistic update for detail+ // UPDATE — optimistic update + refreshupdateBenchmark: async (params) => {const { id } = params;@@ -246,14 +213,12 @@ export const createBenchmarkSlice: StateCreator<id,value: params,});-// 2. Set loadingget().internal_updateBenchmarkDetailLoading(id, true);try {// 3. Call serviceawait agentEvalService.updateBenchmark(params);-// 4. Refresh from serverawait get().refreshBenchmarks();await get().refreshBenchmarkDetail(id);@@ -262,50 +227,37 @@ export const createBenchmarkSlice: StateCreator<}},- // DELETE - Refresh list and remove from detail map+ // DELETE — optimistic update + refreshdeleteBenchmark: async (id) => {- // 1. Optimistic update- get().internal_dispatchBenchmarkDetail({- type: 'deleteBenchmarkDetail',- id,- });-- // 2. Set loading+ get().internal_dispatchBenchmarkDetail({ type: 'deleteBenchmarkDetail', id });get().internal_updateBenchmarkDetailLoading(id, true);try {- // 3. Call serviceawait agentEvalService.deleteBenchmark(id);-- // 4. Refresh listawait get().refreshBenchmarks();} finally {get().internal_updateBenchmarkDetailLoading(id, false);}},- // Internal - Dispatch to reducer (for detail map)+ // Internal — dispatch to reducer (for detail map)internal_dispatchBenchmarkDetail: (payload) => {const currentMap = get().benchmarkDetailMap;const nextMap = benchmarkDetailReducer(currentMap, payload);- // No need to update if map is the same+ // Skip set when nothing changed — avoids unnecessary re-rendersif (isEqual(nextMap, currentMap)) return;-set({ benchmarkDetailMap: nextMap }, false, `dispatchBenchmarkDetail/${payload.type}`);},- // Internal - Update loading state for specific detail+ // Internal — update loading state for specific detailinternal_updateBenchmarkDetailLoading: (id, loading) => {set(- (state) => {- if (loading) {- return { loadingBenchmarkDetailIds: [...state.loadingBenchmarkDetailIds, id] };- }- return {- loadingBenchmarkDetailIds: state.loadingBenchmarkDetailIds.filter((i) => i !== id),- };- },+ (state) => ({+ loadingBenchmarkDetailIds: loading+ ? [...state.loadingBenchmarkDetailIds, id]+ : state.loadingBenchmarkDetailIds.filter((i) => i !== id),+ }),false,'updateBenchmarkDetailLoading',);@@ -326,14 +278,10 @@ export const createBenchmarkSlice: StateCreator<## Layer 3: Component Usage-### Data Fetching in Components--**Fetching List Data:**--```typescript-// Component using list data - ✅ CORRECT-import { useEvalStore } from '@/store/eval';+### Fetching List Data+```tsx+// ✅ CORRECTconst BenchmarkList = () => {// 1. Get the hook from storeconst useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);@@ -350,39 +298,35 @@ const BenchmarkList = () => {return (<div><h2>Total: {benchmarks.length}</h2>- {benchmarks.map(b => <BenchmarkCard key={b.id} {...b} />)}+ {benchmarks.map((b) => (+ <BenchmarkCard key={b.id} {...b} />+ ))}</div>);};```-**Fetching Detail Data:**--```typescript-// Component using detail data from map - ✅ CORRECT-import { useEvalStore } from '@/store/eval';-import { useParams } from 'react-router-dom';+### Fetching Detail Data+```tsx+// ✅ CORRECTconst BenchmarkDetail = () => {const { benchmarkId } = useParams<{ benchmarkId: string }>();- // 1. Get the hookconst useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);- // 2. Get detail from map+ // Detail from mapconst benchmark = useEvalStore((s) =>benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,);- // 3. Get loading state+ // Per-item loadingconst isLoading = useEvalStore((s) =>benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,);- // 4. Call the hookuseFetchBenchmarkDetail(benchmarkId);- // 5. Use the dataif (!benchmark) return <Loading />;return (<div>@@ -394,7 +338,7 @@ const BenchmarkDetail = () => {};```-**Using Selectors (Recommended):**+### Using Selectors (Recommended)```typescript// src/store/eval/slices/benchmark/selectors.ts@@ -416,22 +360,20 @@ const BenchmarkDetail = () => {};```-### What NOT to Do+### Anti-pattern-```typescript-// ❌ WRONG - Don't use useEffect for data fetching+```tsx+// ❌ WRONG — Don't use useEffect for data fetchingconst BenchmarkList = () => {const [data, setData] = useState([]);const [loading, setLoading] = useState(false);useEffect(() => {- const fetchData = async () => {- setLoading(true);- const result = await lambdaClient.agentEval.listBenchmarks.query();- setData(result);- setLoading(false);- };- fetchData();+ setLoading(true);+ lambdaClient.agentEval.listBenchmarks+ .query()+ .then(setData)+ .finally(() => setLoading(false));}, []);return <div>...</div>;@@ -440,17 +382,15 @@ const BenchmarkList = () => {### Mutations in Components-```typescript-// Mutations (Create/Update/Delete) with optimistic updates - ✅ CORRECT-import { useEvalStore } from '@/store/eval';-import { benchmarkSelectors } from '@/store/eval/selectors';-+```tsx+// Create — global mutation flag drives form loadingconst CreateBenchmarkModal = () => {const createBenchmark = useEvalStore((s) => s.createBenchmark);+ const isCreating = useEvalStore((s) => s.isCreatingBenchmark);const handleSubmit = async (values) => {try {- // Optimistic update happens inside createBenchmark+ // Optimistic update + refresh happen inside createBenchmarkawait createBenchmark(values);message.success('Created successfully');onClose();@@ -459,14 +399,18 @@ const CreateBenchmarkModal = () => {}};- return <Form onSubmit={handleSubmit}>...</Form>;+ return (+ <Form onSubmit={handleSubmit} loading={isCreating}>+ ...+ </Form>+ );};-// With loading state for specific item+// Update / delete — per-item loading so only the row being mutated spinsconst BenchmarkItem = ({ id }: { id: string }) => {const updateBenchmark = useEvalStore((s) => s.updateBenchmark);const deleteBenchmark = useEvalStore((s) => s.deleteBenchmark);- const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmark(id));+ const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(id));const handleUpdate = async (data) => {await updateBenchmark({ id, ...data });@@ -486,469 +430,49 @@ const BenchmarkItem = ({ id }: { id: string }) => {};```------> **Data Structures:** For detailed comparison of List vs Detail patterns, see the `store-data-structures` skill.+**Why two patterns:** create has no id yet, so a single `isCreatingXxx` flag is enough. Update/delete target a specific row, so global flags would freeze unrelated rows — keep per-item state in `loadingXxxIds`.----## Complete Example: Adding a New Feature--### Scenario: Add "Dataset" data fetching with optimistic updates--#### Step 1: Create Service--```typescript-// src/services/agentEval.ts-class AgentEvalService {- // ... existing methods ...-- // Add new methods- async listDatasets(benchmarkId: string) {- return lambdaClient.agentEval.listDatasets.query({ benchmarkId });- }-- async getDataset(id: string) {- return lambdaClient.agentEval.getDataset.query({ id });- }-- async createDataset(params: CreateDatasetParams) {- return lambdaClient.agentEval.createDataset.mutate(params);- }-}-```--#### Step 2: Create Reducer--```typescript-// src/store/eval/slices/dataset/reducer.ts-import { produce } from 'immer';-import type { Dataset } from '@/types/dataset';--type AddDatasetAction = {- type: 'addDataset';- value: Dataset;-};--type UpdateDatasetAction = {- id: string;- type: 'updateDataset';- value: Partial<Dataset>;-};--type DeleteDatasetAction = {- id: string;- type: 'deleteDataset';-};--export type DatasetDispatch = AddDatasetAction | UpdateDatasetAction | DeleteDatasetAction;--export const datasetReducer = (state: Dataset[] = [], payload: DatasetDispatch): Dataset[] => {- switch (payload.type) {- case 'addDataset': {- return produce(state, (draft) => {- draft.unshift(payload.value);- });- }-- case 'updateDataset': {- return produce(state, (draft) => {- const index = draft.findIndex((item) => item.id === payload.id);- if (index !== -1) {- draft[index] = { ...draft[index], ...payload.value };- }- });- }-- case 'deleteDataset': {- return produce(state, (draft) => {- const index = draft.findIndex((item) => item.id === payload.id);- if (index !== -1) {- draft.splice(index, 1);- }- });- }-- default:- return state;- }-};-```--#### Step 3: Create Store Slice--```typescript-// src/store/eval/slices/dataset/initialState.ts-import type { Dataset } from '@/types/dataset';--export interface DatasetData {- currentPage: number;- hasMore: boolean;- isLoading: boolean;- items: Dataset[];- pageSize: number;- total: number;-}--export interface DatasetSliceState {- // Map keyed by benchmarkId- datasetMap: Record<string, DatasetData>;- // Simple state for single item (read-only, used in modals)- datasetDetail: Dataset | null;- isLoadingDatasetDetail: boolean;- loadingDatasetIds: string[];-}--export const datasetInitialState: DatasetSliceState = {- datasetMap: {},- datasetDetail: null,- isLoadingDatasetDetail: false,- loadingDatasetIds: [],-};-```--```typescript-// src/store/eval/slices/dataset/action.ts-import type { SWRResponse } from 'swr';-import type { StateCreator } from 'zustand/vanilla';-import isEqual from 'fast-deep-equal';--import { mutate, useClientDataSWR } from '@/libs/swr';-import { agentEvalService } from '@/services/agentEval';-import type { EvalStore } from '@/store/eval/store';-import { datasetReducer, type DatasetDispatch } from './reducer';--const FETCH_DATASETS_KEY = 'FETCH_DATASETS';-const FETCH_DATASET_DETAIL_KEY = 'FETCH_DATASET_DETAIL';--export interface DatasetAction {- // SWR Hooks- useFetchDatasets: (benchmarkId?: string) => SWRResponse;- useFetchDatasetDetail: (id?: string) => SWRResponse;-- // Refresh methods- refreshDatasets: (benchmarkId: string) => Promise<void>;- refreshDatasetDetail: (id: string) => Promise<void>;-- // Mutations- createDataset: (params: any) => Promise<any>;- updateDataset: (params: any) => Promise<void>;- deleteDataset: (id: string, benchmarkId: string) => Promise<void>;-- // Internal methods- internal_dispatchDataset: (payload: DatasetDispatch, benchmarkId: string) => void;- internal_updateDatasetLoading: (id: string, loading: boolean) => void;-}--export const createDatasetSlice: StateCreator<- EvalStore,- [['zustand/devtools', never]],- [],- DatasetAction-> = (set, get) => ({- // Fetch list with Map- useFetchDatasets: (benchmarkId) => {- return useClientDataSWR(- benchmarkId ? [FETCH_DATASETS_KEY, benchmarkId] : null,- () => agentEvalService.listDatasets(benchmarkId!),- {- onSuccess: (data: any) => {- set(- {- datasetMap: {- ...get().datasetMap,- [benchmarkId!]: {- currentPage: 1,- hasMore: false,- isLoading: false,- items: data,- pageSize: data.length,- total: data.length,- },- },- },- false,- 'useFetchDatasets/success',- );- },- },- );- },-- // Fetch single item (for modal display)- useFetchDatasetDetail: (id) => {- return useClientDataSWR(- id ? [FETCH_DATASET_DETAIL_KEY, id] : null,- () => agentEvalService.getDataset(id!),- {- onSuccess: (data: any) => {- set(- { datasetDetail: data, isLoadingDatasetDetail: false },- false,- 'useFetchDatasetDetail/success',- );- },- },- );- },-- refreshDatasets: async (benchmarkId) => {- await mutate([FETCH_DATASETS_KEY, benchmarkId]);- },-- refreshDatasetDetail: async (id) => {- await mutate([FETCH_DATASET_DETAIL_KEY, id]);- },-- // CREATE with optimistic update- createDataset: async (params) => {- const tmpId = Date.now().toString();- const { benchmarkId } = params;-- get().internal_dispatchDataset(- {- type: 'addDataset',- value: { ...params, id: tmpId, createdAt: Date.now() } as any,- },- benchmarkId,- );-- get().internal_updateDatasetLoading(tmpId, true);-- try {- const result = await agentEvalService.createDataset(params);- await get().refreshDatasets(benchmarkId);- return result;- } finally {- get().internal_updateDatasetLoading(tmpId, false);- }- },-- // UPDATE with optimistic update- updateDataset: async (params) => {- const { id, benchmarkId } = params;-- get().internal_dispatchDataset(- {- type: 'updateDataset',- id,- value: params,- },- benchmarkId,- );-- get().internal_updateDatasetLoading(id, true);-- try {- await agentEvalService.updateDataset(params);- await get().refreshDatasets(benchmarkId);- } finally {- get().internal_updateDatasetLoading(id, false);- }- },-- // DELETE with optimistic update- deleteDataset: async (id, benchmarkId) => {- get().internal_dispatchDataset(- {- type: 'deleteDataset',- id,- },- benchmarkId,- );-- get().internal_updateDatasetLoading(id, true);-- try {- await agentEvalService.deleteDataset(id);- await get().refreshDatasets(benchmarkId);- } finally {- get().internal_updateDatasetLoading(id, false);- }- },+## Need a fuller worked example?- // Internal - Dispatch to reducer- internal_dispatchDataset: (payload, benchmarkId) => {- const currentData = get().datasetMap[benchmarkId];- const nextItems = datasetReducer(currentData?.items, payload);-- if (isEqual(nextItems, currentData?.items)) return;-- set(- {- datasetMap: {- ...get().datasetMap,- [benchmarkId]: {- ...currentData,- currentPage: currentData?.currentPage ?? 1,- hasMore: currentData?.hasMore ?? false,- isLoading: false,- items: nextItems,- pageSize: currentData?.pageSize ?? nextItems.length,- total: currentData?.total ?? nextItems.length,- },- },- },- false,- `dispatchDataset/${payload.type}`,- );- },-- // Internal - Update loading state- internal_updateDatasetLoading: (id, loading) => {- set(- (state) => {- if (loading) {- return { loadingDatasetIds: [...state.loadingDatasetIds, id] };- }- return {- loadingDatasetIds: state.loadingDatasetIds.filter((i) => i !== id),- };- },- false,- 'updateDatasetLoading',- );- },-});-```--#### Step 3: Integrate into Store--```typescript-// src/store/eval/store.ts-import { createDatasetSlice, type DatasetAction } from './slices/dataset/action';--export type EvalStore = EvalStoreState &- BenchmarkAction &- DatasetAction & // Add here- RunAction;--const createStore: StateCreator<EvalStore, [['zustand/devtools', never]]> = (set, get, store) => ({- ...initialState,- ...createBenchmarkSlice(set, get, store),- ...createDatasetSlice(set, get, store), // Add here- ...createRunSlice(set, get, store),-});-```--```typescript-// src/store/eval/initialState.ts-import { datasetInitialState, type DatasetSliceState } from './slices/dataset/initialState';--export interface EvalStoreState extends BenchmarkSliceState, DatasetSliceState {- // ...-}--export const initialState: EvalStoreState = {- ...benchmarkInitialState,- ...datasetInitialState, // Add here- ...runInitialState,-};-```--#### Step 4: Create Selectors (Optional but Recommended)--```typescript-// src/store/eval/slices/dataset/selectors.ts-import type { EvalStore } from '@/store/eval/store';--export const datasetSelectors = {- getDatasetData: (benchmarkId: string) => (s: EvalStore) => s.datasetMap[benchmarkId],-- getDatasets: (benchmarkId: string) => (s: EvalStore) => s.datasetMap[benchmarkId]?.items ?? [],-- isLoadingDataset: (id: string) => (s: EvalStore) => s.loadingDatasetIds.includes(id),-};-```--#### Step 5: Use in Component--```typescript-// Component - List with Map-import { useEvalStore } from '@/store/eval';-import { datasetSelectors } from '@/store/eval/selectors';--const DatasetList = ({ benchmarkId }: { benchmarkId: string }) => {- const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);- const datasets = useEvalStore(datasetSelectors.getDatasets(benchmarkId));- const datasetData = useEvalStore(datasetSelectors.getDatasetData(benchmarkId));-- useFetchDatasets(benchmarkId);-- if (datasetData?.isLoading) return <Loading />;-- return (- <div>- <h2>Total: {datasetData?.total ?? 0}</h2>- <List data={datasets} />- </div>- );-};--// Component - Single item (for modal)-const DatasetImportModal = ({ open, datasetId }: Props) => {- const useFetchDatasetDetail = useEvalStore((s) => s.useFetchDatasetDetail);- const dataset = useEvalStore((s) => s.datasetDetail);- const isLoading = useEvalStore((s) => s.isLoadingDatasetDetail);-- // Only fetch when modal is open- useFetchDatasetDetail(open && datasetId ? datasetId : undefined);-- return (- <Modal open={open}>- {isLoading ? <Loading /> : <div>{dataset?.name}</div>}- </Modal>- );-};-```+The canonical `Benchmark` example above is the one to copy for a flat list + detail map. If you need to maintain a list **keyed by a parent id** (e.g. `datasetMap[benchmarkId]` because the same shape appears under multiple parents), read [`references/walkthrough.md`](./references/walkthrough.md) — it walks through the full 6 steps (service → reducer → slice → store wiring → selectors → component) for that variant.---## Common Patterns-### Pattern 1: List + Detail+### Pattern 1: Pagination++Cache key array must include every parameter that should trigger a refetch.```typescript-// List with pagination-useFetchTestCases: (params) => {- const { datasetId, limit, offset } = params;- return useClientDataSWR(- datasetId ? [FETCH_TEST_CASES_KEY, datasetId, limit, offset] : null,- () => agentEvalService.listTestCases({ datasetId, limit, offset }),+useFetchTestCases: (params: { datasetId: string; limit: number; offset: number }) =>+ useClientDataSWR(+ params.datasetId ? [FETCH_TEST_CASES_KEY, params.datasetId, params.limit, params.offset] : null,+ () => agentEvalService.listTestCases(params),{- onSuccess: (data: any) => {- set(- {- testCaseList: data.data,- testCaseTotal: data.total,- isLoadingTestCases: false,- },- false,- 'useFetchTestCases/success',- );- },+ onSuccess: (data) =>+ set({+ testCaseList: data.data,+ testCaseTotal: data.total,+ isLoadingTestCases: false,+ }),},);-};```### Pattern 2: Dependent Fetching-```typescript-// Component+Both hooks run in parallel — SWR dedupes, no manual sequencing needed.++```tsxconst BenchmarkDetail = () => {const { benchmarkId } = useParams();-const useFetchBenchmarkDetail = useEvalStore((s) => s.useFetchBenchmarkDetail);- const benchmark = useEvalStore((s) => s.benchmarkDetail);-const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);- const datasets = useEvalStore((s) => s.datasetList);- // Fetch benchmark firstuseFetchBenchmarkDetail(benchmarkId);-- // Then fetch datasets for this benchmarkuseFetchDatasets(benchmarkId);return <div>...</div>;@@ -957,34 +481,20 @@ const BenchmarkDetail = () => {### Pattern 3: Conditional Fetching-```typescript-// Only fetch when modal is open-const DatasetImportModal = ({ open, datasetId }: Props) => {- const useFetchDatasetDetail = useEvalStore((s) => s.useFetchDatasetDetail);- const dataset = useEvalStore((s) => s.datasetDetail);-- // Only fetch when open AND datasetId exists- useFetchDatasetDetail(open && datasetId ? datasetId : undefined);+Pass `undefined` to disable the hook entirely.- return <Modal open={open}>...</Modal>;-};+```tsx+// only fetch when modal is open AND id present+useFetchDatasetDetail(open && datasetId ? datasetId : undefined);```-### Pattern 4: Refresh After Mutation+### Pattern 4: Cross-domain Refresh```typescript-// Store action-createDataset: async (params) => {- const result = await agentEvalService.createDataset(params);- // Refresh the list after creation- await get().refreshDatasets(params.benchmarkId);- return result;-};--deleteDataset: async (id, benchmarkId) => {- await agentEvalService.deleteDataset(id);- // Refresh the list after deletion- await get().refreshDatasets(benchmarkId);+deleteBenchmark: async (id) => {+ await agentEvalService.deleteBenchmark(id);+ await get().refreshBenchmarks();+ await get().refreshDatasets(id); // related cache invalidated too};```@@ -994,24 +504,17 @@ deleteDataset: async (id, benchmarkId) => {### Before (❌ Wrong)-```typescript+```tsxconst TestCaseList = ({ datasetId }: Props) => {const [data, setData] = useState<any[]>([]);const [loading, setLoading] = useState(false);useEffect(() => {- const fetchData = async () => {- setLoading(true);- try {- const result = await lambdaClient.agentEval.listTestCases.query({- datasetId,- });- setData(result.data);- } finally {- setLoading(false);- }- };- fetchData();+ setLoading(true);+ lambdaClient.agentEval.listTestCases+ .query({ datasetId })+ .then((r) => setData(r.data))+ .finally(() => setLoading(false));}, [datasetId]);return <Table data={data} loading={loading} />;@@ -1021,33 +524,27 @@ const TestCaseList = ({ datasetId }: Props) => {### After (✅ Correct)```typescript-// 1. Create service method+// 1. Add service methodclass AgentEvalService {async listTestCases(params: { datasetId: string }) {return lambdaClient.agentEval.listTestCases.query(params);}}-// 2. Create store slice+// 2. Add store slice hookexport const createTestCaseSlice: StateCreator<...> = (set) => ({- useFetchTestCases: (params) => {- return useClientDataSWR(+ useFetchTestCases: (params) =>+ useClientDataSWR(params.datasetId ? [FETCH_TEST_CASES_KEY, params.datasetId] : null,() => agentEvalService.listTestCases(params),{- onSuccess: (data: any) => {- set(- { testCaseList: data.data, isLoadingTestCases: false },- false,- 'useFetchTestCases/success',- );- },+ onSuccess: (data) =>+ set({ testCaseList: data.data, isLoadingTestCases: false }),},- );- },+ ),});-// 3. Use in component+// 3. Component reads from storeconst TestCaseList = ({ datasetId }: Props) => {const useFetchTestCases = useEvalStore((s) => s.useFetchTestCases);const data = useEvalStore((s) => s.testCaseList);@@ -1061,93 +558,44 @@ const TestCaseList = ({ datasetId }: Props) => {----## Best Practices--### ✅ DO--1. **Always use service layer** - Never call lambdaClient directly in stores/components-2. **Use SWR hooks in stores** - Not useEffect in components-3. **Clear naming** - `useFetchXxx` for hooks, `refreshXxx` for cache invalidation-4. **Proper cache keys** - Use constants, include parameters in array form-5. **Update state in onSuccess** - Set loading states and data-6. **Refresh after mutations** - Call refresh methods after create/update/delete-7. **Handle loading states** - Provide loading indicators to users--### ❌ DON'T--1. **Don't use useEffect** for data fetching-2. **Don't use useState** for server data-3. **Don't call lambdaClient** directly in components or stores-4. **Don't forget to refresh** cache after mutations-5. **Don't duplicate state** - Use store as single source of truth------## Troubleshooting-### Problem: Data not loading--**Check:**--1. Is the hook being called? `useFetchXxx()`-2. Is the key valid? (not null/undefined)-3. Is the service method correct?-4. Check browser network tab for API calls--### Problem: Data not refreshing after mutation--**Check:**--1. Did you call `refreshXxx()` after mutation?-2. Is the cache key the same in both hook and refresh?-3. Check devtools for state updates--### Problem: Loading state stuck--**Check:**--1. Is `onSuccess` updating `isLoadingXxx: false`?-2. Is there an error in the API call?-3. Check error boundary or console+| Symptom | Check |+| --------------------------- | ------------------------------------------------------------------- |+| Data never loads | Hook called? Key not `null`/`undefined`? Network tab shows request? |+| Stale data after mutation | Did `refreshXxx` run? Cache key matches what the hook uses? |+| Loading state stuck `true` | `onSuccess` writes loading=false? Promise rejected silently? |+| Detail map missing an entry | Reducer dispatch ran? `isEqual` short-circuited on stale data? |---## Summary Checklist-When implementing new data fetching:+When adding new data fetching:-### Step 1: Data Structures+### Step 1: Types & State-> See `store-data-structures` skill for detailed patterns+See `store-data-structures` for details.-- [ ] **Define types** in `@lobechat/types`:- - [ ] Detail type (e.g., `AgentEvalBenchmark`)- - [ ] List item type (e.g., `AgentEvalBenchmarkListItem`)-- [ ] **Design state structure**:- - [ ] List: `xxxList: XxxListItem[]`- - [ ] Detail: `xxxDetailMap: Record<string, Xxx>`- - [ ] Loading: `loadingXxxDetailIds: string[]`-- [ ] **Create reducer** if optimistic updates needed+- [ ] Define types in `@lobechat/types`: Detail type + List item type+- [ ] State structure: `xxxList: XxxListItem[]`, `xxxDetailMap: Record<string, Xxx>`, `loadingXxxDetailIds: string[]`+- [ ] Reducer if optimistic updates are needed### Step 2: Service Layer- [ ] Create service in `src/services/xxxService.ts`-- [ ] Add methods:- - [ ] `listXxx()` - fetch list- - [ ] `getXxx(id)` - fetch detail- - [ ] `createXxx()`, `updateXxx()`, `deleteXxx()` - mutations+- [ ] Methods: `listXxx()`, `getXxx(id)`, `createXxx()`, `updateXxx()`, `deleteXxx()`### Step 3: Store Actions-- [ ] Create `initialState.ts` with state structure-- [ ] Create `action.ts` with:- - [ ] `useFetchXxxList()` - list SWR hook- - [ ] `useFetchXxxDetail(id)` - detail SWR hook- - [ ] `refreshXxxList()`, `refreshXxxDetail(id)` - cache invalidation+- [ ] `initialState.ts` with state structure+- [ ] `action.ts` with:+ - [ ] `useFetchXxxList()`, `useFetchXxxDetail(id)` — SWR hooks+ - [ ] `refreshXxxList()`, `refreshXxxDetail(id)` — cache invalidation- [ ] CRUD methods calling service- - [ ] `internal_dispatch` and `internal_updateLoading` if using reducer-- [ ] Create `selectors.ts` (optional but recommended)-- [ ] Integrate slice into main store+ - [ ] `internal_dispatch`, `internal_updateLoading` if using reducer+- [ ] `selectors.ts` (optional but recommended)+- [ ] Integrate slice into main store + initialState### Step 4: Component Usage@@ -1156,20 +604,11 @@ When implementing new data fetching:- [ ] Detail pages: access `xxxDetailMap[id]`- [ ] Use loading states for UI feedback-Remember: **Types → Service → Store (SWR + Reducer) → Component** 🎯--## Key Architecture Patterns--1. **Service Layer**: Clean API abstraction (`xxxService`)-2. **Data Structures**: List arrays + Detail maps (see `store-data-structures` skill)-3. **SWR Hooks**: Automatic caching and revalidation (`useFetchXxx`)-4. **Cache Invalidation**: Manual refresh methods (`refreshXxx`)-5. **Optimistic Updates**: Update UI immediately, then sync with server-6. **Loading States**: Per-item loading for better UX+**Mental model:** Types → Service → Reducer → Slice → Component 🎯---## Related Skills-- **`store-data-structures`** - How to structure List and Detail data in stores-- **`zustand`** - General Zustand patterns and best practices+- **`store-data-structures`** — How to structure List and Detail data in stores+- **`zustand`** — General Zustand patterns and best practicesdiff --git a/.agents/skills/data-fetching/references/walkthrough.md b/.agents/skills/data-fetching/references/walkthrough.mdnew file mode 100644index 00000000000..893e9ed69e4--- /dev/null+++ b/.agents/skills/data-fetching/references/walkthrough.md@@ -0,0 +1,244 @@+# Walkthrough: Adding a New Feature End-to-End++This is a worked example of the canonical 6-step recipe applied to a new entity (`Dataset`), showing a variant of the main skill's pattern: **a list keyed by a parent id** (`datasetMap[benchmarkId]`), useful when the same shape appears under different parents.++If you only need the canonical (single-array) pattern, the main `SKILL.md` already shows it for `Benchmark`. Read this file when you need the parent-keyed Map variant, or when you want a checklist-style walkthrough.++## Step 1: Add Service methods++```typescript+class AgentEvalService {+ async listDatasets(benchmarkId: string) {+ return lambdaClient.agentEval.listDatasets.query({ benchmarkId });+ }+ async getDataset(id: string) {+ return lambdaClient.agentEval.getDataset.query({ id });+ }+ async createDataset(params: CreateDatasetParams) {+ return lambdaClient.agentEval.createDataset.mutate(params);+ }+ // updateDataset / deleteDataset follow the same shape+}+```++## Step 2: Reducer (optimistic updates)++```typescript+// src/store/eval/slices/dataset/reducer.ts+export type DatasetDispatch =+ | { type: 'addDataset'; value: Dataset }+ | { type: 'updateDataset'; id: string; value: Partial<Dataset> }+ | { type: 'deleteDataset'; id: string };++export const datasetReducer = (state: Dataset[] = [], payload: DatasetDispatch): Dataset[] =>+ produce(state, (draft) => {+ switch (payload.type) {+ case 'addDataset':+ draft.unshift(payload.value);+ break;+ case 'updateDataset': {+ const i = draft.findIndex((item) => item.id === payload.id);+ if (i !== -1) draft[i] = { ...draft[i], ...payload.value };+ break;+ }+ case 'deleteDataset': {+ const i = draft.findIndex((item) => item.id === payload.id);+ if (i !== -1) draft.splice(i, 1);+ break;+ }+ }+ });+```++## Step 3: Store slice++```typescript+// src/store/eval/slices/dataset/initialState.ts+export interface DatasetData {+ currentPage: number;+ hasMore: boolean;+ isLoading: boolean;+ items: Dataset[];+ pageSize: number;+ total: number;+}++export interface DatasetSliceState {+ // Map keyed by benchmarkId — multiple parent contexts share the slice+ datasetMap: Record<string, DatasetData>;+ // Single item for modal display+ datasetDetail: Dataset | null;+ isLoadingDatasetDetail: boolean;+ loadingDatasetIds: string[];+}++export const datasetInitialState: DatasetSliceState = {+ datasetMap: {},+ datasetDetail: null,+ isLoadingDatasetDetail: false,+ loadingDatasetIds: [],+};+```++```typescript+// src/store/eval/slices/dataset/action.ts+const FETCH_DATASETS_KEY = 'FETCH_DATASETS';+const FETCH_DATASET_DETAIL_KEY = 'FETCH_DATASET_DETAIL';++export const createDatasetSlice: StateCreator<EvalStore, any, [], DatasetAction> = (set, get) => ({+ // Cache key includes benchmarkId so each parent has its own SWR entry+ useFetchDatasets: (benchmarkId) =>+ useClientDataSWR(+ benchmarkId ? [FETCH_DATASETS_KEY, benchmarkId] : null,+ () => agentEvalService.listDatasets(benchmarkId!),+ {+ onSuccess: (data) => {+ set({+ datasetMap: {+ ...get().datasetMap,+ [benchmarkId!]: {+ currentPage: 1,+ hasMore: false,+ isLoading: false,+ items: data,+ pageSize: data.length,+ total: data.length,+ },+ },+ });+ },+ },+ ),++ useFetchDatasetDetail: (id) =>+ useClientDataSWR(+ id ? [FETCH_DATASET_DETAIL_KEY, id] : null,+ () => agentEvalService.getDataset(id!),+ {+ onSuccess: (data) => set({ datasetDetail: data, isLoadingDatasetDetail: false }),+ },+ ),++ refreshDatasets: (benchmarkId) => mutate([FETCH_DATASETS_KEY, benchmarkId]),+ refreshDatasetDetail: (id) => mutate([FETCH_DATASET_DETAIL_KEY, id]),++ // CREATE with optimistic update — note the temp id pattern+ createDataset: async (params) => {+ const tmpId = Date.now().toString();+ const { benchmarkId } = params;++ get().internal_dispatchDataset(+ { type: 'addDataset', value: { ...params, id: tmpId, createdAt: Date.now() } as any },+ benchmarkId,+ );+ get().internal_updateDatasetLoading(tmpId, true);++ try {+ const result = await agentEvalService.createDataset(params);+ await get().refreshDatasets(benchmarkId);+ return result;+ } finally {+ get().internal_updateDatasetLoading(tmpId, false);+ }+ },++ // UPDATE / DELETE follow the same optimistic + refresh pattern as BenchmarkSlice+ // (see the main SKILL.md)++ // Internal — dispatch reducer scoped to a parent+ internal_dispatchDataset: (payload, benchmarkId) => {+ const currentData = get().datasetMap[benchmarkId];+ const nextItems = datasetReducer(currentData?.items, payload);++ // Skip set when nothing changed — avoids unnecessary re-renders+ if (isEqual(nextItems, currentData?.items)) return;++ set({+ datasetMap: {+ ...get().datasetMap,+ [benchmarkId]: {+ ...currentData,+ currentPage: currentData?.currentPage ?? 1,+ hasMore: currentData?.hasMore ?? false,+ isLoading: false,+ items: nextItems,+ pageSize: currentData?.pageSize ?? nextItems.length,+ total: currentData?.total ?? nextItems.length,+ },+ },+ });+ },++ internal_updateDatasetLoading: (id, loading) => {+ set((state) => ({+ loadingDatasetIds: loading+ ? [...state.loadingDatasetIds, id]+ : state.loadingDatasetIds.filter((i) => i !== id),+ }));+ },+});+```++## Step 4: Wire into the store++```typescript+// src/store/eval/store.ts+export type EvalStore = EvalStoreState & BenchmarkAction & DatasetAction & RunAction;++const createStore: StateCreator<EvalStore, [['zustand/devtools', never]]> = (set, get, store) => ({+ ...initialState,+ ...createBenchmarkSlice(set, get, store),+ ...createDatasetSlice(set, get, store),+ ...createRunSlice(set, get, store),+});++// src/store/eval/initialState.ts+export const initialState: EvalStoreState = {+ ...benchmarkInitialState,+ ...datasetInitialState,+ ...runInitialState,+};+```++## Step 5: Selectors (optional but recommended)++```typescript+export const datasetSelectors = {+ getDatasetData: (benchmarkId: string) => (s: EvalStore) => s.datasetMap[benchmarkId],+ getDatasets: (benchmarkId: string) => (s: EvalStore) => s.datasetMap[benchmarkId]?.items ?? [],+ isLoadingDataset: (id: string) => (s: EvalStore) => s.loadingDatasetIds.includes(id),+};+```++## Step 6: Use in component++```tsx+// List scoped to a parent+const DatasetList = ({ benchmarkId }: { benchmarkId: string }) => {+ const useFetchDatasets = useEvalStore((s) => s.useFetchDatasets);+ const datasets = useEvalStore(datasetSelectors.getDatasets(benchmarkId));+ const datasetData = useEvalStore(datasetSelectors.getDatasetData(benchmarkId));++ useFetchDatasets(benchmarkId);++ if (datasetData?.isLoading) return <Loading />;+ return (+ <div>+ <h2>Total: {datasetData?.total ?? 0}</h2>+ <List data={datasets} />+ </div>+ );+};++// Single item for modal — conditional fetching pattern+const DatasetImportModal = ({ open, datasetId }: Props) => {+ const useFetchDatasetDetail = useEvalStore((s) => s.useFetchDatasetDetail);+ const dataset = useEvalStore((s) => s.datasetDetail);+ const isLoading = useEvalStore((s) => s.isLoadingDatasetDetail);++ // Only fetch when modal is open AND id present+ useFetchDatasetDetail(open && datasetId ? datasetId : undefined);++ return <Modal open={open}>{isLoading ? <Loading /> : <div>{dataset?.name}</div>}</Modal>;+};+```diff --git a/.agents/skills/db-migrations/SKILL.md b/.agents/skills/db-migrations/SKILL.mdindex 3adcfd2f581..33ce3673c46 100644--- a/.agents/skills/db-migrations/SKILL.md+++ b/.agents/skills/db-migrations/SKILL.md@@ -1,6 +1,7 @@---name: db-migrationsdescription: 'Use when generating or regenerating Drizzle migration files, changing database schema tables or columns, resolving migration sequence conflicts after rebase, reviewing migration SQL for idempotent patterns, or renaming migration files.'+user-invocable: false---# Database Migrations Guidediff --git a/.agents/skills/debug/SKILL.md b/.agents/skills/debug-package/SKILL.mdsimilarity index 63%rename from .agents/skills/debug/SKILL.mdrename to .agents/skills/debug-package/SKILL.mdindex ed28ae77f8a..53443c86b00 100644--- a/.agents/skills/debug/SKILL.md+++ b/.agents/skills/debug-package/SKILL.md@@ -1,6 +1,6 @@----name: debug-description: Debug package usage guide. Use when adding debug logging, understanding log namespaces, or implementing debugging features. Triggers on debug logging requests or logging implementation.+name: debug-package+description: "Guide for the `debug` npm package and LobeHub log namespaces (lobe-server:*, lobe-desktop:*, lobe-client:*, lobe-*-router:*). Use whenever adding a `debug(...)` logger, picking a namespace for new server/desktop/client/router code, troubleshooting why DEBUG=lobe-* logs don't show up, or when the user asks to 'add logging', 'add a logger', 'instrument this', 'trace this call', 'why isn't my log printing', or mentions `debug(`, `DEBUG=`, `localStorage.debug`, or log format specifiers like %O / %o / %s / %d in a LobeHub codebase."user-invocable: false---diff --git a/.agents/skills/drizzle/SKILL.md b/.agents/skills/drizzle/SKILL.mdindex 2eaa8eb69e5..af20373e389 100644--- a/.agents/skills/drizzle/SKILL.md+++ b/.agents/skills/drizzle/SKILL.md@@ -1,6 +1,7 @@---name: drizzle-description: Drizzle ORM schema and database guide. Use when working with database schemas (src/database/schemas/*), defining tables, creating migrations, or database model code. Triggers on Drizzle schema definition, database migrations, or ORM usage questions.+description: "Drizzle ORM schema authoring and query style for LobeHub (postgres, strict mode). Use when editing anything under `src/database/schemas/`, defining `pgTable` columns/indexes/junction tables, spreading `...timestamps`, generating `createInsertSchema`/`$inferSelect`/`$inferInsert` types, writing `db.select().from(...).leftJoin(...)` queries, or deciding when to split a relational `with:` into two queries. Triggers on `pgTable`, `db.select`, `db.query`, `eq()`/`and()`/`inArray()`, `uniqueIndex`, `primaryKey`, `references({ onDelete })`, 'add a column', 'new table', 'foreign key', 'junction table', 'schema field'. For migration files specifically, see the `db-migrations` skill."+user-invocable: false---# Drizzle ORM Schema Style Guide@@ -125,11 +126,7 @@ The relational API generates complex lateral joins with `json_build_array` that```typescript// ✅ Good-const [result] = await this.db- .select()- .from(agents)- .where(eq(agents.id, id))- .limit(1);+const [result] = await this.db.select().from(agents).where(eq(agents.id, id)).limit(1);return result;// ❌ Bad: relational APIdiff --git a/.agents/skills/hotkey/SKILL.md b/.agents/skills/hotkey/SKILL.mdindex 0517c2e9aa3..9ca441f7c2d 100644--- a/.agents/skills/hotkey/SKILL.md+++ b/.agents/skills/hotkey/SKILL.md@@ -1,6 +1,7 @@---name: hotkey-description: Guide for adding keyboard shortcuts. Use when implementing new hotkeys, registering shortcuts, or working with keyboard interactions. Triggers on hotkey implementation or keyboard shortcut tasks.+description: "Adding or editing keyboard shortcuts in LobeHub. Use when registering a new hotkey, changing a key combo, scoping a shortcut to chat vs global, or wiring a hotkey hook + tooltip. Covers the 5-step flow: add to `HotkeyEnum` in `src/types/hotkey.ts`, register in `HOTKEYS_REGISTRATION` (`src/const/hotkeys.ts`) with `combineKeys([Key.Mod, …])`, add i18n in `src/locales/default/hotkey.ts`, expose via `useHotkeyById` in `src/hooks/useHotkeys/`, and render `<Tooltip hotkey={…}>`. Triggers on `HotkeyEnum`, `HOTKEYS_REGISTRATION`, `useHotkeyById`, `combineKeys`, `Key.Mod`/`Key.Shift`, 'add a hotkey', 'add a shortcut', '加快捷键', '快捷键', 'Cmd+K', 'keyboard shortcut', 'hotkey scope', 'hotkey conflict'."+user-invocable: false---# Adding Keyboard Shortcuts Guidediff --git a/.agents/skills/i18n/SKILL.md b/.agents/skills/i18n/SKILL.mdindex 5009f90fd6d..9c89e691449 100644--- a/.agents/skills/i18n/SKILL.md+++ b/.agents/skills/i18n/SKILL.md@@ -1,6 +1,7 @@---name: i18n-description: Internationalization guide using react-i18next. Use when adding translations, creating i18n keys, or working with localized text in React components (.tsx files). Triggers on translation tasks, locale management, or i18n implementation.+description: "LobeHub internationalization with react-i18next. Use when adding any user-facing string in `.tsx`/`.ts` files, creating or renaming a key under `src/locales/default/{namespace}.ts`, deciding the `{feature}.{context}.{action}` flat-key pattern, wiring a new namespace into `src/locales/default/index.ts`, or translating zh-CN/en-US JSON for dev preview. Triggers on `useTranslation`, `t('foo.bar')`, `i18next.t`, `{{variable}}` interpolation, hardcoded UI strings (zh or en) that should be extracted, 'add i18n', '加 i18n key', '翻译', 'locale key', 'namespace', 'pnpm i18n'."+user-invocable: false---# LobeHub Internationalization Guidediff --git a/.agents/skills/linear/SKILL.md b/.agents/skills/linear/SKILL.mdindex 9566f6a108d..e18bf95b0ec 100644--- a/.agents/skills/linear/SKILL.md+++ b/.agents/skills/linear/SKILL.md@@ -1,55 +1,55 @@---name: linear-description: "Linear issue management. MUST USE when: (1) user mentions LOBE-xxx issue IDs (e.g. LOBE-4540), (2) user says 'linear', 'linear issue', 'link linear', (3) creating PRs that reference Linear issues. Provides workflows for retrieving issues, updating status, and adding comments."+description: "Linear issue management. Use when the user mentions LOBE-xxx issue IDs (e.g. LOBE-4540), says 'linear' / 'linear issue' / 'link linear', or when creating PRs that reference Linear issues. Covers retrieving issues, updating status, adding completion comments, and creating sub-issue trees."+user-invocable: false---# Linear Issue ManagementBefore using Linear workflows, search for `linear` MCP tools. If not found, treat as not installed.-## ⚠️ CRITICAL: PR Creation with Linear Issues+## PR Creation with Linear Issues-**When creating a PR that references Linear issues (LOBE-xxx), you MUST:**+A PR that fixes a Linear issue has **two separate jobs to do**, and both matter:-1. Create the PR with magic keywords (`Fixes LOBE-xxx`)-2. **IMMEDIATELY after PR creation**, add completion comments to ALL referenced Linear issues-3. Do NOT consider the task complete until Linear comments are added+1. **`Fixes LOBE-xxx` in the PR body** — Linear watches GitHub for these magic keywords and auto-links the PR and auto-closes the issue on merge. This is the machine-readable side.+2. **A completion comment on the Linear issue** — gives the reviewer/PM/teammate landing in Linear a human-readable summary of what changed and why, without forcing them to click through to GitHub and read a diff.-This is NON-NEGOTIABLE. Skipping Linear comments is a workflow violation.+If you only do step 1, Linear watchers (often non-engineers) hit the issue and see no context. So pair PR creation with the Linear comment as part of the same task — finish both before considering the work done.## Workflow1. **Retrieve issue details** before starting: `mcp__linear-server__get_issue`-2. **Read images**: If the issue description contains images, MUST use `mcp__linear-server__extract_images` to read image content for full context-3. **Check for sub-issues**: Use `mcp__linear-server__list_issues` with `parentId` filter-4. **Mark as In Progress**: When starting to plan or implement an issue, immediately update status to **"In Progress"** via `mcp__linear-server__update_issue`+2. **Read images** — issue descriptions often contain screenshots with critical context (mockups, error states, before/after). Use `mcp__linear-server__extract_images` so you actually see them; reading raw markdown alone misses what the reporter was looking at.+3. **Check for sub-issues**: `mcp__linear-server__list_issues` with `parentId` filter+4. **Mark as In Progress** at the moment you start planning or implementing — this signals to teammates the issue is owned, so they don't double-pick it up.5. **Update issue status** when completing: `mcp__linear-server__update_issue`-6. **Add completion comment** (REQUIRED): `mcp__linear-server__create_comment`+6. **Add completion comment** (see [format below](#completion-comment-format))## Creating Issues-When creating issues with `mcp__linear-server__create_issue`, **MUST add the `claude code` label**.+When creating issues with `mcp__linear-server__create_issue`, add the `claude code` label. Reason: the label is how the team filters/audits AI-generated issues; without it those issues vanish into the general backlog and the team loses visibility into AI contribution patterns.## Language-Issue titles, descriptions, and comments **MUST follow the language of the current conversation**, not default to English.+Match the issue language to the conversation that produced it — if you're discussing in 中文,write the issue in 中文;if discussing in English, write it in English. Reason: the issue is a continuation of the conversation, and forcing a language switch creates translation friction for the collaborator who started the thread.-- Conversation in 中文 → issue body in 中文;technical terms (file paths, identifiers, library names, commands, error messages) stay in English.-- Conversation in English → issue body in English.-- Code blocks, file paths, and quoted strings always stay in their original form regardless of surrounding language.-- This applies equally to **updates** — when editing an existing issue (description **and titles**), preserve the language of the conversation that triggered the edit; do not switch the issue language during a refactor (Chinese → English or vice versa).+Specifics:-Rationale: the issue is a continuation of the conversation. Forcing English when the discussion is in Chinese creates translation friction for the collaborator who came from that thread.+- 中文 conversation → 中文 body; technical terms (file paths, identifiers, library names, commands, error messages) stay in English.+- English conversation → English body.+- Code blocks, file paths, and quoted strings always stay in their original form regardless of surrounding language.+- This applies equally to **updates** — when editing an existing issue (description **and titles**), preserve the language of the conversation that triggered the edit; don't switch the issue language mid-refactor.## Creating Sub-issue TreesWhen breaking a parent issue into a tree of sub-issues (e.g., task decomposition for LOBE-xxx), follow these rules — they work around real limitations of the Linear MCP tools.-### 1. ALWAYS prefix titles with an ordering index+### 1. Prefix titles with an ordering index-The Linear Sub-issues panel displays children by `sortOrder`, which **defaults to newest-first** (most recently created appears on top). Neither parallel nor serial creation will produce the intended top-to-bottom reading order, and the MCP `save_issue` tool does **not expose a `sortOrder` parameter** — you cannot set order at create time.+The Linear Sub-issues panel orders children by `sortOrder`, which **defaults to newest-first** (most recently created appears on top). Neither parallel nor serial creation produces the intended top-to-bottom reading order, and the MCP `save_issue` tool does **not expose a `sortOrder` parameter** — you can't set order at create time.-**Workaround**: encode execution order in the title itself:+Workaround: encode execution order in the title itself:```plaintext[1] [db] add schema fields@@ -100,7 +100,7 @@ The implementer may open only the sub-issue, not the parent — don't rely on co## Completion Comment Format-Every completed issue MUST have a comment summarizing work done:+Each completed issue gets a comment summarizing the work, so reviewers and future readers don't have to reconstruct it from the PR diff:```markdown## Changes Summary@@ -116,34 +116,28 @@ Every completed issue MUST have a comment summarizing work done:- ...```-This is critical for:+This gives team visibility, code-review context, and a paper trail for future reference.-- Team visibility-- Code review context-- Future reference+## PR Association-## PR Association (REQUIRED)--When creating PRs for Linear issues, include magic keywords in PR body:+When creating PRs for Linear issues, include magic keywords in the PR body:- `Fixes LOBE-123`- `Closes LOBE-123`- `Resolves LOBE-123`+These trigger Linear's auto-link + auto-close on merge.+## Per-Issue Completion Rule-When working on multiple issues, update EACH issue IMMEDIATELY after completing it:+When working on multiple issues, close out **each one before starting the next** — don't batch all the Linear updates to the end. Batching is where comments get forgotten and issues stay stuck in "In Progress" days after the PR shipped.++For each issue:1. Complete implementation2. Run `bun run type-check`3. Run related tests4. Create PR if needed-5. Update status to **"In Review"** (NOT "Done")-6. **Add completion comment immediately**-7. Move to next issue--**Note:** Status → "In Review" when PR created. "Done" only after PR merged.--**❌ Wrong:** Complete all → Create PR → Forget Linear comments--**✅ Correct:** Complete → Create PR → Add Linear comments → Task done+5. Update status to **"In Review"** (not "Done" — "Done" is for after the PR merges)+6. Add the completion comment+7. Move to the next issuediff --git a/.agents/skills/microcopy/SKILL.md b/.agents/skills/microcopy/SKILL.mdindex 2a161024a48..66746382a29 100644--- a/.agents/skills/microcopy/SKILL.md+++ b/.agents/skills/microcopy/SKILL.md@@ -1,10 +1,16 @@---name: microcopydescription: UI copy and microcopy guidelines. Use when writing UI text, buttons, error messages, empty states, onboarding, or any user-facing copy. Triggers on i18n translation, UI text writing, or copy improvement tasks. Supports both Chinese and English.+user-invocable: false---# LobeHub UI Microcopy Guidelines+This file is the quick-reference summary. For full prompt-style guidelines with extensive examples (anti-patterns, tone matrices, scenario walk-throughs), load the language-specific reference:++- **中文文案** — [`references/zh.md`](./references/zh.md)+- **English copy** — [`references/en.md`](./references/en.md)+Brand: **Where Agents Collaborate** - Focus on collaborative agent system, not just "generation".## Fixed Terminologydiff --git a/.agents/skills/microcopy/microcopy-en.md b/.agents/skills/microcopy/references/en.mdsimilarity index 100%rename from .agents/skills/microcopy/microcopy-en.mdrename to .agents/skills/microcopy/references/en.mddiff --git a/.agents/skills/microcopy/microcopy-cn.md b/.agents/skills/microcopy/references/zh.mdsimilarity index 100%rename from .agents/skills/microcopy/microcopy-cn.mdrename to .agents/skills/microcopy/references/zh.mddiff --git a/.agents/skills/modal/SKILL.md b/.agents/skills/modal/SKILL.mdindex 6d9bb936f6b..6d6f6aaf064 100644--- a/.agents/skills/modal/SKILL.md+++ b/.agents/skills/modal/SKILL.md@@ -1,6 +1,6 @@---name: modal-description: MUST use when creating, editing, or writing modal dialogs or imperative modals. Prefer createModal / useModalContext / confirmModal from @lobehub/ui/base-ui; root @lobehub/ui is legacy (antd Modal). Covers patterns, ModalHost, and migration notes.+description: "LobeHub imperative-modal conventions. Use whenever creating, editing, opening, or migrating a modal/dialog/popup — prefer `createModal` / `confirmModal` / `useModalContext` from `@lobehub/ui/base-ui` (headless) over the legacy root `@lobehub/ui` `createModal` (antd Modal props) and over any declarative `open` state + `<Modal />` pattern. Covers required `ModalHost` mounting, the `Content` + `index.tsx` file layout, `content` vs `children` slot, i18n inside `createModal()` (`import { t } from 'i18next'`), and migration notes. Triggers on `createModal`, `confirmModal`, `useModalContext`, `ModalHost`, `antd Modal`, `<Modal open>`, 'open a modal', 'popup', 'dialog', 'confirm dialog', '弹框', '弹窗', '确认框', 'migrate to base-ui'."user-invocable: false---diff --git a/.agents/skills/project-overview/SKILL.md b/.agents/skills/project-overview/SKILL.mdindex 222fce7f00f..3ebc348f929 100644--- a/.agents/skills/project-overview/SKILL.md+++ b/.agents/skills/project-overview/SKILL.md@@ -1,6 +1,7 @@---name: project-overviewdescription: Complete project architecture and structure guide. Use when exploring the codebase, understanding project organization, finding files, or needing comprehensive architectural context. Triggers on architecture questions, directory navigation, or project overview needs.+user-invocable: false---# LobeHub Project Overviewdiff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.mdindex f765c50decb..e2f49fd20cc 100644--- a/.agents/skills/react/SKILL.md+++ b/.agents/skills/react/SKILL.md@@ -1,6 +1,7 @@---name: react-description: React component development guide. Use when working with React components (.tsx files), creating UI, using @lobehub/ui components, implementing routing, or building frontend features. Triggers on React component creation, modification, layout implementation, or navigation tasks.+description: "LobeHub React/SPA component conventions: antd-style with `createStaticStyles` + `cssVar.*` (prefer zero-runtime over `createStyles` + `token`), `@lobehub/ui/base-ui` primitives before `@lobehub/ui` before antd, `Flexbox`/`Center` for layouts, react-router-dom navigation, and the `.desktop.tsx` sync rule. Use when writing or editing any `.tsx` under `src/**`, picking a styling helper, choosing a component (Select/Modal/Drawer/Button/Tooltip), wiring routes in `desktopRouter.config.tsx`/`.desktop.tsx`, or adding a `Link`/`useNavigate` call in the SPA. Triggers on `createStyles`/`createStaticStyles`, `cssVar`, `@lobehub/ui`, `antd-style`, `Flexbox`, `useNavigate`, `react-router-dom`, `Link`, 'new component', 'add a page', 'edit a layout', 'desktopRouter', 'componentMap.desktop'."+user-invocable: false---# React Component Writing Guidediff --git a/.agents/skills/review-checklist/SKILL.md b/.agents/skills/review-checklist/SKILL.mdindex f69fc1c0680..4fcb3b4d163 100644--- a/.agents/skills/review-checklist/SKILL.md+++ b/.agents/skills/review-checklist/SKILL.md@@ -1,6 +1,7 @@---name: review-checklistdescription: 'Common recurring mistakes in LobeHub code review — console leftovers, missing return await, hardcoded secrets, hardcoded i18n strings, desktop router pair drift, antd vs @lobehub/ui, non-idempotent migrations, cloud impact red flags. Use as a quick checklist when reviewing PRs, diffs, or branch changes.'+user-invocable: false---# Review Checklistdiff --git a/.agents/skills/spa-routes/SKILL.md b/.agents/skills/spa-routes/SKILL.mdindex dbc6a653e37..dc6fcf80aca 100644--- a/.agents/skills/spa-routes/SKILL.md+++ b/.agents/skills/spa-routes/SKILL.md@@ -1,6 +1,7 @@---name: spa-routesdescription: MUST use when editing src/routes/ segments, src/spa/router/desktopRouter.config.tsx or desktopRouter.config.desktop.tsx (always change both together), mobileRouter.config.tsx, or when moving UI/logic between routes and src/features/.+user-invocable: false---# SPA Routes and Features Guide@@ -84,10 +85,10 @@ Each feature should:## 3a. Desktop router pair (`desktopRouter.config` × 2)-| File | Role |-|------|------|-| `desktopRouter.config.tsx` | Dynamic imports via `dynamicElement` / `dynamicLayout` — code-splitting; used by `entry.web.tsx` and `entry.desktop.tsx`. |-| `desktopRouter.config.desktop.tsx` | Same route tree with **synchronous** imports — kept for Electron / local parity and predictable bundling. |+| File | Role |+| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |+| `desktopRouter.config.tsx` | Dynamic imports via `dynamicElement` / `dynamicLayout` — code-splitting; used by `entry.web.tsx` and `entry.desktop.tsx`. |+| `desktopRouter.config.desktop.tsx` | Same route tree with **synchronous** imports — kept for Electron / local parity and predictable bundling. |Anything that changes the tree (new segment, renamed `path`, moved layout, new child route) must be reflected in **both** files in one PR or commit. Remove routes from both when deleting.diff --git a/.agents/skills/store-data-structures/SKILL.md b/.agents/skills/store-data-structures/SKILL.mdindex 28e7956923c..c1d74284046 100644--- a/.agents/skills/store-data-structures/SKILL.md+++ b/.agents/skills/store-data-structures/SKILL.md@@ -1,257 +1,91 @@---name: store-data-structuresdescription: Zustand store data structure patterns for LobeHub. Covers List vs Detail data structures, Map + Reducer patterns, type definitions, and when to use each pattern. Use when designing store state, choosing data structures, or implementing list/detail pages.+user-invocable: false---# LobeHub Store Data Structures-This guide covers how to structure data in Zustand stores for optimal performance and user experience.+How to structure data in Zustand stores for fast list rendering, multi-detail caching, and ergonomic optimistic updates.## Core Principles### ✅ DO-1. **Separate List and Detail** - Use different structures for list pages and detail pages-2. **Use Map for Details** - Cache multiple detail pages with `Record<string, Detail>`-3. **Use Array for Lists** - Simple arrays for list display-4. **Types from @lobechat/types** - Never use `@lobechat/database` types in stores-5. **Distinguish List and Detail types** - List types may have computed UI fields+1. **Separate List and Detail** — different structures for list pages and detail pages+2. **Use Map for Details** — cache multiple detail pages with `Record<string, Detail>`+3. **Use Array for Lists** — simple arrays for list display+4. **Types from `@lobechat/types`** — never use `@lobechat/database` types in stores+5. **Distinguish List and Detail types** — List types may have computed UI fields### ❌ DON'T-1. **Don't use single detail object** - Can't cache multiple pages-2. **Don't mix List and Detail types** - They have different purposes-3. **Don't use database types** - Use types from `@lobechat/types`-4. **Don't use Map for lists** - Simple arrays are sufficient+1. **Don't use a single detail object** — can't cache multiple pages+2. **Don't mix List and Detail types** — they have different purposes+3. **Don't use database types** — use types from `@lobechat/types`+4. **Don't use Map for lists** — simple arrays are sufficient---## Type Definitions-Types should be organized by entity in separate files:+Each entity gets its own file under `@lobechat/types/`. Each file exports two types:-```-@lobechat/types/src/eval/-├── benchmark.ts # Benchmark types-├── agentEvalDataset.ts # Dataset types-├── agentEvalRun.ts # Run types-└── index.ts # Re-exports-```+- **Detail type** — full entity, including heavy fields (rubrics, content, editor state, …)+- **List item type** — a **subset** that excludes heavy fields, may add computed UI fields (counts, timestamps formatted for display)-### Example: Benchmark Types+**Important:** the List type is a **subset**, not an `extends` of Detail. Extending pulls the heavy fields right back in.-```typescript-// packages/types/src/eval/benchmark.ts-import type { EvalBenchmarkRubric } from './rubric';--// ============================================-// Detail Type - Full entity (for detail pages)-// ============================================--/**- * Full benchmark entity with all fields including heavy data- */-export interface AgentEvalBenchmark {- createdAt: Date;- description?: string | null;- id: string;- identifier: string;- isSystem: boolean;- metadata?: Record<string, unknown> | null;- name: string;- referenceUrl?: string | null;- rubrics: EvalBenchmarkRubric[]; // Heavy field- updatedAt: Date;-}--// ============================================-// List Type - Lightweight (for list display)-// ============================================--/**- * Lightweight benchmark item - excludes heavy fields- * May include computed statistics for UI- */-export interface AgentEvalBenchmarkListItem {- createdAt: Date;- description?: string | null;- id: string;- identifier: string;- isSystem: boolean;- name: string;- // Note: rubrics NOT included (heavy field)-- // Computed statistics for UI display- datasetCount?: number;- runCount?: number;- testCaseCount?: number;-}-```--### Example: Document Types (with heavy content)--```typescript-// packages/types/src/document.ts--/**- * Full document entity - includes heavy content fields- */-export interface Document {- id: string;- title: string;- description?: string;- content: string; // Heavy field - full markdown content- editorData: any; // Heavy field - editor state- metadata?: Record<string, unknown>;- createdAt: Date;- updatedAt: Date;-}--/**- * Lightweight document item - excludes heavy content- */-export interface DocumentListItem {- id: string;- title: string;- description?: string;- // Note: content and editorData NOT included- createdAt: Date;- updatedAt: Date;-- // Computed statistics- wordCount?: number;- lastEditedBy?: string;-}-```--**Key Points:**--- **Detail types** include ALL fields from database (full entity)-- **List types** are **subsets** that exclude heavy/large fields-- List types may add computed statistics for UI (e.g., `testCaseCount`)-- **Each entity gets its own file** (not mixed together)-- **All types** exported from `@lobechat/types`, NOT `@lobechat/database`--**Heavy fields to exclude from List:**--- Large text content (`content`, `editorData`, `fullDescription`)-- Complex objects (`rubrics`, `config`, `metrics`)-- Binary data (`image`, `file`)-- Large arrays (`messages`, `items`)+> See [`references/types.md`](./references/types.md) for full worked examples (Benchmark, Document) and the heavy-field exclusion checklist.---## When to Use Map vs Array-### Use Map + Reducer (for Detail Data)--✅ **Detail page data caching** - Cache multiple detail pages simultaneously-✅ **Optimistic updates** - Update UI before API responds-✅ **Per-item loading states** - Track which items are being updated-✅ **Multiple pages open** - User can navigate between details without refetching+### Use Map + Reducer — for Detail Data-**Structure:**+✅ Detail page data caching — multiple detail pages cached simultaneously+✅ Optimistic updates — update UI before API responds+✅ Per-item loading states — track which items are being updated+✅ Multi-page navigation — user can switch between details without refetching```typescriptbenchmarkDetailMap: Record<string, AgentEvalBenchmark>;```-**Example:** Benchmark detail pages, Dataset detail pages, User profiles--### Use Simple Array (for List Data)+Examples: benchmark detail pages, dataset detail pages, user profiles.-✅ **List display** - Lists, tables, cards-✅ **Read-only or refresh-as-whole** - Entire list refreshes together-✅ **No per-item updates** - No need to update individual items-✅ **Simple data flow** - Easier to understand and maintain+### Use Simple Array — for List Data-**Structure:**+✅ List display — lists, tables, cards+✅ Refresh as a whole — entire list refreshes together+✅ No per-item updates — no need to mutate individual rows in place+✅ Simple data flow — fewer moving parts```typescript-benchmarkList: AgentEvalBenchmarkListItem[]+benchmarkList: AgentEvalBenchmarkListItem[];```-**Example:** Benchmark list, Dataset list, User list+Examples: benchmark list, dataset list, user list.---## State Structure Pattern-### Complete Example--```typescript-// packages/types/src/eval/benchmark.ts-import type { EvalBenchmarkRubric } from './rubric';--/**- * Full benchmark entity (for detail pages)- */-export interface AgentEvalBenchmark {- id: string;- name: string;- description?: string | null;- identifier: string;- rubrics: EvalBenchmarkRubric[]; // Heavy field- metadata?: Record<string, unknown> | null;- isSystem: boolean;- createdAt: Date;- updatedAt: Date;-}--/**- * Lightweight benchmark (for list display)- * Excludes heavy fields like rubrics- */-export interface AgentEvalBenchmarkListItem {- id: string;- name: string;- description?: string | null;- identifier: string;- isSystem: boolean;- createdAt: Date;- // Note: rubrics excluded-- // Computed statistics- testCaseCount?: number;- datasetCount?: number;- runCount?: number;-}-```-```typescript// src/store/eval/slices/benchmark/initialState.tsimport type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';export interface BenchmarkSliceState {- // ============================================- // List Data - Simple Array- // ============================================- /**- * List of benchmarks for list page display- * May include computed fields like testCaseCount- */+ // List — simple arraybenchmarkList: AgentEvalBenchmarkListItem[];benchmarkListInit: boolean;- // ============================================- // Detail Data - Map for Caching- // ============================================- /**- * Map of benchmark details keyed by ID- * Caches detail page data for multiple benchmarks- * Enables optimistic updates and per-item loading- */+ // Detail — map for multi-entity cachingbenchmarkDetailMap: Record<string, AgentEvalBenchmark>;+ loadingBenchmarkDetailIds: string[]; // per-item loading- /**- * Track which benchmark details are being loaded/updated- * For showing spinners on specific items- */- loadingBenchmarkDetailIds: string[];-- // ============================================- // Mutation States- // ============================================+ // Mutation states (drive form-level UI)isCreatingBenchmark: boolean;isUpdatingBenchmark: boolean;isDeletingBenchmark: boolean;@@ -272,180 +106,51 @@ export const benchmarkInitialState: BenchmarkSliceState = {## Reducer Pattern (for Detail Map)-### Why Use Reducer?--- **Immutable updates** - Immer ensures immutability-- **Type-safe actions** - TypeScript discriminated unions-- **Testable** - Pure functions easy to test-- **Reusable** - Same reducer for optimistic updates and server data--### Reducer Structure--```typescript-// src/store/eval/slices/benchmark/reducer.ts-import { produce } from 'immer';-import type { AgentEvalBenchmark } from '@lobechat/types';--// ============================================-// Action Types-// ============================================--type SetBenchmarkDetailAction = {- id: string;- type: 'setBenchmarkDetail';- value: AgentEvalBenchmark;-};--type UpdateBenchmarkDetailAction = {- id: string;- type: 'updateBenchmarkDetail';- value: Partial<AgentEvalBenchmark>;-};--type DeleteBenchmarkDetailAction = {- id: string;- type: 'deleteBenchmarkDetail';-};--export type BenchmarkDetailDispatch =- | SetBenchmarkDetailAction- | UpdateBenchmarkDetailAction- | DeleteBenchmarkDetailAction;--// ============================================-// Reducer Function-// ============================================--export const benchmarkDetailReducer = (- state: Record<string, AgentEvalBenchmark> = {},- payload: BenchmarkDetailDispatch,-): Record<string, AgentEvalBenchmark> => {- switch (payload.type) {- case 'setBenchmarkDetail': {- return produce(state, (draft) => {- draft[payload.id] = payload.value;- });- }-- case 'updateBenchmarkDetail': {- return produce(state, (draft) => {- if (draft[payload.id]) {- draft[payload.id] = { ...draft[payload.id], ...payload.value };- }- });- }-- case 'deleteBenchmarkDetail': {- return produce(state, (draft) => {- delete draft[payload.id];- });- }-- default:- return state;- }-};-```--### Internal Dispatch Methods--```typescript-// In action.ts-export interface BenchmarkAction {- // ... other methods ...-- // Internal methods - not for direct UI use- internal_dispatchBenchmarkDetail: (payload: BenchmarkDetailDispatch) => void;- internal_updateBenchmarkDetailLoading: (id: string, loading: boolean) => void;-}+When the Detail Map needs optimistic updates (i.e. the user edits a row and the UI should reflect it before the server confirms), wire a typed reducer instead of inlining `set` calls. This keeps mutations testable and the dispatch surface small.-export const createBenchmarkSlice: StateCreator<...> = (set, get) => ({- // ... other methods ...-- // Internal - Dispatch to reducer- internal_dispatchBenchmarkDetail: (payload) => {- const currentMap = get().benchmarkDetailMap;- const nextMap = benchmarkDetailReducer(currentMap, payload);-- // Only update if changed- if (isEqual(nextMap, currentMap)) return;-- set(- { benchmarkDetailMap: nextMap },- false,- `dispatchBenchmarkDetail/${payload.type}`,- );- },-- // Internal - Update loading state- internal_updateBenchmarkDetailLoading: (id, loading) => {- set(- (state) => {- if (loading) {- return { loadingBenchmarkDetailIds: [...state.loadingBenchmarkDetailIds, id] };- }- return {- loadingBenchmarkDetailIds: state.loadingBenchmarkDetailIds.filter((i) => i !== id),- };- },- false,- 'updateBenchmarkDetailLoading',- );- },-});-```+> See [`references/reducer.md`](./references/reducer.md) for the full discriminated-union action types, the `produce`-based reducer, and the `internal_dispatch*` slice methods that connect them to Zustand.---## Data Structure Comparison-### ❌ WRONG - Single Detail Object+### ❌ WRONG — Single Detail Object```typescriptinterface BenchmarkSliceState {- // ❌ Can only cache one detailbenchmarkDetail: AgentEvalBenchmark | null;-- // ❌ Global loading stateisLoadingBenchmarkDetail: boolean;}```-**Problems:**+Problems:- Can only cache one detail page at a time-- Switching between details causes unnecessary refetches+- Switching between details forces refetch- No optimistic updates- No per-item loading states-### ✅ CORRECT - Separate List and Detail+### ✅ CORRECT — Separate List and Detail```typescript-import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';-interface BenchmarkSliceState {- // ✅ List data - simple arraybenchmarkList: AgentEvalBenchmarkListItem[];benchmarkListInit: boolean;- // ✅ Detail data - map for cachingbenchmarkDetailMap: Record<string, AgentEvalBenchmark>;-- // ✅ Per-item loadingloadingBenchmarkDetailIds: string[];- // ✅ Mutation statesisCreatingBenchmark: boolean;isUpdatingBenchmark: boolean;isDeletingBenchmark: boolean;}```-**Benefits:**+Benefits:- Cache multiple detail pages- Fast navigation between cached details-- Optimistic updates with reducer+- Optimistic updates via reducer- Per-item loading states- Clear separation of concerns@@ -455,22 +160,16 @@ interface BenchmarkSliceState {### Accessing List Data-```typescript+```tsxconst BenchmarkList = () => {- // Simple array accessconst benchmarks = useEvalStore((s) => s.benchmarkList);const isInit = useEvalStore((s) => s.benchmarkListInit);if (!isInit) return <Loading />;-return (<div>- {benchmarks.map(b => (- <BenchmarkCard- key={b.id}- name={b.name}- testCaseCount={b.testCaseCount} // Computed field- />+ {benchmarks.map((b) => (+ <BenchmarkCard key={b.id} name={b.name} testCaseCount={b.testCaseCount} />))}</div>);@@ -479,22 +178,18 @@ const BenchmarkList = () => {### Accessing Detail Data-```typescript+```tsxconst BenchmarkDetail = () => {const { benchmarkId } = useParams<{ benchmarkId: string }>();- // Get from mapconst benchmark = useEvalStore((s) =>benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,);-- // Check loadingconst isLoading = useEvalStore((s) =>benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,);if (!benchmark) return <Loading />;-return (<div><h1>{benchmark.name}</h1>@@ -510,7 +205,6 @@ const BenchmarkDetail = () => {// src/store/eval/slices/benchmark/selectors.tsexport const benchmarkSelectors = {getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],-isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>s.loadingBenchmarkDetailIds.includes(id),};@@ -524,7 +218,7 @@ const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(bench## Decision Tree-```+```textNeed to store data?│├─ Is it a LIST for display?@@ -547,43 +241,40 @@ Need to store data?When designing store state structure:-- [ ] **Organize types by entity** in separate files (e.g., `benchmark.ts`, `agentEvalDataset.ts`)+- [ ] **Organize types by entity** in separate files (e.g. `benchmark.ts`, `agentEvalDataset.ts`)- [ ] Create **Detail** type (full entity with all fields including heavy ones)- [ ] Create **ListItem** type:- - [ ] Subset of Detail type (exclude heavy fields)+ - [ ] Subset of Detail (exclude heavy fields)- [ ] May include computed statistics for UI- - [ ] **NOT** extending Detail type (it's a subset, not extension)+ - [ ] **NOT** `extends` Detail- [ ] Use **array** for list data: `xxxList: XxxListItem[]`- [ ] Use **Map** for detail data: `xxxDetailMap: Record<string, Xxx>`-- [ ] Add per-item loading: `loadingXxxDetailIds: string[]`-- [ ] Create **reducer** for detail map if optimistic updates needed-- [ ] Add **internal dispatch** and **loading** methods-- [ ] Create **selectors** for clean access (optional but recommended)-- [ ] Document in comments:- - [ ] What fields are excluded from List and why- - [ ] What computed fields mean- - [ ] What each Map is for+- [ ] Per-item loading: `loadingXxxDetailIds: string[]`+- [ ] **Reducer** for detail map if optimistic updates needed (see [`references/reducer.md`](./references/reducer.md))+- [ ] **Internal dispatch** and **loading** methods+- [ ] **Selectors** for clean access (optional but recommended)+- [ ] Document in comments which fields are excluded from List and why---## Best Practices-1. **File organization** - One entity per file, not mixed together-2. **List is subset** - ListItem excludes heavy fields, not extends Detail-3. **Clear naming** - `xxxList` for arrays, `xxxDetailMap` for maps-4. **Consistent patterns** - All detail maps follow same structure-5. **Type safety** - Never use `any`, always use proper types-6. **Document exclusions** - Comment which fields are excluded from List and why-7. **Selectors** - Encapsulate access patterns-8. **Loading states** - Per-item for details, global for lists-9. **Immutability** - Use Immer in reducers+1. **File organization** — one entity per file, not mixed+2. **List is a subset** — ListItem excludes heavy fields, does not `extends` Detail+3. **Clear naming** — `xxxList` for arrays, `xxxDetailMap` for maps+4. **Consistent patterns** — all detail maps follow the same shape+5. **Type safety** — never use `any`, always use proper types+6. **Document exclusions** — comment which fields are excluded and why+7. **Selectors** — encapsulate access patterns+8. **Loading states** — per-item for details, global for mutations+9. **Immutability** — use Immer in reducers### Common Mistakes to Avoid❌ **DON'T extend Detail in List:**```typescript-// Wrong - List should not extend Detail+// Wrong — pulls heavy fields back inexport interface BenchmarkListItem extends Benchmark {testCaseCount?: number;}@@ -592,7 +283,6 @@ export interface BenchmarkListItem extends Benchmark {✅ **DO create separate subset:**```typescript-// Correct - List is a subset with computed fieldsexport interface BenchmarkListItem {id: string;name: string;@@ -603,14 +293,14 @@ export interface BenchmarkListItem {❌ **DON'T mix entities in one file:**-```typescript-// Wrong - all entities in agentEvalEntities.ts+```text+// Wrong — all entities in agentEvalEntities.ts```✅ **DO separate by entity:**-```typescript-// Correct - separate files+```text+// Correct — separate files// benchmark.ts// agentEvalDataset.ts// agentEvalRun.ts@@ -620,5 +310,5 @@ export interface BenchmarkListItem {## Related Skills-- `data-fetching` - How to fetch and update this data-- `zustand` - General Zustand patterns+- `data-fetching` — how to fetch and update this data+- `zustand` — general Zustand patternsdiff --git a/.agents/skills/store-data-structures/references/reducer.md b/.agents/skills/store-data-structures/references/reducer.mdnew file mode 100644index 00000000000..d400b2a87a0--- /dev/null+++ b/.agents/skills/store-data-structures/references/reducer.md@@ -0,0 +1,118 @@+# Reducer Pattern (for Detail Map)++## Why Use a Reducer?++- **Immutable updates** — Immer makes immutability easy+- **Type-safe actions** — discriminated union of action types prevents typos+- **Testable** — pure function, easy to unit test+- **Reusable** — same reducer powers optimistic updates and server-data writes++## Reducer Structure++```typescript+// src/store/eval/slices/benchmark/reducer.ts+import { produce } from 'immer';+import type { AgentEvalBenchmark } from '@lobechat/types';++// Action types — discriminated union+type SetBenchmarkDetailAction = {+ id: string;+ type: 'setBenchmarkDetail';+ value: AgentEvalBenchmark;+};++type UpdateBenchmarkDetailAction = {+ id: string;+ type: 'updateBenchmarkDetail';+ value: Partial<AgentEvalBenchmark>;+};++type DeleteBenchmarkDetailAction = {+ id: string;+ type: 'deleteBenchmarkDetail';+};++export type BenchmarkDetailDispatch =+ | SetBenchmarkDetailAction+ | UpdateBenchmarkDetailAction+ | DeleteBenchmarkDetailAction;++export const benchmarkDetailReducer = (+ state: Record<string, AgentEvalBenchmark> = {},+ payload: BenchmarkDetailDispatch,+): Record<string, AgentEvalBenchmark> => {+ switch (payload.type) {+ case 'setBenchmarkDetail': {+ return produce(state, (draft) => {+ draft[payload.id] = payload.value;+ });+ }++ case 'updateBenchmarkDetail': {+ return produce(state, (draft) => {+ if (draft[payload.id]) {+ draft[payload.id] = { ...draft[payload.id], ...payload.value };+ }+ });+ }++ case 'deleteBenchmarkDetail': {+ return produce(state, (draft) => {+ delete draft[payload.id];+ });+ }++ default:+ return state;+ }+};+```++## Internal Dispatch Methods++The slice exposes two `internal_*` methods so the reducer and the loading state stay encapsulated behind a stable contract:++```typescript+// In action.ts+export interface BenchmarkAction {+ // ... other methods ...++ // Internal — not for direct UI use+ internal_dispatchBenchmarkDetail: (payload: BenchmarkDetailDispatch) => void;+ internal_updateBenchmarkDetailLoading: (id: string, loading: boolean) => void;+}++export const createBenchmarkSlice: StateCreator<...> = (set, get) => ({+ // ... other methods ...++ // Dispatch to reducer+ internal_dispatchBenchmarkDetail: (payload) => {+ const currentMap = get().benchmarkDetailMap;+ const nextMap = benchmarkDetailReducer(currentMap, payload);++ // Skip set when nothing changed — avoids unnecessary re-renders+ if (isEqual(nextMap, currentMap)) return;++ set(+ { benchmarkDetailMap: nextMap },+ false,+ `dispatchBenchmarkDetail/${payload.type}`,+ );+ },++ // Update loading state for a specific id+ internal_updateBenchmarkDetailLoading: (id, loading) => {+ set(+ (state) => ({+ loadingBenchmarkDetailIds: loading+ ? [...state.loadingBenchmarkDetailIds, id]+ : state.loadingBenchmarkDetailIds.filter((i) => i !== id),+ }),+ false,+ 'updateBenchmarkDetailLoading',+ );+ },+});+```++The `internal_` prefix is a convention — UI components should call the public mutation methods (e.g. `updateBenchmark`), which in turn call `internal_dispatch*`. This keeps reducer dispatch shapes out of the component layer.diff --git a/.agents/skills/store-data-structures/references/types.md b/.agents/skills/store-data-structures/references/types.mdnew file mode 100644index 00000000000..b3c9e51acff--- /dev/null+++ b/.agents/skills/store-data-structures/references/types.md@@ -0,0 +1,101 @@+# Type Definitions in Detail++The skill body's Type Definitions section covers the rules; this file holds the full worked examples to keep SKILL.md lean.++## Organization++Types should be organized by entity in separate files (not mixed):++```text+@lobechat/types/src/eval/+├── benchmark.ts # Benchmark types+├── agentEvalDataset.ts # Dataset types+├── agentEvalRun.ts # Run types+└── index.ts # Re-exports+```++## Example: Benchmark Types++```typescript+// packages/types/src/eval/benchmark.ts+import type { EvalBenchmarkRubric } from './rubric';++/**+ * Full benchmark entity with all fields including heavy data.+ */+export interface AgentEvalBenchmark {+ createdAt: Date;+ description?: string | null;+ id: string;+ identifier: string;+ isSystem: boolean;+ metadata?: Record<string, unknown> | null;+ name: string;+ referenceUrl?: string | null;+ rubrics: EvalBenchmarkRubric[]; // Heavy field+ updatedAt: Date;+}++/**+ * Lightweight benchmark item — excludes heavy fields, may add computed stats.+ */+export interface AgentEvalBenchmarkListItem {+ createdAt: Date;+ description?: string | null;+ id: string;+ identifier: string;+ isSystem: boolean;+ name: string;+ // Note: rubrics NOT included (heavy field)++ // Computed statistics for UI display+ datasetCount?: number;+ runCount?: number;+ testCaseCount?: number;+}+```++## Example: Document Types (with heavy content)++```typescript+// packages/types/src/document.ts++/**+ * Full document entity — includes heavy content fields.+ */+export interface Document {+ id: string;+ title: string;+ description?: string;+ content: string; // Heavy field — full markdown content+ editorData: any; // Heavy field — editor state+ metadata?: Record<string, unknown>;+ createdAt: Date;+ updatedAt: Date;+}++/**+ * Lightweight document item — excludes heavy content.+ */+export interface DocumentListItem {+ id: string;+ title: string;+ description?: string;+ // Note: content and editorData NOT included+ createdAt: Date;+ updatedAt: Date;++ // Computed statistics+ wordCount?: number;+ lastEditedBy?: string;+}+```++## Heavy Fields to Exclude from List++- Large text content (`content`, `editorData`, `fullDescription`)+- Complex objects (`rubrics`, `config`, `metrics`)+- Binary data (`image`, `file`)+- Large arrays (`messages`, `items`)++The reason these belong only on Detail: list pages render many rows, so pulling heavy fields blows up payload size and slows render. Detail pages render one entity, so the full payload is fine.diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.mdindex 886aa5862a0..2b0173f763c 100644--- a/.agents/skills/testing/SKILL.md+++ b/.agents/skills/testing/SKILL.md@@ -1,6 +1,7 @@---name: testingdescription: Testing guide using Vitest. Use when writing tests (.test.ts, .test.tsx), fixing failing tests, improving test coverage, or debugging test issues. Triggers on test creation, test debugging, mock setup, or test-related questions.+user-invocable: false---# LobeHub Testing Guidediff --git a/.agents/skills/trpc-router/SKILL.md b/.agents/skills/trpc-router/SKILL.mdindex ea7ea888199..1ba751241f3 100644--- a/.agents/skills/trpc-router/SKILL.md+++ b/.agents/skills/trpc-router/SKILL.md@@ -1,6 +1,7 @@---name: trpc-routerdescription: TRPC router development guide. Use when creating or modifying TRPC routers (src/server/routers/**), adding procedures, or working with server-side API endpoints. Triggers on TRPC router creation, procedure implementation, or API endpoint tasks.+user-invocable: false---# TRPC Router Guidediff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.mdindex 6948ea88b67..6fe15909dc6 100644--- a/.agents/skills/typescript/SKILL.md+++ b/.agents/skills/typescript/SKILL.md@@ -1,6 +1,7 @@---name: typescript-description: TypeScript code style and optimization guidelines. MUST READ before writing or modifying any TypeScript code (.ts, .tsx, .mts files). Also use when reviewing code quality or implementing type-safe patterns. Triggers on any TypeScript file edit, code style discussions, or type safety questions.+description: "TypeScript code style and type-safety guide for LobeHub. Read before writing or editing any `.ts` / `.tsx` / `.mts` — covers `interface` vs `type`, `Record<PropertyKey, unknown>` over `any`/`object`, `as const satisfies`, `@ts-expect-error` over `@ts-ignore`, `import type` (`separate-type-imports`), `async`/`await` + `Promise.all`, `for…of` over indexed `for`, and the no-silent-`.catch(() => fallback)` rule. Also use when reviewing type quality, deciding module augmentation (`declare module`) over `namespace`, or designing extensible types (e.g. `PipelineContext.metadata`). Triggers on any TypeScript file edit, 'fix the type', 'why is this `any`', 'should this be interface or type', 'eslint type-import', 'ts-expect-error'."+user-invocable: false---# TypeScript Code Style Guide@@ -28,12 +29,16 @@ description: TypeScript code style and optimization guidelines. MUST READ before## Imports- This project uses `simple-import-sort/imports` and `consistent-type-imports` (`fixStyle: 'separate-type-imports'`)+- **Separate type imports**: always use `import type { ... }` for type-only imports, NOT `import { type ... }` inline syntax+- When a file already has `import type { ... }` from a package and you need to add a value import, keep them as **two separate statements**:+```tsimport type { ChatTopicBotContext } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';```+- Within each import statement, specifiers are sorted **alphabetically by name**## Code Structure@@ -42,6 +47,7 @@ description: TypeScript code style and optimization guidelines. MUST READ before- Use consistent, descriptive naming; avoid obscure abbreviations- Replace magic numbers/strings with well-named constants- Defer formatting to tooling+- Prefer **named exports** over `export default` — keeps refactor renames and IDE auto-import in sync, and avoids the `default` re-naming drift you get with `import Foo from './foo'`. Reserve `export default` for files where the framework requires it (Next.js page/route/layout, React.lazy targets, config files like `vitest.config.ts`)## UI and Theming@@ -51,7 +57,6 @@ description: TypeScript code style and optimization guidelines. MUST READ before## Performance-- Prefer `for…of` loops over index-based `for` loops- Reuse existing utils in `packages/utils` or installed npm packages- Query only required columns from databasediff --git a/.agents/skills/upstash-workflow/SKILL.md b/.agents/skills/upstash-workflow/SKILL.mdindex 1f410280ce3..0f31321093e 100644--- a/.agents/skills/upstash-workflow/SKILL.md+++ b/.agents/skills/upstash-workflow/SKILL.md@@ -1,46 +1,34 @@---name: upstash-workflowdescription: 'Upstash Workflow implementation guide. Use when creating async workflows with QStash, implementing fan-out patterns, or building 3-layer workflow architecture (process → paginate → execute).'+user-invocable: false---# Upstash Workflow Implementation Guide-This guide covers the standard patterns for implementing Upstash Workflow + QStash async workflows in the LobeHub codebase.+Standard patterns for implementing Upstash Workflow + QStash async workflows in the LobeHub codebase.## 🎯 The Three Core Patterns-All workflows in LobeHub follow the same 3-layer architecture with three essential patterns:+Every workflow in LobeHub combines these three patterns. They exist because the platform constrains you in three ways: rate limits make blind fan-out dangerous, step limits cap a single workflow's size, and idempotency demands that retries don't double-process.-1. **🔍 Dry-Run Mode** - Get statistics without triggering actual execution-2. **🌟 Fan-Out Pattern** - Split large batches into smaller chunks for parallel processing-3. **🎯 Single Task Execution** - Each workflow execution processes **ONE item only**--These patterns ensure scalable, debuggable, and cost-efficient async workflows.--## Table of Contents--1. [Architecture Overview](#architecture-overview)-2. [Core Patterns](#core-patterns)-3. [File Structure](#file-structure)-4. [Implementation Patterns](#implementation-patterns)-5. [Best Practices](#best-practices)-6. [Examples](#examples)+1. **🔍 Dry-Run Mode** — get statistics without triggering actual execution+2. **🌟 Fan-Out Pattern** — split large batches into smaller chunks for parallel processing+3. **🎯 Single Task Execution** — each workflow execution processes **exactly ONE item**---## Architecture Overview-### Standard 3-Layer Pattern+All workflows follow the same 3-layer architecture:-All workflows follow a standard 3-layer architecture:--```+```textLayer 1: Entry Point (process-*)├─ Validates prerequisites├─ Calculates total items to process├─ Filters existing items├─ Supports dry-run mode (statistics only)- └─ Triggers Layer 2 if work needed+ └─ Triggers Layer 2 if work is neededLayer 2: Pagination (paginate-*)├─ Handles cursor-based pagination@@ -48,26 +36,22 @@ Layer 2: Pagination (paginate-*)├─ Recursively processes all pages└─ Triggers Layer 3 for each item-Layer 3: Single Task Execution (execute-*/generate-*)+Layer 3: Single Task Execution (execute-* / generate-*)└─ Performs actual business logic for ONE item```-**Examples**: `welcome-placeholder`, `agent-welcome`+**Real examples in this codebase:** `welcome-placeholder`, `agent-welcome` — see [`references/examples.md`](./references/examples.md).----## Core Patterns+## The Three Patterns in 60 Seconds### 1. Dry-Run Mode-**Purpose**: Get statistics without triggering actual execution--**Pattern**:+Short-circuit Layer 1 before any side effects so callers can preview what would happen:```typescript-// Layer 1: Entry Pointif (dryRun) {- console.log('[workflow:process] Dry run mode, returning statistics only');return {...result,dryRun: true,@@ -76,40 +60,17 @@ if (dryRun) {}```-**Use Case**: Check how many items will be processed before committing to execution--**Response**:--```typescript-{- success: true,- totalEligible: 100,- toProcess: 80,- alreadyProcessed: 20,- dryRun: true,- message: "[DryRun] Would process 80 items"-}-```+Use case: check how many items will be processed before committing.### 2. Fan-Out Pattern-**Purpose**: Split large batches into smaller chunks for parallel processing--**Pattern**:+Layer 2 splits oversized batches into chunks and recursively re-triggers itself with each chunk. This avoids hitting workflow step limits when one page contains too many items:```typescript-// Layer 2: Paginationconst CHUNK_SIZE = 20;if (itemIds.length > CHUNK_SIZE) {- // Fan-out to smaller chunksconst chunks = chunk(itemIds, CHUNK_SIZE);- console.log('[workflow:paginate] Fan-out mode:', {- chunks: chunks.length,- chunkSize: CHUNK_SIZE,- totalItems: itemIds.length,- });-await Promise.all(chunks.map((ids, idx) =>context.run(`workflow:fanout:${idx + 1}/${chunks.length}`, () =>@@ -120,70 +81,35 @@ if (itemIds.length > CHUNK_SIZE) {}```-**Use Case**: Avoid hitting workflow step limits by splitting large batches--**Configuration**:--- `PAGE_SIZE = 50` - Items per pagination page-- `CHUNK_SIZE = 20` - Items per fan-out chunk-- If batch > CHUNK_SIZE, split into chunks and recursively trigger pagination+Defaults: `PAGE_SIZE = 50` (items per page), `CHUNK_SIZE = 20` (items per fan-out chunk).### 3. Single Task Execution-**Purpose**: Execute business logic for ONE item at a time--**Pattern**:+Layer 3 always processes exactly one item per invocation. Parallelism comes from Layer 2 fanning out to many Layer 3 invocations, controlled by `flowControl`:```typescript-// Layer 3: Single Task Executionexport const { POST } = serve<ExecutePayload>(async (context) => {const { itemId } = context.requestPayload ?? {};+ if (!itemId) return { success: false, error: 'Missing itemId' };- if (!itemId) {- return { success: false, error: 'Missing itemId' };- }-- // Get item- const item = await context.run('workflow:get-item', async () => {- return getItem(itemId);- });-- // Execute business logic for THIS item only- const result = await context.run('workflow:execute', async () => {- return processItem(item);- });-- // Save result for THIS item- await context.run('workflow:save', async () => {- return saveResult(itemId, result);- });+ const item = await context.run('workflow:get-item', () => getItem(itemId));+ const result = await context.run('workflow:execute', () => processItem(item));+ await context.run('workflow:save', () => saveResult(itemId, result));return { success: true, itemId, result };},{- flowControl: {- key: 'workflow.execute',- parallelism: 10,- ratePerSecond: 5,- },+ flowControl: { key: 'workflow.execute', parallelism: 10, ratePerSecond: 5 },},);```-**Key Principles**:--- Each workflow execution handles **exactly ONE item**-- Parallelism controlled by `flowControl` config-- Multiple items processed via Layer 2 triggering multiple Layer 3 executions----## File Structure-### Directory Layout--```+```textsrc/├── app/(backend)/api/workflows/│ └── {workflow-name}/@@ -196,884 +122,22 @@ src/└── index.ts # Workflow class```-### Cloud Project Configuration--For lobehub-cloud specific configurations (re-exports, cloud-only workflows, deployment patterns), see:--📄 **[Cloud Configuration Guide](./reference/cloud.md)**-------## Implementation Patterns--### 1. Workflow Class--**Location**: `src/server/workflows/{workflowName}/index.ts`--```typescript-import { Client } from '@upstash/workflow';-import debug from 'debug';--const log = debug('lobe-server:workflows:{workflow-name}');--// Workflow paths-const WORKFLOW_PATHS = {- processItems: '/api/workflows/{workflow-name}/process-items',- paginateItems: '/api/workflows/{workflow-name}/paginate-items',- executeItem: '/api/workflows/{workflow-name}/execute-item',-} as const;--// Payload types-export interface ProcessItemsPayload {- dryRun?: boolean;- force?: boolean;-}--export interface PaginateItemsPayload {- cursor?: string;- itemIds?: string[]; // For fanout chunks-}--export interface ExecuteItemPayload {- itemId: string;-}--/**- * Get workflow URL using APP_URL- */-const getWorkflowUrl = (path: string): string => {- const baseUrl = process.env.APP_URL;- if (!baseUrl) throw new Error('APP_URL is required to trigger workflows');- return new URL(path, baseUrl).toString();-};--/**- * Get workflow client- */-const getWorkflowClient = (): Client => {- const token = process.env.QSTASH_TOKEN;- if (!token) throw new Error('QSTASH_TOKEN is required to trigger workflows');-- const config: ConstructorParameters<typeof Client>[0] = { token };- if (process.env.QSTASH_URL) {- (config as Record<string, unknown>).url = process.env.QSTASH_URL;- }- return new Client(config);-};--/**- * {Workflow Name} Workflow- */-export class {WorkflowName}Workflow {- private static client: Client;-- private static getClient(): Client {- if (!this.client) {- this.client = getWorkflowClient();- }- return this.client;- }-- /**- * Trigger workflow to process items (entry point)- */- static triggerProcessItems(payload: ProcessItemsPayload) {- const url = getWorkflowUrl(WORKFLOW_PATHS.processItems);- log('Triggering process-items workflow');- return this.getClient().trigger({ body: payload, url });- }-- /**- * Trigger workflow to paginate items- */- static triggerPaginateItems(payload: PaginateItemsPayload) {- const url = getWorkflowUrl(WORKFLOW_PATHS.paginateItems);- log('Triggering paginate-items workflow');- return this.getClient().trigger({ body: payload, url });- }-- /**- * Trigger workflow to execute a single item- */- static triggerExecuteItem(payload: ExecuteItemPayload) {- const url = getWorkflowUrl(WORKFLOW_PATHS.executeItem);- log('Triggering execute-item workflow: %s', payload.itemId);- return this.getClient().trigger({ body: payload, url });- }-- /**- * Filter items that need processing (e.g., check Redis cache, database state)- */- static async filterItemsNeedingProcessing(itemIds: string[]): Promise<string[]> {- if (itemIds.length === 0) return [];-- // Check existing state (Redis, database, etc.)- // Return items that need processing-- return itemIds;- }-}-```--### 2. Layer 1: Entry Point (process-\*)--**Purpose**: Validates prerequisites, calculates statistics, supports dryRun mode--```typescript-import { serve } from '@upstash/workflow/nextjs';-import { getServerDB } from '@/database/server';-import { WorkflowClass, type ProcessPayload } from '@/server/workflows/{workflowName}';--/**- * Entry workflow for {workflow description}- * 1. Get all eligible items- * 2. Filter items that already have results- * 3. If dryRun, return statistics only- * 4. If no items need processing, return early- * 5. Trigger paginate workflow- */-export const { POST } = serve<ProcessPayload>(- async (context) => {- const { dryRun, force } = context.requestPayload ?? {};-- console.log('[{workflow}:process] Starting with payload:', { dryRun, force });-- // Get all eligible items- const allItemIds = await context.run('{workflow}:get-all-items', async () => {- const db = await getServerDB();- // Query database for eligible items- return items.map((item) => item.id);- });-- console.log('[{workflow}:process] Total eligible items:', allItemIds.length);-- if (allItemIds.length === 0) {- return {- success: true,- totalEligible: 0,- message: 'No eligible items found',- };- }-- // Filter items that need processing- const itemsNeedingProcessing = await context.run('{workflow}:filter-existing', () =>- WorkflowClass.filterItemsNeedingProcessing(allItemIds),- );-- const result = {- success: true,- totalEligible: allItemIds.length,- toProcess: itemsNeedingProcessing.length,- alreadyProcessed: allItemIds.length - itemsNeedingProcessing.length,- };-- console.log('[{workflow}:process] Check result:', result);-- // If dryRun mode, return statistics only- if (dryRun) {- console.log('[{workflow}:process] Dry run mode, returning statistics only');- return {- ...result,- dryRun: true,- message: `[DryRun] Would process ${itemsNeedingProcessing.length} items`,- };- }-- // If no items need processing, return early- if (itemsNeedingProcessing.length === 0) {- console.log('[{workflow}:process] All items already processed');- return {- ...result,- message: 'All items already processed',- };- }-- // Trigger paginate workflow- console.log('[{workflow}:process] Triggering paginate workflow');- await context.run('{workflow}:trigger-paginate', () => WorkflowClass.triggerPaginateItems({}));-- return {- ...result,- message: `Triggered pagination for ${itemsNeedingProcessing.length} items`,- };- },- {- flowControl: {- key: '{workflow}.process',- parallelism: 1,- ratePerSecond: 1,- },- },-);-```--### 3. Layer 2: Pagination (paginate-\*)--**Purpose**: Handles cursor-based pagination, implements fanout for large batches--```typescript-import { serve } from '@upstash/workflow/nextjs';-import { chunk } from 'es-toolkit/compat';-import { getServerDB } from '@/database/server';-import { WorkflowClass, type PaginatePayload } from '@/server/workflows/{workflowName}';--const PAGE_SIZE = 50;-const CHUNK_SIZE = 20;--/**- * Paginate items workflow - handles pagination and fanout- * 1. If specific itemIds provided (from fanout), process them directly- * 2. Otherwise, paginate through all items using cursor- * 3. Filter items that need processing- * 4. If batch > CHUNK_SIZE, fanout to smaller chunks- * 5. Trigger execute workflow for each item- * 6. Schedule next page if cursor exists- */-export const { POST } = serve<PaginatePayload>(- async (context) => {- const { cursor, itemIds: payloadItemIds } = context.requestPayload ?? {};-- console.log('[{workflow}:paginate] Starting with payload:', {- cursor,- itemIdsCount: payloadItemIds?.length ?? 0,- });-- // If specific itemIds are provided, process them directly (from fanout)- if (payloadItemIds && payloadItemIds.length > 0) {- console.log('[{workflow}:paginate] Processing specific itemIds:', {- count: payloadItemIds.length,- });-- await Promise.all(- payloadItemIds.map((itemId) =>- context.run(`{workflow}:execute:${itemId}`, () =>- WorkflowClass.triggerExecuteItem({ itemId }),- ),- ),- );-- return {- success: true,- processedItems: payloadItemIds.length,- };- }-- // Paginate through all items- const itemBatch = await context.run('{workflow}:get-batch', async () => {- const db = await getServerDB();- // Query database with cursor and PAGE_SIZE- const items = await db.query(...);-- if (!items.length) return { ids: [] };-- const last = items.at(-1);- return {- ids: items.map(item => item.id),- cursor: last ? last.id : undefined,- };- });-- const batchItemIds = itemBatch.ids;- const nextCursor = 'cursor' in itemBatch ? itemBatch.cursor : undefined;-- console.log('[{workflow}:paginate] Got batch:', {- batchSize: batchItemIds.length,- nextCursor,- });-- if (batchItemIds.length === 0) {- console.log('[{workflow}:paginate] No more items, pagination complete');- return { success: true, message: 'Pagination complete' };- }-- // Filter items that need processing- const itemIds = await context.run('{workflow}:filter-existing', () =>- WorkflowClass.filterItemsNeedingProcessing(batchItemIds),- );-- console.log('[{workflow}:paginate] After filtering:', {- needProcessing: itemIds.length,- skipped: batchItemIds.length - itemIds.length,- });-- // Process items if any need processing- if (itemIds.length > 0) {- if (itemIds.length > CHUNK_SIZE) {- // Fanout to smaller chunks- const chunks = chunk(itemIds, CHUNK_SIZE);- console.log('[{workflow}:paginate] Fanout mode:', {- chunks: chunks.length,- chunkSize: CHUNK_SIZE,- totalItems: itemIds.length,- });-- await Promise.all(- chunks.map((ids, idx) =>- context.run(`{workflow}:fanout:${idx + 1}/${chunks.length}`, () =>- WorkflowClass.triggerPaginateItems({ itemIds: ids }),- ),- ),- );- } else {- // Process directly- console.log('[{workflow}:paginate] Processing items directly:', {- count: itemIds.length,- });-- await Promise.all(- itemIds.map((itemId) =>- context.run(`{workflow}:execute:${itemId}`, () =>- WorkflowClass.triggerExecuteItem({ itemId }),- ),- ),- );- }- }-- // Schedule next page- if (nextCursor) {- console.log('[{workflow}:paginate] Scheduling next page:', { nextCursor });- await context.run('{workflow}:next-page', () =>- WorkflowClass.triggerPaginateItems({ cursor: nextCursor }),- );- } else {- console.log('[{workflow}:paginate] No more pages');- }-- return {- success: true,- processedItems: itemIds.length,- skippedItems: batchItemIds.length - itemIds.length,- nextCursor: nextCursor ?? null,- };- },- {- flowControl: {- key: '{workflow}.paginate',- parallelism: 20,- ratePerSecond: 5,- },- },-);-```--### 4. Layer 3: Execution (execute-_/generate-_)--**Purpose**: Performs actual business logic--```typescript-import { serve } from '@upstash/workflow/nextjs';-import { getServerDB } from '@/database/server';-import { WorkflowClass, type ExecutePayload } from '@/server/workflows/{workflowName}';--/**- * Execute item workflow - performs actual business logic- * 1. Get item data- * 2. Perform business logic (AI generation, data processing, etc.)- * 3. Save results- */-export const { POST } = serve<ExecutePayload>(- async (context) => {- const { itemId } = context.requestPayload ?? {};-- console.log('[{workflow}:execute] Starting:', { itemId });-- if (!itemId) {- return { success: false, error: 'Missing itemId' };- }-- const db = await getServerDB();-- // Get item data- const item = await context.run('{workflow}:get-item', async () => {- // Query database for item- return item;- });-- if (!item) {- return { success: false, error: 'Item not found' };- }-- // Perform business logic- const result = await context.run('{workflow}:process-item', async () => {- const workflow = new WorkflowClass(db, itemId);- return workflow.generate(); // or process(), execute(), etc.- });-- // Save results- await context.run('{workflow}:save-result', async () => {- const workflow = new WorkflowClass(db, itemId);- return workflow.saveToRedis(result); // or saveToDatabase(), etc.- });-- console.log('[{workflow}:execute] Completed:', { itemId });-- return {- success: true,- itemId,- result,- };- },- {- flowControl: {- key: '{workflow}.execute',- parallelism: 10,- ratePerSecond: 5,- },- },-);-```-------## Best Practices--### 1. Error Handling--```typescript-export const { POST } = serve<Payload>(- async (context) => {- const { itemId } = context.requestPayload ?? {};-- // Validate required parameters- if (!itemId) {- return { success: false, error: 'Missing itemId in payload' };- }-- try {- // Perform work- const result = await context.run('step-name', () => doWork(itemId));-- return { success: true, itemId, result };- } catch (error) {- console.error('[workflow:error]', error);- return {- success: false,- error: error instanceof Error ? error.message : 'Unknown error'- };- }- },- { flowControl: { ... } },-);-```--### 2. Logging--Use consistent log prefixes and structured logging:--```typescript-console.log('[{workflow}:{layer}] Starting with payload:', payload);-console.log('[{workflow}:{layer}] Processing items:', { count: items.length });-console.log('[{workflow}:{layer}] Completed:', result);-console.error('[{workflow}:{layer}:error]', error);-```--### 3. Return Values--Return consistent response shapes:--```typescript-// Success response-return {- success: true,- itemId,- result,- message: 'Optional success message',-};--// Error response-return {- success: false,- error: 'Error description',- itemId, // Include context if available-};--// Statistics response (for entry point)-return {- success: true,- totalEligible: 100,- toProcess: 80,- alreadyProcessed: 20,- dryRun: true, // If applicable- message: 'Summary message',-};-```--### 4. flowControl Configuration--**Purpose**: Control concurrency and rate limiting for workflow executions--Tune concurrency based on layer:--```typescript-// Layer 1: Entry point - single instance only-flowControl: {- key: '{workflow}.process',- parallelism: 1, // Only 1 process workflow at a time- ratePerSecond: 1, // 1 execution per second-}--// Layer 2: Pagination - moderate concurrency-flowControl: {- key: '{workflow}.paginate',- parallelism: 20, // Up to 20 pagination workflows in parallel- ratePerSecond: 5, // 5 new executions per second-}--// Layer 3: Single task execution - high concurrency-flowControl: {- key: '{workflow}.execute',- parallelism: 10, // Up to 10 items processed in parallel- ratePerSecond: 5, // 5 new items per second-}-```--**Guidelines**:--- **Layer 1**: Always use `parallelism: 1` to avoid duplicate processing-- **Layer 2**: Moderate concurrency for pagination (typically 10-20)-- **Layer 3**: Higher concurrency for parallel item processing (typically 5-10)-- Adjust `ratePerSecond` based on external API rate limits or resource constraints--### 5. context.run() Best Practices--- Use descriptive step names with prefixes: `{workflow}:step-name`-- Each step should be idempotent (safe to retry)-- Don't nest context.run() calls - keep them flat-- Use unique step names when processing multiple items:--```typescript-// Good: Unique step names-await Promise.all(- items.map((item) => context.run(`{workflow}:execute:${item.id}`, () => processItem(item))),-);--// Bad: Same step name for all items-await Promise.all(- items.map((item) =>- context.run(`{workflow}:execute`, () =>- // ❌ Not unique- processItem(item),- ),- ),-);-```--### 6. Payload Validation--Always validate required parameters at the start:--```typescript-export const { POST } = serve<Payload>(- async (context) => {- const { itemId, configId } = context.requestPayload ?? {};-- // Validate at the start- if (!itemId) {- return { success: false, error: 'Missing itemId in payload' };- }-- if (!configId) {- return { success: false, error: 'Missing configId in payload' };- }-- // Proceed with work...- },- { flowControl: { ... } },-);-```--### 7. Database Connection--Get database connection once per workflow:--```typescript-export const { POST } = serve<Payload>(- async (context) => {- const db = await getServerDB(); // Get once-- // Use in multiple steps- const item = await context.run('get-item', async () => {- return itemModel.findById(db, itemId);- });-- const result = await context.run('save-result', async () => {- return resultModel.create(db, result);- });- },- { flowControl: { ... } },-);-```--### 8. Testing--Create integration tests for workflows:--```typescript-describe('WorkflowName', () => {- it('should process items successfully', async () => {- // Setup test data- const items = await createTestItems();-- // Trigger workflow- await WorkflowClass.triggerProcessItems({ dryRun: false });-- // Wait for completion (use polling or webhook)- await waitForCompletion();-- // Verify results- const results = await getResults();- expect(results).toHaveLength(items.length);- });-- it('should support dryRun mode', async () => {- const result = await WorkflowClass.triggerProcessItems({ dryRun: true });-- expect(result).toMatchObject({- success: true,- dryRun: true,- totalEligible: expect.any(Number),- toProcess: expect.any(Number),- });- });-});-```-------## Examples--### Example 1: Welcome Placeholder--**Use Case**: Generate AI-powered welcome placeholders for users--**Structure**:--- Layer 1: `process-users` - Entry point, checks eligible users-- Layer 2: `paginate-users` - Paginates through active users-- Layer 3: `generate-user` - **Generates placeholders for ONE user**--**Core Patterns Demonstrated**:--1. **Dry-Run Mode**:--```typescript-// Layer 1: process-users-if (dryRun) {- return {- ...result,- dryRun: true,- message: `[DryRun] Would process ${usersNeedingGeneration.length} users`,- };-}-```--2. **Fan-Out Pattern**:--```typescript-// Layer 2: paginate-users-if (userIds.length > CHUNK_SIZE) {- const chunks = chunk(userIds, CHUNK_SIZE);- await Promise.all(- chunks.map((ids, idx) =>- context.run(`welcome-placeholder:fanout:${idx + 1}/${chunks.length}`, () =>- WelcomePlaceholderWorkflow.triggerPaginateUsers({ userIds: ids }),- ),- ),- );-}-```--3. **Single Task Execution**:--```typescript-// Layer 3: generate-user-export const { POST } = serve<GenerateUserPlaceholderPayload>(async (context) => {- const { userId } = context.requestPayload ?? {};-- // Execute for ONE user only- const workflow = new WelcomePlaceholderWorkflow(db, userId);- const placeholders = await context.run('generate', () => workflow.generate());-- return { success: true, userId, placeholdersCount: placeholders.length };-});-```--**Key Features**:--- ✅ Filters users who already have cached placeholders in Redis-- ✅ Supports `paidOnly` flag to process only subscribed users-- ✅ Supports `dryRun` mode for statistics-- ✅ Uses fan-out for large user batches (CHUNK_SIZE=20)-- ✅ Each execution processes exactly ONE user--**Files**:--- `/api/workflows/welcome-placeholder/process-users/route.ts`-- `/api/workflows/welcome-placeholder/paginate-users/route.ts`-- `/api/workflows/welcome-placeholder/generate-user/route.ts`-- `/server/workflows/welcomePlaceholder/index.ts`--### Example 2: Agent Welcome--**Use Case**: Generate welcome messages and open questions for AI agents--**Structure**:--- Layer 1: `process-agents` - Entry point, checks eligible agents-- Layer 2: `paginate-agents` - Paginates through active agents-- Layer 3: `generate-agent` - **Generates welcome data for ONE agent**--**Core Patterns Demonstrated**:--1. **Dry-Run Mode**:--```typescript-// Layer 1: process-agents-if (dryRun) {- return {- ...result,- dryRun: true,- message: `[DryRun] Would process ${agentsNeedingGeneration.length} agents`,- };-}-```--2. **Fan-Out Pattern**: Same as welcome-placeholder--3. **Single Task Execution**:--```typescript-// Layer 3: generate-agent-export const { POST } = serve<GenerateAgentWelcomePayload>(async (context) => {- const { agentId } = context.requestPayload ?? {};-- // Execute for ONE agent only- const workflow = new AgentWelcomeWorkflow(db, agentId);- const data = await context.run('generate', () => workflow.generate());-- return { success: true, agentId, data };-});-```--**Key Features**:--- ✅ Filters agents who already have cached data in Redis-- ✅ Supports `paidOnly` flag for subscribed users' agents only-- ✅ Supports `dryRun` mode for statistics-- ✅ Uses fan-out for large agent batches (CHUNK_SIZE=20)-- ✅ Each execution processes exactly ONE agent--**Files**:--- `/api/workflows/agent-welcome/process-agents/route.ts`-- `/api/workflows/agent-welcome/paginate-agents/route.ts`-- `/api/workflows/agent-welcome/generate-agent/route.ts`-- `/server/workflows/agentWelcome/index.ts`-------## Key Takeaways from Examples--Both workflows follow the **exact same pattern**:--1. **Layer 1** (Entry Point):- - Calculate statistics- - Filter existing items- - Support dry-run mode- - Trigger pagination only if needed--2. **Layer 2** (Pagination):- - Paginate with cursor (PAGE_SIZE=50)- - Fan-out large batches (CHUNK_SIZE=20)- - Trigger Layer 3 for each item- - Recursively process all pages--3. **Layer 3** (Execution):- - Process **ONE item** per execution- - Perform business logic- - Save results- - Return success/failure--The only differences are:--- Entity type (users vs agents)-- Business logic (placeholder generation vs welcome generation)-- Data source (different database queries)-----## Common Pitfalls--### ❌ Don't: Use context.run() without unique names--```typescript-// Bad: Same step name when processing multiple items-await Promise.all(items.map((item) => context.run('process', () => process(item))));-```--```typescript-// Good: Unique step names-await Promise.all(items.map((item) => context.run(`process:${item.id}`, () => process(item))));-```--### ❌ Don't: Forget to validate payload parameters--```typescript-// Bad: No validation-export const { POST } = serve<Payload>(async (context) => {- const { itemId } = context.requestPayload ?? {};- const result = await process(itemId); // May fail with undefined-});-```--```typescript-// Good: Validate early-export const { POST } = serve<Payload>(async (context) => {- const { itemId } = context.requestPayload ?? {};-- if (!itemId) {- return { success: false, error: 'Missing itemId' };- }+## Where to Go Next- const result = await process(itemId);-});-```--### ❌ Don't: Skip filtering existing items--```typescript-// Bad: No filtering, may duplicate work-const allItems = await getAllItems();-await Promise.all(allItems.map((item) => triggerExecute(item)));-```+Pick the reference that matches what you're doing:-```typescript-// Good: Filter existing items first-const allItems = await getAllItems();-const itemsNeedingProcessing = await filterExisting(allItems);-await Promise.all(itemsNeedingProcessing.map((item) => triggerExecute(item)));-```--### ❌ Don't: Use inconsistent logging--```typescript-// Bad: Inconsistent prefixes and formats-console.log('Starting workflow');-log.info('Processing item:', itemId);-console.log(`Done with ${itemId}`);-```--```typescript-// Good: Consistent structured logging-console.log('[workflow:layer] Starting with payload:', payload);-console.log('[workflow:layer] Processing item:', { itemId });-console.log('[workflow:layer] Completed:', { itemId, result });-```+| You want to... | Read |+| ---------------------------------------------------- | ---------------------------------------------------------------- |+| Write the Workflow class + 3 routes from scratch | [`references/implementation.md`](./references/implementation.md) |+| Tune flowControl, error handling, logging, testing | [`references/best-practices.md`](./references/best-practices.md) |+| See two real workflows end-to-end | [`references/examples.md`](./references/examples.md) |+| Deploy on lobehub-cloud (re-exports, cloud-only ops) | [`references/cloud.md`](./references/cloud.md) |----## Environment Variables Required+## Environment Variables```bash# Required for all workflows@@ -1081,39 +145,39 @@ APP_URL=https://your-app.com # Base URL for workflow endpointsQSTASH_TOKEN=qstash_xxx # QStash authentication token# Optional (for custom QStash URL)-QSTASH_URL=https://custom-qstash.com # Custom QStash endpoint+QSTASH_URL=https://custom-qstash.com```---## Checklist for New Workflows-### Planning Phase+### Planning-- [ ] Identify entity to process (users, agents, items, etc.)-- [ ] Define business logic for single item execution-- [ ] Determine filtering logic (Redis cache, database state, etc.)+- [ ] Identify the entity to process (users, agents, items, …)+- [ ] Define the per-item business logic+- [ ] Determine filtering logic (Redis cache, database state, …)-### Implementation Phase+### Implementation-- [ ] Define payload types with proper TypeScript interfaces+- [ ] Define payload types with TypeScript interfaces- [ ] Create workflow class with static trigger methods-- [ ] **Layer 1**: Implement entry point with **dry-run** support-- [ ] **Layer 1**: Add filtering logic to avoid duplicate work-- [ ] **Layer 2**: Implement pagination with **fan-out** logic-- [ ] **Layer 3**: Implement **single task execution** (ONE item per run)-- [ ] Configure appropriate flowControl for each layer-- [ ] Add consistent logging with workflow prefixes+- [ ] **Layer 1:** entry point with **dry-run** support+- [ ] **Layer 1:** filtering logic to avoid duplicate work+- [ ] **Layer 2:** pagination with **fan-out**+- [ ] **Layer 3:** **single-task execution** (ONE item per run)+- [ ] Configure appropriate `flowControl` for each layer+- [ ] Consistent logging with workflow prefixes- [ ] Validate all required payload parameters-- [ ] Use unique context.run() step names+- [ ] Unique `context.run()` step names### Quality & Deployment- [ ] Return consistent response shapes-- [ ] Configure cloud deployment (see [Cloud Guide](./reference/cloud.md) if using lobehub-cloud)-- [ ] Write integration tests-- [ ] Test with dry-run mode first-- [ ] Test with small batch before full rollout+- [ ] Configure cloud deployment ([`references/cloud.md`](./references/cloud.md) if on lobehub-cloud)+- [ ] Write integration tests (`dryRun` path + full path)+- [ ] Smoke-test with dry-run first+- [ ] Test with a small batch before full rollout---diff --git a/.agents/skills/upstash-workflow/references/best-practices.md b/.agents/skills/upstash-workflow/references/best-practices.mdnew file mode 100644index 00000000000..b1b97786b51--- /dev/null+++ b/.agents/skills/upstash-workflow/references/best-practices.md@@ -0,0 +1,226 @@+# Best Practices & Common Pitfalls++Apply these once your scaffold from `implementation.md` is in place.++## Table of Contents++1. [Error Handling](#1-error-handling)+2. [Logging](#2-logging)+3. [Return Values](#3-return-values)+4. [flowControl Configuration](#4-flowcontrol-configuration)+5. [context.run() Best Practices](#5-contextrun-best-practices)+6. [Payload Validation](#6-payload-validation)+7. [Database Connection](#7-database-connection)+8. [Testing](#8-testing)+9. [Common Pitfalls](#common-pitfalls)++---++## 1. Error Handling++```typescript+export const { POST } = serve<Payload>(+ async (context) => {+ const { itemId } = context.requestPayload ?? {};++ if (!itemId) {+ return { success: false, error: 'Missing itemId in payload' };+ }++ try {+ const result = await context.run('step-name', () => doWork(itemId));+ return { success: true, itemId, result };+ } catch (error) {+ console.error('[workflow:error]', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+ },+ { flowControl: { ... } },+);+```++## 2. Logging++Consistent prefixes make debugging much easier across QStash dashboards and grep:++```typescript+console.log('[{workflow}:{layer}] Starting with payload:', payload);+console.log('[{workflow}:{layer}] Processing items:', { count: items.length });+console.log('[{workflow}:{layer}] Completed:', result);+console.error('[{workflow}:{layer}:error]', error);+```++## 3. Return Values++Pick the shape that matches the layer's purpose — entry points return statistics, execution layers return per-item results.++```typescript+// Success+return { success: true, itemId, result, message: 'Optional success message' };++// Error+return { success: false, error: 'Error description', itemId };++// Statistics (entry point)+return {+ success: true,+ totalEligible: 100,+ toProcess: 80,+ alreadyProcessed: 20,+ dryRun: true, // if applicable+ message: 'Summary message',+};+```++## 4. flowControl Configuration++Tune concurrency by layer — entry points are singletons, execution layers fan out.++```typescript+// Layer 1: Entry — single instance to avoid duplicate processing+flowControl: { key: '{workflow}.process', parallelism: 1, ratePerSecond: 1 }++// Layer 2: Pagination — moderate concurrency+flowControl: { key: '{workflow}.paginate', parallelism: 20, ratePerSecond: 5 }++// Layer 3: Execution — higher concurrency for parallel item work+flowControl: { key: '{workflow}.execute', parallelism: 10, ratePerSecond: 5 }+```++**Why these defaults:**++- **Layer 1** always uses `parallelism: 1` so concurrent triggers don't both start the same batch.+- **Layer 2** can fan out widely (10-20) since pagination is cheap.+- **Layer 3** caps at 5-10 by default; raise/lower based on external API rate limits.++## 5. context.run() Best Practices++- Use descriptive step names with prefixes: `{workflow}:step-name`+- Each step should be idempotent (safe to retry)+- Don't nest `context.run()` calls — keep them flat+- Use unique step names when processing multiple items:++```typescript+// ✅ Unique step names+await Promise.all(+ items.map((item) => context.run(`{workflow}:execute:${item.id}`, () => processItem(item))),+);++// ❌ Same step name — Upstash de-dupes by step name and you'll lose data+await Promise.all(items.map((item) => context.run(`{workflow}:execute`, () => processItem(item))));+```++## 6. Payload Validation++Validate at the top so failures are explicit, not silent `undefined` cascades:++```typescript+export const { POST } = serve<Payload>(+ async (context) => {+ const { itemId, configId } = context.requestPayload ?? {};++ if (!itemId) return { success: false, error: 'Missing itemId in payload' };+ if (!configId) return { success: false, error: 'Missing configId in payload' };++ // Proceed with work...+ },+ { flowControl: { ... } },+);+```++## 7. Database Connection++Get the connection once per workflow — `getServerDB()` is async, repeating it inside each step adds latency:++```typescript+export const { POST } = serve<Payload>(+ async (context) => {+ const db = await getServerDB();++ const item = await context.run('get-item', () => itemModel.findById(db, itemId));+ const result = await context.run('save-result', () => resultModel.create(db, result));+ },+ { flowControl: { ... } },+);+```++## 8. Testing++Integration tests should exercise both the dry-run statistics path and the full execution path:++```typescript+describe('WorkflowName', () => {+ it('should process items successfully', async () => {+ const items = await createTestItems();+ await WorkflowClass.triggerProcessItems({ dryRun: false });+ await waitForCompletion();+ const results = await getResults();+ expect(results).toHaveLength(items.length);+ });++ it('should support dryRun mode', async () => {+ const result = await WorkflowClass.triggerProcessItems({ dryRun: true });+ expect(result).toMatchObject({+ success: true,+ dryRun: true,+ totalEligible: expect.any(Number),+ toProcess: expect.any(Number),+ });+ });+});+```++---++## Common Pitfalls++### ❌ Reusing `context.run()` step names++```typescript+// Bad — Upstash dedupes by step name+await Promise.all(items.map((item) => context.run('process', () => process(item))));++// Good+await Promise.all(items.map((item) => context.run(`process:${item.id}`, () => process(item))));+```++### ❌ Skipping payload validation++```typescript+// Bad — undefined cascades into a confusing failure later+const { itemId } = context.requestPayload ?? {};+const result = await process(itemId);++// Good — fail fast with a clear error+if (!itemId) return { success: false, error: 'Missing itemId' };+```++### ❌ Skipping the filter step++```typescript+// Bad — duplicates work for items that were already processed+const allItems = await getAllItems();+await Promise.all(allItems.map((item) => triggerExecute(item)));++// Good — keeps the pipeline idempotent+const allItems = await getAllItems();+const itemsNeedingProcessing = await filterExisting(allItems);+await Promise.all(itemsNeedingProcessing.map((item) => triggerExecute(item)));+```++### ❌ Inconsistent logging++```typescript+// Bad — different prefixes, mixed formats+console.log('Starting workflow');+log.info('Processing item:', itemId);+console.log(`Done with ${itemId}`);++// Good — uniform prefix lets you grep by workflow+layer+console.log('[workflow:layer] Starting with payload:', payload);+console.log('[workflow:layer] Processing item:', { itemId });+console.log('[workflow:layer] Completed:', { itemId, result });+```diff --git a/.agents/skills/upstash-workflow/reference/cloud.md b/.agents/skills/upstash-workflow/references/cloud.mdsimilarity index 91%rename from .agents/skills/upstash-workflow/reference/cloud.mdrename to .agents/skills/upstash-workflow/references/cloud.mdindex 18f5c8300ca..a4d60b2437c 100644--- a/.agents/skills/upstash-workflow/reference/cloud.md+++ b/.agents/skills/upstash-workflow/references/cloud.md@@ -1,6 +1,20 @@# Cloud Project Workflow Configuration-This document covers cloud-specific workflow configurations and patterns for the lobehub-cloud project.+Cloud-specific workflow configurations and patterns for the lobehub-cloud project.++## Table of Contents++1. [Overview](#overview)+2. [Directory Structure](#directory-structure) — submodule + cloud layout+3. [Cloud-Specific Patterns](#cloud-specific-patterns) — cloud-only workflows + re-export pattern+4. [TypeScript Path Mappings](#typescript-path-mappings)+5. [Workflow Class Location](#workflow-class-location) — cloud-only vs shared+6. [Environment Variables](#environment-variables)+7. [Best Practices](#best-practices) — decide cloud vs OSS, re-export rules, naming+8. [Migration Guide](#migration-guide) — moving workflows from cloud to lobehub+9. [Examples](#examples) — `welcome-placeholder`, `agent-eval-run`+10. [Troubleshooting](#troubleshooting) — circular imports, 404s, type errors+11. [Related Documentation](#related-documentation)## Overview@@ -15,7 +29,7 @@ The lobehub-cloud project extends the open-source lobehub codebase with cloud-sp### Lobehub Submodule (Open-source)-```+```textlobehub/└── src/├── app/(backend)/api/workflows/@@ -28,7 +42,7 @@ lobehub/### Lobehub-cloud (Proprietary)-```+```textlobehub-cloud/└── src/├── app/(backend)/api/workflows/@@ -60,7 +74,7 @@ lobehub-cloud/**Structure**:-```+```textlobehub-cloud/src/├── app/(backend)/api/workflows/│ └── feature-name/@@ -162,7 +176,7 @@ This allows cloud to override specific modules while using lobehub defaults.Place workflow class in cloud:-```+```textlobehub-cloud/src/server/workflows/featureName/index.ts```@@ -170,7 +184,7 @@ lobehub-cloud/src/server/workflows/featureName/index.tsPlace workflow class in lobehub, re-export in cloud if needed:-```+```textlobehub/src/server/workflows/featureName/index.ts```@@ -245,7 +259,7 @@ For shared features:Follow consistent naming across lobehub and cloud:-```+```text# Both should use same structurelobehub/src/app/(backend)/api/workflows/feature-name/lobehub-cloud/src/app/(backend)/api/workflows/feature-name/@@ -306,7 +320,7 @@ import { Workflow } from 'lobehub/src/server/workflows/feature';**Structure**:-```+```textlobehub-cloud/├── src/app/(backend)/api/workflows/welcome-placeholder/│ ├── process-users/route.tsdiff --git a/.agents/skills/upstash-workflow/references/examples.md b/.agents/skills/upstash-workflow/references/examples.mdnew file mode 100644index 00000000000..33deffb4bd9--- /dev/null+++ b/.agents/skills/upstash-workflow/references/examples.md@@ -0,0 +1,91 @@+# Worked Examples++Two real workflows already in the codebase that follow this skill's pattern verbatim. Skim them when you want to see the pattern applied to concrete entities.++## Example 1: Welcome Placeholder++**Use case:** Generate AI-powered welcome placeholders for users.++**Structure:**++- Layer 1: `process-users` — entry point, checks eligible users+- Layer 2: `paginate-users` — paginates through active users+- Layer 3: `generate-user` — generates placeholders for ONE user++**Key features:**++- Filters users who already have cached placeholders in Redis+- `paidOnly` flag to scope to subscribed users+- `dryRun` mode for statistics+- Fan-out for large user batches (`CHUNK_SIZE=20`)++**Layer 3 shape:**++```typescript+export const { POST } = serve<GenerateUserPlaceholderPayload>(async (context) => {+ const { userId } = context.requestPayload ?? {};++ const workflow = new WelcomePlaceholderWorkflow(db, userId);+ const placeholders = await context.run('generate', () => workflow.generate());++ return { success: true, userId, placeholdersCount: placeholders.length };+});+```++**Files:**++- `/api/workflows/welcome-placeholder/process-users/route.ts`+- `/api/workflows/welcome-placeholder/paginate-users/route.ts`+- `/api/workflows/welcome-placeholder/generate-user/route.ts`+- `/server/workflows/welcomePlaceholder/index.ts`++---++## Example 2: Agent Welcome++**Use case:** Generate welcome messages and open questions for AI agents.++**Structure:**++- Layer 1: `process-agents` — entry point, checks eligible agents+- Layer 2: `paginate-agents` — paginates through active agents+- Layer 3: `generate-agent` — generates welcome data for ONE agent++**Key features:**++- Filters agents who already have cached data in Redis+- `paidOnly` flag for subscribed users' agents only+- `dryRun` mode for statistics+- Fan-out for large agent batches (`CHUNK_SIZE=20`)++**Layer 3 shape:**++```typescript+export const { POST } = serve<GenerateAgentWelcomePayload>(async (context) => {+ const { agentId } = context.requestPayload ?? {};++ const workflow = new AgentWelcomeWorkflow(db, agentId);+ const data = await context.run('generate', () => workflow.generate());++ return { success: true, agentId, data };+});+```++**Files:**++- `/api/workflows/agent-welcome/process-agents/route.ts`+- `/api/workflows/agent-welcome/paginate-agents/route.ts`+- `/api/workflows/agent-welcome/generate-agent/route.ts`+- `/server/workflows/agentWelcome/index.ts`++---++## What's identical, what differs++Both workflows are the **same pattern** — they only differ in:++- Entity type (users vs agents)+- Business logic (placeholder generation vs welcome generation)+- Data source (different database queries)++Everything else — the 3-layer split, dry-run handling, fan-out, filter-existing, flowControl tuning — is identical. That's the whole point: once you internalize the pattern, adding a new workflow is mostly entity-substitution.diff --git a/.agents/skills/upstash-workflow/references/implementation.md b/.agents/skills/upstash-workflow/references/implementation.mdnew file mode 100644index 00000000000..6b8f260ee77--- /dev/null+++ b/.agents/skills/upstash-workflow/references/implementation.md@@ -0,0 +1,333 @@+# Implementation Patterns++Full code templates for the 3-layer architecture. Read this when actually writing workflow files.++## Table of Contents++1. [Workflow Class](#workflow-class) — `src/server/workflows/{workflowName}/index.ts`+2. [Layer 1: Entry Point](#layer-1-entry-point-process-) — `process-*` route+3. [Layer 2: Pagination](#layer-2-pagination-paginate-) — `paginate-*` route+4. [Layer 3: Execution](#layer-3-execution-execute--generate-) — `execute-*` / `generate-*` route++---++## Workflow Class++**Location:** `src/server/workflows/{workflowName}/index.ts`++```typescript+import { Client } from '@upstash/workflow';+import debug from 'debug';++const log = debug('lobe-server:workflows:{workflow-name}');++// Workflow paths+const WORKFLOW_PATHS = {+ processItems: '/api/workflows/{workflow-name}/process-items',+ paginateItems: '/api/workflows/{workflow-name}/paginate-items',+ executeItem: '/api/workflows/{workflow-name}/execute-item',+} as const;++// Payload types+export interface ProcessItemsPayload {+ dryRun?: boolean;+ force?: boolean;+}++export interface PaginateItemsPayload {+ cursor?: string;+ itemIds?: string[]; // For fanout chunks+}++export interface ExecuteItemPayload {+ itemId: string;+}++const getWorkflowUrl = (path: string): string => {+ const baseUrl = process.env.APP_URL;+ if (!baseUrl) throw new Error('APP_URL is required to trigger workflows');+ return new URL(path, baseUrl).toString();+};++const getWorkflowClient = (): Client => {+ const token = process.env.QSTASH_TOKEN;+ if (!token) throw new Error('QSTASH_TOKEN is required to trigger workflows');++ const config: ConstructorParameters<typeof Client>[0] = { token };+ if (process.env.QSTASH_URL) {+ (config as Record<string, unknown>).url = process.env.QSTASH_URL;+ }+ return new Client(config);+};++export class {WorkflowName}Workflow {+ private static client: Client;++ private static getClient(): Client {+ if (!this.client) this.client = getWorkflowClient();+ return this.client;+ }++ static triggerProcessItems(payload: ProcessItemsPayload) {+ const url = getWorkflowUrl(WORKFLOW_PATHS.processItems);+ log('Triggering process-items workflow');+ return this.getClient().trigger({ body: payload, url });+ }++ static triggerPaginateItems(payload: PaginateItemsPayload) {+ const url = getWorkflowUrl(WORKFLOW_PATHS.paginateItems);+ log('Triggering paginate-items workflow');+ return this.getClient().trigger({ body: payload, url });+ }++ static triggerExecuteItem(payload: ExecuteItemPayload) {+ const url = getWorkflowUrl(WORKFLOW_PATHS.executeItem);+ log('Triggering execute-item workflow: %s', payload.itemId);+ return this.getClient().trigger({ body: payload, url });+ }++ /**+ * Filter items that need processing (e.g. check Redis cache, database state).+ * Return only the ones that actually need work — keeps the pipeline idempotent.+ */+ static async filterItemsNeedingProcessing(itemIds: string[]): Promise<string[]> {+ if (itemIds.length === 0) return [];+ // Check existing state and return items that need processing+ return itemIds;+ }+}+```++---++## Layer 1: Entry Point (process-\*)++**Purpose:** Validates prerequisites, calculates statistics, supports dry-run mode.++```typescript+import { serve } from '@upstash/workflow/nextjs';+import { getServerDB } from '@/database/server';+import { WorkflowClass, type ProcessPayload } from '@/server/workflows/{workflowName}';++export const { POST } = serve<ProcessPayload>(+ async (context) => {+ const { dryRun, force } = context.requestPayload ?? {};++ console.log('[{workflow}:process] Starting with payload:', { dryRun, force });++ const allItemIds = await context.run('{workflow}:get-all-items', async () => {+ const db = await getServerDB();+ // Query database for eligible items+ return items.map((item) => item.id);+ });++ console.log('[{workflow}:process] Total eligible items:', allItemIds.length);++ if (allItemIds.length === 0) {+ return { success: true, totalEligible: 0, message: 'No eligible items found' };+ }++ const itemsNeedingProcessing = await context.run('{workflow}:filter-existing', () =>+ WorkflowClass.filterItemsNeedingProcessing(allItemIds),+ );++ const result = {+ success: true,+ totalEligible: allItemIds.length,+ toProcess: itemsNeedingProcessing.length,+ alreadyProcessed: allItemIds.length - itemsNeedingProcessing.length,+ };++ // Dry-run short-circuits before any side effects+ if (dryRun) {+ console.log('[{workflow}:process] Dry run mode, returning statistics only');+ return {+ ...result,+ dryRun: true,+ message: `[DryRun] Would process ${itemsNeedingProcessing.length} items`,+ };+ }++ if (itemsNeedingProcessing.length === 0) {+ return { ...result, message: 'All items already processed' };+ }++ await context.run('{workflow}:trigger-paginate', () => WorkflowClass.triggerPaginateItems({}));++ return {+ ...result,+ message: `Triggered pagination for ${itemsNeedingProcessing.length} items`,+ };+ },+ {+ flowControl: {+ key: '{workflow}.process',+ parallelism: 1, // single instance — avoids duplicate processing+ ratePerSecond: 1,+ },+ },+);+```++---++## Layer 2: Pagination (paginate-\*)++**Purpose:** Handles cursor-based pagination, implements fan-out for large batches.++```typescript+import { serve } from '@upstash/workflow/nextjs';+import { chunk } from 'es-toolkit/compat';+import { getServerDB } from '@/database/server';+import { WorkflowClass, type PaginatePayload } from '@/server/workflows/{workflowName}';++const PAGE_SIZE = 50;+const CHUNK_SIZE = 20;++export const { POST } = serve<PaginatePayload>(+ async (context) => {+ const { cursor, itemIds: payloadItemIds } = context.requestPayload ?? {};++ console.log('[{workflow}:paginate] Starting:', {+ cursor,+ itemIdsCount: payloadItemIds?.length ?? 0,+ });++ // If specific itemIds were passed in (from a fanout chunk), process them directly+ if (payloadItemIds && payloadItemIds.length > 0) {+ await Promise.all(+ payloadItemIds.map((itemId) =>+ context.run(`{workflow}:execute:${itemId}`, () =>+ WorkflowClass.triggerExecuteItem({ itemId }),+ ),+ ),+ );+ return { success: true, processedItems: payloadItemIds.length };+ }++ // Paginate through all items+ const itemBatch = await context.run('{workflow}:get-batch', async () => {+ const db = await getServerDB();+ const items = await db.query(...);+ if (!items.length) return { ids: [] };+ const last = items.at(-1);+ return {+ ids: items.map((item) => item.id),+ cursor: last ? last.id : undefined,+ };+ });++ const batchItemIds = itemBatch.ids;+ const nextCursor = 'cursor' in itemBatch ? itemBatch.cursor : undefined;++ if (batchItemIds.length === 0) {+ return { success: true, message: 'Pagination complete' };+ }++ const itemIds = await context.run('{workflow}:filter-existing', () =>+ WorkflowClass.filterItemsNeedingProcessing(batchItemIds),+ );++ if (itemIds.length > 0) {+ if (itemIds.length > CHUNK_SIZE) {+ // Fan out — recursively re-enter pagination with each chunk+ const chunks = chunk(itemIds, CHUNK_SIZE);+ console.log('[{workflow}:paginate] Fanout mode:', {+ chunks: chunks.length,+ chunkSize: CHUNK_SIZE,+ });++ await Promise.all(+ chunks.map((ids, idx) =>+ context.run(`{workflow}:fanout:${idx + 1}/${chunks.length}`, () =>+ WorkflowClass.triggerPaginateItems({ itemIds: ids }),+ ),+ ),+ );+ } else {+ // Process this page directly+ await Promise.all(+ itemIds.map((itemId) =>+ context.run(`{workflow}:execute:${itemId}`, () =>+ WorkflowClass.triggerExecuteItem({ itemId }),+ ),+ ),+ );+ }+ }++ // Tail-call into the next page+ if (nextCursor) {+ await context.run('{workflow}:next-page', () =>+ WorkflowClass.triggerPaginateItems({ cursor: nextCursor }),+ );+ }++ return {+ success: true,+ processedItems: itemIds.length,+ skippedItems: batchItemIds.length - itemIds.length,+ nextCursor: nextCursor ?? null,+ };+ },+ {+ flowControl: {+ key: '{workflow}.paginate',+ parallelism: 20,+ ratePerSecond: 5,+ },+ },+);+```++---++## Layer 3: Execution (execute-\* / generate-\*)++**Purpose:** Performs the actual business logic for exactly ONE item.++```typescript+import { serve } from '@upstash/workflow/nextjs';+import { getServerDB } from '@/database/server';+import { WorkflowClass, type ExecutePayload } from '@/server/workflows/{workflowName}';++export const { POST } = serve<ExecutePayload>(+ async (context) => {+ const { itemId } = context.requestPayload ?? {};++ if (!itemId) {+ return { success: false, error: 'Missing itemId' };+ }++ const db = await getServerDB();++ const item = await context.run('{workflow}:get-item', async () => {+ // Query database for item+ return item;+ });++ if (!item) {+ return { success: false, error: 'Item not found' };+ }++ const result = await context.run('{workflow}:process-item', async () => {+ const workflow = new WorkflowClass(db, itemId);+ return workflow.generate(); // or process(), execute(), etc.+ });++ await context.run('{workflow}:save-result', async () => {+ const workflow = new WorkflowClass(db, itemId);+ return workflow.saveToRedis(result); // or saveToDatabase(), etc.+ });++ return { success: true, itemId, result };+ },+ {+ flowControl: {+ key: '{workflow}.execute',+ parallelism: 10,+ ratePerSecond: 5,+ },+ },+);+```diff --git a/.agents/skills/version-release/SKILL.md b/.agents/skills/version-release/SKILL.mdindex 52763f792fd..328fc85be68 100644--- a/.agents/skills/version-release/SKILL.md+++ b/.agents/skills/version-release/SKILL.md@@ -1,11 +1,13 @@---name: version-releasedescription: "Version release workflow. Use when the user mentions 'release', 'hotfix', 'version upgrade', 'weekly release', or '发版'/'发布'/'小班车'. This skill is for release process and GitHub Release notes (not docs/changelog page writing)."+disable-model-invocation: true+argument-hint: '[minor|patch] [version?]'---# Version Release Workflow-This skill is a router. The detailed steps live in `reference/`.+This skill is a router. The detailed steps live in `references/`.## Scope Boundary (Important)@@ -30,12 +32,12 @@ The primary development branch is **canary**. All day-to-day development happensOnly two release types are used in practice (major releases are extremely rare and can be ignored):-| Type | Use Case | Frequency | Source Branch | PR Title Format | Version | Reference |-| ----- | ---------------------------------------------- | --------------------- | -------------- | ------------------------------------ | ------------- | -------------------------------------- |-| Minor | Feature iteration release | \~Every 4 weeks | canary | `🚀 release: v{x.y.0}` | Manually set | `reference/minor-release.md` |-| Patch | Weekly release / hotfix / model / DB migration | \~Weekly or as needed | canary or main | Custom (e.g. `🚀 release: 20260222`) | Auto patch +1 | `reference/patch-release-scenarios.md` |+| Type | Use Case | Frequency | Source Branch | PR Title Format | Version | Reference |+| ----- | ---------------------------------------------- | --------------------- | -------------- | ------------------------------------ | ------------- | --------------------------------------- |+| Minor | Feature iteration release | \~Every 4 weeks | canary | `🚀 release: v{x.y.0}` | Manually set | `references/minor-release.md` |+| Patch | Weekly release / hotfix / model / DB migration | \~Weekly or as needed | canary or main | Custom (e.g. `🚀 release: 20260222`) | Auto patch +1 | `references/patch-release-scenarios.md` |-For writing the release-note body (any release type), see `reference/release-notes-style.md`.+For writing the release-note body (any release type), see `references/release-notes-style.md`.## Auto-Release Trigger Rules (`auto-tag-release.yml`)@@ -85,9 +87,9 @@ Before creating the release branch, verify the source branch:Pick the right reference and follow it end-to-end:-- **Minor release** → `reference/minor-release.md`-- **Patch release** (weekly / hotfix / model launch / DB migration) → `reference/patch-release-scenarios.md`-- **Writing the PR body / release notes** (any release type) → `reference/release-notes-style.md`+- **Minor release** → `references/minor-release.md`+- **Patch release** (weekly / hotfix / model launch / DB migration) → `references/patch-release-scenarios.md`+- **Writing the PR body / release notes** (any release type) → `references/release-notes-style.md`### Hard Rules (apply to every release type)@@ -95,4 +97,4 @@ Pick the right reference and follow it end-to-end:- **Do NOT** manually create tags — CI handles them.- Minor PR title format is strict (`🚀 release: v{x.y.z}`).- Patch PRs do not need an explicit version number.-- Keep release facts accurate; do not invent metrics or availability statements. Release-note inputs (compare base, PR refs, contributor list) **must be derived from `git`** per `reference/release-notes-style.md` § Computing Inputs — never from memory or descriptions.+- Keep release facts accurate; do not invent metrics or availability statements. Release-note inputs (compare base, PR refs, contributor list) **must be derived from `git`** per `references/release-notes-style.md` § Computing Inputs — never from memory or descriptions.diff --git a/.agents/skills/version-release/reference/changelog-example/db-migration.md b/.agents/skills/version-release/references/changelog-example/db-migration.mdsimilarity index 100%rename from .agents/skills/version-release/reference/changelog-example/db-migration.mdrename to .agents/skills/version-release/references/changelog-example/db-migration.mddiff --git a/.agents/skills/version-release/reference/changelog-example/hotfix.md b/.agents/skills/version-release/references/changelog-example/hotfix.mdsimilarity index 100%rename from .agents/skills/version-release/reference/changelog-example/hotfix.mdrename to .agents/skills/version-release/references/changelog-example/hotfix.mddiff --git a/.agents/skills/version-release/reference/changelog-example/weekly-release.md b/.agents/skills/version-release/references/changelog-example/weekly-release.mdsimilarity index 100%rename from .agents/skills/version-release/reference/changelog-example/weekly-release.mdrename to .agents/skills/version-release/references/changelog-example/weekly-release.mddiff --git a/.agents/skills/version-release/reference/minor-release.md b/.agents/skills/version-release/references/minor-release.mdsimilarity index 100%rename from .agents/skills/version-release/reference/minor-release.mdrename to .agents/skills/version-release/references/minor-release.mddiff --git a/.agents/skills/version-release/reference/patch-release-scenarios.md b/.agents/skills/version-release/references/patch-release-scenarios.mdsimilarity index 100%rename from .agents/skills/version-release/reference/patch-release-scenarios.mdrename to .agents/skills/version-release/references/patch-release-scenarios.mddiff --git a/.agents/skills/version-release/reference/release-notes-style.md b/.agents/skills/version-release/references/release-notes-style.mdsimilarity index 93%rename from .agents/skills/version-release/reference/release-notes-style.mdrename to .agents/skills/version-release/references/release-notes-style.mdindex 60da739930c..ffed37f4c00 100644--- a/.agents/skills/version-release/reference/release-notes-style.md+++ b/.agents/skills/version-release/references/release-notes-style.md@@ -2,6 +2,20 @@Use this guide for **GitHub Release notes** — the body of a release PR that becomes the GitHub Release after merge. Do **not** use it for `docs/changelog/*.mdx` website pages (load `../../docs-changelog/SKILL.md` instead).+## Table of Contents++1. [Positioning](#positioning) — what this style optimizes for+2. [Required Inputs Before Writing](#required-inputs-before-writing)+3. [Computing Inputs (Hard Rules — Verify, Never Guess)](#computing-inputs-hard-rules--verify-never-guess) — base ref, PR refs, metrics, authors, pre-publish verification+4. [Canonical Structure (Long-Form: Minor / Weekly)](#canonical-structure-long-form-minor--weekly)+5. [Variants for Shorter Releases](#variants-for-shorter-releases) — hotfix, DB migration+6. [Writing Rules (Hard)](#writing-rules-hard)+7. [Style Rules (Long-Form)](#style-rules-long-form)+8. [Release Size Heuristics](#release-size-heuristics) — when to use which variant+9. [Contributor Ordering](#contributor-ordering)+10. [Template](#template) — copy-paste skeleton+11. [Quick Checklist](#quick-checklist) — long-form + hotfix+## PositioningThis release-note style is:diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.mdindex 94616de4519..935f6dae283 100644--- a/.agents/skills/zustand/SKILL.md+++ b/.agents/skills/zustand/SKILL.md@@ -1,6 +1,7 @@---name: zustand-description: Zustand state management guide. Use when working with store code (src/store/**), implementing actions, managing state, or creating slices. Triggers on Zustand store development, state management questions, or action implementation.+description: "LobeHub Zustand store conventions: public/internal/dispatch action layers, optimistic update pattern, slice composition via `flattenActions`, and class-based action migration. Use whenever working under `src/store/**`, adding a `createXxxSlice`, writing `internal_*` or `internal_dispatch*` actions, designing `messagesMap`/`topicsMap` reducers, refactoring a `StateCreator` object slice into a `XxxActionImpl` class, or debugging stale store reads. Triggers on `useChatStore`/`useUserStore`/`useGlobalStore`, `createStore`, `flattenActions`, `StoreSetter`, `internal_dispatch`, 'add an action', 'zustand selector', 'store slice', 'class action', 'optimistic update'."+user-invocable: false---# LobeHub Zustand State Management