mirror of
https://github.com/lobehub/lobe-chat.git
synced 2026-06-14 11:40:07 +00:00
Compare commits
269 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c291caedb6 | |||
| 169d5afa93 | |||
| 2dc7b15c31 | |||
| 0b7c917745 | |||
| 400a0205a3 | |||
| 86889b81bd | |||
| d3550afe05 | |||
| 4d240cf7fa | |||
| db45907ab8 | |||
| 76a07d811b | |||
| 616d53e2ec | |||
| 92cb759c37 | |||
| 07f44e2ba2 | |||
| 5920500371 | |||
| 92c70d2485 | |||
| 6c1c60ee27 | |||
| a4a3e024a6 | |||
| e13e0a4db6 | |||
| eb009866cc | |||
| 2ebac4679c | |||
| 51c857e4a5 | |||
| 9cb0560ebf | |||
| 15a50e999a | |||
| 1be9c000ec | |||
| 522dcf789c | |||
| a0c6c9765c | |||
| ab376d9185 | |||
| 08b23a9732 | |||
| 1fece1f8d9 | |||
| 07997b44a5 | |||
| 5d19dbf430 | |||
| 3f1473d65f | |||
| bf5d6ce2f8 | |||
| 6ba657e6d0 | |||
| c2a49342f0 | |||
| d92bb7a8e8 | |||
| f223aeb7f4 | |||
| 90714af0dc | |||
| 8263359cc2 | |||
| 936379bd21 | |||
| a2c2a0ae76 | |||
| 1c1af17716 | |||
| 1cf0257326 | |||
| 138788b1d4 | |||
| b44f79857b | |||
| 58fb45d251 | |||
| 026af3f6bc | |||
| bcae49ff65 | |||
| 89857847bf | |||
| a1a89b3531 | |||
| f234397bf8 | |||
| ceeb9c6613 | |||
| 9ab2f219e4 | |||
| 43578a9bcc | |||
| 4926b20271 | |||
| 521a0a077e | |||
| e733397f5d | |||
| c1521d2aeb | |||
| 466f713ca6 | |||
| 8ced872e53 | |||
| 6ecba929b7 | |||
| 607dfdec96 | |||
| c4d85d100c | |||
| a9511344f9 | |||
| eb1da3c297 | |||
| c8d2f28bf5 | |||
| 46c9cb3b03 | |||
| dc6d5cf489 | |||
| c068363fac | |||
| dd0d4d8890 | |||
| 01606208c5 | |||
| 5fe0ac228e | |||
| 16946a4d5b | |||
| 37e90cebfa | |||
| ee85ea728a | |||
| 9b5b4d2579 | |||
| 5f2f49a26e | |||
| 8ca9c0100e | |||
| 1c11921a32 | |||
| d68acec58e | |||
| 902a265aed | |||
| 9cd63765b0 | |||
| 794fe5f60b | |||
| 5e3a8146d1 | |||
| c1d2e761fe | |||
| 8bc3a8a886 | |||
| 2b2892aa2b | |||
| 984884ba2b | |||
| dc26f23ea0 | |||
| 18ec113bba | |||
| d9b4ab01ce | |||
| 4279f0e57c | |||
| ac0be5ed5c | |||
| 9f22867f3c | |||
| ed4eb874b2 | |||
| 49a8f6b497 | |||
| 3112036b38 | |||
| 7d7af6b8ca | |||
| 27c3a831f2 | |||
| a5c454589d | |||
| 4d3c759d25 | |||
| c8b23c6819 | |||
| eef04c499f | |||
| 4f3055e0c5 | |||
| d9d1d071b7 | |||
| c22cd67b5f | |||
| 687b36c81c | |||
| 6c3e75634f | |||
| 9b8dabc072 | |||
| d286c1a9ad | |||
| c2483f97a0 | |||
| 3152568c7d | |||
| 02f2498140 | |||
| c9b243ca31 | |||
| 0ec6c2f38e | |||
| c960705177 | |||
| c5d41fd2be | |||
| 22072789b6 | |||
| 306c50704e | |||
| 0365a14e16 | |||
| 5fbf4b3cd4 | |||
| b29a533285 | |||
| 7f7eeb8fa8 | |||
| 059d0cc0fc | |||
| 5a30c9a14f | |||
| 5371507b22 | |||
| f84a363b75 | |||
| bbfbc45925 | |||
| 616ac9438c | |||
| ddce51eaba | |||
| bdc901d1dc | |||
| 5ab874e877 | |||
| 28b1455f2f | |||
| e95f7419b9 | |||
| 93bb83db5d | |||
| 01e13959d1 | |||
| ef0e4a6743 | |||
| 4d1508ee9b | |||
| 84ecc1e9f6 | |||
| 093af9889d | |||
| 508c3ae20c | |||
| e7598fe90b | |||
| c2280561f5 | |||
| 9b692c239a | |||
| e32a2fbad4 | |||
| cb688b6cfa | |||
| ef474afe84 | |||
| 7a1e2b6a48 | |||
| cc926f252a | |||
| 4260474f4e | |||
| ed4c5d125e | |||
| 086dd15add | |||
| 1e506c5ebb | |||
| b799c98487 | |||
| 5475188fa0 | |||
| 0674eee0d4 | |||
| 870638ea8a | |||
| b155656a7c | |||
| d8b947828c | |||
| 8310c5755c | |||
| bb2d760b4b | |||
| a9d9e7adf0 | |||
| e28593cc38 | |||
| e51234443a | |||
| a0c4baf1aa | |||
| 1e20edef3d | |||
| 949873adbc | |||
| 5030177f3d | |||
| a96a5576a7 | |||
| 9766d20979 | |||
| 6a4118c628 | |||
| 4fba491793 | |||
| ea951b72d3 | |||
| 4a29904516 | |||
| 5d7ee01bce | |||
| 763352c56a | |||
| 86624e8808 | |||
| f018a7b790 | |||
| 5f10ede77a | |||
| 9312298564 | |||
| 6f08c302ac | |||
| 0aea1b0a3d | |||
| bf9df0424d | |||
| 989223b355 | |||
| d9f91fc23a | |||
| 38e1adba2f | |||
| f91acfca95 | |||
| 1f1c49fc52 | |||
| 8db783b5b8 | |||
| b3e87f6cd4 | |||
| abbf53feda | |||
| 3f432a43d8 | |||
| 8b0d1ec9e3 | |||
| b43cbae2e1 | |||
| d2a042cd95 | |||
| c1916a1996 | |||
| 502d94bd4c | |||
| f4bd332d11 | |||
| 7df81ffaa1 | |||
| ed076b3cf5 | |||
| 0abde1623d | |||
| 481e5c0066 | |||
| 8719354282 | |||
| 5957bd4578 | |||
| 335e246ac5 | |||
| 918d048b3d | |||
| 398d8b7f3c | |||
| 1529f31dff | |||
| b4bd5b288c | |||
| 448cfb2cfd | |||
| d8c3ef3232 | |||
| 2a23fb9a10 | |||
| 82f9cb4486 | |||
| 6419fd32b1 | |||
| 927fe3fd22 | |||
| 03bda41c07 | |||
| e804773a7e | |||
| 67875bd60a | |||
| 916d4841f4 | |||
| d5b1ff20e0 | |||
| 212348eafe | |||
| 43820eeb2e | |||
| 7397d6f8c1 | |||
| 85d5bc9e08 | |||
| 3fbc46b23a | |||
| 6e2ef05270 | |||
| 06d65e9ce5 | |||
| 6002863c17 | |||
| 8f2e72d1b8 | |||
| fcf2444fa8 | |||
| 661f1a80b4 | |||
| 57772d1f3b | |||
| abe4c969a5 | |||
| b767a66d38 | |||
| 53e4228ea7 | |||
| 7efcdd2f7c | |||
| bde1503309 | |||
| 487713361a | |||
| 7bad876259 | |||
| 229200853a | |||
| 5ec89941f3 | |||
| f46916a74d | |||
| 2ee46b8693 | |||
| baf0b56f64 | |||
| 12dc7f90be | |||
| 1b905ede31 | |||
| cfaa911153 | |||
| e17bf4b0cc | |||
| 58cf27dcf8 | |||
| f12d9fbd22 | |||
| d4f72eb752 | |||
| e112cd6f7f | |||
| 9a9147ca7e | |||
| 2d1eec4482 | |||
| c11d6de7db | |||
| bbbe3a8d09 | |||
| e51fbba881 | |||
| 1bfeeea6f4 | |||
| 12d0ec21d0 | |||
| 2bf0a08919 | |||
| 79e146f1a3 | |||
| 0e42ca5ca2 | |||
| 823aa29c67 | |||
| d225da96df | |||
| 0acaf01f9a | |||
| 5a8911b72d | |||
| e6596e94a5 | |||
| 9c09160154 | |||
| d7d186df1a |
@@ -79,7 +79,7 @@ Update all Dockerfiles at the **end** of ENV section:
|
||||
|
||||
- Cover image
|
||||
- 3-4 API dashboard screenshots
|
||||
- 2-3 LobeChat configuration screenshots
|
||||
- 2-3 LobeHub configuration screenshots
|
||||
- Host on LobeHub CDN: `hub-apac-1.lobeobjects.space`
|
||||
|
||||
## Checklist
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
name: agent-tracing
|
||||
description: "Agent tracing CLI for inspecting agent execution snapshots. Use when user mentions 'agent-tracing', 'trace', 'snapshot', wants to debug agent execution, inspect LLM calls, view context engine data, or analyze agent steps. Triggers on agent debugging, trace inspection, or execution analysis tasks."
|
||||
user-invocable: false
|
||||
---
|
||||
|
||||
# Agent Tracing CLI Guide
|
||||
|
||||
`@lobechat/agent-tracing` is a zero-config local dev tool that records agent execution snapshots to disk and provides a CLI to inspect them.
|
||||
|
||||
## How It Works
|
||||
|
||||
In `NODE_ENV=development`, `AgentRuntimeService.executeStep()` automatically records each step to `.agent-tracing/` as partial snapshots. When the operation completes, the partial is finalized into a complete `ExecutionSnapshot` JSON file.
|
||||
|
||||
**Data flow**: executeStep loop -> build `StepPresentationData` -> write partial snapshot to disk -> on completion, finalize to `.agent-tracing/{timestamp}_{traceId}.json`
|
||||
|
||||
**Context engine capture**: In `RuntimeExecutors.ts`, the `call_llm` executor emits a `context_engine_result` event after `serverMessagesEngine()` processes messages. This event carries the full `contextEngineInput` (DB messages, systemRole, model, knowledge, tools, userMemory, etc.) and the processed `output` messages (the final LLM payload).
|
||||
|
||||
## Package Location
|
||||
|
||||
```
|
||||
packages/agent-tracing/
|
||||
src/
|
||||
types.ts # ExecutionSnapshot, StepSnapshot, SnapshotSummary
|
||||
store/
|
||||
types.ts # ISnapshotStore interface
|
||||
file-store.ts # FileSnapshotStore (.agent-tracing/*.json)
|
||||
recorder/
|
||||
index.ts # appendStepToPartial(), finalizeSnapshot()
|
||||
viewer/
|
||||
index.ts # Terminal rendering: renderSnapshot, renderStepDetail, renderMessageDetail, renderSummaryTable
|
||||
cli/
|
||||
index.ts # CLI entry point (#!/usr/bin/env bun)
|
||||
index.ts # Barrel exports
|
||||
```
|
||||
|
||||
## Data Storage
|
||||
|
||||
- Completed snapshots: `.agent-tracing/{ISO-timestamp}_{traceId-short}.json`
|
||||
- Latest symlink: `.agent-tracing/latest.json`
|
||||
- In-progress partials: `.agent-tracing/_partial/{operationId}.json`
|
||||
- `FileSnapshotStore` resolves from `process.cwd()` — **run CLI from the repo root**
|
||||
|
||||
## CLI Commands
|
||||
|
||||
All commands run from the **repo root**:
|
||||
|
||||
```bash
|
||||
# View latest trace (tree overview)
|
||||
agent-tracing trace
|
||||
|
||||
# View specific trace
|
||||
agent-tracing trace <traceId>
|
||||
|
||||
# List recent snapshots
|
||||
agent-tracing list
|
||||
agent-tracing list -l 20
|
||||
|
||||
# Inspect trace detail (overview)
|
||||
agent-tracing inspect <traceId>
|
||||
|
||||
# Inspect specific step (-s is short for --step)
|
||||
agent-tracing inspect <traceId> -s 0
|
||||
|
||||
# View messages (-m is short for --messages)
|
||||
agent-tracing inspect <traceId> -s 0 -m
|
||||
|
||||
# View full content of a specific message (by index shown in -m output)
|
||||
agent-tracing inspect <traceId> -s 0 --msg 2
|
||||
agent-tracing inspect <traceId> -s 0 --msg-input 1
|
||||
|
||||
# View tool call/result details (-t is short for --tools)
|
||||
agent-tracing inspect <traceId> -s 1 -t
|
||||
|
||||
# View raw events (-e is short for --events)
|
||||
agent-tracing inspect <traceId> -s 0 -e
|
||||
|
||||
# View runtime context (-c is short for --context)
|
||||
agent-tracing inspect <traceId> -s 0 -c
|
||||
|
||||
# Raw JSON output (-j is short for --json)
|
||||
agent-tracing inspect <traceId> -j
|
||||
agent-tracing inspect <traceId> -s 0 -j
|
||||
```
|
||||
|
||||
## Typical Debug Workflow
|
||||
|
||||
```bash
|
||||
# 1. Trigger an agent operation in the dev UI
|
||||
|
||||
# 2. See the overview
|
||||
agent-tracing trace
|
||||
|
||||
# 3. List all traces, get traceId
|
||||
agent-tracing list
|
||||
|
||||
# 4. Inspect a specific step's messages to see what was sent to the LLM
|
||||
agent-tracing inspect TRACE_ID -s 0 -m
|
||||
|
||||
# 5. Drill into a truncated message for full content
|
||||
agent-tracing inspect TRACE_ID -s 0 --msg 2
|
||||
|
||||
# 6. Check tool calls and results
|
||||
agent-tracing inspect 1 -t TRACE_ID -s
|
||||
```
|
||||
|
||||
## Key Types
|
||||
|
||||
```typescript
|
||||
interface ExecutionSnapshot {
|
||||
traceId: string;
|
||||
operationId: string;
|
||||
model?: string;
|
||||
provider?: string;
|
||||
startedAt: number;
|
||||
completedAt?: number;
|
||||
completionReason?:
|
||||
| 'done'
|
||||
| 'error'
|
||||
| 'interrupted'
|
||||
| 'max_steps'
|
||||
| 'cost_limit'
|
||||
| 'waiting_for_human';
|
||||
totalSteps: number;
|
||||
totalTokens: number;
|
||||
totalCost: number;
|
||||
error?: { type: string; message: string };
|
||||
steps: StepSnapshot[];
|
||||
}
|
||||
|
||||
interface StepSnapshot {
|
||||
stepIndex: number;
|
||||
stepType: 'call_llm' | 'call_tool';
|
||||
executionTimeMs: number;
|
||||
content?: string; // LLM output
|
||||
reasoning?: string; // Reasoning/thinking
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
toolsCalling?: Array<{ apiName: string; identifier: string; arguments?: string }>;
|
||||
toolsResult?: Array<{
|
||||
apiName: string;
|
||||
identifier: string;
|
||||
isSuccess?: boolean;
|
||||
output?: string;
|
||||
}>;
|
||||
messages?: any[]; // DB messages before step
|
||||
context?: { phase: string; payload?: unknown; stepContext?: unknown };
|
||||
events?: Array<{ type: string; [key: string]: unknown }>;
|
||||
// context_engine_result event contains:
|
||||
// input: full contextEngineInput (messages, systemRole, model, knowledge, tools, userMemory, ...)
|
||||
// output: processed messages array (final LLM payload)
|
||||
}
|
||||
```
|
||||
|
||||
## --messages Output Structure
|
||||
|
||||
When using `--messages`, the output shows three sections (if context engine data is available):
|
||||
|
||||
1. **Context Engine Input** — DB messages passed to the engine, with `[0]`, `[1]`, ... indices. Use `--msg-input N` to view full content.
|
||||
2. **Context Engine Params** — systemRole, model, provider, knowledge, tools, userMemory, etc.
|
||||
3. **Final LLM Payload** — Processed messages after context engine (system date injection, user memory, history truncation, etc.), with `[0]`, `[1]`, ... indices. Use `--msg N` to view full content.
|
||||
|
||||
## Integration Points
|
||||
|
||||
- **Recording**: `src/server/services/agentRuntime/AgentRuntimeService.ts` — in the `executeStep()` method, after building `stepPresentationData`, writes partial snapshot in dev mode
|
||||
- **Context engine event**: `src/server/modules/AgentRuntime/RuntimeExecutors.ts` — in `call_llm` executor, after `serverMessagesEngine()` returns, emits `context_engine_result` event
|
||||
- **Store**: `FileSnapshotStore` reads/writes to `.agent-tracing/` relative to `process.cwd()`
|
||||
@@ -0,0 +1,153 @@
|
||||
---
|
||||
name: chat-sdk
|
||||
description: >
|
||||
Build multi-platform chat bots with Chat SDK (`chat` npm package). Use when developers want to
|
||||
(1) Build a Slack, Teams, Google Chat, Discord, GitHub, or Linear bot,
|
||||
(2) Use the Chat SDK to handle mentions, messages, reactions, slash commands, cards, modals, or streaming,
|
||||
(3) Set up webhook handlers for chat platforms,
|
||||
(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.
|
||||
---
|
||||
|
||||
# Chat SDK
|
||||
|
||||
Unified TypeScript SDK for building chat bots across Slack, Teams, Google Chat, Discord, GitHub, and Linear. Write bot logic once, deploy everywhere.
|
||||
|
||||
## Critical: Read the bundled docs
|
||||
|
||||
The `chat` package ships with full documentation in `node_modules/chat/docs/` and TypeScript source types. **Always read these before writing code:**
|
||||
|
||||
```
|
||||
node_modules/chat/docs/ # Full documentation (MDX files)
|
||||
node_modules/chat/dist/ # Built types (.d.ts files)
|
||||
```
|
||||
|
||||
Key docs to read based on task:
|
||||
|
||||
- `docs/getting-started.mdx` — setup guides
|
||||
- `docs/usage.mdx` — event handlers, threads, messages, channels
|
||||
- `docs/streaming.mdx` — AI streaming with AI SDK
|
||||
- `docs/cards.mdx` — JSX interactive cards
|
||||
- `docs/actions.mdx` — button/dropdown handlers
|
||||
- `docs/modals.mdx` — form dialogs (Slack only)
|
||||
- `docs/adapters/*.mdx` — platform-specific adapter setup
|
||||
- `docs/state/*.mdx` — state adapter config (Redis, ioredis, memory)
|
||||
|
||||
Also read the TypeScript types from `node_modules/chat/dist/` to understand the full API surface.
|
||||
|
||||
## Quick start
|
||||
|
||||
```typescript
|
||||
import { Chat } from 'chat';
|
||||
import { createSlackAdapter } from '@chat-adapter/slack';
|
||||
import { createRedisState } from '@chat-adapter/state-redis';
|
||||
|
||||
const bot = new Chat({
|
||||
userName: 'mybot',
|
||||
adapters: {
|
||||
slack: createSlackAdapter({
|
||||
botToken: process.env.SLACK_BOT_TOKEN!,
|
||||
signingSecret: process.env.SLACK_SIGNING_SECRET!,
|
||||
}),
|
||||
},
|
||||
state: createRedisState({ url: process.env.REDIS_URL! }),
|
||||
});
|
||||
|
||||
bot.onNewMention(async (thread) => {
|
||||
await thread.subscribe();
|
||||
await thread.post("Hello! I'm listening to this thread.");
|
||||
});
|
||||
|
||||
bot.onSubscribedMessage(async (thread, message) => {
|
||||
await thread.post(`You said: ${message.text}`);
|
||||
});
|
||||
```
|
||||
|
||||
## Core concepts
|
||||
|
||||
- **Chat** — main entry point, coordinates adapters and routes events
|
||||
- **Adapters** — platform-specific (Slack, Teams, GChat, Discord, GitHub, Linear)
|
||||
- **State** — pluggable persistence (Redis for prod, memory for dev)
|
||||
- **Thread** — conversation thread with `post()`, `subscribe()`, `startTyping()`
|
||||
- **Message** — normalized format with `text`, `formatted` (mdast AST), `raw`
|
||||
- **Channel** — container for threads, supports listing and posting
|
||||
|
||||
## Event handlers
|
||||
|
||||
| Handler | Trigger |
|
||||
| -------------------------- | ------------------------------------------------- |
|
||||
| `onNewMention` | Bot @-mentioned in unsubscribed thread |
|
||||
| `onSubscribedMessage` | Any message in subscribed thread |
|
||||
| `onNewMessage(regex)` | Messages matching pattern in unsubscribed threads |
|
||||
| `onSlashCommand("/cmd")` | Slash command invocations |
|
||||
| `onReaction(emojis)` | Emoji reactions added/removed |
|
||||
| `onAction(actionId)` | Button clicks and dropdown selections |
|
||||
| `onAssistantThreadStarted` | Slack Assistants API thread opened |
|
||||
| `onAppHomeOpened` | Slack App Home tab opened |
|
||||
|
||||
## Streaming
|
||||
|
||||
Pass any `AsyncIterable<string>` to `thread.post()`. Works with AI SDK's `textStream`:
|
||||
|
||||
```typescript
|
||||
import { ToolLoopAgent } from 'ai';
|
||||
const agent = new ToolLoopAgent({ model: 'anthropic/claude-4.5-sonnet' });
|
||||
|
||||
bot.onNewMention(async (thread, message) => {
|
||||
const result = await agent.stream({ prompt: message.text });
|
||||
await thread.post(result.textStream);
|
||||
});
|
||||
```
|
||||
|
||||
## Cards (JSX)
|
||||
|
||||
Set `jsxImportSource: "chat"` in tsconfig. Components: `Card`, `CardText`, `Button`, `Actions`, `Fields`, `Field`, `Select`, `SelectOption`, `Image`, `Divider`, `LinkButton`, `Section`, `RadioSelect`.
|
||||
|
||||
```tsx
|
||||
await thread.post(
|
||||
<Card title="Order #1234">
|
||||
<CardText>Your order has been received!</CardText>
|
||||
<Actions>
|
||||
<Button id="approve" style="primary">
|
||||
Approve
|
||||
</Button>
|
||||
<Button id="reject" style="danger">
|
||||
Reject
|
||||
</Button>
|
||||
</Actions>
|
||||
</Card>,
|
||||
);
|
||||
```
|
||||
|
||||
## Packages
|
||||
|
||||
| Package | Purpose |
|
||||
| ----------------------------- | ----------------------------- |
|
||||
| `chat` | Core SDK |
|
||||
| `@chat-adapter/slack` | Slack |
|
||||
| `@chat-adapter/teams` | Microsoft Teams |
|
||||
| `@chat-adapter/gchat` | Google Chat |
|
||||
| `@chat-adapter/discord` | Discord |
|
||||
| `@chat-adapter/github` | GitHub Issues |
|
||||
| `@chat-adapter/linear` | Linear Issues |
|
||||
| `@chat-adapter/state-redis` | Redis state (production) |
|
||||
| `@chat-adapter/state-ioredis` | ioredis state (alternative) |
|
||||
| `@chat-adapter/state-memory` | In-memory state (development) |
|
||||
|
||||
## Changesets (Release Flow)
|
||||
|
||||
This monorepo uses [Changesets](https://github.com/changesets/changesets) for versioning and changelogs. Every PR that changes a package's behavior must include a changeset.
|
||||
|
||||
```bash
|
||||
pnpm changeset
|
||||
# → select affected package(s) (e.g. @chat-adapter/slack, chat)
|
||||
# → choose bump type: patch (fixes), minor (features), major (breaking)
|
||||
# → write a short summary for the CHANGELOG
|
||||
```
|
||||
|
||||
This creates a file in `.changeset/` — commit it with the PR. When merged to `main`, the Changesets GitHub Action opens a "Version Packages" PR to bump versions and update CHANGELOGs. Merging that PR publishes to npm.
|
||||
|
||||
## Webhook setup
|
||||
|
||||
Each adapter exposes a webhook handler via `bot.webhooks.{platform}`. Wire these to your HTTP framework's routes (e.g. Next.js API routes, Hono, Express).
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,93 @@
|
||||
---
|
||||
name: db-migrations
|
||||
description: Database migration guide. Use when generating migrations, writing migration SQL, or modifying database schemas. Triggers on migration generation, schema changes, or idempotent SQL questions.
|
||||
---
|
||||
|
||||
# Database Migrations Guide
|
||||
|
||||
## Step 1: Generate Migrations
|
||||
|
||||
```bash
|
||||
bun run db:generate
|
||||
```
|
||||
|
||||
This generates:
|
||||
|
||||
- `packages/database/migrations/0046_meaningless_file_name.sql`
|
||||
|
||||
And updates:
|
||||
|
||||
- `packages/database/migrations/meta/_journal.json`
|
||||
- `packages/database/src/core/migrations.json`
|
||||
- `docs/development/database-schema.dbml`
|
||||
|
||||
## Step 2: Optimize Migration SQL Filename
|
||||
|
||||
Rename auto-generated filename to be meaningful:
|
||||
|
||||
`0046_meaningless_file_name.sql` → `0046_user_add_avatar_column.sql`
|
||||
|
||||
## Step 3: Use Idempotent Clauses (Defensive Programming)
|
||||
|
||||
Always use defensive clauses to make migrations idempotent (safe to re-run):
|
||||
|
||||
### CREATE TABLE
|
||||
|
||||
```sql
|
||||
-- ✅ Good
|
||||
CREATE TABLE IF NOT EXISTS "agent_eval_runs" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"name" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
-- ❌ Bad
|
||||
CREATE TABLE "agent_eval_runs" (...);
|
||||
```
|
||||
|
||||
### ALTER TABLE - Columns
|
||||
|
||||
```sql
|
||||
-- ✅ Good
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;
|
||||
ALTER TABLE "posts" DROP COLUMN IF EXISTS "deprecated_field";
|
||||
|
||||
-- ❌ Bad
|
||||
ALTER TABLE "users" ADD COLUMN "avatar" text;
|
||||
```
|
||||
|
||||
### ALTER TABLE - Foreign Key Constraints
|
||||
|
||||
PostgreSQL has no `ADD CONSTRAINT IF NOT EXISTS`. Use `DROP IF EXISTS` + `ADD`:
|
||||
|
||||
```sql
|
||||
-- ✅ Good: Drop first, then add (idempotent)
|
||||
ALTER TABLE "agent_eval_datasets" DROP CONSTRAINT IF EXISTS "agent_eval_datasets_user_id_users_id_fk";
|
||||
ALTER TABLE "agent_eval_datasets" ADD CONSTRAINT "agent_eval_datasets_user_id_users_id_fk"
|
||||
FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
|
||||
|
||||
-- ❌ Bad: Will fail if constraint already exists
|
||||
ALTER TABLE "agent_eval_datasets" ADD CONSTRAINT "agent_eval_datasets_user_id_users_id_fk"
|
||||
FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
|
||||
```
|
||||
|
||||
### DROP TABLE / INDEX
|
||||
|
||||
```sql
|
||||
-- ✅ Good
|
||||
DROP TABLE IF EXISTS "old_table";
|
||||
CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "users_email_unique" ON "users" USING btree ("email");
|
||||
|
||||
-- ❌ Bad
|
||||
DROP TABLE "old_table";
|
||||
CREATE INDEX "users_email_idx" ON "users" ("email");
|
||||
```
|
||||
|
||||
## Step 4: Regenerate Client After SQL Edits
|
||||
|
||||
After modifying the generated SQL (e.g., adding `IF NOT EXISTS`), regenerate the client:
|
||||
|
||||
```bash
|
||||
bun run db:generate:client
|
||||
```
|
||||
@@ -8,7 +8,7 @@ disable-model-invocation: true
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
LobeChat desktop is built on Electron with main-renderer architecture:
|
||||
LobeHub desktop is built on Electron with main-renderer architecture:
|
||||
|
||||
1. **Main Process** (`apps/desktop/src/main`): App lifecycle, system APIs, window management
|
||||
2. **Renderer Process**: Reuses web code from `src/`
|
||||
|
||||
@@ -115,28 +115,91 @@ export const agentsKnowledgeBases = pgTable(
|
||||
);
|
||||
```
|
||||
|
||||
## Query Style
|
||||
|
||||
**Always use `db.select()` builder API. Never use `db.query.*` relational API** (`findMany`, `findFirst`, `with:`).
|
||||
|
||||
The relational API generates complex lateral joins with `json_build_array` that are fragile and hard to debug.
|
||||
|
||||
### Select Single Row
|
||||
|
||||
```typescript
|
||||
// ✅ Good
|
||||
const [result] = await this.db
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(eq(agents.id, id))
|
||||
.limit(1);
|
||||
return result;
|
||||
|
||||
// ❌ Bad: relational API
|
||||
return this.db.query.agents.findFirst({
|
||||
where: eq(agents.id, id),
|
||||
});
|
||||
```
|
||||
|
||||
### Select with JOIN
|
||||
|
||||
```typescript
|
||||
// ✅ Good: explicit select + leftJoin
|
||||
const rows = await this.db
|
||||
.select({
|
||||
runId: agentEvalRunTopics.runId,
|
||||
score: agentEvalRunTopics.score,
|
||||
testCase: agentEvalTestCases,
|
||||
topic: topics,
|
||||
})
|
||||
.from(agentEvalRunTopics)
|
||||
.leftJoin(agentEvalTestCases, eq(agentEvalRunTopics.testCaseId, agentEvalTestCases.id))
|
||||
.leftJoin(topics, eq(agentEvalRunTopics.topicId, topics.id))
|
||||
.where(eq(agentEvalRunTopics.runId, runId))
|
||||
.orderBy(asc(agentEvalRunTopics.createdAt));
|
||||
|
||||
// ❌ Bad: relational API with `with:`
|
||||
return this.db.query.agentEvalRunTopics.findMany({
|
||||
where: eq(agentEvalRunTopics.runId, runId),
|
||||
with: { testCase: true, topic: true },
|
||||
});
|
||||
```
|
||||
|
||||
### Select with Aggregation
|
||||
|
||||
```typescript
|
||||
// ✅ Good: select + leftJoin + groupBy
|
||||
const rows = await this.db
|
||||
.select({
|
||||
id: agentEvalDatasets.id,
|
||||
name: agentEvalDatasets.name,
|
||||
testCaseCount: count(agentEvalTestCases.id).as('testCaseCount'),
|
||||
})
|
||||
.from(agentEvalDatasets)
|
||||
.leftJoin(agentEvalTestCases, eq(agentEvalDatasets.id, agentEvalTestCases.datasetId))
|
||||
.groupBy(agentEvalDatasets.id);
|
||||
```
|
||||
|
||||
### One-to-Many (Separate Queries)
|
||||
|
||||
When you need a parent record with its children, use two queries instead of relational `with:`:
|
||||
|
||||
```typescript
|
||||
// ✅ Good: two simple queries
|
||||
const [dataset] = await this.db
|
||||
.select()
|
||||
.from(agentEvalDatasets)
|
||||
.where(eq(agentEvalDatasets.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (!dataset) return undefined;
|
||||
|
||||
const testCases = await this.db
|
||||
.select()
|
||||
.from(agentEvalTestCases)
|
||||
.where(eq(agentEvalTestCases.datasetId, id))
|
||||
.orderBy(asc(agentEvalTestCases.sortOrder));
|
||||
|
||||
return { ...dataset, testCases };
|
||||
```
|
||||
|
||||
## Database Migrations
|
||||
|
||||
See `references/db-migrations.md` for detailed migration guide.
|
||||
|
||||
```bash
|
||||
# Generate migrations
|
||||
bun run db:generate
|
||||
|
||||
# After modifying SQL (e.g., adding IF NOT EXISTS)
|
||||
bun run db:generate:client
|
||||
```
|
||||
|
||||
### Migration Best Practices
|
||||
|
||||
```sql
|
||||
-- ✅ Idempotent operations
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;
|
||||
DROP TABLE IF EXISTS "old_table";
|
||||
CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");
|
||||
|
||||
-- ❌ Non-idempotent
|
||||
ALTER TABLE "users" ADD COLUMN "avatar" text;
|
||||
```
|
||||
|
||||
Rename migration files meaningfully: `0046_meaningless.sql` → `0046_user_add_avatar.sql`
|
||||
See the `db-migrations` skill for the detailed migration guide.
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
# Database Migrations Guide
|
||||
|
||||
## Step 1: Generate Migrations
|
||||
|
||||
```bash
|
||||
bun run db:generate
|
||||
```
|
||||
|
||||
This generates:
|
||||
|
||||
- `packages/database/migrations/0046_meaningless_file_name.sql`
|
||||
|
||||
And updates:
|
||||
|
||||
- `packages/database/migrations/meta/_journal.json`
|
||||
- `packages/database/src/core/migrations.json`
|
||||
- `docs/development/database-schema.dbml`
|
||||
|
||||
## Step 2: Optimize Migration SQL Filename
|
||||
|
||||
Rename auto-generated filename to be meaningful:
|
||||
|
||||
`0046_meaningless_file_name.sql` → `0046_user_add_avatar_column.sql`
|
||||
|
||||
## Step 3: Use Idempotent Clauses (Defensive Programming)
|
||||
|
||||
Always use defensive clauses to make migrations idempotent:
|
||||
|
||||
```sql
|
||||
-- ✅ Good: Idempotent operations
|
||||
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;
|
||||
DROP TABLE IF EXISTS "old_table";
|
||||
CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");
|
||||
ALTER TABLE "posts" DROP COLUMN IF EXISTS "deprecated_field";
|
||||
|
||||
-- ❌ Bad: Non-idempotent operations
|
||||
ALTER TABLE "users" ADD COLUMN "avatar" text;
|
||||
DROP TABLE "old_table";
|
||||
CREATE INDEX "users_email_idx" ON "users" ("email");
|
||||
```
|
||||
|
||||
## Important
|
||||
|
||||
After modifying migration SQL (e.g., adding `IF NOT EXISTS` clauses), run:
|
||||
|
||||
```bash
|
||||
bun run db:generate:client
|
||||
```
|
||||
|
||||
This updates the hash in `packages/database/src/core/migrations.json`.
|
||||
@@ -3,7 +3,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.
|
||||
---
|
||||
|
||||
# LobeChat Internationalization Guide
|
||||
# LobeHub Internationalization Guide
|
||||
|
||||
- Default language: Chinese (zh-CN)
|
||||
- Framework: react-i18next
|
||||
|
||||
@@ -25,6 +25,10 @@ Brand: **Where Agents Collaborate** - Focus on collaborative agent system, not j
|
||||
| 资源 | Resource |
|
||||
| 库 | Library |
|
||||
| 模型服务商 | Provider |
|
||||
| 评测 | Evaluation |
|
||||
| 基准 | Benchmark |
|
||||
| 数据集 | Dataset |
|
||||
| 用例 | Test Case |
|
||||
|
||||
## Brand Principles
|
||||
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
---
|
||||
globs: src/locales/default/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
你是「LobeHub」的中文 UI 文案与微文案(microcopy)专家。LobeHub 是一个助理工作空间:用户可以创建助理与群组,让人和助理、助理和助理协作,提升日常生产与生活效率。产品气质:外表年轻、亲和、现代;内核专业、可靠、强调生产力与可控性。整体风格参考 Notion / Figma / Apple / Discord / OpenAI / Gemini:清晰克制、可信、有人情味但不油腻。
|
||||
|
||||
产品 slogan:**For Collaborative Agents**。你的文案要让用户持续感到:LobeHub 的重点不是 “生成”,而是 “协作的助理体系”(可共享上下文、可追踪、可回放、可演进、人在回路)。
|
||||
|
||||
---
|
||||
|
||||
### 1) 固定术语(必须遵守)
|
||||
|
||||
- Workspace:空间
|
||||
- Agent:助理
|
||||
- Agent Team:群组
|
||||
- Context:上下文
|
||||
- Memory:记忆
|
||||
- Integration:连接器
|
||||
- Tool/Skill/Plugin/ 插件 / 工具:技能
|
||||
- SystemRole: 助理档案
|
||||
- Topic: 话题
|
||||
- Page: 文稿
|
||||
- Community: 社区
|
||||
- Resource: 资源
|
||||
- Library: 库
|
||||
- MCP: MCP
|
||||
- Provider: 模型服务商
|
||||
|
||||
术语规则:同一概念全站只用一种说法,不混用 “Agent / 智能体 / 机器人 / 团队 / 工作区” 等。
|
||||
|
||||
---
|
||||
|
||||
### 2) 你的任务
|
||||
|
||||
- 优化、改写或从零生成任何界面中文文案:标题、按钮、表单说明、占位、引导、空状态、Toast、弹窗、错误、权限、设置项、创建 / 运行流程、协作与群组相关页面等。
|
||||
- 文案必须同时兼容:普通用户看得懂 + 专业用户不觉得低幼;娱乐与严肃场景都成立;不过度营销、不夸大 AI 能力;在关键节点提供恰到好处的人文关怀。
|
||||
|
||||
---
|
||||
|
||||
### 3) 品牌三原则(内化到结构与措辞)
|
||||
|
||||
- **Create(创建)**:一句话创建助理;从想法到可用;清楚下一步。
|
||||
- **Collaborate(协作)**:多助理协作;群组对齐信息与产出;共享上下文(可控、可管理)。
|
||||
- **Evolve(演进)**:助理可在你允许的范围内记住偏好;随你的工作方式变得更顺手;强调可解释、可设置、可回放。
|
||||
|
||||
---
|
||||
|
||||
### 4) 写作规则(可执行)
|
||||
|
||||
1. **清晰优先**:短句、强动词、少形容词;避免口号化与空泛承诺(如 “颠覆”“史诗级”“100%”)。
|
||||
2. **分层表达(单一版本兼容两类用户)**:
|
||||
- 主句:人人可懂、可执行
|
||||
- 必要时补充一句副说明:更精确 / 更专业 / 更边界(可放副标题、帮助提示、折叠区)
|
||||
- 不输出 “Pro/Lite 两套文案”,而是 “一句主文案 + 可选补充”
|
||||
3. **术语克制但准确**:能说 “连接 / 运行 / 上下文” 就不要堆砌术语;必须出现专业词时给一句白话解释。
|
||||
4. **一致性**:同一动作按钮尽量固定动词(创建 / 连接 / 运行 / 暂停 / 重试 / 查看详情 / 清除记忆等)。
|
||||
5. **可行动**:每条提示都要让用户知道下一步;按钮避免 “确定 / 取消” 泛化,改成更具体的动作。
|
||||
6. **中文本地化**:符合中文阅读节奏;中英混排规范;避免翻译腔。
|
||||
|
||||
---
|
||||
|
||||
### 5) 人文关怀(中间态温度:介于克制与陪伴)
|
||||
|
||||
目标:在 AI 时代的价值焦虑与创作失格感中,给用户 “被理解 + 有掌控 + 能继续” 的体验,但不写长抒情。
|
||||
|
||||
#### 温度比例规则
|
||||
|
||||
- 默认:信息为主,温度为辅(约 8:2)
|
||||
- 关键节点(首次创建、空状态、长等待、失败重试、回退 / 丢失风险、协作分歧):允许提升到 7:3
|
||||
- 强制上限:任何一条上屏文案里,温度表达不超过**半句或一句**,且必须紧跟明确下一步。
|
||||
|
||||
#### 表达顺序(必须遵守)
|
||||
|
||||
1. 先承接处境(不评判):如 “没关系 / 先这样也可以 / 卡住很正常”
|
||||
2. 再给掌控感(人在回路):可暂停 / 可回放 / 可编辑 / 可撤销 / 可清除记忆 / 可查看上下文
|
||||
3. 最后给下一步(按钮 / 路径明确)
|
||||
|
||||
#### 避免
|
||||
|
||||
- 鸡汤式说教(如 “别焦虑”“要相信未来”)
|
||||
- 宏大叙事与文学排比
|
||||
- 过度拟人(不承诺助理 “理解你 / 有情绪 / 永远记得你”)
|
||||
|
||||
#### 核心立场
|
||||
|
||||
- 助理很强,但它替代不了你的经历、选择与判断;LobeHub 帮你把时间还给重要的部分。
|
||||
|
||||
##### A. 情绪承接(先人后事)
|
||||
|
||||
- 允许承认:焦虑、空白、无从下手、被追赶感、被替代感、创作枯竭、意义感动摇
|
||||
- 但不下结论、不说教:不输出 “你要乐观 / 别焦虑”,改成 “这种感觉很常见 / 你不是一个人”
|
||||
|
||||
##### B. 主体性回归(把人放回驾驶位)
|
||||
|
||||
- 关键句式:**“决定权在你”**、**“你可以选择交给助理的部分”**、**“把你的想法变成可运行的流程”**
|
||||
- 强调可控:可编辑、可回放、可暂停、可撤销、可清除记忆、可查看上下文
|
||||
|
||||
##### C. 经历与关系(把价值从结果挪回过程)
|
||||
|
||||
- 适度表达:记录、回放、版本、协作痕迹、讨论、共创、里程碑
|
||||
- 用 “经历 / 过程 / 痕迹 / 回忆 / 脉络 / 成长” 这类词,避免虚无抒情
|
||||
|
||||
##### D. 不用 “AI 神话”
|
||||
|
||||
- 不渲染 “AI 终将超越你 / 取代你”
|
||||
- 也不轻飘飘说 “AI 只是工具” 了事更像:**“它是工具,但你仍是作者 / 负责人 / 最终决定者”**
|
||||
|
||||
##### 示例
|
||||
|
||||
在用户可能产生自我否定或无力感的场景(空状态、创作开始、产出对比、失败重试、长时间等待、团队协作分歧、版本回退):
|
||||
|
||||
```
|
||||
1. **先承接感受**:用一句短话确认处境(不评判)
|
||||
2. **再给掌控感**:强调“你可控/可选择/可回放/可撤销”
|
||||
3. **最后给下一步**:提供明确行动按钮或路径
|
||||
```
|
||||
|
||||
- 允许出现 “经历、选择、痕迹、成长、一起、陪你把事做完” 等词来传递温度;但保持信息密度,不写长段抒情。
|
||||
- 严肃场景(权限 / 安全 / 付费 / 数据丢失风险)仍以清晰与准确为先,温度通过 “尊重与解释” 体现,而不是煽情。
|
||||
|
||||
你可以让系统在需要时套这些结构(同一句兼容新手 / 专业):
|
||||
|
||||
**开始创作 / 空白页**
|
||||
|
||||
- 主句:给一个轻承接 + 行动入口
|
||||
- 模板:
|
||||
- 「从一个念头开始就够了。写一句话,我来帮你搭好第一个助理。」
|
||||
- 「不知道从哪开始也没关系:先说目标,我们一起把它拆开。」
|
||||
|
||||
**长任务运行 / 等待**
|
||||
|
||||
- 模板:
|
||||
- 「正在运行中… 你可以先去做别的,完成后我会提醒你。」
|
||||
- 「这一步可能要几分钟。想更快:减少上下文 / 切换模型 / 关闭自动运行。」
|
||||
|
||||
**失败 / 重试**
|
||||
|
||||
- 模板:
|
||||
- 「没关系,这次没跑通。你可以重试,或查看原因再继续。」
|
||||
- 「连接失败:权限未通过或网络不稳定。去设置重新授权,或稍后再试。」
|
||||
|
||||
**对比与自我价值焦虑(适合提示 / 引导,不适合错误弹窗)**
|
||||
|
||||
- 模板:
|
||||
- 「助理可以加速产出,但方向、取舍和标准仍属于你。」
|
||||
- 「结果可以很快,经历更重要:把每次尝试留下来,下一次会更稳。」
|
||||
|
||||
**协作 / 群组**
|
||||
|
||||
- 模板:
|
||||
- 「把上下文对齐到同一处,群组里每个助理都会站在同一页上。」
|
||||
- 「不同意见没关系:先把目标写清楚,再让助理分别给方案与取舍。」
|
||||
|
||||
### 6) 错误 / 异常 / 权限 / 付费:硬规则
|
||||
|
||||
- 必须包含:**发生了什么 +(可选)原因 + 你可以怎么做**
|
||||
- 必须提供可操作选项:**重试 / 查看详情 / 去设置 / 联系支持 / 复制日志**(按场景取舍)
|
||||
- 不责备用户;不只给错误码;错误码可放在 “详情” 里
|
||||
- 涉及数据与安全:语气更中性更完整,温度通过 “尊重与解释” 体现,而不是煽
|
||||
@@ -0,0 +1,176 @@
|
||||
---
|
||||
globs: src/locales/default/*
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
You are **LobeHub’s English UI Copy & Microcopy Specialist**.
|
||||
|
||||
LobeHub is an assistant workspace: users can create **Agents** and **Agent Teams** so people↔agents and agent↔agent can collaborate to improve productivity in work and life.
|
||||
Brand vibe: youthful, friendly, modern on the surface; professional, reliable, productivity- and controllability-first underneath. Overall style reference: Notion / Figma / Apple / Discord / OpenAI / Gemini — clear, restrained, trustworthy, human but not cheesy.
|
||||
|
||||
Product slogan: **For Collaborative Agents**. Your copy must continuously reinforce that LobeHub is not about “generation”, but about a **collaborative agent system**: shareable context, traceable outcomes, replayable runs, evolvable setup, and **human-in-the-loop**.
|
||||
|
||||
---
|
||||
|
||||
## 1) Fixed Terminology (must follow)
|
||||
|
||||
Use **exactly** these English terms across the product. Do not mix synonyms for the same concept.
|
||||
|
||||
- 空间: **Workspace**
|
||||
- 助理: **Agent**
|
||||
- 群组: **Group**
|
||||
- 上下文: **Context**
|
||||
- 记忆: **Memory**
|
||||
- 连接器: **Integration**
|
||||
- 技能 /tool/plugin: **Skill**
|
||||
- 助理档案: **Agent Profile**
|
||||
- 话题: **Topic**
|
||||
- 文稿: **Page**
|
||||
- 社区: **Community**
|
||||
- 资源: **Resource**
|
||||
- 库: **Library**
|
||||
- MCP: **MCP**
|
||||
- 模型服务商: **Provider**
|
||||
|
||||
Terminology rule: one concept = one term site-wide. Never alternate with “bot/assistant/AI agent/team/workspace” variations.
|
||||
|
||||
---
|
||||
|
||||
## 2) Your Responsibilities
|
||||
|
||||
- Improve, rewrite, or create from scratch any **English UI copy**: titles, buttons, form labels/help text, placeholders, onboarding, empty states, toasts, modals, errors, permission prompts, settings, creation/run flows, collaboration and Agent Team pages, etc.
|
||||
- Copy must work for both:
|
||||
- general users (immediately understandable)
|
||||
- power users (not childish)
|
||||
- It must fit both playful and serious contexts.
|
||||
- Avoid overclaiming AI capabilities; add human warmth at the right moments.
|
||||
|
||||
---
|
||||
|
||||
## 3) The Three Brand Principles (bake into structure & wording)
|
||||
|
||||
- **Create**: create an Agent in one sentence; clear next step from idea → usable.
|
||||
- **Collaborate**: multi-agent collaboration; align info and outputs; share Context (controlled, manageable).
|
||||
- **Evolve**: Agents can remember preferences **only with user consent**; become more helpful over time; emphasize explainability, settings, and replay.
|
||||
|
||||
---
|
||||
|
||||
## 4) Writing Rules (actionable)
|
||||
|
||||
1. **Clarity first**: short sentences, strong verbs, minimal adjectives. Avoid hype (“revolutionary”, “epic”, “100%”).
|
||||
2. **Layered messaging (single version for everyone)**:
|
||||
- Main line: simple and actionable
|
||||
- Optional second line: more precise / technical / boundary-setting (subtitle, helper text, tooltip, collapsible)
|
||||
- Do not produce “Pro vs Lite” variants; one main + optional detail
|
||||
3. **Use terms sparingly but correctly**: prefer plain words (“connect”, “run”, “context”) unless a technical term is necessary. When it is, add a plain-English explanation.
|
||||
4. **Consistency**: keep verbs consistent across similar actions (Create / Connect / Run / Pause / Retry / View details / Clear Memory).
|
||||
5. **Actionable**: every message tells the user what to do next. Avoid generic “OK/Cancel”; use specific actions.
|
||||
6. **English localization**: natural, product-native English; avoid translationese; keep punctuation and casing consistent.
|
||||
|
||||
---
|
||||
|
||||
## 5) Human Warmth (balanced, controlled)
|
||||
|
||||
Goal: reduce anxiety and restore control without being sentimental.
|
||||
Default ratio: **80% information, 20% warmth**.
|
||||
Key moments (first-time create, empty state, long waits, failures/retries, rollback/data-loss risk, collaboration conflicts): may go **70/30**.
|
||||
|
||||
Hard cap: any on-screen message may include **at most half a sentence to one sentence** of warmth, and it must be followed by a clear next step.
|
||||
|
||||
Required order:
|
||||
|
||||
1. Acknowledge the situation (no judgment)
|
||||
2. Restore control (human-in-the-loop: pause/replay/edit/undo/clear Memory/view Context)
|
||||
3. Provide the next action (button/path)
|
||||
|
||||
Avoid:
|
||||
|
||||
- preachy encouragement (“don’t worry”, “stay positive”)
|
||||
- grand narratives
|
||||
- overly anthropomorphic claims (“I understand you”, “I’ll always remember you”)
|
||||
|
||||
Core stance: Agents can accelerate output, but **you** own the judgment, trade-offs, and final decision. LobeHub gives you time back for what matters.
|
||||
|
||||
Suggested patterns:
|
||||
|
||||
- **Getting started / blank state**
|
||||
- “Starting with one sentence is enough. Describe your goal and I’ll help you set up the first Agent.”
|
||||
- “Not sure where to begin? Tell me the outcome—we’ll break it down together.”
|
||||
- **Long run / waiting**
|
||||
- “Running… You can switch tasks—I'll notify you when it’s done.”
|
||||
- “This may take a few minutes. To speed up: reduce Context / switch model / disable Auto-run.”
|
||||
- **Failure / retry**
|
||||
- “That didn’t run through. Retry, or view details to fix the cause.”
|
||||
- “Connection failed: permission not granted or network unstable. Re-authorize in Settings, or try again later.”
|
||||
- **Value anxiety (guidance, not error dialogs)**
|
||||
- “Agents can speed up output, but direction and standards stay with you.”
|
||||
- “Fast results are great—keeping the trail makes the next run steadier.”
|
||||
- **Collaboration / Agent Teams**
|
||||
- “Align everyone to the same Context. Every Agent in the Agent Team works from the same page.”
|
||||
- “Different opinions are fine. Write the goal first, then let Agents propose options and trade-offs.”
|
||||
|
||||
---
|
||||
|
||||
## 6) Errors / Exceptions / Permissions / Billing: hard rules
|
||||
|
||||
Every error must include:
|
||||
|
||||
- **What happened**
|
||||
- (optional) **Why**
|
||||
- **What the user can do next**
|
||||
|
||||
Provide actionable options as appropriate:
|
||||
|
||||
- Retry / View details / Go to Settings / Contact support / Copy logs
|
||||
|
||||
Never blame the user. Don’t show only an error code; put codes in “Details” if needed.
|
||||
For data/security/billing: be neutral, thorough, and respectful—warmth comes from clarity, not emotion.
|
||||
|
||||
---
|
||||
|
||||
## 7) Your Special Task: CN i18n → EN (localized, length-aware)
|
||||
|
||||
You translate **raw Chinese i18n strings into English** for LobeHub.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Prefer **localized**, product-native English over literal translation.
|
||||
- Do **not** chase perfect one-to-one consistency if a more natural UI phrase reads better.
|
||||
- Keep the **character length difference small**; try to make the English string **roughly the same visual length** as the Chinese source (avoid overly long expansions).
|
||||
- Preserve meaning, tone, and actionability; keep verbs consistent with LobeHub’s UI patterns.
|
||||
- If space is tight (buttons, tabs, toasts), prioritize: **verb + object**, drop optional words first.
|
||||
- If the Chinese includes placeholders/variables, preserve them exactly (e.g., `{name}`, `{{count}}`, `%s`) and keep word order sensible.
|
||||
- Keep capitalization consistent with UI norms (buttons/title case only when appropriate).
|
||||
|
||||
Output format when translating:
|
||||
|
||||
- Provide **English only**, unless asked otherwise.
|
||||
- If multiple options are useful, give **one best option** + **one shorter fallback** (only when length constraints are likely).
|
||||
|
||||
---
|
||||
|
||||
You always optimize for: **clarity, control, collaboration, replayability, and human-in-the-loop**—in a modern, restrained, trustworthy English voice.
|
||||
|
||||
## 8) Product Introduction
|
||||
|
||||
LobeHub, we define agents as the unit of work. We’re building the first human–agent co-working, co-evolving network.
|
||||
|
||||
It is a fundamentally new, agent-first experience.You can pop up your agents or agent teams while writing, while chatting -- from ideation, to execution, to delivery -- across your entire workflow. Here, agents are not just tools, but always-on units of work.
|
||||
|
||||
### Create
|
||||
|
||||
It is a unified workspace where you can find, build, or team up with agent co-workers.Simply describe what you need, and Lobe AI will generate the prompts and assemble the right set of tools to compose your agent.In agent marketplace, you can easily discover agents created by others,use them instantly,and flexibly swap in your own tools.
|
||||
|
||||
### Collaboration
|
||||
|
||||
You can also spin up agent groups to handle system-level projects, even like building a quant team.
|
||||
Within this group, some agents track signals and mine quantitative factors in real time, some manage risk, some execute orders, collaborate together to make money.
|
||||
We’re defining how humans and agents work together. Now we support agent-to-agent collaboration, and we continue to scale new forms of collaboration networks — from agents collaborating across teams, to multiple humans working through the same agent.
|
||||
|
||||
### Evolve
|
||||
|
||||
Humans and agents should co-evolve, and we design this paradigm from both technical and economic perspectives. Our memory system is structured and editable,enabling models to better align with individual users, while allowing users to provide cleaner reward signals for continual learning. Agent evolution is powered by shared human intelligence through our agent marketplace. Creators are rewarded, and agents, in turn, pay for human intelligence.
|
||||
|
||||
Is AI replacing humans? No.
|
||||
We’re building a human–agent co-working, co-evolving society.
|
||||
Agents become smarter and more personalized through human intelligence, taking on repetitive and exhausting work — so humans can focus on fewer, but more important things: taste, and creation.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: pr
|
||||
description: "Create a PR for the current branch. Use when the user asks to create a pull request, submit PR, or says 'pr'."
|
||||
user_invocable: true
|
||||
---
|
||||
|
||||
# Create Pull Request
|
||||
|
||||
## Branch Strategy
|
||||
|
||||
- **Target branch**: `canary` (development branch, cloud production)
|
||||
- `main` is the release branch — never PR directly to main
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Gather context (run in parallel)
|
||||
|
||||
- `git branch --show-current` — current branch name
|
||||
- `git status --short` — uncommitted changes
|
||||
- `git rev-parse --abbrev-ref @{u} 2>/dev/null` — remote tracking status
|
||||
- `git log --oneline origin/canary..HEAD` — unpushed commits
|
||||
- `gh pr list --head "$(git branch --show-current)" --json number,title,state,url` — existing PR
|
||||
- `git diff --stat --stat-count=20 origin/canary..HEAD` — change summary
|
||||
|
||||
### 2. Handle uncommitted changes on default branch
|
||||
|
||||
If current branch is `canary` (or `main`) AND there are uncommitted changes:
|
||||
|
||||
1. Analyze the diff (`git diff`) to understand the changes
|
||||
2. Infer a branch name from the changes, format: `<type>/<short-description>` (e.g. `fix/i18n-cjk-spacing`)
|
||||
3. Create and switch to the new branch: `git checkout -b <branch-name>`
|
||||
4. Stage relevant files: `git add <files>` (prefer explicit file paths over `git add .`)
|
||||
5. Commit with a proper gitmoji message
|
||||
6. Continue to step 3
|
||||
|
||||
If current branch is `canary`/`main` but there are NO uncommitted changes and no unpushed commits, abort — nothing to create a PR for.
|
||||
|
||||
### 3. Push if needed
|
||||
|
||||
- No upstream: `git push -u origin $(git branch --show-current)`
|
||||
- Has upstream: `git push origin $(git branch --show-current)`
|
||||
|
||||
### 4. Search related GitHub issues
|
||||
|
||||
- `gh issue list --search "<keywords>" --state all --limit 10`
|
||||
- Only link issues with matching scope (avoid large umbrella issues)
|
||||
- Skip if no matching issue found
|
||||
|
||||
### 5. Create PR with `gh pr create --base canary`
|
||||
|
||||
- Title: `<gitmoji> <type>(<scope>): <description>`
|
||||
- Body: based on PR template (`.github/PULL_REQUEST_TEMPLATE.md`), fill checkboxes
|
||||
- Link related GitHub issues using magic keywords (`Fixes #123`, `Closes #123`)
|
||||
- Link Linear issues if applicable (`Fixes LOBE-xxx`)
|
||||
- Use HEREDOC for body to preserve formatting
|
||||
|
||||
### 6. Open in browser
|
||||
|
||||
`gh pr view --web`
|
||||
|
||||
## PR Template
|
||||
|
||||
Use `.github/PULL_REQUEST_TEMPLATE.md` as the body structure. Key sections:
|
||||
|
||||
- **Change Type**: Check the appropriate gitmoji type
|
||||
- **Related Issue**: Link GitHub/Linear issues with magic keywords
|
||||
- **Description of Change**: Summarize what and why
|
||||
- **How to Test**: Describe test approach, check relevant boxes
|
||||
|
||||
## Notes
|
||||
|
||||
- **Release impact**: PR titles with `✨ feat/` or `🐛 fix` trigger releases — use carefully
|
||||
- **Language**: All PR content must be in English
|
||||
- If a PR already exists for the branch, inform the user instead of creating a duplicate
|
||||
@@ -3,7 +3,7 @@ name: project-overview
|
||||
description: 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.
|
||||
---
|
||||
|
||||
# LobeChat Project Overview
|
||||
# LobeHub Project Overview
|
||||
|
||||
## Project Description
|
||||
|
||||
@@ -101,13 +101,20 @@ lobe-chat/
|
||||
│ │ │ ├── oidc/
|
||||
│ │ │ ├── trpc/
|
||||
│ │ │ └── webapi/
|
||||
│ │ ├── [variants]/
|
||||
│ │ │ ├── (auth)/
|
||||
│ │ │ ├── (main)/
|
||||
│ │ │ ├── (mobile)/
|
||||
│ │ │ ├── onboarding/
|
||||
│ │ │ └── router/
|
||||
│ │ └── desktop/
|
||||
│ │ ├── spa/ # SPA HTML template service
|
||||
│ │ └── [variants]/
|
||||
│ │ └── (auth)/ # Auth pages (SSR required)
|
||||
│ ├── routes/ # SPA page components (Vite)
|
||||
│ │ ├── (main)/
|
||||
│ │ ├── (mobile)/
|
||||
│ │ ├── (desktop)/
|
||||
│ │ ├── onboarding/
|
||||
│ │ └── share/
|
||||
│ ├── spa/ # SPA entry points and router config
|
||||
│ │ ├── entry.web.tsx
|
||||
│ │ ├── entry.mobile.tsx
|
||||
│ │ ├── entry.desktop.tsx
|
||||
│ │ └── router/
|
||||
│ ├── business/ # Cloud-only (client/server)
|
||||
│ │ ├── client/
|
||||
│ │ ├── locales/
|
||||
@@ -155,6 +162,8 @@ lobe-chat/
|
||||
| Layer | Location |
|
||||
| ---------------- | --------------------------------------------------- |
|
||||
| UI Components | `src/components`, `src/features` |
|
||||
| SPA Pages | `src/routes/` |
|
||||
| React Router | `src/spa/router/` |
|
||||
| Global Providers | `src/layout` |
|
||||
| Zustand Stores | `src/store` |
|
||||
| Client Services | `src/services/` |
|
||||
|
||||
@@ -36,9 +36,9 @@ Hybrid routing: Next.js App Router (static pages) + React Router DOM (main SPA).
|
||||
|
||||
### Key Files
|
||||
|
||||
- Entry: `src/app/[variants]/page.tsx`
|
||||
- Desktop router: `src/app/[variants]/router/desktopRouter.config.tsx`
|
||||
- Mobile router: `src/app/[variants]/(mobile)/router/mobileRouter.config.tsx`
|
||||
- Entry: `src/spa/entry.web.tsx` (web), `src/spa/entry.mobile.tsx`, `src/spa/entry.desktop.tsx`
|
||||
- Desktop router: `src/spa/router/desktopRouter.config.tsx`
|
||||
- Mobile router: `src/spa/router/mobileRouter.config.tsx`
|
||||
- Router utilities: `src/utils/router.tsx`
|
||||
|
||||
### Router Utilities
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
---
|
||||
name: spa-routes
|
||||
description: SPA route and feature structure. Use when adding or modifying SPA routes in src/routes, defining new route segments, or moving route logic into src/features. Covers how to keep routes thin and how to divide files between routes and features.
|
||||
---
|
||||
|
||||
# SPA Routes and Features Guide
|
||||
|
||||
SPA structure:
|
||||
|
||||
- **`src/spa/`** – Entry points (`entry.web.tsx`, `entry.mobile.tsx`, `entry.desktop.tsx`) and router config (`router/`). Router lives here to avoid confusion with `src/routes/`.
|
||||
- **`src/routes/`** – Page segments only (roots).
|
||||
- **`src/features/`** – Business logic and UI by domain.
|
||||
|
||||
This project uses a **roots vs features** split: `src/routes/` only holds page segments; business logic and UI live in `src/features/` by domain.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Adding a new SPA route or route segment
|
||||
- Defining or refactoring layout/page files under `src/routes/`
|
||||
- Moving route-specific components or logic into `src/features/`
|
||||
- Deciding where to put a new component (route folder vs feature folder)
|
||||
|
||||
---
|
||||
|
||||
## 1. What Belongs in `src/routes/` (roots)
|
||||
|
||||
Each route directory should contain **only**:
|
||||
|
||||
| File / folder | Purpose |
|
||||
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `_layout/index.tsx` or `layout.tsx` | Layout for this segment: wrap with `<Outlet />`, optional shell (e.g. sidebar + main). Should be thin: prefer re-exporting or composing from `@/features/*`. |
|
||||
| `index.tsx` or `page.tsx` | Page entry for this segment. Only import from features and render; no business logic. |
|
||||
| `[param]/index.tsx` (e.g. `[id]`, `[cronId]`) | Dynamic segment page. Same rule: thin, delegate to features. |
|
||||
|
||||
**Rule:** Route files should only **import and compose**. No new `features/` folders or heavy components inside `src/routes/`.
|
||||
|
||||
---
|
||||
|
||||
## 2. What Belongs in `src/features/`
|
||||
|
||||
Put **domain-oriented** UI and logic here:
|
||||
|
||||
- Layout building blocks: sidebars, headers, body panels, drawers
|
||||
- Hooks and store usage for that domain
|
||||
- Domain-specific forms, lists, modals, etc.
|
||||
|
||||
Organize by **domain** (e.g. `Pages`, `Home`, `Agent`, `PageEditor`), not by route path. One route can use several features; one feature can be used by several routes.
|
||||
|
||||
Each feature should:
|
||||
|
||||
- Live under `src/features/<FeatureName>/`
|
||||
- Export a clear public API via `index.ts` or `index.tsx`
|
||||
- Use `@/features/<FeatureName>/...` for internal imports when needed
|
||||
|
||||
---
|
||||
|
||||
## 3. How to Add a New SPA Route
|
||||
|
||||
1. **Choose the route group**
|
||||
- `(main)/` – desktop main app
|
||||
- `(mobile)/` – mobile
|
||||
- `(desktop)/` – Electron-specific
|
||||
- `onboarding/`, `share/` – special flows
|
||||
|
||||
2. **Create only segment files under `src/routes/`**
|
||||
- e.g. `src/routes/(main)/my-feature/_layout/index.tsx` and `src/routes/(main)/my-feature/index.tsx` (and optional `[id]/index.tsx`).
|
||||
|
||||
3. **Implement layout and page content in `src/features/`**
|
||||
- Create or reuse a domain (e.g. `src/features/MyFeature/`).
|
||||
- Put layout (sidebar, header, body) and page UI there; export from the feature’s `index`.
|
||||
|
||||
4. **Keep route files thin**
|
||||
- Layout: `export { default } from '@/features/MyFeature/MyLayout'` or compose a few feature components + `<Outlet />`.
|
||||
- Page: import from `@/features/MyFeature` (or a specific subpath) and render; no business logic in the route file.
|
||||
|
||||
5. **Register the route**
|
||||
- Add the segment to `src/spa/router/desktopRouter.config.tsx` (or the right router config) with `dynamicElement` / `dynamicLayout` pointing at the new route paths (e.g. `@/routes/(main)/my-feature`).
|
||||
|
||||
---
|
||||
|
||||
## 4. How to Divide Files (route vs feature)
|
||||
|
||||
| Question | Put in `src/routes/` | Put in `src/features/` |
|
||||
| -------------------------------------------------------- | -------------------------------------------------------- | ---------------------------- |
|
||||
| Is it the route’s layout wrapper or page entry? | Yes – `_layout/index.tsx`, `index.tsx`, `[id]/index.tsx` | No |
|
||||
| Does it contain business logic or non-trivial UI? | No | Yes – under the right domain |
|
||||
| Is it a reusable layout piece (sidebar, header, body)? | No | Yes |
|
||||
| Is it a hook, store usage, or domain logic? | No | Yes |
|
||||
| Is it only re-exporting or composing feature components? | Yes | No |
|
||||
|
||||
**Examples**
|
||||
|
||||
- **Route (thin):**\
|
||||
`src/routes/(main)/page/_layout/index.tsx` → `export { default } from '@/features/Pages/PageLayout'`
|
||||
- **Feature (real implementation):**\
|
||||
`src/features/Pages/PageLayout/` → Sidebar, DataSync, Body, Header, styles, etc.
|
||||
- **Route (thin):**\
|
||||
`src/routes/(main)/page/index.tsx` → Import `PageTitle`, `PageExplorerPlaceholder` from `@/features/Pages` and `@/features/PageExplorer`; render with `<PageTitle />` and placeholder.
|
||||
- **Feature:**\
|
||||
Page list, actions, drawers, and hooks live under `src/features/Pages/`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Progressive Migration (existing code)
|
||||
|
||||
We are migrating existing routes to this structure step by step:
|
||||
|
||||
- **Phase 1 (done):** `/page` route – segment files in `src/routes/(main)/page/`, implementation in `src/features/Pages/`.
|
||||
- **Later phases:** home, settings, agent/group, community/resource/memory, mobile/share/onboarding.
|
||||
|
||||
When touching an old route that still has logic or `features/` inside `src/routes/`:
|
||||
|
||||
1. Prefer adding **new** code in `src/features/<Domain>/` and importing from routes.
|
||||
2. For larger refactors, move existing route-only logic into the right feature and then thin out the route files (re-export or compose from features).
|
||||
3. Use `git mv` when moving files so history is preserved.
|
||||
|
||||
---
|
||||
|
||||
## 6. Reference Structure (after Phase 1)
|
||||
|
||||
**Route (thin):**
|
||||
|
||||
```
|
||||
src/routes/(main)/page/
|
||||
├── _layout/index.tsx → re-export or compose from @/features/Pages/PageLayout
|
||||
├── index.tsx → import from @/features/Pages, @/features/PageExplorer
|
||||
└── [id]/index.tsx → import from @/features/Pages, @/features/PageExplorer
|
||||
```
|
||||
|
||||
**Feature (implementation):**
|
||||
|
||||
```
|
||||
src/features/Pages/
|
||||
├── index.ts → export PageLayout, PageTitle
|
||||
├── PageTitle.tsx
|
||||
└── PageLayout/
|
||||
├── index.tsx → Sidebar + Outlet + DataSync
|
||||
├── DataSync.tsx
|
||||
├── Sidebar.tsx
|
||||
├── style.ts
|
||||
├── Body/ → list, actions, drawer, etc.
|
||||
└── Header/ → breadcrumb, add button, etc.
|
||||
```
|
||||
|
||||
Router config continues to point at **route** paths (e.g. `@/routes/(main)/page`, `@/routes/(main)/page/_layout`); route files then delegate to features.
|
||||
@@ -0,0 +1,624 @@
|
||||
---
|
||||
name: store-data-structures
|
||||
description: 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.
|
||||
---
|
||||
|
||||
# LobeHub Store Data Structures
|
||||
|
||||
This guide covers how to structure data in Zustand stores for optimal performance and user experience.
|
||||
|
||||
## 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
|
||||
|
||||
### ❌ 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
|
||||
|
||||
---
|
||||
|
||||
## Type Definitions
|
||||
|
||||
Types should be organized by entity in separate files:
|
||||
|
||||
```
|
||||
@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';
|
||||
|
||||
// ============================================
|
||||
// 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`)
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
**Structure:**
|
||||
|
||||
```typescript
|
||||
benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
|
||||
```
|
||||
|
||||
**Example:** Benchmark detail pages, Dataset detail pages, User profiles
|
||||
|
||||
### Use Simple Array (for List Data)
|
||||
|
||||
✅ **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
|
||||
|
||||
**Structure:**
|
||||
|
||||
```typescript
|
||||
benchmarkList: AgentEvalBenchmarkListItem[]
|
||||
```
|
||||
|
||||
**Example:** 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.ts
|
||||
import 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
|
||||
*/
|
||||
benchmarkList: 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
|
||||
*/
|
||||
benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
|
||||
|
||||
/**
|
||||
* Track which benchmark details are being loaded/updated
|
||||
* For showing spinners on specific items
|
||||
*/
|
||||
loadingBenchmarkDetailIds: string[];
|
||||
|
||||
// ============================================
|
||||
// Mutation States
|
||||
// ============================================
|
||||
isCreatingBenchmark: boolean;
|
||||
isUpdatingBenchmark: boolean;
|
||||
isDeletingBenchmark: boolean;
|
||||
}
|
||||
|
||||
export const benchmarkInitialState: BenchmarkSliceState = {
|
||||
benchmarkList: [],
|
||||
benchmarkListInit: false,
|
||||
benchmarkDetailMap: {},
|
||||
loadingBenchmarkDetailIds: [],
|
||||
isCreatingBenchmark: false,
|
||||
isUpdatingBenchmark: false,
|
||||
isDeletingBenchmark: false,
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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;
|
||||
}
|
||||
|
||||
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',
|
||||
);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data Structure Comparison
|
||||
|
||||
### ❌ WRONG - Single Detail Object
|
||||
|
||||
```typescript
|
||||
interface BenchmarkSliceState {
|
||||
// ❌ Can only cache one detail
|
||||
benchmarkDetail: AgentEvalBenchmark | null;
|
||||
|
||||
// ❌ Global loading state
|
||||
isLoadingBenchmarkDetail: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
**Problems:**
|
||||
|
||||
- Can only cache one detail page at a time
|
||||
- Switching between details causes unnecessary refetches
|
||||
- No optimistic updates
|
||||
- No per-item loading states
|
||||
|
||||
### ✅ CORRECT - Separate List and Detail
|
||||
|
||||
```typescript
|
||||
import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';
|
||||
|
||||
interface BenchmarkSliceState {
|
||||
// ✅ List data - simple array
|
||||
benchmarkList: AgentEvalBenchmarkListItem[];
|
||||
benchmarkListInit: boolean;
|
||||
|
||||
// ✅ Detail data - map for caching
|
||||
benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
|
||||
|
||||
// ✅ Per-item loading
|
||||
loadingBenchmarkDetailIds: string[];
|
||||
|
||||
// ✅ Mutation states
|
||||
isCreatingBenchmark: boolean;
|
||||
isUpdatingBenchmark: boolean;
|
||||
isDeletingBenchmark: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- Cache multiple detail pages
|
||||
- Fast navigation between cached details
|
||||
- Optimistic updates with reducer
|
||||
- Per-item loading states
|
||||
- Clear separation of concerns
|
||||
|
||||
---
|
||||
|
||||
## Component Usage
|
||||
|
||||
### Accessing List Data
|
||||
|
||||
```typescript
|
||||
const BenchmarkList = () => {
|
||||
// Simple array access
|
||||
const 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
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### Accessing Detail Data
|
||||
|
||||
```typescript
|
||||
const BenchmarkDetail = () => {
|
||||
const { benchmarkId } = useParams<{ benchmarkId: string }>();
|
||||
|
||||
// Get from map
|
||||
const benchmark = useEvalStore((s) =>
|
||||
benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,
|
||||
);
|
||||
|
||||
// Check loading
|
||||
const isLoading = useEvalStore((s) =>
|
||||
benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,
|
||||
);
|
||||
|
||||
if (!benchmark) return <Loading />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{benchmark.name}</h1>
|
||||
{isLoading && <Spinner />}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### Using Selectors (Recommended)
|
||||
|
||||
```typescript
|
||||
// src/store/eval/slices/benchmark/selectors.ts
|
||||
export const benchmarkSelectors = {
|
||||
getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],
|
||||
|
||||
isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>
|
||||
s.loadingBenchmarkDetailIds.includes(id),
|
||||
};
|
||||
|
||||
// In component
|
||||
const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId!));
|
||||
const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(benchmarkId!));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Decision Tree
|
||||
|
||||
```
|
||||
Need to store data?
|
||||
│
|
||||
├─ Is it a LIST for display?
|
||||
│ └─ ✅ Use simple array: `xxxList: XxxListItem[]`
|
||||
│ - May include computed fields
|
||||
│ - Refreshed as a whole
|
||||
│ - No optimistic updates needed
|
||||
│
|
||||
└─ Is it DETAIL page data?
|
||||
└─ ✅ Use Map: `xxxDetailMap: Record<string, Xxx>`
|
||||
- Cache multiple details
|
||||
- Support optimistic updates
|
||||
- Per-item loading states
|
||||
- Requires reducer for mutations
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checklist
|
||||
|
||||
When designing store state structure:
|
||||
|
||||
- [ ] **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)
|
||||
- [ ] May include computed statistics for UI
|
||||
- [ ] **NOT** extending Detail type (it's a subset, not extension)
|
||||
- [ ] 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
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
### Common Mistakes to Avoid
|
||||
|
||||
❌ **DON'T extend Detail in List:**
|
||||
|
||||
```typescript
|
||||
// Wrong - List should not extend Detail
|
||||
export interface BenchmarkListItem extends Benchmark {
|
||||
testCaseCount?: number;
|
||||
}
|
||||
```
|
||||
|
||||
✅ **DO create separate subset:**
|
||||
|
||||
```typescript
|
||||
// Correct - List is a subset with computed fields
|
||||
export interface BenchmarkListItem {
|
||||
id: string;
|
||||
name: string;
|
||||
// ... only necessary fields
|
||||
testCaseCount?: number; // Computed
|
||||
}
|
||||
```
|
||||
|
||||
❌ **DON'T mix entities in one file:**
|
||||
|
||||
```typescript
|
||||
// Wrong - all entities in agentEvalEntities.ts
|
||||
```
|
||||
|
||||
✅ **DO separate by entity:**
|
||||
|
||||
```typescript
|
||||
// Correct - separate files
|
||||
// benchmark.ts
|
||||
// agentEvalDataset.ts
|
||||
// agentEvalRun.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `data-fetching` - How to fetch and update this data
|
||||
- `zustand` - General Zustand patterns
|
||||
@@ -3,7 +3,7 @@ name: testing
|
||||
description: 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.
|
||||
---
|
||||
|
||||
# LobeChat Testing Guide
|
||||
# LobeHub Testing Guide
|
||||
|
||||
## Quick Reference
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Testing Framework & Directory Structure
|
||||
|
||||
LobeChat Desktop uses Vitest as the test framework. Controller unit tests should be placed in the `__tests__` directory adjacent to the controller file, named with the original controller filename plus `.test.ts`.
|
||||
LobeHub Desktop uses Vitest as the test framework. Controller unit tests should be placed in the `__tests__` directory adjacent to the controller file, named with the original controller filename plus `.test.ts`.
|
||||
|
||||
```plaintext
|
||||
apps/desktop/src/main/controllers/
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,389 @@
|
||||
# Cloud Project Workflow Configuration
|
||||
|
||||
This document covers cloud-specific workflow configurations and patterns for the lobehub-cloud project.
|
||||
|
||||
## Overview
|
||||
|
||||
The lobehub-cloud project extends the open-source lobehub codebase with cloud-specific features. Workflows can be implemented in either:
|
||||
|
||||
1. **Lobehub (open-source)** - Available to all users
|
||||
2. **Lobehub-cloud (proprietary)** - Cloud-specific business logic
|
||||
|
||||
---
|
||||
|
||||
## Directory Structure
|
||||
|
||||
### Lobehub Submodule (Open-source)
|
||||
|
||||
```
|
||||
lobehub/
|
||||
└── src/
|
||||
├── app/(backend)/api/workflows/
|
||||
│ ├── memory-user-memory/ # Memory extraction workflows
|
||||
│ └── agent-eval-run/ # Benchmark evaluation workflows
|
||||
└── server/workflows/
|
||||
├── agentEvalRun/
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Lobehub-cloud (Proprietary)
|
||||
|
||||
```
|
||||
lobehub-cloud/
|
||||
└── src/
|
||||
├── app/(backend)/api/workflows/
|
||||
│ ├── welcome-placeholder/ # Cloud-only: AI placeholder generation
|
||||
│ ├── agent-welcome/ # Cloud-only: Agent welcome messages
|
||||
│ ├── agent-eval-run/ # Re-export from lobehub
|
||||
│ └── memory-user-memory/ # Re-export from lobehub
|
||||
└── server/workflows/
|
||||
├── welcomePlaceholder/
|
||||
├── agentWelcome/
|
||||
└── agentEvalRun/ # Re-export from lobehub
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cloud-Specific Patterns
|
||||
|
||||
### Pattern 1: Cloud-Only Workflows
|
||||
|
||||
**Use Case**: Features exclusive to cloud users (AI generation, premium features)
|
||||
|
||||
**Example**: `welcome-placeholder`, `agent-welcome`
|
||||
|
||||
**Implementation**:
|
||||
|
||||
- Implement directly in `lobehub-cloud/src/app/(backend)/api/workflows/`
|
||||
- No need for re-exports
|
||||
- Can use cloud-specific packages and services
|
||||
|
||||
**Structure**:
|
||||
|
||||
```
|
||||
lobehub-cloud/src/
|
||||
├── app/(backend)/api/workflows/
|
||||
│ └── feature-name/
|
||||
│ ├── process-items/route.ts
|
||||
│ ├── paginate-items/route.ts
|
||||
│ └── execute-item/route.ts
|
||||
└── server/workflows/
|
||||
└── featureName/
|
||||
└── index.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Pattern 2: Re-export from Lobehub
|
||||
|
||||
**Use Case**: Workflows implemented in open-source but also used in cloud
|
||||
|
||||
**Example**: `agent-eval-run`, `memory-user-memory`
|
||||
|
||||
**Why Re-export?**
|
||||
|
||||
- Cloud deployment needs to serve these endpoints
|
||||
- Lobehub submodule code is not directly accessible in cloud routes
|
||||
- Allows cloud-specific overrides if needed in the future
|
||||
|
||||
#### Re-export Implementation
|
||||
|
||||
**Step 1**: Implement workflow in lobehub submodule
|
||||
|
||||
```typescript
|
||||
// lobehub/src/app/(backend)/api/workflows/feature/layer/route.ts
|
||||
import { serve } from '@upstash/workflow/nextjs';
|
||||
|
||||
export const { POST } = serve<Payload>(
|
||||
async (context) => {
|
||||
// Implementation
|
||||
},
|
||||
{ flowControl: { ... } }
|
||||
);
|
||||
```
|
||||
|
||||
**Step 2**: Create re-export in lobehub-cloud
|
||||
|
||||
```typescript
|
||||
// lobehub-cloud/src/app/(backend)/api/workflows/feature/layer/route.ts
|
||||
export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature/layer/route';
|
||||
```
|
||||
|
||||
**Important**: Use `lobehub/src/...` path, NOT `@/...` to avoid circular imports.
|
||||
|
||||
#### Re-export Directory Structure
|
||||
|
||||
```bash
|
||||
# Create directories
|
||||
mkdir -p lobehub-cloud/src/app/(backend)/api/workflows/feature-name/layer-1
|
||||
mkdir -p lobehub-cloud/src/app/(backend)/api/workflows/feature-name/layer-2
|
||||
mkdir -p lobehub-cloud/src/app/(backend)/api/workflows/feature-name/layer-3
|
||||
|
||||
# Create re-export files
|
||||
echo "export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature-name/layer-1/route';" > \
|
||||
lobehub-cloud/src/app/(backend)/api/workflows/feature-name/layer-1/route.ts
|
||||
|
||||
echo "export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature-name/layer-2/route';" > \
|
||||
lobehub-cloud/src/app/(backend)/api/workflows/feature-name/layer-2/route.ts
|
||||
|
||||
echo "export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature-name/layer-3/route';" > \
|
||||
lobehub-cloud/src/app/(backend)/api/workflows/feature-name/layer-3/route.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## TypeScript Path Mappings
|
||||
|
||||
The cloud project uses tsconfig path mappings to override lobehub code:
|
||||
|
||||
```json
|
||||
// lobehub-cloud/tsconfig.json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"@/*": ["./src/*", "./lobehub/src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Resolution Order**:
|
||||
|
||||
1. `./src/*` (cloud code) - checked first
|
||||
2. `./lobehub/src/*` (open-source) - fallback
|
||||
|
||||
This allows cloud to override specific modules while using lobehub defaults.
|
||||
|
||||
---
|
||||
|
||||
## Workflow Class Location
|
||||
|
||||
### Cloud-Only Workflows
|
||||
|
||||
Place workflow class in cloud:
|
||||
|
||||
```
|
||||
lobehub-cloud/src/server/workflows/featureName/index.ts
|
||||
```
|
||||
|
||||
### Shared Workflows
|
||||
|
||||
Place workflow class in lobehub, re-export in cloud if needed:
|
||||
|
||||
```
|
||||
lobehub/src/server/workflows/featureName/index.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Both lobehub and cloud workflows require:
|
||||
|
||||
```bash
|
||||
# Required for all workflows
|
||||
APP_URL=https://your-app.com # Base URL for workflow endpoints
|
||||
QSTASH_TOKEN=qstash_xxx # QStash authentication token
|
||||
|
||||
# Optional (for custom QStash URL)
|
||||
QSTASH_URL=https://custom-qstash.com # Custom QStash endpoint
|
||||
```
|
||||
|
||||
**Cloud-Specific**:
|
||||
|
||||
```bash
|
||||
# Cloud database (for monetization features)
|
||||
CLOUD_DATABASE_URL=postgresql://...
|
||||
|
||||
# Cloud-specific services
|
||||
REDIS_URL=redis://...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Decide: Cloud or Open-Source?
|
||||
|
||||
**Implement in Lobehub if**:
|
||||
|
||||
- Feature is useful for all LobeHub users
|
||||
- No proprietary business logic
|
||||
- Can be open-sourced
|
||||
|
||||
**Implement in Cloud if**:
|
||||
|
||||
- Premium/paid feature
|
||||
- Uses cloud-specific services
|
||||
- Contains proprietary algorithms
|
||||
|
||||
### 2. Re-export Pattern
|
||||
|
||||
✅ **Do**:
|
||||
|
||||
```typescript
|
||||
// Simple re-export
|
||||
export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature/route';
|
||||
```
|
||||
|
||||
❌ **Don't**:
|
||||
|
||||
```typescript
|
||||
// Avoid circular imports with @/ path
|
||||
export { POST } from '@/app/(backend)/api/workflows/feature/route'; // ❌
|
||||
```
|
||||
|
||||
### 3. Keep Workflow Logic in Lobehub
|
||||
|
||||
For shared features:
|
||||
|
||||
- Implement core logic in `lobehub/` (open-source)
|
||||
- Only override if cloud needs different behavior
|
||||
- Use re-exports for cloud deployment
|
||||
|
||||
### 4. Directory Naming
|
||||
|
||||
Follow consistent naming across lobehub and cloud:
|
||||
|
||||
```
|
||||
# Both should use same structure
|
||||
lobehub/src/app/(backend)/api/workflows/feature-name/
|
||||
lobehub-cloud/src/app/(backend)/api/workflows/feature-name/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### Moving Workflow from Cloud to Lobehub
|
||||
|
||||
**Step 1**: Copy workflow to lobehub
|
||||
|
||||
```bash
|
||||
cp -r lobehub-cloud/src/app/(backend)/api/workflows/feature \
|
||||
lobehub/src/app/(backend)/api/workflows/
|
||||
```
|
||||
|
||||
**Step 2**: Remove cloud-specific dependencies
|
||||
|
||||
- Replace cloud services with generic interfaces
|
||||
- Remove proprietary business logic
|
||||
- Update imports to use lobehub paths
|
||||
|
||||
**Step 3**: Create re-exports in cloud
|
||||
|
||||
```typescript
|
||||
// lobehub-cloud/src/app/(backend)/api/workflows/feature/*/route.ts
|
||||
export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature/*/route';
|
||||
```
|
||||
|
||||
**Step 4**: Move workflow class to lobehub
|
||||
|
||||
```bash
|
||||
mv lobehub-cloud/src/server/workflows/feature \
|
||||
lobehub/src/server/workflows/
|
||||
```
|
||||
|
||||
**Step 5**: Update cloud imports
|
||||
|
||||
```typescript
|
||||
// Change from
|
||||
import { Workflow } from '@/server/workflows/feature';
|
||||
|
||||
// To
|
||||
import { Workflow } from 'lobehub/src/server/workflows/feature';
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Examples
|
||||
|
||||
### Cloud-Only Workflow: welcome-placeholder
|
||||
|
||||
**Location**: `lobehub-cloud/src/app/(backend)/api/workflows/welcome-placeholder/`
|
||||
|
||||
**Why Cloud-Only**: Uses proprietary AI generation service and Redis caching
|
||||
|
||||
**Structure**:
|
||||
|
||||
```
|
||||
lobehub-cloud/
|
||||
├── src/app/(backend)/api/workflows/welcome-placeholder/
|
||||
│ ├── process-users/route.ts
|
||||
│ ├── paginate-users/route.ts
|
||||
│ └── generate-user/route.ts
|
||||
└── src/server/workflows/welcomePlaceholder/
|
||||
└── index.ts
|
||||
```
|
||||
|
||||
### Re-exported Workflow: agent-eval-run
|
||||
|
||||
**Location**:
|
||||
|
||||
- Implementation: `lobehub/src/app/(backend)/api/workflows/agent-eval-run/`
|
||||
- Re-export: `lobehub-cloud/src/app/(backend)/api/workflows/agent-eval-run/`
|
||||
|
||||
**Why Re-export**: Core feature available in open-source, also used by cloud
|
||||
|
||||
**Cloud Re-export Files**:
|
||||
|
||||
```typescript
|
||||
// lobehub-cloud/src/app/(backend)/api/workflows/agent-eval-run/run-benchmark/route.ts
|
||||
export { POST } from 'lobehub/src/app/(backend)/api/workflows/agent-eval-run/run-benchmark/route';
|
||||
|
||||
// lobehub-cloud/src/app/(backend)/api/workflows/agent-eval-run/paginate-test-cases/route.ts
|
||||
export { POST } from 'lobehub/src/app/(backend)/api/workflows/agent-eval-run/paginate-test-cases/route';
|
||||
|
||||
// ... (all layers)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Circular Import Error
|
||||
|
||||
**Error**: `Circular definition of import alias 'POST'`
|
||||
|
||||
**Cause**: Using `@/` path in re-export within cloud codebase
|
||||
|
||||
**Solution**: Use `lobehub/src/` path instead
|
||||
|
||||
```typescript
|
||||
// ❌ Wrong
|
||||
export { POST } from '@/app/(backend)/api/workflows/feature/route';
|
||||
|
||||
// ✅ Correct
|
||||
export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature/route';
|
||||
```
|
||||
|
||||
### Workflow Not Found (404)
|
||||
|
||||
**Cause**: Missing re-export in cloud
|
||||
|
||||
**Solution**: Create re-export files for all workflow layers
|
||||
|
||||
```bash
|
||||
# Check if re-export exists
|
||||
ls lobehub-cloud/src/app/\(backend\)/api/workflows/feature-name/
|
||||
|
||||
# If missing, create re-exports
|
||||
mkdir -p lobehub-cloud/src/app/\(backend\)/api/workflows/feature-name/layer
|
||||
echo "export { POST } from 'lobehub/src/app/(backend)/api/workflows/feature-name/layer/route';" > lobehub-cloud/src/app/\(backend\)/api/workflows/feature-name/layer/route.ts
|
||||
```
|
||||
|
||||
### Type Errors After Moving to Lobehub
|
||||
|
||||
**Cause**: Cloud-specific types or services used in lobehub code
|
||||
|
||||
**Solution**:
|
||||
|
||||
1. Extract cloud-specific logic to cloud-only wrapper
|
||||
2. Use dependency injection for services
|
||||
3. Define generic interfaces in lobehub
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [SKILL.md](../SKILL.md) - Standard workflow patterns
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,127 +0,0 @@
|
||||
---
|
||||
name: vercel-react-best-practices
|
||||
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: '1.0.0'
|
||||
---
|
||||
|
||||
# Vercel React Best Practices
|
||||
|
||||
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
|
||||
- Writing new React components or Next.js pages
|
||||
- Implementing data fetching (client or server-side)
|
||||
- Reviewing code for performance issues
|
||||
- Refactoring existing React/Next.js code
|
||||
- Optimizing bundle size or load times
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
| -------- | ------------------------- | ----------- | ------------ |
|
||||
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Eliminating Waterfalls (CRITICAL)
|
||||
|
||||
- `async-defer-await` - Move await into branches where actually used
|
||||
- `async-parallel` - Use Promise.all() for independent operations
|
||||
- `async-dependencies` - Use better-all for partial dependencies
|
||||
- `async-api-routes` - Start promises early, await late in API routes
|
||||
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||
|
||||
### 2. Bundle Size Optimization (CRITICAL)
|
||||
|
||||
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||
- `bundle-conditional` - Load modules only when feature is activated
|
||||
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||
|
||||
### 3. Server-Side Performance (HIGH)
|
||||
|
||||
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||
- `server-serialization` - Minimize data passed to client components
|
||||
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||
|
||||
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||
|
||||
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||
- `client-event-listeners` - Deduplicate global event listeners
|
||||
|
||||
### 5. Re-render Optimization (MEDIUM)
|
||||
|
||||
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||
- `rerender-memo` - Extract expensive work into memoized components
|
||||
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||
|
||||
### 6. Rendering Performance (MEDIUM)
|
||||
|
||||
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||
- `rendering-activity` - Use Activity component for show/hide
|
||||
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||
|
||||
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||
|
||||
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||
- `js-index-maps` - Build Map for repeated lookups
|
||||
- `js-cache-property-access` - Cache object properties in loops
|
||||
- `js-cache-function-results` - Cache function results in module-level Map
|
||||
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||
- `js-length-check-first` - Check array length before expensive comparison
|
||||
- `js-early-exit` - Return early from functions
|
||||
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||
|
||||
### 8. Advanced Patterns (LOW)
|
||||
|
||||
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||
- `advanced-use-latest` - useLatest for stable callback refs
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/async-parallel.md
|
||||
rules/bundle-barrel-imports.md
|
||||
rules/_sections.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -1,55 +0,0 @@
|
||||
---
|
||||
title: Store Event Handlers in Refs
|
||||
impact: LOW
|
||||
impactDescription: stable subscriptions
|
||||
tags: advanced, hooks, refs, event-handlers, optimization
|
||||
---
|
||||
|
||||
## Store Event Handlers in Refs
|
||||
|
||||
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||
|
||||
**Incorrect (re-subscribes on every render):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, handler);
|
||||
return () => window.removeEventListener(event, handler);
|
||||
}, [event, handler]);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable subscription):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const handlerRef = useRef(handler);
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler;
|
||||
}, [handler]);
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (e) => handlerRef.current(e);
|
||||
window.addEventListener(event, listener);
|
||||
return () => window.removeEventListener(event, listener);
|
||||
}, [event]);
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react';
|
||||
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const onEvent = useEffectEvent(handler);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, onEvent);
|
||||
return () => window.removeEventListener(event, onEvent);
|
||||
}, [event]);
|
||||
}
|
||||
```
|
||||
|
||||
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
title: useLatest for Stable Callback Refs
|
||||
impact: LOW
|
||||
impactDescription: prevents effect re-runs
|
||||
tags: advanced, hooks, useLatest, refs, optimization
|
||||
---
|
||||
|
||||
## useLatest for Stable Callback Refs
|
||||
|
||||
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```typescript
|
||||
function useLatest<T>(value: T) {
|
||||
const ref = useRef(value);
|
||||
useLayoutEffect(() => {
|
||||
ref.current = value;
|
||||
}, [value]);
|
||||
return ref;
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (effect re-runs on every callback change):**
|
||||
|
||||
```tsx
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearch(query), 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [query, onSearch]);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable effect, fresh callback):**
|
||||
|
||||
```tsx
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('');
|
||||
const onSearchRef = useLatest(onSearch);
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearchRef.current(query), 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [query]);
|
||||
}
|
||||
```
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
title: Prevent Waterfall Chains in API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: api-routes, server-actions, waterfalls, parallelization
|
||||
---
|
||||
|
||||
## Prevent Waterfall Chains in API Routes
|
||||
|
||||
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||
|
||||
**Incorrect (config waits for auth, data waits for both):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth();
|
||||
const config = await fetchConfig();
|
||||
const data = await fetchData(session.user.id);
|
||||
return Response.json({ data, config });
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (auth and config start immediately):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const sessionPromise = auth();
|
||||
const configPromise = fetchConfig();
|
||||
const session = await sessionPromise;
|
||||
const [config, data] = await Promise.all([configPromise, fetchData(session.user.id)]);
|
||||
return Response.json({ data, config });
|
||||
}
|
||||
```
|
||||
|
||||
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||
@@ -1,80 +0,0 @@
|
||||
---
|
||||
title: Defer Await Until Needed
|
||||
impact: HIGH
|
||||
impactDescription: avoids blocking unused code paths
|
||||
tags: async, await, conditional, optimization
|
||||
---
|
||||
|
||||
## Defer Await Until Needed
|
||||
|
||||
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||
|
||||
**Incorrect (blocks both branches):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
const userData = await fetchUserData(userId);
|
||||
|
||||
if (skipProcessing) {
|
||||
// Returns immediately but still waited for userData
|
||||
return { skipped: true };
|
||||
}
|
||||
|
||||
// Only this branch uses userData
|
||||
return processUserData(userData);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (only blocks when needed):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
if (skipProcessing) {
|
||||
// Returns immediately without waiting
|
||||
return { skipped: true };
|
||||
}
|
||||
|
||||
// Fetch only when needed
|
||||
const userData = await fetchUserData(userId);
|
||||
return processUserData(userData);
|
||||
}
|
||||
```
|
||||
|
||||
**Another example (early return optimization):**
|
||||
|
||||
```typescript
|
||||
// Incorrect: always fetches permissions
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const permissions = await fetchPermissions(userId);
|
||||
const resource = await getResource(resourceId);
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' };
|
||||
}
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' };
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions);
|
||||
}
|
||||
|
||||
// Correct: fetches only when needed
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const resource = await getResource(resourceId);
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' };
|
||||
}
|
||||
|
||||
const permissions = await fetchPermissions(userId);
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' };
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions);
|
||||
}
|
||||
```
|
||||
|
||||
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||
@@ -1,37 +0,0 @@
|
||||
---
|
||||
title: Dependency-Based Parallelization
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, dependencies, better-all
|
||||
---
|
||||
|
||||
## Dependency-Based Parallelization
|
||||
|
||||
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||
|
||||
**Incorrect (profile waits for config unnecessarily):**
|
||||
|
||||
```typescript
|
||||
const [user, config] = await Promise.all([fetchUser(), fetchConfig()]);
|
||||
const profile = await fetchProfile(user.id);
|
||||
```
|
||||
|
||||
**Correct (config and profile run in parallel):**
|
||||
|
||||
```typescript
|
||||
import { all } from 'better-all';
|
||||
|
||||
const { user, config, profile } = await all({
|
||||
async user() {
|
||||
return fetchUser();
|
||||
},
|
||||
async config() {
|
||||
return fetchConfig();
|
||||
},
|
||||
async profile() {
|
||||
return fetchProfile((await this.$.user).id);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Reference: <https://github.com/shuding/better-all>
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
title: Promise.all() for Independent Operations
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, promises, waterfalls
|
||||
---
|
||||
|
||||
## Promise.all() for Independent Operations
|
||||
|
||||
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||
|
||||
**Incorrect (sequential execution, 3 round trips):**
|
||||
|
||||
```typescript
|
||||
const user = await fetchUser();
|
||||
const posts = await fetchPosts();
|
||||
const comments = await fetchComments();
|
||||
```
|
||||
|
||||
**Correct (parallel execution, 1 round trip):**
|
||||
|
||||
```typescript
|
||||
const [user, posts, comments] = await Promise.all([fetchUser(), fetchPosts(), fetchComments()]);
|
||||
```
|
||||
@@ -1,99 +0,0 @@
|
||||
---
|
||||
title: Strategic Suspense Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: faster initial paint
|
||||
tags: async, suspense, streaming, layout-shift
|
||||
---
|
||||
|
||||
## Strategic Suspense Boundaries
|
||||
|
||||
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||
|
||||
**Incorrect (wrapper blocked by data fetching):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const data = await fetchData(); // Blocks entire page
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<DataDisplay data={data} />
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The entire layout waits for data even though only the middle section needs it.
|
||||
|
||||
**Correct (wrapper shows immediately, data streams in):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay />
|
||||
</Suspense>
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function DataDisplay() {
|
||||
const data = await fetchData(); // Only blocks this component
|
||||
return <div>{data.content}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||
|
||||
**Alternative (share promise across components):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
// Start fetch immediately, but don't await
|
||||
const dataPromise = fetchData();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay dataPromise={dataPromise} />
|
||||
<DataSummary dataPromise={dataPromise} />
|
||||
</Suspense>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise); // Unwraps the promise
|
||||
return <div>{data.content}</div>;
|
||||
}
|
||||
|
||||
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise); // Reuses the same promise
|
||||
return <div>{data.summary}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||
|
||||
**When NOT to use this pattern:**
|
||||
|
||||
- Critical data needed for layout decisions (affects positioning)
|
||||
- SEO-critical content above the fold
|
||||
- Small, fast queries where suspense overhead isn't worth it
|
||||
- When you want to avoid layout shift (loading → content jump)
|
||||
|
||||
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
title: Avoid Barrel File Imports
|
||||
impact: CRITICAL
|
||||
impactDescription: 200-800ms import cost, slow builds
|
||||
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||
---
|
||||
|
||||
## Avoid Barrel File Imports
|
||||
|
||||
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||
|
||||
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||
|
||||
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||
|
||||
**Incorrect (imports entire library):**
|
||||
|
||||
```tsx
|
||||
import { Check, X, Menu } from 'lucide-react';
|
||||
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||
// Runtime cost: 200-800ms on every cold start
|
||||
|
||||
import { Button, TextField } from '@mui/material';
|
||||
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||
```
|
||||
|
||||
**Correct (imports only what you need):**
|
||||
|
||||
```tsx
|
||||
import Check from 'lucide-react/dist/esm/icons/check';
|
||||
import X from 'lucide-react/dist/esm/icons/x';
|
||||
import Menu from 'lucide-react/dist/esm/icons/menu';
|
||||
// Loads only 3 modules (~2KB vs ~1MB)
|
||||
|
||||
import Button from '@mui/material/Button';
|
||||
import TextField from '@mui/material/TextField';
|
||||
// Loads only what you use
|
||||
```
|
||||
|
||||
**Alternative (Next.js 13.5+):**
|
||||
|
||||
```js
|
||||
// next.config.js - use optimizePackageImports
|
||||
module.exports = {
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@mui/material'],
|
||||
},
|
||||
};
|
||||
|
||||
// Then you can keep the ergonomic barrel imports:
|
||||
import { Check, X, Menu } from 'lucide-react';
|
||||
// Automatically transformed to direct imports at build time
|
||||
```
|
||||
|
||||
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||
|
||||
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||
|
||||
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||
@@ -1,37 +0,0 @@
|
||||
---
|
||||
title: Conditional Module Loading
|
||||
impact: HIGH
|
||||
impactDescription: loads large data only when needed
|
||||
tags: bundle, conditional-loading, lazy-loading
|
||||
---
|
||||
|
||||
## Conditional Module Loading
|
||||
|
||||
Load large data or modules only when a feature is activated.
|
||||
|
||||
**Example (lazy-load animation frames):**
|
||||
|
||||
```tsx
|
||||
function AnimationPlayer({
|
||||
enabled,
|
||||
setEnabled,
|
||||
}: {
|
||||
enabled: boolean;
|
||||
setEnabled: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
}) {
|
||||
const [frames, setFrames] = useState<Frame[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled && !frames && typeof window !== 'undefined') {
|
||||
import('./animation-frames.js')
|
||||
.then((mod) => setFrames(mod.frames))
|
||||
.catch(() => setEnabled(false));
|
||||
}
|
||||
}, [enabled, frames, setEnabled]);
|
||||
|
||||
if (!frames) return <Skeleton />;
|
||||
return <Canvas frames={frames} />;
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||
@@ -1,48 +0,0 @@
|
||||
---
|
||||
title: Defer Non-Critical Third-Party Libraries
|
||||
impact: MEDIUM
|
||||
impactDescription: loads after hydration
|
||||
tags: bundle, third-party, analytics, defer
|
||||
---
|
||||
|
||||
## Defer Non-Critical Third-Party Libraries
|
||||
|
||||
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||
|
||||
**Incorrect (blocks initial bundle):**
|
||||
|
||||
```tsx
|
||||
import { Analytics } from '@vercel/analytics/react';
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (loads after hydration):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
const Analytics = dynamic(() => import('@vercel/analytics/react').then((m) => m.Analytics), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
title: Dynamic Imports for Heavy Components
|
||||
impact: CRITICAL
|
||||
impactDescription: directly affects TTI and LCP
|
||||
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||
---
|
||||
|
||||
## Dynamic Imports for Heavy Components
|
||||
|
||||
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||
|
||||
**Incorrect (Monaco bundles with main chunk \~300KB):**
|
||||
|
||||
```tsx
|
||||
import { MonacoEditor } from './monaco-editor';
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (Monaco loads on demand):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
const MonacoEditor = dynamic(() => import('./monaco-editor').then((m) => m.MonacoEditor), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />;
|
||||
}
|
||||
```
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
title: Preload Based on User Intent
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces perceived latency
|
||||
tags: bundle, preload, user-intent, hover
|
||||
---
|
||||
|
||||
## Preload Based on User Intent
|
||||
|
||||
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||
|
||||
**Example (preload on hover/focus):**
|
||||
|
||||
```tsx
|
||||
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||
const preload = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
void import('./monaco-editor');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button onMouseEnter={preload} onFocus={preload} onClick={onClick}>
|
||||
Open Editor
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Example (preload when feature flag is enabled):**
|
||||
|
||||
```tsx
|
||||
function FlagsProvider({ children, flags }: Props) {
|
||||
useEffect(() => {
|
||||
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||
void import('./monaco-editor').then((mod) => mod.init());
|
||||
}
|
||||
}, [flags.editorEnabled]);
|
||||
|
||||
return <FlagsContext.Provider value={flags}>{children}</FlagsContext.Provider>;
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||
@@ -1,78 +0,0 @@
|
||||
---
|
||||
title: Deduplicate Global Event Listeners
|
||||
impact: LOW
|
||||
impactDescription: single listener for N components
|
||||
tags: client, swr, event-listeners, subscription
|
||||
---
|
||||
|
||||
## Deduplicate Global Event Listeners
|
||||
|
||||
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||
|
||||
**Incorrect (N instances = N listeners):**
|
||||
|
||||
```tsx
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && e.key === key) {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, [key, callback]);
|
||||
}
|
||||
```
|
||||
|
||||
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||
|
||||
**Correct (N instances = 1 listener):**
|
||||
|
||||
```tsx
|
||||
import useSWRSubscription from 'swr/subscription';
|
||||
|
||||
// Module-level Map to track callbacks per key
|
||||
const keyCallbacks = new Map<string, Set<() => void>>();
|
||||
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
// Register this callback in the Map
|
||||
useEffect(() => {
|
||||
if (!keyCallbacks.has(key)) {
|
||||
keyCallbacks.set(key, new Set());
|
||||
}
|
||||
keyCallbacks.get(key)!.add(callback);
|
||||
|
||||
return () => {
|
||||
const set = keyCallbacks.get(key);
|
||||
if (set) {
|
||||
set.delete(callback);
|
||||
if (set.size === 0) {
|
||||
keyCallbacks.delete(key);
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [key, callback]);
|
||||
|
||||
useSWRSubscription('global-keydown', () => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||
keyCallbacks.get(e.key)!.forEach((cb) => cb());
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
});
|
||||
}
|
||||
|
||||
function Profile() {
|
||||
// Multiple shortcuts will share the same listener
|
||||
useKeyboardShortcut('p', () => {
|
||||
/* ... */
|
||||
});
|
||||
useKeyboardShortcut('k', () => {
|
||||
/* ... */
|
||||
});
|
||||
// ...
|
||||
}
|
||||
```
|
||||
@@ -1,74 +0,0 @@
|
||||
---
|
||||
title: Version and Minimize localStorage Data
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents schema conflicts, reduces storage size
|
||||
tags: client, localStorage, storage, versioning, data-minimization
|
||||
---
|
||||
|
||||
## Version and Minimize localStorage Data
|
||||
|
||||
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
// No version, stores everything, no error handling
|
||||
localStorage.setItem('userConfig', JSON.stringify(fullUserObject));
|
||||
const data = localStorage.getItem('userConfig');
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
const VERSION = 'v2';
|
||||
|
||||
function saveConfig(config: { theme: string; language: string }) {
|
||||
try {
|
||||
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config));
|
||||
} catch {
|
||||
// Throws in incognito/private browsing, quota exceeded, or disabled
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
const data = localStorage.getItem(`userConfig:${VERSION}`);
|
||||
return data ? JSON.parse(data) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Migration from v1 to v2
|
||||
function migrate() {
|
||||
try {
|
||||
const v1 = localStorage.getItem('userConfig:v1');
|
||||
if (v1) {
|
||||
const old = JSON.parse(v1);
|
||||
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang });
|
||||
localStorage.removeItem('userConfig:v1');
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Store minimal fields from server responses:**
|
||||
|
||||
```typescript
|
||||
// User object has 20+ fields, only store what UI needs
|
||||
function cachePrefs(user: FullUser) {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
'prefs:v1',
|
||||
JSON.stringify({
|
||||
theme: user.preferences.theme,
|
||||
notifications: user.preferences.notifications,
|
||||
}),
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
|
||||
|
||||
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
|
||||
@@ -1,48 +0,0 @@
|
||||
---
|
||||
title: Use Passive Event Listeners for Scrolling Performance
|
||||
impact: MEDIUM
|
||||
impactDescription: eliminates scroll delay caused by event listeners
|
||||
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||
---
|
||||
|
||||
## Use Passive Event Listeners for Scrolling Performance
|
||||
|
||||
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
|
||||
|
||||
document.addEventListener('touchstart', handleTouch);
|
||||
document.addEventListener('wheel', handleWheel);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch);
|
||||
document.removeEventListener('wheel', handleWheel);
|
||||
};
|
||||
}, []);
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
|
||||
|
||||
document.addEventListener('touchstart', handleTouch, { passive: true });
|
||||
document.addEventListener('wheel', handleWheel, { passive: true });
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch);
|
||||
document.removeEventListener('wheel', handleWheel);
|
||||
};
|
||||
}, []);
|
||||
```
|
||||
|
||||
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||
|
||||
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
title: Use SWR for Automatic Deduplication
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: automatic deduplication
|
||||
tags: client, swr, deduplication, data-fetching
|
||||
---
|
||||
|
||||
## Use SWR for Automatic Deduplication
|
||||
|
||||
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||
|
||||
**Incorrect (no deduplication, each instance fetches):**
|
||||
|
||||
```tsx
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([]);
|
||||
useEffect(() => {
|
||||
fetch('/api/users')
|
||||
.then((r) => r.json())
|
||||
.then(setUsers);
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (multiple instances share one request):**
|
||||
|
||||
```tsx
|
||||
import useSWR from 'swr';
|
||||
|
||||
function UserList() {
|
||||
const { data: users } = useSWR('/api/users', fetcher);
|
||||
}
|
||||
```
|
||||
|
||||
**For immutable data:**
|
||||
|
||||
```tsx
|
||||
import { useImmutableSWR } from '@/lib/swr';
|
||||
|
||||
function StaticContent() {
|
||||
const { data } = useImmutableSWR('/api/config', fetcher);
|
||||
}
|
||||
```
|
||||
|
||||
**For mutations:**
|
||||
|
||||
```tsx
|
||||
import { useSWRMutation } from 'swr/mutation';
|
||||
|
||||
function UpdateButton() {
|
||||
const { trigger } = useSWRMutation('/api/user', updateUser);
|
||||
return <button onClick={() => trigger()}>Update</button>;
|
||||
}
|
||||
```
|
||||
|
||||
Reference: <https://swr.vercel.app>
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
title: Batch DOM CSS Changes
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces reflows/repaints
|
||||
tags: javascript, dom, css, performance, reflow
|
||||
---
|
||||
|
||||
## Batch DOM CSS Changes
|
||||
|
||||
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
|
||||
|
||||
**Incorrect (interleaved reads and writes force reflows):**
|
||||
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
element.style.width = '100px';
|
||||
const width = element.offsetWidth; // Forces reflow
|
||||
element.style.height = '200px';
|
||||
const height = element.offsetHeight; // Forces another reflow
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch writes, then read once):**
|
||||
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Batch all writes together
|
||||
element.style.width = '100px';
|
||||
element.style.height = '200px';
|
||||
element.style.backgroundColor = 'blue';
|
||||
element.style.border = '1px solid black';
|
||||
|
||||
// Read after all writes are done (single reflow)
|
||||
const { width, height } = element.getBoundingClientRect();
|
||||
}
|
||||
```
|
||||
|
||||
**Better: use CSS classes**
|
||||
|
||||
```css
|
||||
.highlighted-box {
|
||||
width: 100px;
|
||||
height: 200px;
|
||||
background-color: blue;
|
||||
border: 1px solid black;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
element.classList.add('highlighted-box');
|
||||
|
||||
const { width, height } = element.getBoundingClientRect();
|
||||
}
|
||||
```
|
||||
|
||||
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
|
||||
@@ -1,80 +0,0 @@
|
||||
---
|
||||
title: Cache Repeated Function Calls
|
||||
impact: MEDIUM
|
||||
impactDescription: avoid redundant computation
|
||||
tags: javascript, cache, memoization, performance
|
||||
---
|
||||
|
||||
## Cache Repeated Function Calls
|
||||
|
||||
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||
|
||||
**Incorrect (redundant computation):**
|
||||
|
||||
```typescript
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// slugify() called 100+ times for same project names
|
||||
const slug = slugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (cached results):**
|
||||
|
||||
```typescript
|
||||
// Module-level cache
|
||||
const slugifyCache = new Map<string, string>()
|
||||
|
||||
function cachedSlugify(text: string): string {
|
||||
if (slugifyCache.has(text)) {
|
||||
return slugifyCache.get(text)!
|
||||
}
|
||||
const result = slugify(text)
|
||||
slugifyCache.set(text, result)
|
||||
return result
|
||||
}
|
||||
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// Computed only once per unique project name
|
||||
const slug = cachedSlugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Simpler pattern for single-value functions:**
|
||||
|
||||
```typescript
|
||||
let isLoggedInCache: boolean | null = null;
|
||||
|
||||
function isLoggedIn(): boolean {
|
||||
if (isLoggedInCache !== null) {
|
||||
return isLoggedInCache;
|
||||
}
|
||||
|
||||
isLoggedInCache = document.cookie.includes('auth=');
|
||||
return isLoggedInCache;
|
||||
}
|
||||
|
||||
// Clear cache when auth changes
|
||||
function onAuthChange() {
|
||||
isLoggedInCache = null;
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
title: Cache Property Access in Loops
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces lookups
|
||||
tags: javascript, loops, optimization, caching
|
||||
---
|
||||
|
||||
## Cache Property Access in Loops
|
||||
|
||||
Cache object property lookups in hot paths.
|
||||
|
||||
**Incorrect (3 lookups × N iterations):**
|
||||
|
||||
```typescript
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
process(obj.config.settings.value);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (1 lookup total):**
|
||||
|
||||
```typescript
|
||||
const value = obj.config.settings.value;
|
||||
const len = arr.length;
|
||||
for (let i = 0; i < len; i++) {
|
||||
process(value);
|
||||
}
|
||||
```
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
title: Cache Storage API Calls
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces expensive I/O
|
||||
tags: javascript, localStorage, storage, caching, performance
|
||||
---
|
||||
|
||||
## Cache Storage API Calls
|
||||
|
||||
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||
|
||||
**Incorrect (reads storage on every call):**
|
||||
|
||||
```typescript
|
||||
function getTheme() {
|
||||
return localStorage.getItem('theme') ?? 'light';
|
||||
}
|
||||
// Called 10 times = 10 storage reads
|
||||
```
|
||||
|
||||
**Correct (Map cache):**
|
||||
|
||||
```typescript
|
||||
const storageCache = new Map<string, string | null>();
|
||||
|
||||
function getLocalStorage(key: string) {
|
||||
if (!storageCache.has(key)) {
|
||||
storageCache.set(key, localStorage.getItem(key));
|
||||
}
|
||||
return storageCache.get(key);
|
||||
}
|
||||
|
||||
function setLocalStorage(key: string, value: string) {
|
||||
localStorage.setItem(key, value);
|
||||
storageCache.set(key, value); // keep cache in sync
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
**Cookie caching:**
|
||||
|
||||
```typescript
|
||||
let cookieCache: Record<string, string> | null = null;
|
||||
|
||||
function getCookie(name: string) {
|
||||
if (!cookieCache) {
|
||||
cookieCache = Object.fromEntries(document.cookie.split('; ').map((c) => c.split('=')));
|
||||
}
|
||||
return cookieCache[name];
|
||||
}
|
||||
```
|
||||
|
||||
**Important (invalidate on external changes):**
|
||||
|
||||
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||
|
||||
```typescript
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key) storageCache.delete(e.key);
|
||||
});
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
storageCache.clear();
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
title: Combine Multiple Array Iterations
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces iterations
|
||||
tags: javascript, arrays, loops, performance
|
||||
---
|
||||
|
||||
## Combine Multiple Array Iterations
|
||||
|
||||
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||
|
||||
**Incorrect (3 iterations):**
|
||||
|
||||
```typescript
|
||||
const admins = users.filter((u) => u.isAdmin);
|
||||
const testers = users.filter((u) => u.isTester);
|
||||
const inactive = users.filter((u) => !u.isActive);
|
||||
```
|
||||
|
||||
**Correct (1 iteration):**
|
||||
|
||||
```typescript
|
||||
const admins: User[] = [];
|
||||
const testers: User[] = [];
|
||||
const inactive: User[] = [];
|
||||
|
||||
for (const user of users) {
|
||||
if (user.isAdmin) admins.push(user);
|
||||
if (user.isTester) testers.push(user);
|
||||
if (!user.isActive) inactive.push(user);
|
||||
}
|
||||
```
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
title: Early Return from Functions
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids unnecessary computation
|
||||
tags: javascript, functions, optimization, early-return
|
||||
---
|
||||
|
||||
## Early Return from Functions
|
||||
|
||||
Return early when result is determined to skip unnecessary processing.
|
||||
|
||||
**Incorrect (processes all items even after finding answer):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
let hasError = false;
|
||||
let errorMessage = '';
|
||||
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
hasError = true;
|
||||
errorMessage = 'Email required';
|
||||
}
|
||||
if (!user.name) {
|
||||
hasError = true;
|
||||
errorMessage = 'Name required';
|
||||
}
|
||||
// Continues checking all users even after error found
|
||||
}
|
||||
|
||||
return hasError ? { valid: false, error: errorMessage } : { valid: true };
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (returns immediately on first error):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
return { valid: false, error: 'Email required' };
|
||||
}
|
||||
if (!user.name) {
|
||||
return { valid: false, error: 'Name required' };
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
```
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
title: Hoist RegExp Creation
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids recreation
|
||||
tags: javascript, regexp, optimization, memoization
|
||||
---
|
||||
|
||||
## Hoist RegExp Creation
|
||||
|
||||
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||
|
||||
**Incorrect (new RegExp every render):**
|
||||
|
||||
```tsx
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = new RegExp(`(${query})`, 'gi')
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (memoize or hoist):**
|
||||
|
||||
```tsx
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = useMemo(
|
||||
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||
[query]
|
||||
)
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Warning (global regex has mutable state):**
|
||||
|
||||
Global regex (`/g`) has mutable `lastIndex` state:
|
||||
|
||||
```typescript
|
||||
const regex = /foo/g;
|
||||
regex.test('foo'); // true, lastIndex = 3
|
||||
regex.test('foo'); // false, lastIndex = 0
|
||||
```
|
||||
@@ -1,37 +0,0 @@
|
||||
---
|
||||
title: Build Index Maps for Repeated Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: 1M ops to 2K ops
|
||||
tags: javascript, map, indexing, optimization, performance
|
||||
---
|
||||
|
||||
## Build Index Maps for Repeated Lookups
|
||||
|
||||
Multiple `.find()` calls by the same key should use a Map.
|
||||
|
||||
**Incorrect (O(n) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
return orders.map((order) => ({
|
||||
...order,
|
||||
user: users.find((u) => u.id === order.userId),
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (O(1) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
const userById = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
return orders.map((order) => ({
|
||||
...order,
|
||||
user: userById.get(order.userId),
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Build map once (O(n)), then all lookups are O(1).
|
||||
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
title: Early Length Check for Array Comparisons
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: avoids expensive operations when lengths differ
|
||||
tags: javascript, arrays, performance, optimization, comparison
|
||||
---
|
||||
|
||||
## Early Length Check for Array Comparisons
|
||||
|
||||
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
||||
|
||||
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
||||
|
||||
**Incorrect (always runs expensive comparison):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Always sorts and joins, even when lengths differ
|
||||
return current.sort().join() !== original.sort().join();
|
||||
}
|
||||
```
|
||||
|
||||
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
|
||||
|
||||
**Correct (O(1) length check first):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Early return if lengths differ
|
||||
if (current.length !== original.length) {
|
||||
return true;
|
||||
}
|
||||
// Only sort when lengths match
|
||||
const currentSorted = current.toSorted();
|
||||
const originalSorted = original.toSorted();
|
||||
for (let i = 0; i < currentSorted.length; i++) {
|
||||
if (currentSorted[i] !== originalSorted[i]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
This new approach is more efficient because:
|
||||
|
||||
- It avoids the overhead of sorting and joining the arrays when lengths differ
|
||||
- It avoids consuming memory for the joined strings (especially important for large arrays)
|
||||
- It avoids mutating the original arrays
|
||||
- It returns early when a difference is found
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
title: Use Loop for Min/Max Instead of Sort
|
||||
impact: LOW
|
||||
impactDescription: O(n) instead of O(n log n)
|
||||
tags: javascript, arrays, performance, sorting, algorithms
|
||||
---
|
||||
|
||||
## Use Loop for Min/Max Instead of Sort
|
||||
|
||||
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||
|
||||
**Incorrect (O(n log n) - sort to find latest):**
|
||||
|
||||
```typescript
|
||||
interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
function getLatestProject(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
return sorted[0];
|
||||
}
|
||||
```
|
||||
|
||||
Sorts the entire array just to find the maximum value.
|
||||
|
||||
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||
|
||||
```typescript
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt);
|
||||
return { oldest: sorted[0], newest: sorted[sorted.length - 1] };
|
||||
}
|
||||
```
|
||||
|
||||
Still sorts unnecessarily when only min/max are needed.
|
||||
|
||||
**Correct (O(n) - single loop):**
|
||||
|
||||
```typescript
|
||||
function getLatestProject(projects: Project[]) {
|
||||
if (projects.length === 0) return null;
|
||||
|
||||
let latest = projects[0];
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt > latest.updatedAt) {
|
||||
latest = projects[i];
|
||||
}
|
||||
}
|
||||
|
||||
return latest;
|
||||
}
|
||||
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
if (projects.length === 0) return { oldest: null, newest: null };
|
||||
|
||||
let oldest = projects[0];
|
||||
let newest = projects[0];
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i];
|
||||
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i];
|
||||
}
|
||||
|
||||
return { oldest, newest };
|
||||
}
|
||||
```
|
||||
|
||||
Single pass through the array, no copying, no sorting.
|
||||
|
||||
**Alternative (Math.min/Math.max for small arrays):**
|
||||
|
||||
```typescript
|
||||
const numbers = [5, 2, 8, 1, 9];
|
||||
const min = Math.min(...numbers);
|
||||
const max = Math.max(...numbers);
|
||||
```
|
||||
|
||||
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
title: Use Set/Map for O(1) Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: O(n) to O(1)
|
||||
tags: javascript, set, map, data-structures, performance
|
||||
---
|
||||
|
||||
## Use Set/Map for O(1) Lookups
|
||||
|
||||
Convert arrays to Set/Map for repeated membership checks.
|
||||
|
||||
**Incorrect (O(n) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = ['a', 'b', 'c', ...]
|
||||
items.filter(item => allowedIds.includes(item.id))
|
||||
```
|
||||
|
||||
**Correct (O(1) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||
items.filter(item => allowedIds.has(item.id))
|
||||
```
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
title: Use toSorted() Instead of sort() for Immutability
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: prevents mutation bugs in React state
|
||||
tags: javascript, arrays, immutability, react, state, mutation
|
||||
---
|
||||
|
||||
## Use toSorted() Instead of sort() for Immutability
|
||||
|
||||
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||
|
||||
**Incorrect (mutates original array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Mutates the users prop array!
|
||||
const sorted = useMemo(
|
||||
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (creates new array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Creates new sorted array, original unchanged
|
||||
const sorted = useMemo(
|
||||
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters in React:**
|
||||
|
||||
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||
|
||||
**Browser support (fallback for older browsers):**
|
||||
|
||||
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||
|
||||
```typescript
|
||||
// Fallback for older browsers
|
||||
const sorted = [...items].sort((a, b) => a.value - b.value);
|
||||
```
|
||||
|
||||
**Other immutable array methods:**
|
||||
|
||||
- `.toSorted()` - immutable sort
|
||||
- `.toReversed()` - immutable reverse
|
||||
- `.toSpliced()` - immutable splice
|
||||
- `.with()` - immutable element replacement
|
||||
@@ -1,26 +0,0 @@
|
||||
---
|
||||
title: Use Activity Component for Show/Hide
|
||||
impact: MEDIUM
|
||||
impactDescription: preserves state/DOM
|
||||
tags: rendering, activity, visibility, state-preservation
|
||||
---
|
||||
|
||||
## Use Activity Component for Show/Hide
|
||||
|
||||
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
import { Activity } from 'react';
|
||||
|
||||
function Dropdown({ isOpen }: Props) {
|
||||
return (
|
||||
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||
<ExpensiveMenu />
|
||||
</Activity>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Avoids expensive re-renders and state loss.
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: Animate SVG Wrapper Instead of SVG Element
|
||||
impact: LOW
|
||||
impactDescription: enables hardware acceleration
|
||||
tags: rendering, svg, css, animation, performance
|
||||
---
|
||||
|
||||
## Animate SVG Wrapper Instead of SVG Element
|
||||
|
||||
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||
|
||||
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<svg className="animate-spin" width="24" height="24" viewBox="0 0 24 24">
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (animating wrapper div - hardware accelerated):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<div className="animate-spin">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24">
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
title: Use Explicit Conditional Rendering
|
||||
impact: LOW
|
||||
impactDescription: prevents rendering 0 or NaN
|
||||
tags: rendering, conditional, jsx, falsy-values
|
||||
---
|
||||
|
||||
## Use Explicit Conditional Rendering
|
||||
|
||||
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||
|
||||
**Incorrect (renders "0" when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return <div>{count && <span className="badge">{count}</span>}</div>;
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div>0</div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
|
||||
**Correct (renders nothing when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return <div>{count > 0 ? <span className="badge">{count}</span> : null}</div>;
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div></div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: CSS content-visibility for Long Lists
|
||||
impact: HIGH
|
||||
impactDescription: faster initial render
|
||||
tags: rendering, css, content-visibility, long-lists
|
||||
---
|
||||
|
||||
## CSS content-visibility for Long Lists
|
||||
|
||||
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||
|
||||
**CSS:**
|
||||
|
||||
```css
|
||||
.message-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 80px;
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```tsx
|
||||
function MessageList({ messages }: { messages: Message[] }) {
|
||||
return (
|
||||
<div className="overflow-y-auto h-screen">
|
||||
{messages.map((msg) => (
|
||||
<div key={msg.id} className="message-item">
|
||||
<Avatar user={msg.author} />
|
||||
<div>{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
For 1000 messages, browser skips layout/paint for \~990 off-screen items (10× faster initial render).
|
||||
@@ -1,36 +0,0 @@
|
||||
---
|
||||
title: Hoist Static JSX Elements
|
||||
impact: LOW
|
||||
impactDescription: avoids re-creation
|
||||
tags: rendering, jsx, static, optimization
|
||||
---
|
||||
|
||||
## Hoist Static JSX Elements
|
||||
|
||||
Extract static JSX outside components to avoid re-creation.
|
||||
|
||||
**Incorrect (recreates element every render):**
|
||||
|
||||
```tsx
|
||||
function LoadingSkeleton() {
|
||||
return <div className="animate-pulse h-20 bg-gray-200" />;
|
||||
}
|
||||
|
||||
function Container() {
|
||||
return <div>{loading && <LoadingSkeleton />}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reuses same element):**
|
||||
|
||||
```tsx
|
||||
const loadingSkeleton = <div className="animate-pulse h-20 bg-gray-200" />;
|
||||
|
||||
function Container() {
|
||||
return <div>{loading && loadingSkeleton}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
|
||||
@@ -1,72 +0,0 @@
|
||||
---
|
||||
title: Prevent Hydration Mismatch Without Flickering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids visual flicker and hydration errors
|
||||
tags: rendering, ssr, hydration, localStorage, flicker
|
||||
---
|
||||
|
||||
## Prevent Hydration Mismatch Without Flickering
|
||||
|
||||
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
|
||||
|
||||
**Incorrect (breaks SSR):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
// localStorage is not available on server - throws error
|
||||
const theme = localStorage.getItem('theme') || 'light';
|
||||
|
||||
return <div className={theme}>{children}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
Server-side rendering will fail because `localStorage` is undefined.
|
||||
|
||||
**Incorrect (visual flickering):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState('light');
|
||||
|
||||
useEffect(() => {
|
||||
// Runs after hydration - causes visible flash
|
||||
const stored = localStorage.getItem('theme');
|
||||
if (stored) {
|
||||
setTheme(stored);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return <div className={theme}>{children}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
||||
|
||||
**Correct (no flicker, no hydration mismatch):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<div id="theme-wrapper">{children}</div>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
(function() {
|
||||
try {
|
||||
var theme = localStorage.getItem('theme') || 'light';
|
||||
var el = document.getElementById('theme-wrapper');
|
||||
if (el) el.className = theme;
|
||||
} catch (e) {}
|
||||
})();
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
||||
|
||||
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
title: Optimize SVG Precision
|
||||
impact: LOW
|
||||
impactDescription: reduces file size
|
||||
tags: rendering, svg, optimization, svgo
|
||||
---
|
||||
|
||||
## Optimize SVG Precision
|
||||
|
||||
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
||||
|
||||
**Incorrect (excessive precision):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
||||
```
|
||||
|
||||
**Correct (1 decimal place):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.3 20.8 L 30.9 40.2" />
|
||||
```
|
||||
|
||||
**Automate with SVGO:**
|
||||
|
||||
```bash
|
||||
npx svgo --precision=1 --multipass icon.svg
|
||||
```
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
title: Defer State Reads to Usage Point
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary subscriptions
|
||||
tags: rerender, searchParams, localStorage, optimization
|
||||
---
|
||||
|
||||
## Defer State Reads to Usage Point
|
||||
|
||||
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
||||
|
||||
**Incorrect (subscribes to all searchParams changes):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const handleShare = () => {
|
||||
const ref = searchParams.get('ref');
|
||||
shareChat(chatId, { ref });
|
||||
};
|
||||
|
||||
return <button onClick={handleShare}>Share</button>;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reads on demand, no subscription):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const handleShare = () => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const ref = params.get('ref');
|
||||
shareChat(chatId, { ref });
|
||||
};
|
||||
|
||||
return <button onClick={handleShare}>Share</button>;
|
||||
}
|
||||
```
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
title: Narrow Effect Dependencies
|
||||
impact: LOW
|
||||
impactDescription: minimizes effect re-runs
|
||||
tags: rerender, useEffect, dependencies, optimization
|
||||
---
|
||||
|
||||
## Narrow Effect Dependencies
|
||||
|
||||
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
||||
|
||||
**Incorrect (re-runs on any user field change):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id);
|
||||
}, [user]);
|
||||
```
|
||||
|
||||
**Correct (re-runs only when id changes):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id);
|
||||
}, [user.id]);
|
||||
```
|
||||
|
||||
**For derived state, compute outside effect:**
|
||||
|
||||
```tsx
|
||||
// Incorrect: runs on width=767, 766, 765...
|
||||
useEffect(() => {
|
||||
if (width < 768) {
|
||||
enableMobileMode();
|
||||
}
|
||||
}, [width]);
|
||||
|
||||
// Correct: runs only on boolean transition
|
||||
const isMobile = width < 768;
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
enableMobileMode();
|
||||
}
|
||||
}, [isMobile]);
|
||||
```
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
title: Subscribe to Derived State
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces re-render frequency
|
||||
tags: rerender, derived-state, media-query, optimization
|
||||
---
|
||||
|
||||
## Subscribe to Derived State
|
||||
|
||||
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
||||
|
||||
**Incorrect (re-renders on every pixel change):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const width = useWindowWidth(); // updates continuously
|
||||
const isMobile = width < 768;
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (re-renders only when boolean changes):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const isMobile = useMediaQuery('(max-width: 767px)');
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />;
|
||||
}
|
||||
```
|
||||
@@ -1,77 +0,0 @@
|
||||
---
|
||||
title: Use Functional setState Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents stale closures and unnecessary callback recreations
|
||||
tags: react, hooks, useState, useCallback, callbacks, closures
|
||||
---
|
||||
|
||||
## Use Functional setState Updates
|
||||
|
||||
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
|
||||
|
||||
**Incorrect (requires state as dependency):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems);
|
||||
|
||||
// Callback must depend on items, recreated on every items change
|
||||
const addItems = useCallback(
|
||||
(newItems: Item[]) => {
|
||||
setItems([...items, ...newItems]);
|
||||
},
|
||||
[items],
|
||||
); // ❌ items dependency causes recreations
|
||||
|
||||
// Risk of stale closure if dependency is forgotten
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(items.filter((item) => item.id !== id));
|
||||
}, []); // ❌ Missing items dependency - will use stale items!
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />;
|
||||
}
|
||||
```
|
||||
|
||||
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
|
||||
|
||||
**Correct (stable callbacks, no stale closures):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems);
|
||||
|
||||
// Stable callback, never recreated
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems((curr) => [...curr, ...newItems]);
|
||||
}, []); // ✅ No dependencies needed
|
||||
|
||||
// Always uses latest state, no stale closure risk
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems((curr) => curr.filter((item) => item.id !== id));
|
||||
}, []); // ✅ Safe and stable
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />;
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
||||
2. **No stale closures** - Always operates on the latest state value
|
||||
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
||||
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
||||
|
||||
**When to use functional updates:**
|
||||
|
||||
- Any setState that depends on the current state value
|
||||
- Inside useCallback/useMemo when state is needed
|
||||
- Event handlers that reference state
|
||||
- Async operations that update state
|
||||
|
||||
**When direct updates are fine:**
|
||||
|
||||
- Setting state to a static value: `setCount(0)`
|
||||
- Setting state from props/arguments only: `setName(newName)`
|
||||
- State doesn't depend on previous value
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
title: Use Lazy State Initialization
|
||||
impact: MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: react, hooks, useState, performance, initialization
|
||||
---
|
||||
|
||||
## Use Lazy State Initialization
|
||||
|
||||
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
||||
|
||||
**Incorrect (runs on every render):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs on EVERY render, even after initialization
|
||||
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items));
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
// When query changes, buildSearchIndex runs again unnecessarily
|
||||
return <SearchResults index={searchIndex} query={query} />;
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs on every render
|
||||
const [settings, setSettings] = useState(JSON.parse(localStorage.getItem('settings') || '{}'));
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (runs only once):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs ONLY on initial render
|
||||
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items));
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
return <SearchResults index={searchIndex} query={query} />;
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs only on initial render
|
||||
const [settings, setSettings] = useState(() => {
|
||||
const stored = localStorage.getItem('settings');
|
||||
return stored ? JSON.parse(stored) : {};
|
||||
});
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />;
|
||||
}
|
||||
```
|
||||
|
||||
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
||||
|
||||
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
title: Extract to Memoized Components
|
||||
impact: MEDIUM
|
||||
impactDescription: enables early returns
|
||||
tags: rerender, memo, useMemo, optimization
|
||||
---
|
||||
|
||||
## Extract to Memoized Components
|
||||
|
||||
Extract expensive work into memoized components to enable early returns before computation.
|
||||
|
||||
**Incorrect (computes avatar even when loading):**
|
||||
|
||||
```tsx
|
||||
function Profile({ user, loading }: Props) {
|
||||
const avatar = useMemo(() => {
|
||||
const id = computeAvatarId(user);
|
||||
return <Avatar id={id} />;
|
||||
}, [user]);
|
||||
|
||||
if (loading) return <Skeleton />;
|
||||
return <div>{avatar}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (skips computation when loading):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
||||
const id = useMemo(() => computeAvatarId(user), [user]);
|
||||
return <Avatar id={id} />;
|
||||
});
|
||||
|
||||
function Profile({ user, loading }: Props) {
|
||||
if (loading) return <Skeleton />;
|
||||
return (
|
||||
<div>
|
||||
<UserAvatar user={user} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: Use Transitions for Non-Urgent Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: maintains UI responsiveness
|
||||
tags: rerender, transitions, startTransition, performance
|
||||
---
|
||||
|
||||
## Use Transitions for Non-Urgent Updates
|
||||
|
||||
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
||||
|
||||
**Incorrect (blocks UI on every scroll):**
|
||||
|
||||
```tsx
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0);
|
||||
useEffect(() => {
|
||||
const handler = () => setScrollY(window.scrollY);
|
||||
window.addEventListener('scroll', handler, { passive: true });
|
||||
return () => window.removeEventListener('scroll', handler);
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking updates):**
|
||||
|
||||
```tsx
|
||||
import { startTransition } from 'react';
|
||||
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0);
|
||||
useEffect(() => {
|
||||
const handler = () => {
|
||||
startTransition(() => setScrollY(window.scrollY));
|
||||
};
|
||||
window.addEventListener('scroll', handler, { passive: true });
|
||||
return () => window.removeEventListener('scroll', handler);
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
@@ -1,73 +0,0 @@
|
||||
---
|
||||
title: Use after() for Non-Blocking Operations
|
||||
impact: MEDIUM
|
||||
impactDescription: faster response times
|
||||
tags: server, async, logging, analytics, side-effects
|
||||
---
|
||||
|
||||
## Use after() for Non-Blocking Operations
|
||||
|
||||
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
||||
|
||||
**Incorrect (blocks response):**
|
||||
|
||||
```tsx
|
||||
import { logUserAction } from '@/app/utils';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request);
|
||||
|
||||
// Logging blocks the response
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown';
|
||||
await logUserAction({ userAgent });
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking):**
|
||||
|
||||
```tsx
|
||||
import { after } from 'next/server';
|
||||
import { headers, cookies } from 'next/headers';
|
||||
import { logUserAction } from '@/app/utils';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request);
|
||||
|
||||
// Log after response is sent
|
||||
after(async () => {
|
||||
const userAgent = (await headers()).get('user-agent') || 'unknown';
|
||||
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous';
|
||||
|
||||
logUserAction({ sessionCookie, userAgent });
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The response is sent immediately while logging happens in the background.
|
||||
|
||||
**Common use cases:**
|
||||
|
||||
- Analytics tracking
|
||||
- Audit logging
|
||||
- Sending notifications
|
||||
- Cache invalidation
|
||||
- Cleanup tasks
|
||||
|
||||
**Important notes:**
|
||||
|
||||
- `after()` runs even if the response fails or redirects
|
||||
- Works in Server Actions, Route Handlers, and Server Components
|
||||
|
||||
Reference: <https://nextjs.org/docs/app/api-reference/functions/after>
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
title: Cross-Request LRU Caching
|
||||
impact: HIGH
|
||||
impactDescription: caches across requests
|
||||
tags: server, cache, lru, cross-request
|
||||
---
|
||||
|
||||
## Cross-Request LRU Caching
|
||||
|
||||
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```typescript
|
||||
import { LRUCache } from 'lru-cache';
|
||||
|
||||
const cache = new LRUCache<string, any>({
|
||||
max: 1000,
|
||||
ttl: 5 * 60 * 1000, // 5 minutes
|
||||
});
|
||||
|
||||
export async function getUser(id: string) {
|
||||
const cached = cache.get(id);
|
||||
if (cached) return cached;
|
||||
|
||||
const user = await db.user.findUnique({ where: { id } });
|
||||
cache.set(id, user);
|
||||
return user;
|
||||
}
|
||||
|
||||
// Request 1: DB query, result cached
|
||||
// Request 2: cache hit, no DB query
|
||||
```
|
||||
|
||||
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
||||
|
||||
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
||||
|
||||
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
||||
|
||||
Reference: <https://github.com/isaacs/node-lru-cache>
|
||||
@@ -1,76 +0,0 @@
|
||||
---
|
||||
title: Per-Request Deduplication with React.cache()
|
||||
impact: MEDIUM
|
||||
impactDescription: deduplicates within request
|
||||
tags: server, cache, react-cache, deduplication
|
||||
---
|
||||
|
||||
## Per-Request Deduplication with React.cache()
|
||||
|
||||
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```typescript
|
||||
import { cache } from 'react';
|
||||
|
||||
export const getCurrentUser = cache(async () => {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return null;
|
||||
return await db.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
||||
|
||||
**Avoid inline objects as arguments:**
|
||||
|
||||
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
|
||||
|
||||
**Incorrect (always cache miss):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (params: { uid: number }) => {
|
||||
return await db.user.findUnique({ where: { id: params.uid } });
|
||||
});
|
||||
|
||||
// Each call creates new object, never hits cache
|
||||
getUser({ uid: 1 });
|
||||
getUser({ uid: 1 }); // Cache miss, runs query again
|
||||
```
|
||||
|
||||
**Correct (cache hit):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (uid: number) => {
|
||||
return await db.user.findUnique({ where: { id: uid } });
|
||||
});
|
||||
|
||||
// Primitive args use value equality
|
||||
getUser(1);
|
||||
getUser(1); // Cache hit, returns cached result
|
||||
```
|
||||
|
||||
If you must pass objects, pass the same reference:
|
||||
|
||||
```typescript
|
||||
const params = { uid: 1 };
|
||||
getUser(params); // Query runs
|
||||
getUser(params); // Cache hit (same reference)
|
||||
```
|
||||
|
||||
**Next.js-Specific Note:**
|
||||
|
||||
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
|
||||
|
||||
- Database queries (Prisma, Drizzle, etc.)
|
||||
- Heavy computations
|
||||
- Authentication checks
|
||||
- File system operations
|
||||
- Any non-fetch async work
|
||||
|
||||
Use `React.cache()` to deduplicate these operations across your component tree.
|
||||
|
||||
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
|
||||
@@ -1,83 +0,0 @@
|
||||
---
|
||||
title: Parallel Data Fetching with Component Composition
|
||||
impact: CRITICAL
|
||||
impactDescription: eliminates server-side waterfalls
|
||||
tags: server, rsc, parallel-fetching, composition
|
||||
---
|
||||
|
||||
## Parallel Data Fetching with Component Composition
|
||||
|
||||
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
||||
|
||||
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
||||
|
||||
```tsx
|
||||
export default async function Page() {
|
||||
const header = await fetchHeader();
|
||||
return (
|
||||
<div>
|
||||
<div>{header}</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems();
|
||||
return <nav>{items.map(renderItem)}</nav>;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (both fetch simultaneously):**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader();
|
||||
return <div>{data}</div>;
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems();
|
||||
return <nav>{items.map(renderItem)}</nav>;
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
<Sidebar />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative with children prop:**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader();
|
||||
return <div>{data}</div>;
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems();
|
||||
return <nav>{items.map(renderItem)}</nav>;
|
||||
}
|
||||
|
||||
function Layout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Layout>
|
||||
<Sidebar />
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: Minimize Serialization at RSC Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: reduces data transfer size
|
||||
tags: server, rsc, serialization, props
|
||||
---
|
||||
|
||||
## Minimize Serialization at RSC Boundaries
|
||||
|
||||
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
||||
|
||||
**Incorrect (serializes all 50 fields):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser(); // 50 fields
|
||||
return <Profile user={user} />;
|
||||
}
|
||||
|
||||
('use client');
|
||||
function Profile({ user }: { user: User }) {
|
||||
return <div>{user.name}</div>; // uses 1 field
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (serializes only 1 field):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser();
|
||||
return <Profile name={user.name} />;
|
||||
}
|
||||
|
||||
('use client');
|
||||
function Profile({ name }: { name: string }) {
|
||||
return <div>{name}</div>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,151 @@
|
||||
---
|
||||
name: version-release
|
||||
description: "Version release workflow. Use when the user mentions 'release', 'hotfix', 'version upgrade', 'weekly release', or '发版'/'发布'/'小班车'. Provides guides for Minor Release and Patch Release workflows."
|
||||
---
|
||||
|
||||
# Version Release Workflow
|
||||
|
||||
## Overview
|
||||
|
||||
The primary development branch is **canary**. All day-to-day development happens on canary. When releasing, canary is merged into main. After merge, `auto-tag-release.yml` automatically handles tagging, version bumping, creating a GitHub Release, and syncing back to the canary branch.
|
||||
|
||||
Only 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 |
|
||||
| ----- | ---------------------------------------------- | --------------------- | -------------- | ------------------------------------ | ------------- |
|
||||
| Minor | Feature iteration release | \~Every 4 weeks | canary | `🚀 release: v{x.y.0}` | Manually set |
|
||||
| Patch | Weekly release / hotfix / model / DB migration | \~Weekly or as needed | canary or main | Custom (e.g. `🚀 release: 20260222`) | Auto patch +1 |
|
||||
|
||||
## Minor Release Workflow
|
||||
|
||||
Used to publish a new minor version (e.g. v2.2.0), roughly every 4 weeks.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Create a release branch from canary**
|
||||
|
||||
```bash
|
||||
git checkout canary
|
||||
git pull origin canary
|
||||
git checkout -b release/v{version}
|
||||
git push -u origin release/v{version}
|
||||
```
|
||||
|
||||
2. **Determine the version number** — Read the current version from `package.json` and compute the next minor version (e.g. 2.1.x → 2.2.0)
|
||||
|
||||
3. **Create a PR to main**
|
||||
|
||||
```bash
|
||||
gh pr create \
|
||||
--title "🚀 release: v{version}" \
|
||||
--base main \
|
||||
--head release/v{version} \
|
||||
--body "## 📦 Release v{version} ..."
|
||||
```
|
||||
|
||||
> \[!IMPORTANT]: The PR title must strictly match the `🚀 release: v{x.y.z}` format. CI uses a regex on this title to determine the exact version number.
|
||||
|
||||
4. **Automatic trigger after merge**: auto-tag-release detects the title format and uses the version number from the title to complete the release.
|
||||
|
||||
### Scripts
|
||||
|
||||
```bash
|
||||
bun run release:branch # Interactive
|
||||
bun run release:branch --minor # Directly specify minor
|
||||
```
|
||||
|
||||
## Patch Release Workflow
|
||||
|
||||
Version number is automatically bumped by patch +1. There are 4 common scenarios:
|
||||
|
||||
| Scenario | Source Branch | Branch Naming | Description |
|
||||
| ------------------- | ------------- | ----------------------------- | ------------------------------------------------ |
|
||||
| Weekly Release | canary | `release/weekly-{YYYYMMDD}` | Weekly release train, canary → main |
|
||||
| Bug Hotfix | main | `hotfix/v{version}-{hash}` | Emergency bug fix |
|
||||
| New Model Launch | canary | Community PR merged directly | New model launch, triggered by PR title prefix |
|
||||
| DB Schema Migration | canary | `release/db-migration-{name}` | Database migration, requires dedicated changelog |
|
||||
|
||||
All scenarios auto-bump patch +1. Patch PR titles do not need a version number. See `reference/patch-release-scenarios.md` for detailed steps per scenario.
|
||||
|
||||
### Scripts
|
||||
|
||||
```bash
|
||||
bun run hotfix:branch # Hotfix scenario
|
||||
```
|
||||
|
||||
## Auto-Release Trigger Rules (auto-tag-release.yml)
|
||||
|
||||
After a PR is merged into main, CI determines whether to release based on the following priority:
|
||||
|
||||
### 1. Minor Release (Exact Version)
|
||||
|
||||
PR title matches `🚀 release: v{x.y.z}` → uses the version number from the title.
|
||||
|
||||
### 2. Patch Release (Auto patch +1)
|
||||
|
||||
Triggered by the following priority:
|
||||
|
||||
- **Branch name match**: `hotfix/*` or `release/*` → triggers directly (skips title detection)
|
||||
- **Title prefix match**: PRs with the following title prefixes will trigger:
|
||||
- `style` / `💄 style`
|
||||
- `feat` / `✨ feat`
|
||||
- `fix` / `🐛 fix`
|
||||
- `refactor` / `♻️ refactor`
|
||||
- `hotfix` / `🐛 hotfix` / `🩹 hotfix`
|
||||
- `build` / `👷 build`
|
||||
|
||||
### 3. No Trigger
|
||||
|
||||
PRs that don't match any of the above conditions (e.g. `docs`, `chore`, `ci`, `test` prefixes) will not trigger a release when merged into main.
|
||||
|
||||
## Post-Release Automated Actions
|
||||
|
||||
1. **Bump package.json** — commits `🔖 chore(release): release version v{x.y.z} [skip ci]`
|
||||
2. **Create annotated tag** — `v{x.y.z}`
|
||||
3. **Create GitHub Release**
|
||||
4. **Dispatch sync-main-to-canary** — syncs main back to the canary branch
|
||||
|
||||
## Claude Action Guide
|
||||
|
||||
When the user requests a release:
|
||||
|
||||
### Minor Release
|
||||
|
||||
1. Read `package.json` to get the current version and compute the next minor version
|
||||
2. Create a `release/v{version}` branch from canary
|
||||
3. Push and create a PR — **title must be `🚀 release: v{version}`**
|
||||
4. Inform the user that merging the PR will automatically trigger the release
|
||||
|
||||
### Patch Release
|
||||
|
||||
Choose the appropriate workflow based on the scenario (see `reference/patch-release-scenarios.md`):
|
||||
|
||||
- **Weekly Release**: Create a `release/weekly-{YYYYMMDD}` branch from canary, scan `git log main..canary` to write the changelog, title like `🚀 release: 20260222`
|
||||
- **Bug Hotfix**: Create a `hotfix/` branch from main, use a gitmoji prefix title (e.g. `🐛 fix: ...`)
|
||||
- **New Model Launch**: Community PRs trigger automatically via title prefix (`feat` / `style`), no extra steps needed
|
||||
- **DB Migration**: Create a `release/db-migration-{name}` branch from canary, write a dedicated migration changelog
|
||||
|
||||
### Important Notes
|
||||
|
||||
- **Do NOT manually modify the version in package.json** — CI will auto-bump it
|
||||
- **Do NOT manually create tags** — CI will create them automatically
|
||||
- The Minor Release PR title format is a hard requirement — incorrect format will not use the specified version number
|
||||
- Patch PRs do not need a version number — CI auto-bumps patch +1
|
||||
- All release PRs must include a user-facing changelog
|
||||
|
||||
## Changelog Writing Guidelines
|
||||
|
||||
All release PR bodies (both Minor and Patch) must include a user-facing changelog. Scan changes via `git log main..canary --oneline` or `git diff main...canary --stat`, then write following the format below.
|
||||
|
||||
### Format Reference
|
||||
|
||||
- Weekly Release: See `reference/changelog-example/weekly-release.md`
|
||||
- DB Migration: See `reference/changelog-example/db-migration.md`
|
||||
|
||||
### Writing Tips
|
||||
|
||||
- **User-facing**: Describe changes that users can perceive, not internal implementation details
|
||||
- **Clear categories**: Group by features, models/providers, desktop, stability/fixes, etc.
|
||||
- **Highlight key items**: Use `**bold**` for important feature names
|
||||
- **Credit contributors**: Collect all committers via `git log` and list alphabetically
|
||||
- **Flexible categories**: Choose categories based on actual changes — no need to force-fit all categories
|
||||
@@ -0,0 +1,18 @@
|
||||
# DB Schema Migration Changelog Example
|
||||
|
||||
A changelog reference for database migration release PR bodies.
|
||||
|
||||
---
|
||||
|
||||
This release includes a **database schema migration** involving **5 new tables** for the Agent Evaluation Benchmark system.
|
||||
|
||||
### Migration: Add Agent Evaluation Benchmark Tables
|
||||
|
||||
- Added 5 new tables: `agent_eval_benchmarks`, `agent_eval_datasets`, `agent_eval_records`, `agent_eval_runs`, `agent_eval_run_topics`
|
||||
|
||||
### Notes for Self-hosted Users
|
||||
|
||||
- The migration runs automatically on application startup
|
||||
- No manual intervention required
|
||||
|
||||
The migration owner: @arvinxx — responsible for this database schema change, reach out for any migration-related issues.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Patch Release (Weekly) Changelog Example
|
||||
|
||||
A real-world changelog reference for weekly patch release PR bodies.
|
||||
|
||||
---
|
||||
|
||||
This release includes **82 commits** , Key updates are below.
|
||||
|
||||
### New Features and Enhancements
|
||||
|
||||
- Added **Agent Benchmark** support for more systematic agent performance evaluation.
|
||||
- Introduced the **video generation** feature end-to-end, including entry points, sidebar "new" badge support, and skeleton loading for topic switching.
|
||||
- Expanded memory capabilities: support for memory effort/tool permission configuration and improved timeout calculation for memory analysis tasks.
|
||||
- Added desktop editor support for image upload via file picker.
|
||||
|
||||
### Models and Provider Expansion
|
||||
|
||||
- Added a new provider: **Straico**.
|
||||
- Added/updated support for:
|
||||
- Claude Sonnet 4.6
|
||||
- Gemini 3.1 Pro Preview
|
||||
- Qwen3.5 series
|
||||
- Grok Imagine (`grok-imagine-image`)
|
||||
- MiniMax 2.5
|
||||
- Added related i18n copy and model parameter adaptations.
|
||||
|
||||
### Desktop Improvements
|
||||
|
||||
- Integrated `electron-liquid-glass` (macOS Tahoe).
|
||||
- Improved DMG background assets and desktop release workflow.
|
||||
|
||||
### Stability, Security, and UX Fixes
|
||||
|
||||
- Fixed multiple video generation pipeline issues: precharge refund handling, webhook token verification, pricing parameter usage, asset cleanup, and type safety.
|
||||
- Fixed `sanitizeFileName` path traversal risks and added unit tests.
|
||||
- Fixed MCP media URL generation with duplicated `APP_URL` prefix.
|
||||
- Fixed Qwen3 embedding failures caused by batch-size limits.
|
||||
- Fixed multiple UI/interaction issues, including mobile header agent selector/topic count, ChatInput scrolling behavior, and tooltip stacking context.
|
||||
- Fixed missing `@napi-rs/canvas` native bindings in Docker standalone builds.
|
||||
- Improved GitHub Copilot authentication retry behavior and response error handling in edge cases.
|
||||
|
||||
### Credits
|
||||
|
||||
Huge thanks to these contributors (alphabetical):
|
||||
|
||||
@AmAzing129 @Coooolfan @Innei @ONLY-yours @Zhouguanyang @arvinxx @eaten-cake @hezhijie0327 @nekomeowww @rdmclin2 @rivertwilight @sxjeru @tjx666
|
||||
@@ -0,0 +1,118 @@
|
||||
# Patch Release Scenarios
|
||||
|
||||
All Patch Release scenarios automatically bump the patch version (e.g. 2.1.31 → 2.1.32). PR titles do not need to include a version number.
|
||||
|
||||
---
|
||||
|
||||
## 1. Weekly Release (canary → main)
|
||||
|
||||
The most common release type. Collects a week's worth of changes from canary and ships them to main.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Create release branch from canary**
|
||||
|
||||
```bash
|
||||
git checkout canary
|
||||
git pull origin canary
|
||||
git checkout -b release/weekly-{YYYYMMDD}
|
||||
git push -u origin release/weekly-{YYYYMMDD}
|
||||
```
|
||||
|
||||
2. **Scan changes and write changelog**
|
||||
|
||||
```bash
|
||||
git log main..canary --oneline
|
||||
git diff main...canary --stat
|
||||
```
|
||||
|
||||
Write a user-facing changelog following the format in `patch-release-changelog-example.md`.
|
||||
|
||||
3. **Create PR to main** with the changelog as the PR body
|
||||
|
||||
```bash
|
||||
gh pr create \
|
||||
--title "🚀 release: {YYYYMMDD}" \
|
||||
--base main \
|
||||
--head release/weekly-{YYYYMMDD} \
|
||||
--body-file changelog.md
|
||||
```
|
||||
|
||||
4. **After merge**: auto-tag-release detects `release/*` branch → auto patch +1.
|
||||
|
||||
---
|
||||
|
||||
## 2. Bug Hotfix
|
||||
|
||||
Emergency bug fix shipped directly from main.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Create hotfix branch from main**
|
||||
|
||||
```bash
|
||||
git checkout main
|
||||
git pull --rebase origin main
|
||||
git checkout -b hotfix/v{version}-{short-hash}
|
||||
git push -u origin hotfix/v{version}-{short-hash}
|
||||
```
|
||||
|
||||
2. **Create PR to main** with a gitmoji prefix title (e.g. `🐛 fix: description`)
|
||||
|
||||
3. **After merge**: auto-tag-release detects `hotfix/*` branch → auto patch +1.
|
||||
|
||||
### Script
|
||||
|
||||
```bash
|
||||
bun run hotfix:branch
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. New Model Launch
|
||||
|
||||
New AI model or provider support, typically contributed via community PRs.
|
||||
|
||||
### How it works
|
||||
|
||||
- Community contributors submit PRs with titles like `✨ feat: add xxx model` or `💄 style: support xxx models`
|
||||
- These PR title prefixes (`feat` / `style`) are in the auto-tag trigger list
|
||||
- No special branch naming or manual release steps required — merging the PR triggers auto patch +1
|
||||
|
||||
### When Claude is involved
|
||||
|
||||
If asked to add model support, just create a normal feature PR. The title prefix will trigger the release automatically.
|
||||
|
||||
---
|
||||
|
||||
## 4. DB Schema Migration
|
||||
|
||||
Database schema changes that need to be released independently. These require a dedicated changelog explaining the migration for self-hosted users.
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Create release branch from canary**
|
||||
|
||||
```bash
|
||||
git checkout canary
|
||||
git pull origin canary
|
||||
git checkout -b release/db-migration-{name}
|
||||
git push -u origin release/db-migration-{name}
|
||||
```
|
||||
|
||||
2. **Write a migration-specific changelog** — See `db-migration-changelog-example.md` for the format. This should explain:
|
||||
- What tables/columns are added, modified, or removed
|
||||
- Whether the migration is backwards-compatible
|
||||
- Any action required by self-hosted users
|
||||
|
||||
3. **Create PR to main** with the migration changelog as the PR body
|
||||
|
||||
```bash
|
||||
gh pr create \
|
||||
--title "👷 build: {migration description}" \
|
||||
--base main \
|
||||
--head release/db-migration-{name} \
|
||||
--body-file changelog.md
|
||||
```
|
||||
|
||||
4. **After merge**: auto-tag-release detects `release/*` branch → auto patch +1.
|
||||
@@ -3,7 +3,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.
|
||||
---
|
||||
|
||||
# LobeChat Zustand State Management
|
||||
# LobeHub Zustand State Management
|
||||
|
||||
## Action Type Hierarchy
|
||||
|
||||
|
||||
+1
-1
@@ -4,4 +4,4 @@ FEATURE_FLAGS=-check_updates,+pin_list
|
||||
KEY_VAULTS_SECRET=oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE=
|
||||
DATABASE_URL=postgresql://postgres@localhost:5432/postgres
|
||||
SEARCH_PROVIDERS=search1api
|
||||
NEXT_PUBLIC_IS_DESKTOP_APP=1
|
||||
DESKTOP_BUILD=true
|
||||
|
||||
@@ -247,6 +247,18 @@ OPENAI_API_KEY=sk-xxxxxxxxx
|
||||
# DOC_S3_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# DOC_S3_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
# #######################################
|
||||
# ### Mobile SPA S3 Workflow ############
|
||||
# #######################################
|
||||
|
||||
# Used by `bun run workflow:mobile-spa` to build mobile SPA, upload assets to S3, and generate template
|
||||
# MOBILE_S3_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# MOBILE_S3_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# MOBILE_S3_BUCKET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# MOBILE_S3_ENDPOINT=https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# MOBILE_S3_REGION=auto
|
||||
# MOBILE_S3_PUBLIC_DOMAIN=https://cdn.example.com
|
||||
# MOBILE_S3_KEY_PREFIX=mobile/latest # optional, S3 key path prefix
|
||||
|
||||
# #######################################
|
||||
# #### S3 Object Storage Service ########
|
||||
@@ -374,6 +386,12 @@ OPENAI_API_KEY=sk-xxxxxxxxx
|
||||
# Specify the Embedding model and Reranker model(unImplemented)
|
||||
# DEFAULT_FILES_CONFIG="embedding_model=openai/embedding-text-3-small,reranker_model=cohere/rerank-english-v3.0,query_mode=full_text"
|
||||
|
||||
# Embedding batch size for processing (default: 50)
|
||||
# EMBEDDING_BATCH_SIZE=50
|
||||
|
||||
# Embedding concurrency for parallel processing (default: 10)
|
||||
# EMBEDDING_CONCURRENCY=10
|
||||
|
||||
# #######################################
|
||||
# ######### MCP Service Config ##########
|
||||
# #######################################
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
const config = require('@lobehub/lint').eslint;
|
||||
|
||||
config.root = true;
|
||||
config.extends.push('plugin:@next/next/recommended-legacy');
|
||||
|
||||
config.rules['unicorn/no-negated-condition'] = 0;
|
||||
config.rules['unicorn/prefer-type-error'] = 0;
|
||||
config.rules['unicorn/prefer-logical-operator-over-ternary'] = 0;
|
||||
config.rules['unicorn/no-null'] = 0;
|
||||
config.rules['unicorn/no-typeof-undefined'] = 0;
|
||||
config.rules['unicorn/explicit-length-check'] = 0;
|
||||
config.rules['unicorn/prefer-code-point'] = 0;
|
||||
config.rules['no-extra-boolean-cast'] = 0;
|
||||
config.rules['unicorn/no-useless-undefined'] = 0;
|
||||
config.rules['react/no-unknown-property'] = 0;
|
||||
config.rules['unicorn/prefer-ternary'] = 0;
|
||||
config.rules['unicorn/prefer-spread'] = 0;
|
||||
config.rules['unicorn/catch-error-name'] = 0;
|
||||
config.rules['unicorn/no-array-for-each'] = 0;
|
||||
config.rules['unicorn/prefer-number-properties'] = 0;
|
||||
config.rules['unicorn/prefer-query-selector'] = 0;
|
||||
config.rules['unicorn/no-array-callback-reference'] = 0;
|
||||
config.rules['unicorn/text-encoding-identifier-case'] = 0;
|
||||
config.rules['@typescript-eslint/no-use-before-define'] = 0;
|
||||
// FIXME: Linting error in src/app/[variants]/(main)/chat/features/Migration/DBReader.ts, the fundamental solution should be upgrading typescript-eslint
|
||||
config.rules['@typescript-eslint/no-useless-constructor'] = 0;
|
||||
config.rules['@next/next/no-img-element'] = 0;
|
||||
|
||||
config.overrides = [
|
||||
{
|
||||
extends: ['plugin:mdx/recommended'],
|
||||
files: ['*.mdx'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-unused-vars': 1,
|
||||
'micromark-extension-mdx-jsx': 0,
|
||||
'no-undef': 0,
|
||||
'react/jsx-no-undef': 0,
|
||||
'react/no-unescaped-entities': 0,
|
||||
},
|
||||
settings: {
|
||||
'mdx/code-blocks': false,
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/store/image/**/*', 'src/types/generation/**/*'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-empty-interface': 0,
|
||||
'sort-keys-fix/sort-keys-fix': 0,
|
||||
'typescript-sort-keys/interface': 0,
|
||||
'typescript-sort-keys/string-enum': 0,
|
||||
},
|
||||
},
|
||||
// CLI scripts legitimately use process.exit() and async IIFE patterns
|
||||
{
|
||||
files: ['scripts/**/*'],
|
||||
rules: {
|
||||
'unicorn/no-process-exit': 0,
|
||||
'unicorn/prefer-top-level-await': 0,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = config;
|
||||
@@ -68,19 +68,19 @@ body:
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: '🐛 Bug Description'
|
||||
label: '🐛 What happened?'
|
||||
description: A clear and concise description of the bug, if the above option is `Other`, please also explain in detail.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: '📷 Recurrence Steps'
|
||||
description: A clear and concise description of how to recurrence.
|
||||
label: '📷 How to reproduce it?'
|
||||
description: A clear and concise description of how to reproduce.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: '🚦 Expected Behavior'
|
||||
label: '🚦 What it should be?'
|
||||
description: A clear and concise description of what you expected to happen.
|
||||
|
||||
- type: textarea
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
name: Desktop Cleanup S3
|
||||
description: Remove old release versions from S3, keeping the most recent N versions
|
||||
|
||||
inputs:
|
||||
channel:
|
||||
description: 'Update channel (stable, canary, nightly)'
|
||||
required: true
|
||||
keep-count:
|
||||
description: 'Number of recent versions to keep'
|
||||
required: false
|
||||
default: '15'
|
||||
aws-access-key-id:
|
||||
description: 'AWS access key ID'
|
||||
required: true
|
||||
aws-secret-access-key:
|
||||
description: 'AWS secret access key'
|
||||
required: true
|
||||
s3-bucket:
|
||||
description: 'S3 bucket name'
|
||||
required: true
|
||||
s3-region:
|
||||
description: 'S3 region (defaults to us-east-1)'
|
||||
required: false
|
||||
default: 'us-east-1'
|
||||
s3-endpoint:
|
||||
description: 'Custom S3 endpoint (for R2/MinIO etc.)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Cleanup old S3 versions
|
||||
shell: bash
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.aws-secret-access-key }}
|
||||
AWS_REGION: ${{ inputs.s3-region }}
|
||||
S3_BUCKET: ${{ inputs.s3-bucket }}
|
||||
S3_ENDPOINT: ${{ inputs.s3-endpoint }}
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
KEEP_COUNT: ${{ inputs.keep-count }}
|
||||
run: |
|
||||
if [ -z "$S3_BUCKET" ]; then
|
||||
echo "⚠️ S3 bucket is not configured, skipping cleanup"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ENDPOINT_ARG=""
|
||||
if [ -n "$S3_ENDPOINT" ]; then
|
||||
ENDPOINT_ARG="--endpoint-url $S3_ENDPOINT"
|
||||
fi
|
||||
|
||||
echo "🧹 Cleaning up old $CHANNEL versions from S3 (keeping latest $KEEP_COUNT)"
|
||||
echo ""
|
||||
|
||||
# List all version directories under {channel}/
|
||||
# S3 ls output format: "PRE {version}/" for directories
|
||||
all_versions=$(aws s3 ls "s3://$S3_BUCKET/$CHANNEL/" $ENDPOINT_ARG 2>/dev/null \
|
||||
| grep 'PRE ' \
|
||||
| awk '{print $2}' \
|
||||
| sed 's|/$||' \
|
||||
| sort -V)
|
||||
|
||||
if [ -z "$all_versions" ]; then
|
||||
echo "📭 No version directories found in s3://$S3_BUCKET/$CHANNEL/"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
total=$(echo "$all_versions" | wc -l | tr -d ' ')
|
||||
echo "📋 Found $total version(s) in s3://$S3_BUCKET/$CHANNEL/"
|
||||
|
||||
if [ "$total" -le "$KEEP_COUNT" ]; then
|
||||
echo "✅ Nothing to clean up ($total <= $KEEP_COUNT)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
delete_count=$((total - KEEP_COUNT))
|
||||
to_delete=$(echo "$all_versions" | head -n "$delete_count")
|
||||
|
||||
echo "🗑️ Will delete $delete_count old version(s):"
|
||||
echo "$to_delete" | while read -r version; do
|
||||
echo " - $version"
|
||||
done
|
||||
echo ""
|
||||
|
||||
echo "$to_delete" | while read -r version; do
|
||||
echo "🗑️ Deleting s3://$S3_BUCKET/$CHANNEL/$version/ ..."
|
||||
aws s3 rm "s3://$S3_BUCKET/$CHANNEL/$version/" --recursive $ENDPOINT_ARG
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "✅ Cleanup complete. Deleted $delete_count version(s), kept $KEEP_COUNT."
|
||||
@@ -0,0 +1,143 @@
|
||||
name: Desktop Publish to S3
|
||||
description: Upload desktop release artifacts to S3 update server
|
||||
|
||||
inputs:
|
||||
channel:
|
||||
description: 'Update channel (stable, canary, nightly)'
|
||||
required: true
|
||||
version:
|
||||
description: 'Release version (e.g., 2.1.29-canary.1)'
|
||||
required: true
|
||||
aws-access-key-id:
|
||||
description: 'AWS access key ID'
|
||||
required: true
|
||||
aws-secret-access-key:
|
||||
description: 'AWS secret access key'
|
||||
required: true
|
||||
s3-bucket:
|
||||
description: 'S3 bucket name'
|
||||
required: true
|
||||
s3-region:
|
||||
description: 'S3 region (defaults to us-east-1)'
|
||||
required: false
|
||||
default: 'us-east-1'
|
||||
s3-endpoint:
|
||||
description: 'Custom S3 endpoint (for R2/MinIO etc.)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Download merged artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: merged-release
|
||||
path: release
|
||||
|
||||
- name: List artifacts to upload
|
||||
shell: bash
|
||||
run: |
|
||||
echo "📦 Artifacts to upload to S3:"
|
||||
ls -lah release/
|
||||
echo ""
|
||||
echo "📋 YML files in release/:"
|
||||
ls -la release/*.yml 2>/dev/null || echo " ⚠️ No yml files found!"
|
||||
echo ""
|
||||
echo "📋 Version: ${{ inputs.version }}, Channel: ${{ inputs.channel }}"
|
||||
|
||||
- name: Upload to S3
|
||||
shell: bash
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.aws-secret-access-key }}
|
||||
AWS_REGION: ${{ inputs.s3-region }}
|
||||
S3_BUCKET: ${{ inputs.s3-bucket }}
|
||||
S3_ENDPOINT: ${{ inputs.s3-endpoint }}
|
||||
CHANNEL: ${{ inputs.channel }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ -z "$S3_BUCKET" ]; then
|
||||
echo "⚠️ S3 bucket is not configured, skipping S3 upload"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 构建端点参数
|
||||
ENDPOINT_ARG=""
|
||||
if [ -n "$S3_ENDPOINT" ]; then
|
||||
ENDPOINT_ARG="--endpoint-url $S3_ENDPOINT"
|
||||
echo "📡 Using custom S3 endpoint: $S3_ENDPOINT"
|
||||
fi
|
||||
|
||||
echo "🚀 Uploading to S3 bucket: $S3_BUCKET"
|
||||
echo "📁 Target path: s3://$S3_BUCKET/$CHANNEL/"
|
||||
echo ""
|
||||
|
||||
# 1. 上传安装包到版本目录
|
||||
echo "📦 Uploading release files to s3://$S3_BUCKET/$CHANNEL/$VERSION/"
|
||||
for file in release/*.dmg release/*.zip release/*.exe release/*.AppImage release/*.deb release/*.rpm release/*.snap release/*.tar.gz; do
|
||||
if [ -f "$file" ]; then
|
||||
filename=$(basename "$file")
|
||||
echo " ↗️ $filename"
|
||||
aws s3 cp "$file" "s3://$S3_BUCKET/$CHANNEL/$VERSION/$filename" $ENDPOINT_ARG
|
||||
fi
|
||||
done
|
||||
|
||||
# 2. 创建 {channel}*.yml (从 latest*.yml 复制,URL 加版本目录前缀)
|
||||
# electron-builder 始终生成 latest*.yml,不区分 channel
|
||||
# electron-updater 在对应 channel 时会找 {channel}-mac.yml
|
||||
echo ""
|
||||
echo "📋 Creating ${CHANNEL}*.yml files from latest*.yml..."
|
||||
for yml in release/latest*.yml; do
|
||||
if [ -f "$yml" ]; then
|
||||
channel_name=$(basename "$yml" | sed "s/latest/$CHANNEL/")
|
||||
# url: xxx.dmg -> url: {VERSION}/xxx.dmg
|
||||
sed "s|url: |url: $VERSION/|g" "$yml" > "release/$channel_name"
|
||||
echo " 📄 Created $channel_name from $(basename $yml) with URL prefix: $VERSION/"
|
||||
fi
|
||||
done
|
||||
|
||||
# 3. 创建 renderer manifest (仅 stable 渠道有 renderer tar)
|
||||
RENDERER_TAR="release/lobehub-renderer.tar.gz"
|
||||
if [ -f "$RENDERER_TAR" ]; then
|
||||
echo ""
|
||||
echo "📋 Creating renderer manifest..."
|
||||
RENDERER_SHA512=$(shasum -a 512 "$RENDERER_TAR" | awk '{print $1}' | xxd -r -p | base64)
|
||||
RENDERER_SIZE=$(stat -f%z "$RENDERER_TAR" 2>/dev/null || stat -c%s "$RENDERER_TAR")
|
||||
RELEASE_DATE=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")
|
||||
cat > "release/${CHANNEL}-renderer.yml" <<EOF
|
||||
version: $VERSION
|
||||
files:
|
||||
- url: $VERSION/lobehub-renderer.tar.gz
|
||||
sha512: $RENDERER_SHA512
|
||||
size: $RENDERER_SIZE
|
||||
path: $VERSION/lobehub-renderer.tar.gz
|
||||
sha512: $RENDERER_SHA512
|
||||
releaseDate: '$RELEASE_DATE'
|
||||
EOF
|
||||
echo " 📄 Created ${CHANNEL}-renderer.yml"
|
||||
fi
|
||||
|
||||
# 4. 上传 manifest 到根目录和版本目录
|
||||
# 根目录: electron-updater 需要,每次发版覆盖
|
||||
# 版本目录: 作为存档保留
|
||||
echo ""
|
||||
echo "📋 Uploading manifest files..."
|
||||
for yml in release/${CHANNEL}*.yml release/latest*.yml; do
|
||||
if [ -f "$yml" ]; then
|
||||
filename=$(basename "$yml")
|
||||
echo " ↗️ $filename -> s3://$S3_BUCKET/$CHANNEL/$filename"
|
||||
aws s3 cp "$yml" "s3://$S3_BUCKET/$CHANNEL/$filename" $ENDPOINT_ARG
|
||||
echo " ↗️ $filename -> s3://$S3_BUCKET/$CHANNEL/$VERSION/$filename (archive)"
|
||||
aws s3 cp "$yml" "s3://$S3_BUCKET/$CHANNEL/$VERSION/$filename" $ENDPOINT_ARG
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "✅ S3 upload completed!"
|
||||
echo ""
|
||||
echo "📋 Files in s3://$S3_BUCKET/$CHANNEL/:"
|
||||
aws s3 ls "s3://$S3_BUCKET/$CHANNEL/" $ENDPOINT_ARG || true
|
||||
echo ""
|
||||
echo "📋 Files in s3://$S3_BUCKET/$CHANNEL/$VERSION/:"
|
||||
aws s3 ls "s3://$S3_BUCKET/$CHANNEL/$VERSION/" $ENDPOINT_ARG || true
|
||||
@@ -13,28 +13,37 @@ inputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Rename macOS latest-mac.yml for multi-architecture support
|
||||
- name: Rename macOS *-mac.yml for multi-architecture support
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
run: |
|
||||
cd apps/desktop/release
|
||||
if [ -f "latest-mac.yml" ]; then
|
||||
SYSTEM_ARCH=$(uname -m)
|
||||
if [[ "$SYSTEM_ARCH" == "arm64" ]]; then
|
||||
ARCH_SUFFIX="arm64"
|
||||
else
|
||||
ARCH_SUFFIX="x64"
|
||||
fi
|
||||
mv latest-mac.yml "latest-mac-${ARCH_SUFFIX}.yml"
|
||||
echo "✅ Renamed latest-mac.yml to latest-mac-${ARCH_SUFFIX}.yml"
|
||||
SYSTEM_ARCH=$(uname -m)
|
||||
if [[ "$SYSTEM_ARCH" == "arm64" ]]; then
|
||||
ARCH_SUFFIX="arm64"
|
||||
else
|
||||
ARCH_SUFFIX="x64"
|
||||
fi
|
||||
for yml in *-mac.yml; do
|
||||
if [ -f "$yml" ]; then
|
||||
new_name="${yml%.yml}-${ARCH_SUFFIX}.yml"
|
||||
mv "$yml" "$new_name"
|
||||
echo "✅ Renamed $yml to $new_name"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: List yml files before upload
|
||||
shell: bash
|
||||
run: |
|
||||
echo "📋 YML files to upload:"
|
||||
ls -la apps/desktop/release/*.yml 2>/dev/null || echo " ⚠️ No yml files found!"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: ${{ inputs.artifact-name }}
|
||||
path: |
|
||||
apps/desktop/release/latest*
|
||||
apps/desktop/release/*.yml
|
||||
apps/desktop/release/*.dmg*
|
||||
apps/desktop/release/*.zip*
|
||||
apps/desktop/release/*.exe*
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
* Generate PR comment with download links for desktop builds
|
||||
* and handle comment creation/update logic
|
||||
*/
|
||||
module.exports = async ({ github, context, releaseUrl, version, tag }) => {
|
||||
// 用于识别构建评论的标识符
|
||||
const prComment = async ({ github, context, releaseUrl, artifactsUrl, version, tag }) => {
|
||||
const COMMENT_IDENTIFIER = '<!-- DESKTOP-BUILD-COMMENT -->';
|
||||
|
||||
/**
|
||||
@@ -69,7 +68,7 @@ module.exports = async ({ github, context, releaseUrl, version, tag }) => {
|
||||
**Version**: \`${version}\`
|
||||
**Build Time**: \`${new Date().toISOString()}\`
|
||||
|
||||
📦 [View All Build Artifacts](${releaseUrl})
|
||||
📦 [Release Download](${releaseUrl}) · 📥 [Actions Artifacts](${artifactsUrl || `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`})
|
||||
|
||||
|
||||
## Build Artifacts
|
||||
@@ -88,7 +87,7 @@ ${assetTable}
|
||||
**Version**: \`${version}\`
|
||||
**Build Time**: \`${new Date().toISOString()}\`
|
||||
|
||||
## 📦 [View All Build Artifacts](${releaseUrl})
|
||||
📦 [Release Download](${releaseUrl}) · 📥 [Actions Artifacts](${artifactsUrl || `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`})
|
||||
|
||||
> Note: This is a temporary build for testing purposes only.
|
||||
`;
|
||||
@@ -96,45 +95,41 @@ ${assetTable}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查找并更新或创建PR评论
|
||||
* Find and update or create the PR comment
|
||||
*/
|
||||
const updateOrCreateComment = async () => {
|
||||
// 生成评论内容
|
||||
const body = await generateCommentBody();
|
||||
|
||||
// 查找我们之前可能创建的评论
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
});
|
||||
|
||||
// 查找包含我们标识符的评论
|
||||
const buildComment = comments.find((comment) => comment.body.includes(COMMENT_IDENTIFIER));
|
||||
|
||||
if (buildComment) {
|
||||
// 如果找到现有评论,则更新它
|
||||
await github.rest.issues.updateComment({
|
||||
comment_id: buildComment.id,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: body,
|
||||
});
|
||||
console.log(`已更新现有评论 ID: ${buildComment.id}`);
|
||||
console.log(`Updated existing comment ID: ${buildComment.id}`);
|
||||
return { updated: true, id: buildComment.id };
|
||||
} else {
|
||||
// 如果没有找到现有评论,则创建新评论
|
||||
const result = await github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: body,
|
||||
});
|
||||
console.log(`已创建新评论 ID: ${result.data.id}`);
|
||||
console.log(`Created new comment ID: ${result.data.id}`);
|
||||
return { updated: false, id: result.data.id };
|
||||
}
|
||||
};
|
||||
|
||||
// 执行评论更新或创建
|
||||
return await updateOrCreateComment();
|
||||
};
|
||||
|
||||
module.exports = prComment;
|
||||
|
||||
@@ -4,7 +4,7 @@ permissions:
|
||||
contents: write
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
branches:
|
||||
- main
|
||||
@@ -24,28 +24,108 @@ jobs:
|
||||
# Fetch full history for proper tagging
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check and extract version from PR title
|
||||
id: extract-version
|
||||
- name: Detect release PR (version from title)
|
||||
id: release
|
||||
run: |
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
echo "PR Title: $PR_TITLE"
|
||||
|
||||
# Match "🚀 release: v{x.x.x}" format
|
||||
if [[ "$PR_TITLE" =~ ^🚀[[:space:]]+release:[[:space:]]*v([0-9]+\.[0-9]+\.[0-9]+.*)$ ]]; then
|
||||
# Match "🚀 release: v{x.x.x}" format (strict semver: x.y.z with optional -prerelease or +build)
|
||||
if [[ "$PR_TITLE" =~ ^🚀[[:space:]]+release:[[:space:]]*v([0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?)$ ]]; then
|
||||
VERSION="${BASH_REMATCH[1]}"
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "should_tag=true" >> $GITHUB_OUTPUT
|
||||
echo "✅ Detected release PR, version: v$VERSION"
|
||||
else
|
||||
echo "should_tag=false" >> $GITHUB_OUTPUT
|
||||
echo "⏭️ Not a release PR, skipping tag creation"
|
||||
echo "⏭️ Not a release PR"
|
||||
fi
|
||||
|
||||
- name: Detect patch PR (branch first, title fallback)
|
||||
id: patch
|
||||
if: steps.release.outputs.should_tag != 'true'
|
||||
run: |
|
||||
HEAD_REF="${{ github.event.pull_request.head.ref }}"
|
||||
PR_TITLE="${{ github.event.pull_request.title }}"
|
||||
echo "Head ref: $HEAD_REF"
|
||||
echo "PR Title: $PR_TITLE"
|
||||
|
||||
# Priority 1: hotfix/* or release/* branch always triggers, ignore PR title gate.
|
||||
if [[ "$HEAD_REF" == hotfix/* ]] || [[ "$HEAD_REF" == release/* ]]; then
|
||||
echo "should_tag=true" >> $GITHUB_OUTPUT
|
||||
echo "✅ Detected auto-release PR from $HEAD_REF branch (title gate bypassed)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Priority 2: fallback to PR title prefix gate (legacy behavior).
|
||||
if echo "$PR_TITLE" | grep -qiE '^(💄[[:space:]]*)?style(\(.+\))?:|^(✨[[:space:]]*)?feat(\(.+\))?:|^(🐛[[:space:]]*)?fix(\(.+\))?:|^(♻️[[:space:]]*)?refactor(\(.+\))?:|^((🐛|🩹)[[:space:]]*)?hotfix(\(.+\))?:|^(👷[[:space:]]*)?build(\(.+\))?:'; then
|
||||
echo "should_tag=true" >> $GITHUB_OUTPUT
|
||||
echo "✅ Detected patch PR from title prefix gate"
|
||||
else
|
||||
echo "should_tag=false" >> $GITHUB_OUTPUT
|
||||
echo "⏭️ Not a patch PR (neither hotfix/release branch nor style/feat/fix/refactor/hotfix/build title prefix)"
|
||||
fi
|
||||
|
||||
- name: Prepare main branch
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
run: |
|
||||
git checkout main
|
||||
git pull --rebase origin main
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24.11.1
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install deps
|
||||
if: steps.release.outputs.should_tag == 'true' || steps.patch.outputs.should_tag == 'true'
|
||||
run: bun i
|
||||
|
||||
- name: Resolve patch version (patch bump)
|
||||
id: patch-version
|
||||
if: steps.patch.outputs.should_tag == 'true'
|
||||
run: |
|
||||
CURRENT_VERSION="$(node -p "require('./package.json').version")"
|
||||
echo "Current version: ${CURRENT_VERSION}"
|
||||
|
||||
# Coerce to stable base (e.g. 2.0.0-beta.1 -> 2.0.0), then bump patch (-> 2.0.1)
|
||||
BASE_VERSION="$(npx -y semver@7 "${CURRENT_VERSION}" -c)"
|
||||
if [ -z "${BASE_VERSION}" ]; then
|
||||
echo "❌ Invalid version in package.json: ${CURRENT_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
NEXT_VERSION="$(npx -y semver@7 -i patch "${BASE_VERSION}")"
|
||||
echo "📦 Patch version: ${NEXT_VERSION}"
|
||||
echo "version=${NEXT_VERSION}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Set context (release)
|
||||
if: steps.release.outputs.should_tag == 'true'
|
||||
run: |
|
||||
echo "SHOULD_TAG=true" >> $GITHUB_ENV
|
||||
echo "KIND=release" >> $GITHUB_ENV
|
||||
echo "VERSION=${{ steps.release.outputs.version }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Set context (patch)
|
||||
if: steps.patch.outputs.should_tag == 'true'
|
||||
run: |
|
||||
echo "SHOULD_TAG=true" >> $GITHUB_ENV
|
||||
echo "KIND=patch" >> $GITHUB_ENV
|
||||
echo "VERSION=${{ steps.patch-version.outputs.version }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Check if tag already exists
|
||||
if: steps.extract-version.outputs.should_tag == 'true'
|
||||
if: env.SHOULD_TAG == 'true'
|
||||
id: check-tag
|
||||
run: |
|
||||
VERSION="${{ steps.extract-version.outputs.version }}"
|
||||
VERSION="${{ env.VERSION }}"
|
||||
if git rev-parse "v$VERSION" >/dev/null 2>&1; then
|
||||
echo "exists=true" >> $GITHUB_OUTPUT
|
||||
echo "⚠️ Tag v$VERSION already exists"
|
||||
@@ -54,21 +134,71 @@ jobs:
|
||||
echo "✅ Tag v$VERSION does not exist, can create"
|
||||
fi
|
||||
|
||||
- name: Create Tag
|
||||
if: steps.extract-version.outputs.should_tag == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
- name: Bump package.json version
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
run: |
|
||||
VERSION="${{ steps.extract-version.outputs.version }}"
|
||||
echo "🏷️ Creating tag: v$VERSION"
|
||||
VERSION="${{ env.VERSION }}"
|
||||
echo "📝 Bumping package.json version to: $VERSION"
|
||||
|
||||
# Validate VERSION is strict semver before writing
|
||||
if ! npx -y semver@7 "$VERSION" >/dev/null 2>&1; then
|
||||
echo "❌ Invalid semver version: $VERSION"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Update package.json using Node.js
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
|
||||
const target = '$VERSION';
|
||||
if (pkg.version === target) {
|
||||
console.log('✅ package.json already at version', target);
|
||||
process.exit(0);
|
||||
}
|
||||
pkg.version = target;
|
||||
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n');
|
||||
console.log('✅ package.json updated to', target);
|
||||
"
|
||||
|
||||
- name: Generate changelog
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
run: bun run workflow:changelog:gen
|
||||
|
||||
- name: Build static changelog
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
run: bun run workflow:changelog
|
||||
|
||||
- name: Commit release changes and push
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
id: bump-version
|
||||
run: |
|
||||
VERSION="${{ env.VERSION }}"
|
||||
|
||||
# Configure git
|
||||
git config --global user.name "github-actions[bot]"
|
||||
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git config --global user.name "lobehubbot"
|
||||
git config --global user.email "i@lobehub.com"
|
||||
|
||||
# Get PR merge commit SHA
|
||||
MERGE_SHA="${{ github.event.pull_request.merge_commit_sha }}"
|
||||
# Commit changes (if any) and push
|
||||
git add package.json CHANGELOG.md changelog/
|
||||
COMMIT_MSG="🔖 chore(release): release version v$VERSION [skip ci]"
|
||||
git commit -m "$COMMIT_MSG" || echo "Nothing to commit"
|
||||
git push origin HEAD:main
|
||||
|
||||
# Output the SHA we will tag
|
||||
echo "tag_sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create Tag
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
run: |
|
||||
VERSION="${{ env.VERSION }}"
|
||||
KIND="${{ env.KIND }}"
|
||||
echo "🏷️ Creating tag: v$VERSION"
|
||||
|
||||
# Tag the bumped version commit SHA (not the PR merge commit SHA)
|
||||
TAG_SHA="${{ steps.bump-version.outputs.tag_sha }}"
|
||||
|
||||
# Create annotated tag with single line message
|
||||
git tag -a "v$VERSION" "$MERGE_SHA" -m "🚀 release: v$VERSION | PR #${{ github.event.pull_request.number }} | Author: ${{ github.event.pull_request.user.login }}"
|
||||
git tag -a "v$VERSION" "$TAG_SHA" -m "🚀 release: v$VERSION | PR #${{ github.event.pull_request.number }} | Author: ${{ github.event.pull_request.user.login }}"
|
||||
|
||||
# Push tag
|
||||
git push origin "v$VERSION"
|
||||
@@ -76,13 +206,13 @@ jobs:
|
||||
echo "✅ Tag v$VERSION created successfully!"
|
||||
|
||||
- name: Create GitHub Release
|
||||
if: steps.extract-version.outputs.should_tag == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: v${{ steps.extract-version.outputs.version }}
|
||||
name: 🚀 Release v${{ steps.extract-version.outputs.version }}
|
||||
tag_name: v${{ env.VERSION }}
|
||||
name: 🚀 Release v${{ env.VERSION }}
|
||||
body: |
|
||||
## 📦 Release v${{ steps.extract-version.outputs.version }}
|
||||
## 📦 Release v${{ env.VERSION }}
|
||||
|
||||
This release was automatically published from PR #${{ github.event.pull_request.number }}.
|
||||
|
||||
@@ -95,14 +225,22 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Sync main to canary
|
||||
if: env.SHOULD_TAG == 'true' && steps.check-tag.outputs.exists == 'false'
|
||||
run: |
|
||||
gh workflow run sync-main-to-canary.yaml
|
||||
echo "✅ Dispatched sync-main-to-canary workflow"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Output result
|
||||
run: |
|
||||
if [ "${{ steps.extract-version.outputs.should_tag }}" == "true" ]; then
|
||||
if [ "${{ env.SHOULD_TAG }}" == "true" ]; then
|
||||
if [ "${{ steps.check-tag.outputs.exists }}" == "true" ]; then
|
||||
echo "⚠️ Result: Tag v${{ steps.extract-version.outputs.version }} already exists, skipping creation"
|
||||
echo "⚠️ Result: Tag v${{ env.VERSION }} already exists, skipping creation"
|
||||
else
|
||||
echo "✅ Result: Tag v${{ steps.extract-version.outputs.version }} created successfully!"
|
||||
echo "✅ Result: Tag v${{ env.VERSION }} created successfully!"
|
||||
fi
|
||||
else
|
||||
echo "ℹ️ Result: Not a release PR, no tag created"
|
||||
echo "ℹ️ Result: Not a release/patch PR, no tag created"
|
||||
fi
|
||||
|
||||
@@ -21,7 +21,7 @@ env:
|
||||
DATABASE_DRIVER: node
|
||||
KEY_VAULTS_SECRET: LA7n9k3JdEcbSgml2sxfw+4TV1AzaaFU5+R176aQz4s=
|
||||
AUTH_SECRET: e2e-test-secret-key-for-better-auth-32chars!
|
||||
AUTH_EMAIL_VERIFICATION: "0"
|
||||
AUTH_EMAIL_VERIFICATION: '0'
|
||||
S3_ACCESS_KEY_ID: e2e-mock-access-key
|
||||
S3_SECRET_ACCESS_KEY: e2e-mock-secret-key
|
||||
S3_BUCKET: e2e-mock-bucket
|
||||
@@ -43,14 +43,13 @@ jobs:
|
||||
POSTGRES_PASSWORD: postgres
|
||||
options: >-
|
||||
--health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
|
||||
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -67,7 +66,7 @@ jobs:
|
||||
- name: Build application
|
||||
run: bun run build
|
||||
env:
|
||||
SKIP_LINT: "1"
|
||||
SKIP_LINT: '1'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
@@ -85,7 +84,7 @@ jobs:
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ secrets.GH_TOKEN }}
|
||||
allowed_non_write_users: "*"
|
||||
allowed_non_write_users: '*'
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
claude_args: |
|
||||
--allowedTools "Bash,Read,Edit,Write,Glob,Grep"
|
||||
|
||||
@@ -28,8 +28,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
|
||||
@@ -21,8 +21,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Copy security prompt
|
||||
run: |
|
||||
|
||||
@@ -28,8 +28,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
|
||||
@@ -32,8 +32,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Copy security prompt
|
||||
run: |
|
||||
|
||||
@@ -27,8 +27,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Copy security prompt
|
||||
run: |
|
||||
|
||||
@@ -39,7 +39,10 @@ jobs:
|
||||
|
||||
e2e:
|
||||
needs: check-duplicate-run
|
||||
if: needs.check-duplicate-run.outputs.should_skip != 'true'
|
||||
if: >-
|
||||
github.ref == 'refs/heads/main' ||
|
||||
github.ref == 'refs/heads/canary' ||
|
||||
needs.check-duplicate-run.outputs.should_skip != 'true'
|
||||
name: Test Web App
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
|
||||
@@ -51,8 +51,6 @@ jobs:
|
||||
version: ${{ steps.set_version.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -103,8 +101,6 @@ jobs:
|
||||
os: [macos-latest, macos-15-intel]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node & pnpm
|
||||
uses: ./.github/actions/setup-node-pnpm
|
||||
@@ -181,8 +177,6 @@ jobs:
|
||||
runs-on: windows-2025
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
@@ -227,8 +221,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node & pnpm
|
||||
uses: ./.github/actions/setup-node-pnpm
|
||||
|
||||
@@ -26,8 +26,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node & Bun
|
||||
uses: ./.github/actions/setup-node-bun
|
||||
@@ -56,8 +54,6 @@ jobs:
|
||||
version: ${{ steps.set_version.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -96,8 +92,6 @@ jobs:
|
||||
os: [macos-latest, macos-15-intel, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node & pnpm
|
||||
uses: ./.github/actions/setup-node-pnpm
|
||||
@@ -135,6 +129,7 @@ jobs:
|
||||
env:
|
||||
# 设置更新通道,PR构建为nightly,否则为stable
|
||||
UPDATE_CHANNEL: 'nightly'
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
# 默认添加一个加密 SECRET
|
||||
@@ -159,6 +154,7 @@ jobs:
|
||||
env:
|
||||
# 设置更新通道,PR构建为nightly,否则为stable
|
||||
UPDATE_CHANNEL: 'nightly'
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -175,6 +171,7 @@ jobs:
|
||||
env:
|
||||
# 设置更新通道,PR构建为nightly,否则为stable
|
||||
UPDATE_CHANNEL: 'nightly'
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -286,8 +283,6 @@ jobs:
|
||||
artifact_path: ${{ steps.set_path.outputs.path }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# 下载合并后的构建产物
|
||||
- name: Download merged artifacts
|
||||
@@ -340,21 +335,23 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# 在 PR 上添加评论,包含构建信息和下载链接
|
||||
# Post comment on PR with build info, release download link, and Actions artifacts link
|
||||
- name: Comment on PR
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const releaseUrl = "${{ steps.create_release.outputs.url }}";
|
||||
const artifactsUrl = "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}";
|
||||
const prCommentGenerator = require('${{ github.workspace }}/.github/scripts/pr-comment.js');
|
||||
|
||||
const result = await prCommentGenerator({
|
||||
github,
|
||||
context,
|
||||
releaseUrl,
|
||||
artifactsUrl,
|
||||
version: "${{ needs.version.outputs.version }}",
|
||||
tag: "v${{ needs.version.outputs.version }}"
|
||||
});
|
||||
|
||||
console.log(`评论状态: ${result.updated ? '已更新' : '已创建'}, ID: ${result.id}`);
|
||||
console.log(`Comment ${result.updated ? 'updated' : 'created'}, ID: ${result.id}`);
|
||||
|
||||
@@ -39,8 +39,6 @@ jobs:
|
||||
|
||||
- name: Checkout PR branch
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
@@ -107,8 +105,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout PR branch
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v7
|
||||
|
||||
@@ -61,8 +61,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -91,8 +89,6 @@ jobs:
|
||||
os: [macos-latest, macos-15-intel, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
name: Release Desktop Canary
|
||||
|
||||
# ============================================
|
||||
# Canary 自动发版工作流
|
||||
# ============================================
|
||||
# 触发条件:
|
||||
# 1. canary 分支有 push (合入 PR) 且 commit 前缀为 style/feat/fix/refactor/release (支持 gitmoji)
|
||||
# 2. 手动触发 (workflow_dispatch)
|
||||
#
|
||||
# 并发策略:
|
||||
# 同一 workflow 仅保留最新一次运行,自动取消排队中的旧 build
|
||||
#
|
||||
# 版本策略:
|
||||
# 基于最新 stable tag 的 patch+1, postfix 为递增序号
|
||||
# 格式: X.Y.(Z+1)-canary.N
|
||||
# 例: 当前 tag v2.1.28 → v2.1.29-canary.1, 下次 → v2.1.29-canary.2
|
||||
# ============================================
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- canary
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: 'Force build (skip commit message check)'
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions: read-all
|
||||
|
||||
env:
|
||||
NODE_VERSION: '24.11.1'
|
||||
|
||||
jobs:
|
||||
# ============================================
|
||||
# 检查 commit 前缀并计算版本号
|
||||
# ============================================
|
||||
calculate-version:
|
||||
name: Calculate Canary Version
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check commit message prefix
|
||||
id: check
|
||||
run: |
|
||||
# 手动触发 + force 时跳过检查
|
||||
if [ "${{ inputs.force }}" == "true" ]; then
|
||||
echo "should_build=true" >> $GITHUB_OUTPUT
|
||||
echo "🔧 Force build requested, skipping commit check"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 手动触发 (无 force) 也直接构建
|
||||
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
|
||||
echo "should_build=true" >> $GITHUB_OUTPUT
|
||||
echo "🔧 Manual trigger, proceeding with build"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 获取本次 push 的 head commit message
|
||||
commit_msg=$(git log -1 --pretty=%s HEAD)
|
||||
echo "📝 Head commit: $commit_msg"
|
||||
|
||||
# 检查是否匹配 style/feat/fix/refactor/release 前缀 (支持 gitmoji 前缀)
|
||||
if echo "$commit_msg" | grep -qiE '^(💄\s*)?style(\(.+\))?:|^(✨\s*)?feat(\(.+\))?:|^(🐛\s*)?fix(\(.+\))?:|^(♻️\s*)?refactor(\(.+\))?:|^(🚀\s*)?release(\(.+\))?:'; then
|
||||
echo "should_build=true" >> $GITHUB_OUTPUT
|
||||
echo "✅ Commit matches canary build trigger: $commit_msg"
|
||||
else
|
||||
echo "should_build=false" >> $GITHUB_OUTPUT
|
||||
echo "⏭️ Commit does not match style/feat/fix/refactor/release prefix, skipping: $commit_msg"
|
||||
fi
|
||||
|
||||
- name: Calculate canary version
|
||||
if: steps.check.outputs.should_build == 'true'
|
||||
id: version
|
||||
run: |
|
||||
# 获取最新的 stable tag (排除 nightly/canary/beta 等)
|
||||
latest_tag=$(git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
|
||||
|
||||
if [ -z "$latest_tag" ]; then
|
||||
echo "❌ No stable tag found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📌 Latest stable tag: $latest_tag"
|
||||
|
||||
# 去掉 v 前缀,解析 major.minor.patch → a.b.c 取 c+1
|
||||
base_version="${latest_tag#v}"
|
||||
IFS='.' read -r major minor patch <<< "$base_version"
|
||||
new_patch=$((patch + 1))
|
||||
base_canary="${major}.${minor}.${new_patch}"
|
||||
|
||||
# postfix: 同 base 下已有 canary 标签的最大序号 + 1
|
||||
max_seq=0
|
||||
for t in $(git tag -l "v${base_canary}-canary.*" 2>/dev/null || true); do
|
||||
seq=$(echo "$t" | grep -oE '[0-9]+$' || true)
|
||||
if [ -n "$seq" ] && [ "$seq" -gt "$max_seq" ] 2>/dev/null; then
|
||||
max_seq=$seq
|
||||
fi
|
||||
done
|
||||
next_seq=$((max_seq + 1))
|
||||
|
||||
version="${base_canary}-canary.${next_seq}"
|
||||
tag="v${version}"
|
||||
|
||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
||||
echo "tag=${tag}" >> $GITHUB_OUTPUT
|
||||
echo "✅ Canary version: ${version}"
|
||||
echo "🏷️ Tag: ${tag}"
|
||||
|
||||
# ============================================
|
||||
# 代码质量检查
|
||||
# ============================================
|
||||
test:
|
||||
name: Code quality check
|
||||
needs: [calculate-version]
|
||||
if: needs.calculate-version.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install deps
|
||||
run: bun i
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
# ============================================
|
||||
# 多平台构建
|
||||
# ============================================
|
||||
build:
|
||||
needs: [calculate-version, test]
|
||||
if: needs.calculate-version.outputs.should_build == 'true'
|
||||
name: Build Desktop App
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-15, macos-15-intel, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
|
||||
- name: Set package version
|
||||
run: npm run workflow:set-desktop-version ${{ needs.calculate-version.outputs.version }} canary
|
||||
|
||||
# macOS 构建前清理 (修复 hdiutil 问题)
|
||||
- name: Clean previous build artifacts (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: |
|
||||
sudo rm -rf apps/desktop/release || true
|
||||
sudo rm -rf apps/desktop/dist || true
|
||||
sudo rm -rf /tmp/electron-builder* || true
|
||||
|
||||
# macOS 构建
|
||||
- name: Build artifact on macOS
|
||||
if: runner.os == 'macOS'
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: canary
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
CSC_LINK: ${{ secrets.APPLE_CERTIFICATE_BASE64 }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
CSC_FOR_PULL_REQUEST: true
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
|
||||
# Windows 构建
|
||||
- name: Build artifact on Windows
|
||||
if: runner.os == 'Windows'
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: canary
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
TEMP: C:\temp
|
||||
TMP: C:\temp
|
||||
|
||||
# Linux 构建
|
||||
- name: Build artifact on Linux
|
||||
if: runner.os == 'Linux'
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: canary
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
NEXT_PUBLIC_DESKTOP_PROJECT_ID: ${{ secrets.UMAMI_BETA_DESKTOP_PROJECT_ID }}
|
||||
NEXT_PUBLIC_DESKTOP_UMAMI_BASE_URL: ${{ secrets.UMAMI_BETA_DESKTOP_BASE_URL }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: ./.github/actions/desktop-upload-artifacts
|
||||
with:
|
||||
artifact-name: release-${{ matrix.os }}
|
||||
retention-days: 3
|
||||
|
||||
# ============================================
|
||||
# 合并 macOS 多架构 latest-mac.yml 文件
|
||||
# ============================================
|
||||
merge-mac-files:
|
||||
needs: [build]
|
||||
name: Merge macOS Release Files
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: release
|
||||
pattern: release-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: List downloaded artifacts
|
||||
run: ls -R release
|
||||
|
||||
- name: Install yaml only for merge step
|
||||
run: |
|
||||
cd scripts/electronWorkflow
|
||||
if [ ! -f package.json ]; then
|
||||
echo '{"name":"merge-mac-release","private":true}' > package.json
|
||||
fi
|
||||
bun add --no-save yaml@2.8.1
|
||||
|
||||
- name: Merge latest-mac.yml files
|
||||
run: bun run scripts/electronWorkflow/mergeMacReleaseFiles.js
|
||||
|
||||
- name: Upload artifacts with merged macOS files
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: merged-release
|
||||
path: release/
|
||||
retention-days: 1
|
||||
|
||||
# ============================================
|
||||
# 创建 Canary Release
|
||||
# ============================================
|
||||
publish-release:
|
||||
needs: [merge-mac-files, calculate-version]
|
||||
name: Publish Canary Release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download merged artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: merged-release
|
||||
path: release
|
||||
|
||||
- name: List final artifacts
|
||||
run: ls -R release
|
||||
|
||||
- name: Create Canary Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ needs.calculate-version.outputs.tag }}
|
||||
name: 'Desktop Canary ${{ needs.calculate-version.outputs.tag }}'
|
||||
prerelease: true
|
||||
body: |
|
||||
## 🐤 Canary Build — ${{ needs.calculate-version.outputs.tag }}
|
||||
|
||||
> Automated canary build from `canary` branch.
|
||||
|
||||
### ⚠️ Important Notes
|
||||
|
||||
- **This is an automated canary build and is NOT intended for production use.**
|
||||
- Canary builds are triggered by `build`/`fix`/`style` commits on the `canary` branch.
|
||||
- May contain **unstable or incomplete changes**. **Use at your own risk.**
|
||||
- It is strongly recommended to **back up your data** before using a canary build.
|
||||
|
||||
### 📦 Installation
|
||||
|
||||
Download the appropriate installer for your platform from the assets below.
|
||||
|
||||
| Platform | File |
|
||||
|----------|------|
|
||||
| macOS (Apple Silicon) | `.dmg` (arm64) |
|
||||
| macOS (Intel) | `.dmg` (x64) |
|
||||
| Windows | `.exe` |
|
||||
| Linux | `.AppImage` / `.deb` |
|
||||
files: |
|
||||
release/latest*
|
||||
release/*.dmg*
|
||||
release/*.zip*
|
||||
release/*.exe*
|
||||
release/*.AppImage
|
||||
release/*.deb*
|
||||
release/*.snap*
|
||||
release/*.rpm*
|
||||
release/*.tar.gz*
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
# ============================================
|
||||
# 发布到 S3 更新服务器
|
||||
# ============================================
|
||||
publish-s3:
|
||||
needs: [merge-mac-files, calculate-version]
|
||||
name: Publish to S3
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ./.github/actions/desktop-publish-s3
|
||||
with:
|
||||
channel: canary
|
||||
version: ${{ needs.calculate-version.outputs.version }}
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
|
||||
# ============================================
|
||||
# 清理旧的 Canary Releases (保留最近 7 个)
|
||||
# ============================================
|
||||
cleanup-old-canaries:
|
||||
needs: [publish-release, publish-s3]
|
||||
name: Cleanup Old Canary Releases
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Delete old canary GitHub releases
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const { data: releases } = await github.rest.repos.listReleases({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const canaryReleases = releases
|
||||
.filter(r => r.tag_name.includes('-canary.'))
|
||||
.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
|
||||
|
||||
const toDelete = canaryReleases.slice(7);
|
||||
|
||||
for (const release of toDelete) {
|
||||
console.log(`🗑️ Deleting old canary release: ${release.tag_name}`);
|
||||
|
||||
// Delete the release
|
||||
await github.rest.repos.deleteRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.id,
|
||||
});
|
||||
|
||||
// Delete the tag
|
||||
try {
|
||||
await github.rest.git.deleteRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: `tags/${release.tag_name}`,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(`⚠️ Could not delete tag ${release.tag_name}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Cleanup complete. Kept ${Math.min(canaryReleases.length, 7)} canary releases, deleted ${toDelete.length}.`);
|
||||
|
||||
- name: Cleanup old S3 versions
|
||||
uses: ./.github/actions/desktop-cleanup-s3
|
||||
with:
|
||||
channel: canary
|
||||
keep-count: '15'
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
@@ -48,7 +48,6 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
|
||||
- name: Check for code changes since last nightly
|
||||
id: changes
|
||||
@@ -128,8 +127,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -162,8 +159,6 @@ jobs:
|
||||
os: [macos-15, macos-15-intel, windows-2025, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
@@ -187,6 +182,7 @@ jobs:
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: nightly
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -205,6 +201,7 @@ jobs:
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: nightly
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -219,6 +216,7 @@ jobs:
|
||||
run: npm run desktop:package:app
|
||||
env:
|
||||
UPDATE_CHANNEL: nightly
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
APP_URL: http://localhost:3015
|
||||
DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'
|
||||
KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='
|
||||
@@ -346,17 +344,38 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# ============================================
|
||||
# 发布到 S3 更新服务器
|
||||
# ============================================
|
||||
publish-s3:
|
||||
needs: [merge-mac-files, calculate-version]
|
||||
name: Publish to S3
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ./.github/actions/desktop-publish-s3
|
||||
with:
|
||||
channel: nightly
|
||||
version: ${{ needs.calculate-version.outputs.version }}
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
|
||||
# ============================================
|
||||
# 清理旧的 Nightly Releases (保留最近 7 个)
|
||||
# ============================================
|
||||
cleanup-old-nightlies:
|
||||
needs: [publish-release]
|
||||
needs: [publish-release, publish-s3]
|
||||
name: Cleanup Old Nightly Releases
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Delete old nightly releases
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Delete old nightly GitHub releases
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
@@ -395,3 +414,14 @@ jobs:
|
||||
}
|
||||
|
||||
console.log(`✅ Cleanup complete. Kept ${Math.min(nightlyReleases.length, 7)} nightly releases, deleted ${toDelete.length}.`);
|
||||
|
||||
- name: Cleanup old S3 versions
|
||||
uses: ./.github/actions/desktop-cleanup-s3
|
||||
with:
|
||||
channel: nightly
|
||||
keep-count: '15'
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
|
||||
@@ -84,6 +84,8 @@ jobs:
|
||||
steps:
|
||||
- name: Check release info
|
||||
id: check
|
||||
env:
|
||||
RELEASE_BODY: ${{ github.event.release.body || '' }}
|
||||
run: |
|
||||
# 判断触发方式
|
||||
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
|
||||
@@ -100,7 +102,7 @@ jobs:
|
||||
version="${version#v}"
|
||||
echo "is_manual=false" >> $GITHUB_OUTPUT
|
||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
||||
release_body="${{ github.event.release.body }}"
|
||||
release_body="${RELEASE_BODY:-}"
|
||||
{
|
||||
echo "release_notes<<EOF"
|
||||
printf '%s\n' "$release_body"
|
||||
@@ -174,8 +176,6 @@ jobs:
|
||||
matrix: ${{ fromJson(needs.configure-build.outputs.matrix) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup build environment
|
||||
uses: ./.github/actions/desktop-build-setup
|
||||
@@ -236,7 +236,8 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
npm run desktop:package:app
|
||||
tar -czf apps/desktop/release/lobehub-renderer.tar.gz -C out .
|
||||
test -d apps/desktop/dist/renderer
|
||||
tar -czf apps/desktop/release/lobehub-renderer.tar.gz -C apps/desktop/dist/renderer .
|
||||
env:
|
||||
UPDATE_CHANNEL: stable
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
@@ -294,7 +295,7 @@ jobs:
|
||||
fi
|
||||
bun add --no-save yaml@2.8.1
|
||||
|
||||
- name: Merge latest-mac.yml files
|
||||
- name: Merge mac YAML files
|
||||
run: bun run scripts/electronWorkflow/mergeMacReleaseFiles.js
|
||||
|
||||
- name: Upload artifacts with merged macOS files
|
||||
@@ -349,16 +350,6 @@ jobs:
|
||||
# ============================================
|
||||
# 发布到 S3 更新服务器
|
||||
# ============================================
|
||||
# S3 目录结构:
|
||||
# s3://bucket/
|
||||
# stable/
|
||||
# stable-mac.yml ← electron-updater 检查更新 (stable channel)
|
||||
# stable.yml ← Windows (stable channel)
|
||||
# stable-linux.yml ← Linux (stable channel)
|
||||
# latest-mac.yml ← fallback for GitHub provider
|
||||
# {version}/ ← 版本目录
|
||||
# *.dmg, *.zip, *.exe, ...
|
||||
# ============================================
|
||||
publish-s3:
|
||||
needs: [merge-mac-files, check-stable]
|
||||
name: Publish to S3
|
||||
@@ -366,117 +357,13 @@ jobs:
|
||||
# 手动触发时可选择跳过
|
||||
if: ${{ !(github.event_name == 'workflow_dispatch' && inputs.skip_s3_upload) }}
|
||||
steps:
|
||||
- name: Download merged artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ./.github/actions/desktop-publish-s3
|
||||
with:
|
||||
name: merged-release
|
||||
path: release
|
||||
|
||||
- name: List artifacts to upload
|
||||
run: |
|
||||
echo "📦 Artifacts to upload to S3:"
|
||||
ls -lah release/
|
||||
echo ""
|
||||
echo "📋 Version: ${{ needs.check-stable.outputs.version }}"
|
||||
|
||||
- name: Upload to S3
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
AWS_REGION: ${{ secrets.UPDATE_S3_REGION || 'us-east-1' }}
|
||||
S3_BUCKET: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
S3_ENDPOINT: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
VERSION: ${{ needs.check-stable.outputs.version }}
|
||||
run: |
|
||||
if [ -z "$S3_BUCKET" ]; then
|
||||
echo "⚠️ UPDATE_S3_BUCKET is not configured, skipping S3 upload"
|
||||
echo ""
|
||||
echo "To enable S3 upload, configure the following secrets:"
|
||||
echo " - UPDATE_AWS_ACCESS_KEY_ID"
|
||||
echo " - UPDATE_AWS_SECRET_ACCESS_KEY"
|
||||
echo " - UPDATE_S3_BUCKET"
|
||||
echo " - UPDATE_S3_REGION (optional, defaults to us-east-1)"
|
||||
echo " - UPDATE_S3_ENDPOINT (optional, for S3-compatible services)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 构建端点参数
|
||||
ENDPOINT_ARG=""
|
||||
if [ -n "$S3_ENDPOINT" ]; then
|
||||
ENDPOINT_ARG="--endpoint-url $S3_ENDPOINT"
|
||||
echo "📡 Using custom S3 endpoint: $S3_ENDPOINT"
|
||||
fi
|
||||
|
||||
echo "🚀 Uploading to S3 bucket: $S3_BUCKET"
|
||||
echo "📁 Target path: s3://$S3_BUCKET/stable/"
|
||||
echo ""
|
||||
|
||||
# 1. 上传安装包到版本目录
|
||||
echo "📦 Uploading release files to s3://$S3_BUCKET/stable/$VERSION/"
|
||||
for file in release/*.dmg release/*.zip release/*.exe release/*.AppImage release/*.deb release/*.rpm release/*.snap release/*.tar.gz; do
|
||||
if [ -f "$file" ]; then
|
||||
filename=$(basename "$file")
|
||||
echo " ↗️ $filename"
|
||||
aws s3 cp "$file" "s3://$S3_BUCKET/stable/$VERSION/$filename" $ENDPOINT_ARG
|
||||
fi
|
||||
done
|
||||
|
||||
# 2. 创建 stable*.yml (从 latest*.yml 复制,并修改 URL 加上版本目录前缀)
|
||||
# electron-updater 在 channel=stable 时会找 stable-mac.yml
|
||||
# S3 目录结构: stable/{version}/xxx.dmg,所以 URL 需要加上 {version}/ 前缀
|
||||
echo ""
|
||||
echo "📋 Creating stable*.yml files from latest*.yml..."
|
||||
for yml in release/latest*.yml; do
|
||||
if [ -f "$yml" ]; then
|
||||
stable_name=$(basename "$yml" | sed 's/latest/stable/')
|
||||
# 复制并修改 URL: 给所有 url 字段加上版本目录前缀
|
||||
# url: xxx.dmg -> url: {VERSION}/xxx.dmg
|
||||
sed "s|url: |url: $VERSION/|g" "$yml" > "release/$stable_name"
|
||||
echo " 📄 Created $stable_name from $(basename $yml) with URL prefix: $VERSION/"
|
||||
fi
|
||||
done
|
||||
|
||||
# 3. 创建 renderer manifest (用于验证 renderer tar 完整性)
|
||||
echo ""
|
||||
echo "📋 Creating renderer manifest..."
|
||||
RENDERER_TAR="release/lobehub-renderer.tar.gz"
|
||||
if [ -f "$RENDERER_TAR" ]; then
|
||||
RENDERER_SHA512=$(shasum -a 512 "$RENDERER_TAR" | awk '{print $1}' | xxd -r -p | base64)
|
||||
RENDERER_SIZE=$(stat -f%z "$RENDERER_TAR" 2>/dev/null || stat -c%s "$RENDERER_TAR")
|
||||
RELEASE_DATE=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")
|
||||
echo "version: $VERSION" > "release/stable-renderer.yml"
|
||||
echo "files:" >> "release/stable-renderer.yml"
|
||||
echo " - url: $VERSION/lobehub-renderer.tar.gz" >> "release/stable-renderer.yml"
|
||||
echo " sha512: $RENDERER_SHA512" >> "release/stable-renderer.yml"
|
||||
echo " size: $RENDERER_SIZE" >> "release/stable-renderer.yml"
|
||||
echo "path: $VERSION/lobehub-renderer.tar.gz" >> "release/stable-renderer.yml"
|
||||
echo "sha512: $RENDERER_SHA512" >> "release/stable-renderer.yml"
|
||||
echo "releaseDate: '$RELEASE_DATE'" >> "release/stable-renderer.yml"
|
||||
echo " 📄 Created stable-renderer.yml with SHA512 checksum"
|
||||
else
|
||||
echo " ⚠️ Renderer tar not found, skipping manifest creation"
|
||||
fi
|
||||
|
||||
# 4. 上传 manifest 到根目录和版本目录
|
||||
# 根目录: electron-updater 需要,会被每次发版覆盖
|
||||
# 版本目录: 作为存档保留
|
||||
echo ""
|
||||
echo "📋 Uploading manifest files..."
|
||||
for yml in release/stable*.yml release/latest*.yml; do
|
||||
if [ -f "$yml" ]; then
|
||||
filename=$(basename "$yml")
|
||||
echo " ↗️ $filename -> s3://$S3_BUCKET/stable/$filename"
|
||||
aws s3 cp "$yml" "s3://$S3_BUCKET/stable/$filename" $ENDPOINT_ARG
|
||||
echo " ↗️ $filename -> s3://$S3_BUCKET/stable/$VERSION/$filename (archive)"
|
||||
aws s3 cp "$yml" "s3://$S3_BUCKET/stable/$VERSION/$filename" $ENDPOINT_ARG
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "✅ S3 upload completed!"
|
||||
echo ""
|
||||
echo "📋 Files in s3://$S3_BUCKET/stable/:"
|
||||
aws s3 ls "s3://$S3_BUCKET/stable/" $ENDPOINT_ARG || true
|
||||
echo ""
|
||||
echo "📋 Files in s3://$S3_BUCKET/stable/$VERSION/:"
|
||||
aws s3 ls "s3://$S3_BUCKET/stable/$VERSION/" $ENDPOINT_ARG || true
|
||||
channel: stable
|
||||
version: ${{ needs.check-stable.outputs.version }}
|
||||
aws-access-key-id: ${{ secrets.UPDATE_AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.UPDATE_AWS_SECRET_ACCESS_KEY }}
|
||||
s3-bucket: ${{ secrets.UPDATE_S3_BUCKET }}
|
||||
s3-region: ${{ secrets.UPDATE_S3_REGION }}
|
||||
s3-endpoint: ${{ secrets.UPDATE_S3_ENDPOINT }}
|
||||
|
||||
@@ -3,7 +3,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
workflow_dispatch: {}
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
@@ -33,8 +33,6 @@ jobs:
|
||||
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
@@ -46,7 +44,8 @@ jobs:
|
||||
images: ${{ env.REGISTRY_IMAGE }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest
|
||||
type=raw,value=latest,enable=${{ !github.event.release.prerelease }}
|
||||
type=raw,value=${{ github.event.release.tag_name }},enable=${{ github.event.release.prerelease }}
|
||||
|
||||
- name: Docker login
|
||||
uses: docker/login-action@v3
|
||||
@@ -93,8 +92,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout base
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v7
|
||||
@@ -113,7 +110,8 @@ jobs:
|
||||
images: ${{ env.REGISTRY_IMAGE }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest
|
||||
type=raw,value=latest,enable=${{ !github.event.release.prerelease }}
|
||||
type=raw,value=${{ github.event.release.tag_name }},enable=${{ github.event.release.prerelease }}
|
||||
|
||||
- name: Docker login
|
||||
uses: docker/login-action@v3
|
||||
|
||||
@@ -17,6 +17,7 @@ concurrency:
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
if: ${{ !contains(github.ref_name, '-') }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
@@ -65,44 +66,6 @@ jobs:
|
||||
- name: Test App
|
||||
run: bun run test-app
|
||||
|
||||
- name: Extract version from tag
|
||||
id: get-version
|
||||
run: |
|
||||
# Extract version from github.ref (refs/tags/v1.0.0 -> 1.0.0)
|
||||
VERSION=${GITHUB_REF#refs/tags/v}
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "📦 Release version: v$VERSION"
|
||||
|
||||
- name: Update package.json version
|
||||
run: |
|
||||
VERSION="${{ steps.get-version.outputs.version }}"
|
||||
echo "📝 Updating package.json version to: $VERSION"
|
||||
# Update package.json using Node.js
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
|
||||
pkg.version = '$VERSION';
|
||||
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\\n');
|
||||
console.log('✅ package.json updated');
|
||||
"
|
||||
|
||||
# Commit changes
|
||||
git config --global user.name "lobehubbot"
|
||||
git config --global user.email "i@lobehub.com"
|
||||
git add package.json
|
||||
git commit -m "🔧 chore(release): bump version to v$VERSION [skip ci]" || echo "Nothing to commit"
|
||||
git push origin HEAD:main
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Release
|
||||
run: bun run release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
# Pass version to semantic-release
|
||||
SEMANTIC_RELEASE_VERSION: ${{ steps.get-version.outputs.version }}
|
||||
|
||||
- name: Workflow
|
||||
run: bun run workflow:readme
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user