| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 0 | 14 | 14 | 0% |
| Commands | 5 | 11 | 1 | 29% |
| Section tags | 7 | 2 | 2 | 64% |
What each file covers
Sections
0 shared · 14 only in A · 14 only in B- − RAGFlow Instructions
- − Core Stance
- − Current stack
- − Code Layout to Expect
- − Go-Specific Rules
- − Go Test Tiers
- − Working Rules
- − Commands
- − Backend
- − Frontend
- − Go
- − or build specific binaries:
- − Validation Preference
- − Default review checklist
- + CLAUDE.md
- + Project Overview
- + Common Commands
- + Development Conventions
- + CSS and Layout Debugging
- + Color Tokens
- + Scope and Boundaries
- + Internationalization (i18n)
- + React Component Refactoring
- + State Management and Data Fetching
- + Network Request Layering
- + Shared UI Component Lock
- + React Patterns and Conventions
- + Utility Libraries and Reuse
Commands
5 shared · 11 only in A · 1 only in B- − uv sync --python 3.13 --all-extras
- − uv run python3 ragflow_deps/download_deps.py
- − docker compose -f docker/docker-compose-base.yml up -d
- − uv run pytest
- − ruff check
- − ruff format
- − npm run type-check
- − uv run ragflow_deps/download_deps.py
- − docker/
- − go test
- − go build
- + npm run format
- npm install
- npm run dev
- npm run build
- npm run lint
- npm run test
Section tags
7 shared · 2 only in A · 2 only in B- − lint-format
- − git-pr
- + dependencies
- + ui
- setup
- build
- test
- code-style
- architecture
- do-not
- agent-behaviour
Line diff
infiniflow/ragflow · AGENTS.md
@@ −1 @@
1# RAGFlow Instructions
2
3Use this file as the local operating guide for the current codebase. Prefer the code and the current CLAUDE.md over any older convention or remembered project shape.
4
5## Core Stance
6- Treat legacy code as liability, not as a compatibility target.
7- Prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migration notes.
8- If old and new implementations coexist, converge to one path unless an external contract forces compatibility.
9- Remove dead tests, commented-out code, stale docs, and "move later" notes instead of preserving them.
10- Reduce public surface area when a helper can be made private or internal.
11- Keep refactors centered on the owning abstraction, not on adjacent compatibility layers.
12
13## Current stack
14- Backend: Python 3.13+, Quart-based API server, Peewee ORM, async workers.
15- Frontend: React + TypeScript + Vite in `web/`.
16- Go: the repository also has a substantial Go module for servers, ingestion, parser/runtime, CLI, and supporting services.
17- Runtime services commonly include MySQL/PostgreSQL, Redis, MinIO, and Elasticsearch/Infinity/OpenSearch depending on configuration.
18
19## Code Layout to Expect
20- `api/`: Python API server entrypoints, blueprints, services, and database code.
21- `rag/`: ingestion, retrieval, LLM integration, and graph RAG logic.
22- `deepdoc/`: parsing and OCR.
23- `agent/`: workflow canvas, components, tools, and templates.
24- `cmd/`: Go entrypoints. `ragflow_main` is the main server/admin/ingestor binary surface; `ragflow-cli` is the CLI entrypoint.
25- `internal/`: main Go application code. Important subtrees:
26- `internal/agent/`: Go agent runtime, canvas execution, components, tool bindings, workflow helpers.
27- `internal/cli/`: CLI parsing, HTTP transport, command execution, response formatting.
28- `internal/dao/`: Go data-access layer and persistence-facing helpers.
29- `internal/deepdoc/`: Go DeepDOC integrations, especially native-backed PDF/DOCX parsing.
30- `internal/engine/`: search/index backends such as Elasticsearch and Infinity.
31- `internal/entity/`: shared Go entities and model definitions.
32- `internal/handler/`: HTTP handlers and route-facing request logic.
33- `internal/ingestion/`: Go ingestion pipeline, canvas adapter, components, wiring, service orchestration.
34- `internal/ingestion/component/`: stage implementations such as file/parser/chunker/tokenizer/extractor.
35- `internal/ingestion/pipeline/`: DSL translation, canvas-driven execution, checkpoints, resume/run logic.
36- `internal/parser/`: parser and chunk libraries used by ingestion and other Go paths.
37- `internal/parser/parser/`: typed parse-result parsers for markdown/html/pdf/docx/xlsx/text and related families.
38- `internal/parser/chunk/`: chunk operator library and DSL/typed execution helpers.
39- `internal/service/`: higher-level business services used by handlers and server flows.
40- `internal/storage/`: storage backends and in-memory test doubles.
41- `internal/router/`: HTTP route registration.
42- `internal/server/`: server bootstrap/config wiring.
43- `internal/cpp/`: C++ sources used by native-backed Go features.
44- `web/`: frontend application.
45- `docker/`: local and production compose files.
46- `sdk/` and `test/`: SDK and automated tests.
47
48## Go-Specific Rules
49- Treat `internal/ingestion`, `internal/parser`, and `internal/deepdoc` as actively refactored code. Prefer collapsing duplicate paths over preserving transitional wrappers.
50- Do not add or preserve deprecated Go APIs just to ease migration inside the repo.
51- Remove commented-out Go code instead of leaving recovery notes in place.
52- Keep package comments and doc comments aligned with the current runtime path, not with migration history.
53
54## Go Test Tiers
55Go tests are classified by build tag so the default `go test ./...` run stays self-contained. Tag a test file with `//go:build <tier>` placed before the `package` clause.
56
57| Tier | Build tag | Runs by default? | Needs |
58|---|---|---|---|
59| Unit | (none) | Yes (`go test ./...`) | Native CGO static libs (wired by `build.sh --test`); no external services — uses in-memory SQLite, miniredis, or `httptest` stubs. |
60| Integration | `integration` | No (`-tags integration`) | A real service: MySQL/MinIO/Elasticsearch/Infinity/LLM. Single component, reasonably fast. |
61| E2E | `e2e` | No (`-tags e2e`) | Full cross-component pipeline (ingest → index → retrieve) against real services; heavy/slow. |
62| Manual | `manual` | No (`-tags manual`) | Very slow/expensive (deepdoc render/parity/snapshot/bench). **Local opt-in ONLY — never run in CI.** |
63| Native (orthogonal) | `cgo` / `!cgo` | `cgo` auto-satisfies under CGO_ENABLED=1 | Native static libs (`office_oxide`/`pdfium`/`pdf_oxide`). Combine with tiers, e.g. `//go:build cgo && integration`. |
64
65Run tiers locally via `build.sh`:
66```bash
67bash build.sh --test # unit tier (no tags)
68bash build.sh --test-integration ./... # integration tier
69bash build.sh --test-e2e # e2e tier
70bash build.sh --test-manual # manual tier (very slow)
71bash build.sh --test-all # integration + e2e (never includes manual)
72```
73Rules:
74- New tests that touch a real external service MUST carry `integration`/`e2e`/`manual` — do not rely on `t.Skip` + env vars to soft-isolate them in the default unit run. Keep an env guard as a harmless secondary safety net if desired.
75- `manual` is never wired into CI or any automated pipeline.
76- `unit` (no tag) must stay free of external-service dependencies so `go test ./...` passes without MySQL/MinIO/ES/Infinity/LLM. The native CGO static libraries (`office_oxide`/`pdfium`/`pdf_oxide`) are still required at build time and are wired automatically by `build.sh --test`; that is expected, not an external service.
77
78## Working Rules
79- Before editing, inspect the nearest code path that actually owns the behavior.
80- Keep changes small and local unless the task is explicitly a broader refactor.
81- Prefer one implementation path instead of preserving old and new versions side by side.
82- Preserve behavior with focused tests when the behavior is still valid; do not keep tests that protect obsolete behavior.
83- If a surface is only there for compatibility, remove it unless the user asks to keep it.
84- Do not add new compatibility wording in comments or docs.
85- When a maintainer takes over a community PR, a new commit generated by rewriting history (e.g. `merge`, `rebase -i`) must preserve the original author and add the maintainer as co-author (via a `Co-authored-by:` trailer) instead of overwriting the author with the maintainer alone.
86
87## Commands
88### Backend
89```bash
90uv sync --python 3.13 --all-extras
91uv run python3 ragflow_deps/download_deps.py
92docker compose -f docker/docker-compose-base.yml up -d
93source .venv/bin/activate
94export PYTHONPATH=$(pwd)
95bash docker/launch_backend_service.sh
96uv run pytest
97ruff check
98ruff format
99```
100
101### Frontend
102```bash
103cd web
104npm install
105npm run dev
106npm run build
107npm run lint
108npm run test
109npm run type-check
110```
111
112### Go
113```bash
114uv run ragflow_deps/download_deps.py
115bash build.sh --test ./path/to/package/...
116bash build.sh --go
117# or build specific binaries:
118bash build.sh --all
119```
120
121## Validation Preference
122- Run the narrowest relevant test, lint, or build command after a change.
123- For backend changes, prefer targeted pytest or ruff checks over full-suite runs.
124- For frontend changes, prefer the touched-package lint, type-check, or test command.
125- For Go changes, prefer package-scoped `bash build.sh --test ...` first.
126- Do not default to raw `go test`, `go build`, or IDE Run/Debug for Go in this repo. They often miss the required CGO flags and native static libraries (`office_oxide`, `pdfium-static`, `pdf_oxide`) that `build.sh` wires correctly.
127- If Go native builds fail, inspect `build.sh` and `internal/development.md` before changing code. Common environment issues are missing downloaded native deps and missing `lld` on Linux.
128
129## Default review checklist
130- Remove instead of retaining `deprecated`, `legacy`, or compatibility-only code.
131- Collapse duplicate implementations to one path.
132- Drop stale comments and documentation that describe a superseded design.
133- Keep exported APIs only when the current code actually needs them.
134
infiniflow/ragflow · web/CLAUDE.md
@@ +1 @@
1# CLAUDE.md
2
3This file provides guidance to Claude Code (claude.ai/code) when working with the RAGFlow frontend (`web/`).
4
5## Project Overview
6
7RAGFlow frontend is a React/TypeScript application built with UmiJS:
8
9- **Components**: shadcn/ui
10- **Styling**: Tailwind CSS
11- **State**: Zustand
12- **Data Fetching**: TanStack Query (React Query)
13- **i18n**: react-i18next
14
15## Common Commands
16
17```bash
18npm install
19npm run dev # Development server
20npm run build # Production build
21npm run lint # oxlint
22npm run format # oxfmt
23npm run test # Jest tests
24```
25
26## Development Conventions
27
28### CSS and Layout Debugging
29
30When fixing CSS/layout issues (especially flex truncation, ellipsis, or element sizing), **always inspect the full parent hierarchy** for `flex-shrink`, `min-width`, and `overflow` constraints before applying fixes like `min-w-0`. Do not repeatedly apply the same fix without verifying the root cause.
31
32- Before editing, explain: (1) the full flex/container hierarchy from the target element up to the nearest non-flex ancestor, (2) what constraint is actually causing the bug, and (3) how the proposed fix addresses that root cause.
33
34### Color Tokens
35
36When writing or modifying styles, **use the project-defined color tokens from `src/tailwind.css`** (e.g., `bg-bg-base`, `text-text-primary`, `text-text-secondary`, `text-text-disabled`, `border-border-button`, `bg-bg-card`). Do not use arbitrary hex/RGB values or Tailwind's default palette colors (e.g., `emerald-500`, `blue-400`) directly in component class names. These tokens are defined for both light and dark modes and keep the UI consistent with the design system.
37
38### Scope and Boundaries
39
40Respect explicit boundaries from the user. If the user says **"only fix the selected line"** or **"do not touch shared types/files"**, follow that instruction exactly. Do not investigate unrelated errors, modify shared schemas (e.g., `LlmSettingFieldSchema`), or refactor other files without confirmation. If a change outside the described scope seems necessary, ask for permission first.
41
42### Internationalization (i18n)
43
44For translation tasks, add keys **only to the explicitly requested language files** (commonly `src/locales/zh.ts` and `src/locales/en.ts`). Do not auto-propagate changes to all language files unless the user explicitly asks.
45
46- **Style for `en.ts`**: Sentence case — first word capitalized, rest lowercase (e.g., `referenceAnswer: 'Reference answer'`). Proper nouns remain as-is.
47
48### React Component Refactoring
49
50When refactoring or extracting components, **verify layout behavior after each structural change** (especially `flex-1`, conditional rendering, or flex direction changes). Check that existing buttons, alignment, and responsive behavior remain intact. After extraction, verify: (1) all original props and behavior are preserved, (2) layout in parent contexts is identical, and (3) no syntax or type errors were introduced.
51
52### State Management and Data Fetching
53
54#### Query Key Factory (Mandatory)
55
56**Never write raw `queryKey` arrays inline.** Always use a query key factory object that returns `as const` tuples. Raw arrays duplicated across `useQuery` and `invalidateQueries` are brittle, unreadable, and cause stale-cache bugs when key structures drift.
57
58```ts
59// ❌ Bad — raw array, hard to match with useQuery
60queryClient.invalidateQueries({
61 queryKey: [
62 LLMApiAction.AddedProviders,
63 params.provider_name,
64 params.instance_name,
65 'models',
66 ],
67});
68
69// ✅ Good — factory reference, self-documenting
70queryClient.invalidateQueries({
71 queryKey: LlmKeys.instanceModels(params.provider_name, params.instance_name),
72});
73```
74
75- Place the factory in the same file as the hooks, named `{Domain}Keys` (e.g., `LlmKeys`, `DatasetKeys`).
76- Every `useQuery` and every `invalidateQueries` must reference the same factory function.
77- Use `as const` on each factory return value for type-safe readonly tuples.
78
79#### Cache Debugging
80
81For React Query / cache invalidation bugs, **carefully compare query keys across all consuming components and mutation hooks**. Mismatched keys (e.g., with/without `refreshCount`) are a common root cause of stale data or duplicate requests.
82
83- Systematically: (1) list every component/hook that calls `useQuery` for this data, (2) compare their query keys character-for-character, (3) check every mutation's `onSuccess` for cache invalidation, and (4) verify no parent re-renders are remounting the observer.
84
85#### Colocate Queries with the Consuming View
86
87**Fire a query in the component that renders its data — not in a parent page.** When a page switches between mutually exclusive views (tabs, view modes), extract each view into its own component that issues its own requests on mount. Conditional rendering then provides lazy loading for free.
88
89- Do not hoist child-view queries into the page component — it fires requests the user may never need (e.g., fetching the skill tree on page entry while the default view is the LLM wiki).
90- Do not thread `enabled` flags or view-mode props through hooks to gate a hoisted query; that is a sign the query lives at the wrong level. Split the view instead.
91- Remember the trade-off: with `gcTime: 0`, unmounting a view drops its cache, so switching back refetches. That is usually desirable for always-fresh data — do not reintroduce eager hoisting just to avoid the refetch.
92
93### Network Request Layering
94
95HTTP requests are organized in three layers. **Never import `@/utils/request`, `@/utils/next-request`, or `@/utils/api` directly inside a hook**:
96
971. `src/hooks/use-xx-request.ts(x)` — React Query hooks; only call the service layer.
982. `src/services/xx-service.ts` — Register endpoints via `registerNextServer`, all going through `@/utils/next-request`.
993. `src/utils/next-request.ts` — The single axios instance; handles token, 401 redirects, and error notifications.
100
101Interface types are split between two folders:
102
103- Response/data shape → `src/interfaces/database/xx.ts`
104- Request params/body → `src/interfaces/request/xx.ts`
105
106Model-related endpoints (LLM provider / factory / my LLM, etc.) are consolidated in `src/services/llm-service.ts` rather than scattered across hooks. For GET endpoints, register with `method: 'get'` in the service, and on the call site pass `true` as the second argument to use the native axios config (e.g., `service.listProviders({ params: { available: true } }, true)`).
107
108### Shared UI Component Lock
109
110The folder `src/components/ui/` is the project's **shared UI library** — it contains both official shadcn/ui primitives and project-authored common components built on top of shadcn. Both kinds are intended to be reused across the app and **must not be modified casually**.
111
112- **Do not modify, refactor, restyle, or "improve"** any file under `src/components/ui/` (including subfolders), even if it seems like the most direct fix.
113- If a component does not meet requirements, **wrap or compose it** in a new component **outside** `src/components/ui/` (e.g., under `src/components/` or a feature folder), and customize via `className`, `props`, or composition.
114- Exceptions require **explicit user approval** in the same conversation. When in doubt, ask first and propose a wrapper-based alternative.
115- Adding a new shared component to `src/components/ui/`, or upgrading a shadcn primitive via the official `shadcn` CLI, is allowed only when the user explicitly requests it.
116
117### React Patterns and Conventions
118
119- **Avoid inline event handlers.** Do not define arrow functions directly on JSX event props like `onClick={() => ...}` or `onChange={(e) => ...}`. Instead, extract the handler and reference it by name (e.g., `onClick={handleClick}`). Inline handlers are recreated on every render, which can break `React.memo` optimizations and make stack traces harder to read.
120- **Prefer `requestAnimationFrame` or `useLayoutEffect`** over `setTimeout(..., 0)` for focus or DOM measurement operations.
121- **Prefer `useTranslation` from `react-i18next`** over project-wrapped utilities like `useTranslate`.
122- Extract complex logic into hooks or utils; keep components lean.
123- Use **PascalCase** for constants and component names.
124 - Components: `EditableTextarea`, `RAGFlowFormItem`
125 - Constants: `InitialMockData`, `DefaultPlaceholder`
126- Avoid camelCase or SCREAMING_SNAKE_CASE for components and top-level constants.
127- Avoid duplicating component structures in JSX; favor render props or reusable components.
128
129### Utility Libraries and Reuse
130
131- **Time/date handling**: Use `dayjs` for all date/time formatting, parsing, and manipulation.
132- **Utility hooks**: Prefer `ahooks` for common reusable hooks (e.g., `useDebounce`, `useSetState`).
133- **General utilities**: Lodash is available for utility functions when needed.
134- **Project utilities first**: Before reaching for a third-party library, check if the project already has an existing utility or hook that covers the need.
135- **Extract and share**: If repeated logic cannot be satisfied by an existing project utility or a third-party library, extract it into an appropriate shared hook (`src/hooks/`) or utility file (`src/utils/`).
136- **Check for duplicate patterns before adding**: When asked to add logic (validation, existence checks, API calls, etc.), first search for existing hooks/functions that do the same or similar thing — especially in the same file or sibling hooks. If a hook already does X, call it instead of re-implementing X inline. This applies to mutations calling mutations, utility wrappers, and boilerplate around API calls.
137
@@ −1 +1 @@
1−# RAGFlow Instructions
1+# CLAUDE.md
22
3−Use this file as the local operating guide for the current codebase. Prefer the code and the current CLAUDE.md over any older convention or remembered project shape.
3+This file provides guidance to Claude Code (claude.ai/code) when working with the RAGFlow frontend (`web/`).
44
5−## Core Stance
6−- Treat legacy code as liability, not as a compatibility target.
7−- Prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migration notes.
8−- If old and new implementations coexist, converge to one path unless an external contract forces compatibility.
9−- Remove dead tests, commented-out code, stale docs, and "move later" notes instead of preserving them.
10−- Reduce public surface area when a helper can be made private or internal.
11−- Keep refactors centered on the owning abstraction, not on adjacent compatibility layers.
5+## Project Overview
126
13−## Current stack
14−- Backend: Python 3.13+, Quart-based API server, Peewee ORM, async workers.
15−- Frontend: React + TypeScript + Vite in `web/`.
16−- Go: the repository also has a substantial Go module for servers, ingestion, parser/runtime, CLI, and supporting services.
17−- Runtime services commonly include MySQL/PostgreSQL, Redis, MinIO, and Elasticsearch/Infinity/OpenSearch depending on configuration.
7+RAGFlow frontend is a React/TypeScript application built with UmiJS:
188
19−## Code Layout to Expect
20−- `api/`: Python API server entrypoints, blueprints, services, and database code.
21−- `rag/`: ingestion, retrieval, LLM integration, and graph RAG logic.
22−- `deepdoc/`: parsing and OCR.
23−- `agent/`: workflow canvas, components, tools, and templates.
24−- `cmd/`: Go entrypoints. `ragflow_main` is the main server/admin/ingestor binary surface; `ragflow-cli` is the CLI entrypoint.
25−- `internal/`: main Go application code. Important subtrees:
26−- `internal/agent/`: Go agent runtime, canvas execution, components, tool bindings, workflow helpers.
27−- `internal/cli/`: CLI parsing, HTTP transport, command execution, response formatting.
28−- `internal/dao/`: Go data-access layer and persistence-facing helpers.
29−- `internal/deepdoc/`: Go DeepDOC integrations, especially native-backed PDF/DOCX parsing.
30−- `internal/engine/`: search/index backends such as Elasticsearch and Infinity.
31−- `internal/entity/`: shared Go entities and model definitions.
32−- `internal/handler/`: HTTP handlers and route-facing request logic.
33−- `internal/ingestion/`: Go ingestion pipeline, canvas adapter, components, wiring, service orchestration.
34−- `internal/ingestion/component/`: stage implementations such as file/parser/chunker/tokenizer/extractor.
35−- `internal/ingestion/pipeline/`: DSL translation, canvas-driven execution, checkpoints, resume/run logic.
36−- `internal/parser/`: parser and chunk libraries used by ingestion and other Go paths.
37−- `internal/parser/parser/`: typed parse-result parsers for markdown/html/pdf/docx/xlsx/text and related families.
38−- `internal/parser/chunk/`: chunk operator library and DSL/typed execution helpers.
39−- `internal/service/`: higher-level business services used by handlers and server flows.
40−- `internal/storage/`: storage backends and in-memory test doubles.
41−- `internal/router/`: HTTP route registration.
42−- `internal/server/`: server bootstrap/config wiring.
43−- `internal/cpp/`: C++ sources used by native-backed Go features.
44−- `web/`: frontend application.
45−- `docker/`: local and production compose files.
46−- `sdk/` and `test/`: SDK and automated tests.
9+- **Components**: shadcn/ui
10+- **Styling**: Tailwind CSS
11+- **State**: Zustand
12+- **Data Fetching**: TanStack Query (React Query)
13+- **i18n**: react-i18next
4714
48−## Go-Specific Rules
49−- Treat `internal/ingestion`, `internal/parser`, and `internal/deepdoc` as actively refactored code. Prefer collapsing duplicate paths over preserving transitional wrappers.
50−- Do not add or preserve deprecated Go APIs just to ease migration inside the repo.
51−- Remove commented-out Go code instead of leaving recovery notes in place.
52−- Keep package comments and doc comments aligned with the current runtime path, not with migration history.
15+## Common Commands
5316
54−## Go Test Tiers
55−Go tests are classified by build tag so the default `go test ./...` run stays self-contained. Tag a test file with `//go:build <tier>` placed before the `package` clause.
56−
57−| Tier | Build tag | Runs by default? | Needs |
58−|---|---|---|---|
59−| Unit | (none) | Yes (`go test ./...`) | Native CGO static libs (wired by `build.sh --test`); no external services — uses in-memory SQLite, miniredis, or `httptest` stubs. |
60−| Integration | `integration` | No (`-tags integration`) | A real service: MySQL/MinIO/Elasticsearch/Infinity/LLM. Single component, reasonably fast. |
61−| E2E | `e2e` | No (`-tags e2e`) | Full cross-component pipeline (ingest → index → retrieve) against real services; heavy/slow. |
62−| Manual | `manual` | No (`-tags manual`) | Very slow/expensive (deepdoc render/parity/snapshot/bench). **Local opt-in ONLY — never run in CI.** |
63−| Native (orthogonal) | `cgo` / `!cgo` | `cgo` auto-satisfies under CGO_ENABLED=1 | Native static libs (`office_oxide`/`pdfium`/`pdf_oxide`). Combine with tiers, e.g. `//go:build cgo && integration`. |
64−
65−Run tiers locally via `build.sh`:
6617 ```bash
67−bash build.sh --test # unit tier (no tags)
68−bash build.sh --test-integration ./... # integration tier
69−bash build.sh --test-e2e # e2e tier
70−bash build.sh --test-manual # manual tier (very slow)
71−bash build.sh --test-all # integration + e2e (never includes manual)
18+npm install
19+npm run dev # Development server
20+npm run build # Production build
21+npm run lint # oxlint
22+npm run format # oxfmt
23+npm run test # Jest tests
7224 ```
73−Rules:
74−- New tests that touch a real external service MUST carry `integration`/`e2e`/`manual` — do not rely on `t.Skip` + env vars to soft-isolate them in the default unit run. Keep an env guard as a harmless secondary safety net if desired.
75−- `manual` is never wired into CI or any automated pipeline.
76−- `unit` (no tag) must stay free of external-service dependencies so `go test ./...` passes without MySQL/MinIO/ES/Infinity/LLM. The native CGO static libraries (`office_oxide`/`pdfium`/`pdf_oxide`) are still required at build time and are wired automatically by `build.sh --test`; that is expected, not an external service.
7725
78−## Working Rules
79−- Before editing, inspect the nearest code path that actually owns the behavior.
80−- Keep changes small and local unless the task is explicitly a broader refactor.
81−- Prefer one implementation path instead of preserving old and new versions side by side.
82−- Preserve behavior with focused tests when the behavior is still valid; do not keep tests that protect obsolete behavior.
83−- If a surface is only there for compatibility, remove it unless the user asks to keep it.
84−- Do not add new compatibility wording in comments or docs.
85−- When a maintainer takes over a community PR, a new commit generated by rewriting history (e.g. `merge`, `rebase -i`) must preserve the original author and add the maintainer as co-author (via a `Co-authored-by:` trailer) instead of overwriting the author with the maintainer alone.
26+## Development Conventions
8627
87−## Commands
88−### Backend
89−```bash
90−uv sync --python 3.13 --all-extras
91−uv run python3 ragflow_deps/download_deps.py
92−docker compose -f docker/docker-compose-base.yml up -d
93−source .venv/bin/activate
94−export PYTHONPATH=$(pwd)
95−bash docker/launch_backend_service.sh
96−uv run pytest
97−ruff check
98−ruff format
99−```
28+### CSS and Layout Debugging
10029
101−### Frontend
102−```bash
103−cd web
104−npm install
105−npm run dev
106−npm run build
107−npm run lint
108−npm run test
109−npm run type-check
110−```
30+When fixing CSS/layout issues (especially flex truncation, ellipsis, or element sizing), **always inspect the full parent hierarchy** for `flex-shrink`, `min-width`, and `overflow` constraints before applying fixes like `min-w-0`. Do not repeatedly apply the same fix without verifying the root cause.
11131
112−### Go
113−```bash
114−uv run ragflow_deps/download_deps.py
115−bash build.sh --test ./path/to/package/...
116−bash build.sh --go
117−# or build specific binaries:
118−bash build.sh --all
32+- Before editing, explain: (1) the full flex/container hierarchy from the target element up to the nearest non-flex ancestor, (2) what constraint is actually causing the bug, and (3) how the proposed fix addresses that root cause.
33+
34+### Color Tokens
35+
36+When writing or modifying styles, **use the project-defined color tokens from `src/tailwind.css`** (e.g., `bg-bg-base`, `text-text-primary`, `text-text-secondary`, `text-text-disabled`, `border-border-button`, `bg-bg-card`). Do not use arbitrary hex/RGB values or Tailwind's default palette colors (e.g., `emerald-500`, `blue-400`) directly in component class names. These tokens are defined for both light and dark modes and keep the UI consistent with the design system.
37+
38+### Scope and Boundaries
39+
40+Respect explicit boundaries from the user. If the user says **"only fix the selected line"** or **"do not touch shared types/files"**, follow that instruction exactly. Do not investigate unrelated errors, modify shared schemas (e.g., `LlmSettingFieldSchema`), or refactor other files without confirmation. If a change outside the described scope seems necessary, ask for permission first.
41+
42+### Internationalization (i18n)
43+
44+For translation tasks, add keys **only to the explicitly requested language files** (commonly `src/locales/zh.ts` and `src/locales/en.ts`). Do not auto-propagate changes to all language files unless the user explicitly asks.
45+
46+- **Style for `en.ts`**: Sentence case — first word capitalized, rest lowercase (e.g., `referenceAnswer: 'Reference answer'`). Proper nouns remain as-is.
47+
48+### React Component Refactoring
49+
50+When refactoring or extracting components, **verify layout behavior after each structural change** (especially `flex-1`, conditional rendering, or flex direction changes). Check that existing buttons, alignment, and responsive behavior remain intact. After extraction, verify: (1) all original props and behavior are preserved, (2) layout in parent contexts is identical, and (3) no syntax or type errors were introduced.
51+
52+### State Management and Data Fetching
53+
54+#### Query Key Factory (Mandatory)
55+
56+**Never write raw `queryKey` arrays inline.** Always use a query key factory object that returns `as const` tuples. Raw arrays duplicated across `useQuery` and `invalidateQueries` are brittle, unreadable, and cause stale-cache bugs when key structures drift.
57+
58+```ts
59+// ❌ Bad — raw array, hard to match with useQuery
60+queryClient.invalidateQueries({
61+ queryKey: [
62+ LLMApiAction.AddedProviders,
63+ params.provider_name,
64+ params.instance_name,
65+ 'models',
66+ ],
67+});
68+
69+// ✅ Good — factory reference, self-documenting
70+queryClient.invalidateQueries({
71+ queryKey: LlmKeys.instanceModels(params.provider_name, params.instance_name),
72+});
11973 ```
12074
121−## Validation Preference
122−- Run the narrowest relevant test, lint, or build command after a change.
123−- For backend changes, prefer targeted pytest or ruff checks over full-suite runs.
124−- For frontend changes, prefer the touched-package lint, type-check, or test command.
125−- For Go changes, prefer package-scoped `bash build.sh --test ...` first.
126−- Do not default to raw `go test`, `go build`, or IDE Run/Debug for Go in this repo. They often miss the required CGO flags and native static libraries (`office_oxide`, `pdfium-static`, `pdf_oxide`) that `build.sh` wires correctly.
127−- If Go native builds fail, inspect `build.sh` and `internal/development.md` before changing code. Common environment issues are missing downloaded native deps and missing `lld` on Linux.
75+- Place the factory in the same file as the hooks, named `{Domain}Keys` (e.g., `LlmKeys`, `DatasetKeys`).
76+- Every `useQuery` and every `invalidateQueries` must reference the same factory function.
77+- Use `as const` on each factory return value for type-safe readonly tuples.
12878
129−## Default review checklist
130−- Remove instead of retaining `deprecated`, `legacy`, or compatibility-only code.
131−- Collapse duplicate implementations to one path.
132−- Drop stale comments and documentation that describe a superseded design.
133−- Keep exported APIs only when the current code actually needs them.
79+#### Cache Debugging
80+
81+For React Query / cache invalidation bugs, **carefully compare query keys across all consuming components and mutation hooks**. Mismatched keys (e.g., with/without `refreshCount`) are a common root cause of stale data or duplicate requests.
82+
83+- Systematically: (1) list every component/hook that calls `useQuery` for this data, (2) compare their query keys character-for-character, (3) check every mutation's `onSuccess` for cache invalidation, and (4) verify no parent re-renders are remounting the observer.
84+
85+#### Colocate Queries with the Consuming View
86+
87+**Fire a query in the component that renders its data — not in a parent page.** When a page switches between mutually exclusive views (tabs, view modes), extract each view into its own component that issues its own requests on mount. Conditional rendering then provides lazy loading for free.
88+
89+- Do not hoist child-view queries into the page component — it fires requests the user may never need (e.g., fetching the skill tree on page entry while the default view is the LLM wiki).
90+- Do not thread `enabled` flags or view-mode props through hooks to gate a hoisted query; that is a sign the query lives at the wrong level. Split the view instead.
91+- Remember the trade-off: with `gcTime: 0`, unmounting a view drops its cache, so switching back refetches. That is usually desirable for always-fresh data — do not reintroduce eager hoisting just to avoid the refetch.
92+
93+### Network Request Layering
94+
95+HTTP requests are organized in three layers. **Never import `@/utils/request`, `@/utils/next-request`, or `@/utils/api` directly inside a hook**:
96+
97+1. `src/hooks/use-xx-request.ts(x)` — React Query hooks; only call the service layer.
98+2. `src/services/xx-service.ts` — Register endpoints via `registerNextServer`, all going through `@/utils/next-request`.
99+3. `src/utils/next-request.ts` — The single axios instance; handles token, 401 redirects, and error notifications.
100+
101+Interface types are split between two folders:
102+
103+- Response/data shape → `src/interfaces/database/xx.ts`
104+- Request params/body → `src/interfaces/request/xx.ts`
105+
106+Model-related endpoints (LLM provider / factory / my LLM, etc.) are consolidated in `src/services/llm-service.ts` rather than scattered across hooks. For GET endpoints, register with `method: 'get'` in the service, and on the call site pass `true` as the second argument to use the native axios config (e.g., `service.listProviders({ params: { available: true } }, true)`).
107+
108+### Shared UI Component Lock
109+
110+The folder `src/components/ui/` is the project's **shared UI library** — it contains both official shadcn/ui primitives and project-authored common components built on top of shadcn. Both kinds are intended to be reused across the app and **must not be modified casually**.
111+
112+- **Do not modify, refactor, restyle, or "improve"** any file under `src/components/ui/` (including subfolders), even if it seems like the most direct fix.
113+- If a component does not meet requirements, **wrap or compose it** in a new component **outside** `src/components/ui/` (e.g., under `src/components/` or a feature folder), and customize via `className`, `props`, or composition.
114+- Exceptions require **explicit user approval** in the same conversation. When in doubt, ask first and propose a wrapper-based alternative.
115+- Adding a new shared component to `src/components/ui/`, or upgrading a shadcn primitive via the official `shadcn` CLI, is allowed only when the user explicitly requests it.
116+
117+### React Patterns and Conventions
118+
119+- **Avoid inline event handlers.** Do not define arrow functions directly on JSX event props like `onClick={() => ...}` or `onChange={(e) => ...}`. Instead, extract the handler and reference it by name (e.g., `onClick={handleClick}`). Inline handlers are recreated on every render, which can break `React.memo` optimizations and make stack traces harder to read.
120+- **Prefer `requestAnimationFrame` or `useLayoutEffect`** over `setTimeout(..., 0)` for focus or DOM measurement operations.
121+- **Prefer `useTranslation` from `react-i18next`** over project-wrapped utilities like `useTranslate`.
122+- Extract complex logic into hooks or utils; keep components lean.
123+- Use **PascalCase** for constants and component names.
124+ - Components: `EditableTextarea`, `RAGFlowFormItem`
125+ - Constants: `InitialMockData`, `DefaultPlaceholder`
126+- Avoid camelCase or SCREAMING_SNAKE_CASE for components and top-level constants.
127+- Avoid duplicating component structures in JSX; favor render props or reusable components.
128+
129+### Utility Libraries and Reuse
130+
131+- **Time/date handling**: Use `dayjs` for all date/time formatting, parsing, and manipulation.
132+- **Utility hooks**: Prefer `ahooks` for common reusable hooks (e.g., `useDebounce`, `useSetState`).
133+- **General utilities**: Lodash is available for utility functions when needed.
134+- **Project utilities first**: Before reaching for a third-party library, check if the project already has an existing utility or hook that covers the need.
135+- **Extract and share**: If repeated logic cannot be satisfied by an existing project utility or a third-party library, extract it into an appropriate shared hook (`src/hooks/`) or utility file (`src/utils/`).
136+- **Check for duplicate patterns before adding**: When asked to add logic (validation, existence checks, API calls, etc.), first search for existing hooks/functions that do the same or similar thing — especially in the same file or sibling hooks. If a hook already does X, call it instead of re-implementing X inline. This applies to mutations calling mutations, utility wrappers, and boilerplate around API calls.
134137
