@nocobase/app-skills 0.1.0-beta.34 → 0.1.0-beta.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. package/package.json +1 -1
  2. package/skills/nocobase-app-development/SKILL.md +24 -22
  3. package/skills/nocobase-app-development/references/database-connections.md +2 -0
  4. package/skills/nocobase-app-development/references/frontend/references/api.md +12 -0
  5. package/skills/nocobase-app-development/references/frontend/references/child-routes.md +2 -1
  6. package/skills/nocobase-app-development/references/frontend/references/page.md +18 -0
  7. package/skills/nocobase-app-development/references/frontend/references/shell.md +3 -3
  8. package/skills/nocobase-app-development/references/frontend/references/styling.md +4 -0
  9. package/skills/nocobase-app-development/references/frontend/references/theme.md +41 -35
  10. package/skills/nocobase-app-development/references/frontend/references/ui-library.md +19 -7
  11. package/skills/nocobase-app-development/references/frontend/ui-guidelines.md +8 -1
  12. package/skills/nocobase-app-development/references/lifecycle-parameters.md +95 -0
  13. package/skills/nocobase-app-development/references/lifecycle.md +21 -0
  14. package/skills/nocobase-app-development/references/server-routes.md +16 -0
  15. package/skills/nocobase-app-development/references/testing.md +10 -9
  16. package/skills/nocobase-app-upgrade/SKILL.md +3 -1
  17. package/skills/nocobase-app-upgrade/references/database-upgrades.md +64 -0
  18. package/skills/nocobase-app-upgrade/references/edge-cases.md +2 -2
  19. package/skills/nocobase-app-upgrade/references/theme-upgrade.md +1 -0
  20. package/skills/nocobase-deployment/SKILL.md +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocobase/app-skills",
3
- "version": "0.1.0-beta.34",
3
+ "version": "0.1.0-beta.36",
4
4
  "description": "Agent Skills for developing, upgrading and deploying NocoBase applications.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -79,28 +79,30 @@ The handbook's "Look up by task" table routes each frontend task to the sections
79
79
 
80
80
  Read the page for the task in front of you. Do not read all of them.
81
81
 
82
- | Task | Read |
83
- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
84
- | Anything under `client/`: pages, routes, components, styling, forms, API calls, copy, frontend tests | [frontend workflow](references/frontend/ui-workflow.md), which routes to the [frontend handbook](references/frontend/frontend-dev.md), the theme reference or the worked example |
85
- | Add an API endpoint, a webhook, or a callback; authenticate and authorize it | [server routes](references/server-routes.md) |
86
- | Name an endpoint, shape its response or errors, validate its input, paginate a list, document it in the API document | [HTTP API design](references/http-api.md) |
87
- | Query or write data, resolve the database, work with transactions | [database and data access](references/database-and-data.md) |
88
- | Create a table, alter a column, add an index, write required initial data | [migrations and seeds](references/migrations.md) |
89
- | Switch the database, register a dialect, add a second connection | [database connections](references/database-connections.md) |
90
- | Translate server-produced text, add a language, set the default language | [internationalization](references/i18n.md) |
91
- | Departments, positions or another organisation dimension that permission sets are assigned to | [organisation dimension](references/organization.md) |
92
- | Design who gets what across departments, heads and cross-department work | [organisation permission design](references/organization/permission-design.md) |
93
- | Add a reusable service, share it across routes, run background or scheduled work | [services and jobs](references/services-and-jobs.md) |
94
- | A record that moves through stages defined in code: approvals, tickets, orders, timeouts, effects after a state change | [record lifecycles](references/lifecycle.md) |
95
- | Flowcharts, process diagrams or lifecycle state diagrams | Use UI Library `@nocobase/flow-diagram` for generic graphs and `@nocobase/lifecycle-diagram` for lifecycle descriptions; see [diagram guidance](references/lifecycle.md#draw-an-interactive-lifecycle-diagram) and the [UI catalog](references/frontend/references/ui-library.md#diagrams). Preserve their application theme tokens. |
96
- | Write server and migration tests, choose a test layer, verify before finishing | [testing and verification](references/testing.md) |
97
- | Run a CLI command: configure, migrate, manage plugins, read the data model | [the command line](references/cli.md) |
98
- | Add or change an application command under `cli/commands/` | [adding an application command](references/commands.md) |
99
- | Where a file goes, how the client and server are composed, configuration, changing the framework structure | [application structure](references/app-structure.md) |
100
- | Register, update, customize or remove a plugin; check what an installed plugin already provides | [plugins](references/plugins.md) |
101
- | Add an npm package, decide `dependencies` versus `devDependencies`, diagnose a missing module or native binary | [adding a dependency](references/dependencies.md) |
102
- | Report the application's URL, dev server restarts and file watching, develop against another backend | [the development server](references/dev-server.md) |
103
- | Understand behavior inherited from an official application template | [template variants](references/template-variants.md) |
82
+ | Task | Read |
83
+ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
84
+ | Anything under `client/`: pages, routes, components, styling, forms, API calls, copy, frontend tests | [frontend workflow](references/frontend/ui-workflow.md), which routes to the [frontend handbook](references/frontend/frontend-dev.md), the theme reference or the worked example |
85
+ | Add an API endpoint, a webhook, or a callback; authenticate and authorize it | [server routes](references/server-routes.md) |
86
+ | Name an endpoint, shape its response or errors, validate its input, paginate a list, document it in the API document | [HTTP API design](references/http-api.md) |
87
+ | A list, dashboard or chart endpoint, or keeping one live: read with a fixed number of queries, refresh only what changed | [server routes](references/server-routes.md#lists-and-statistics-a-fixed-number-of-queries) and [client API requests](references/frontend/references/api.md#keeping-lists-and-charts-live) |
88
+ | Query or write data, resolve the database, work with transactions | [database and data access](references/database-and-data.md) |
89
+ | Create a table, alter a column, add an index, write required initial data | [migrations and seeds](references/migrations.md) |
90
+ | Switch the database, register a dialect, add a second connection | [database connections](references/database-connections.md) |
91
+ | Translate server-produced text, add a language, set the default language | [internationalization](references/i18n.md) |
92
+ | Departments, positions or another organisation dimension that permission sets are assigned to | [organisation dimension](references/organization.md) |
93
+ | Design who gets what across departments, heads and cross-department work | [organisation permission design](references/organization/permission-design.md) |
94
+ | Add a reusable service, share it across routes, run background or scheduled work | [services and jobs](references/services-and-jobs.md) |
95
+ | A record that moves through stages defined in code: approvals, tickets, orders, timeouts, effects after a state change | [record lifecycles](references/lifecycle.md) |
96
+ | Administrator-adjustable approval departments, reviewers, thresholds or business values in a code-defined lifecycle | [configurable lifecycle parameters](references/lifecycle-parameters.md); keep workflow structure in source. When building process pages with node-related parameters, prefer an editing dialog opened from the corresponding diagram node or transition. |
97
+ | Flowcharts, process diagrams or lifecycle state diagrams | Use UI Library `@nocobase/flow-diagram` for generic graphs and `@nocobase/lifecycle-diagram` for lifecycle descriptions; see [diagram guidance](references/lifecycle.md#draw-an-interactive-lifecycle-diagram) and the [UI catalog](references/frontend/references/ui-library.md#diagrams). Preserve their application theme tokens. |
98
+ | Write server and migration tests, choose a test layer, verify before finishing | [testing and verification](references/testing.md) |
99
+ | Run a CLI command: configure, migrate, manage plugins, read the data model | [the command line](references/cli.md) |
100
+ | Add or change an application command under `cli/commands/` | [adding an application command](references/commands.md) |
101
+ | Where a file goes, how the client and server are composed, configuration, changing the framework structure | [application structure](references/app-structure.md) |
102
+ | Register, update, customize or remove a plugin; check what an installed plugin already provides | [plugins](references/plugins.md) |
103
+ | Add an npm package, decide `dependencies` versus `devDependencies`, diagnose a missing module or native binary | [adding a dependency](references/dependencies.md) |
104
+ | Report the application's URL, dev server restarts and file watching, develop against another backend | [the development server](references/dev-server.md) |
105
+ | Understand behavior inherited from an official application template | [template variants](references/template-variants.md) |
104
106
 
105
107
  A feature with a page and an API usually needs migrations, server routes, and a frontend change that follows the frontend workflow.
106
108
 
@@ -210,3 +210,5 @@ With multiple connections, TypeScript may omit suggestions inside an empty `dial
210
210
  Application server builds retain declaration emission with `isolatedDeclarations: false`, allowing direct default exports of configuration factory calls. The helper returns the common `AppConfigFactory<AppDatabaseConfig>` contract; its result does not expose the inferred concrete driver types. Library packages retain isolated declaration checking. `AppDatabaseConfigFromDrivers` remains available for explicit annotations outside the helper.
211
211
 
212
212
  Application templates declare `@nocobase/db-sqlite`, the driver for the dialect their `server/config/database.ts` defaults to, and `create-app` adds no other. Any further driver an application's configuration needs — for its main connection or an additional one — has to be installed into its `dependencies` before building, because a deployment installs only what the application declares.
213
+
214
+ KingbaseES, Dameng and OceanBase drivers are maintained in `nocobase/nocobase3-pro` and distributed through the Pro registry. Install the selected package in the application’s production dependencies, then configure its dialect and connection settings. Automatic loading and `config init --dialect` remain supported; explicit registration in `database.drivers` is optional and takes precedence.
@@ -298,6 +298,18 @@ Other points:
298
298
  - When loading through a Repository (see "Remote Repository"), the request cannot take a `signal` and cannot be aborted, but still check `controller.signal.aborted` in the callbacks to discard stale results.
299
299
  - For the complete list page (search conditions written to the URL, empty and no-results states, the `Spinner` in the toolbar while reloading), see [`table.md`](table.md) and [`example/list-page.md`](example/list-page.md); for loading the latest data before an edit form opens, see [`form.md`](form.md); for the detail drawer, see [`overlay.md`](overlay.md).
300
300
 
301
+ ## Keeping lists and charts live
302
+
303
+ When realtime events refresh what a page shows:
304
+
305
+ - An event that names items refreshes those items: gather the ids of a burst (a few hundred milliseconds), read only those rows, keep one such request in flight, and merge the answer into what the page holds. Read the whole list again only when its membership changed (an item joined or left it, or moved between its groups) or the event names nothing.
306
+ - Do not read a whole list or overview again on every event.
307
+ - Recompute a chart's figures at most every few seconds while it is visible, and not at all while the page is hidden; or update only the figure the event affects.
308
+ - Read nothing for a page that is not shown; read it when it is shown again.
309
+ - A component that needs one small fact reads the small endpoint that answers it, not the list that happens to contain it.
310
+
311
+ The server side of these reads is in [server routes](../../server-routes.md#lists-and-statistics-a-fixed-number-of-queries).
312
+
301
313
  ## Error handling
302
314
 
303
315
  ### ApiClientError
@@ -618,11 +618,12 @@ A page that shows a record whose detail is a page of its own — an orders list'
618
618
  - **Group**: only `name`, `navigation` and `children`, with no `componentLoader`. `path` is optional; when present, it becomes the prefix of the child routes' paths; when absent, the group is only a set of entries in the menu.
619
619
  - A group renders no business component (the route renderer provides its Outlet), cannot declare `authz`, and carries no page permission of its own: the first page below a group with no page above it declares its own `authz`.
620
620
  - Groups can contain groups. A group's `name` must be unique, like a route name.
621
+ - **How a group shows in the menu**: a top-level group is a section, its title a small heading over its entries, which are always shown; use it to sort the menu into areas such as Records or Settings. A group inside another group is a collapsible sub-menu. `NavigationMenu`'s `sections={false}` draws top-level groups as collapsible sub-menus too.
621
622
  - **Clickable parent**: a page can also have `navigation` and child pages with `navigation`. In the menu it is then both a link and expandable: the link and the expand button are two separate controls. Choose how the child pages are presented according to [section 3](#3-four-ways-to-present-a-child-route).
622
623
  - Pages that should not appear in the menu, such as details and tab content, have no `navigation`. A descendant can still declare `navigation` when its ancestor does not.
623
624
  - A path with a parameter cannot have `navigation`.
624
625
  - `navigation.order` sets the order among siblings; lower numbers come first.
625
- - Navigation groups keep their expanded or collapsed state while the navigation tree stays mounted; opening a new page automatically expands its ancestor groups.
626
+ - Collapsible groups keep their expanded or collapsed state while the navigation tree stays mounted; opening a new page automatically expands its ancestor groups.
626
627
 
627
628
  ## 7. Settings pages
628
629
 
@@ -275,6 +275,24 @@ Write `navigation` on the route. The application sidebar reads its menu entries
275
275
  - Do not change the shell (`client/layouts/`) or the ServiceProvider to add a menu entry, and do not add a Refine resource for a menu. Refine resources produce no menu entries (see ["Loading data in a component" in `api.md`](api.md#loading-data-in-a-component) for what they are for); the home page entry is declared in the routes as well.
276
276
  - A new page with a menu entry usually touches four places: `client/routes.ts`, the page component, `client/locales/` and, for an App page that requires sign-in, the page grant list in `tests/logic/client-routes.test.ts` ([section 12](#12-update-the-route-test)).
277
277
 
278
+ ### A count beside an entry
279
+
280
+ An entry can show how many things wait on the viewer behind it, such as unread messages or requests to decide. A count changes while the page is open, so it is not part of the route's `navigation`: the App layout reads it with the hook that keeps it current and passes it to `NavigationMenu` in `badges`, keyed by the route's `name`:
281
+
282
+ ```tsx
283
+ // client/layouts/app-layout.tsx
284
+ const { data: unread = 0 } = useInboxUnreadCount(); // @nocobase/app-plugin-notification-in-app/client/inbox
285
+
286
+ <NavigationMenu
287
+ items={menuItems}
288
+ label={navigationLabel}
289
+ selectedKey={selectedKey}
290
+ badges={{ inbox: unread }}
291
+ />;
292
+ ```
293
+
294
+ A number is something waiting; `{ count, live: true, hint }` is work under way, such as runs in progress, drawn in the primary color behind a pulsing dot, with `hint` (translated, such as "2 running") as its words. The menu does the rest: nothing at zero, "99+" above 99, the count in the entry's accessible name and tooltip, and in the collapsed sidebar a dot on the icon's corner. A count goes on a page entry the menu always shows — a top-level entry or a section's — not on a group or an entry inside a sub-menu. Which counts belong in the menu at all is guideline L8 of [`../ui-guidelines.md`](../ui-guidelines.md).
295
+
278
296
  ## 7. Back button and breadcrumbs
279
297
 
280
298
  The shell header shows the current page's breadcrumb after the sidebar toggle, on every page; pages never render breadcrumbs themselves. A page that sits below another one — a covering child page, a record's own page, a form too long for a dialog — has a back button above its title (guideline L6), unless its header trail already leads back the same way; do not render both, and do not add a "Back to list" button to `actions`.
@@ -6,9 +6,9 @@ The shell is `client/routing/` and `client/layouts/`, with the header, sidebar a
6
6
 
7
7
  - There is no settings area and no Settings or Inbox entry in the header: every signed-in page renders inside `AppLayout`, and settings pages are ordinary pages in the sidebar ([section 5 of `page.md`](page.md#5-settings-pages)). Do not add a second layout or a `/settings` route split to the router.
8
8
  - The account menu's language control (`client/layouts/components/language-switcher.tsx`) is a submenu with radio items and must stay inside `DropdownMenuContent`, which provides its keyboard navigation and selected state.
9
- - Navigation groups keep their expanded or collapsed state while the navigation tree stays mounted; opening a new page expands its ancestor groups without collapsing the others.
10
- - The sidebar is shadcn's `Sidebar`, composed in `client/layouts/components/app-sidebar.tsx` (provider, desktop sidebar, phone sheet, header toggle) and `navigation-menu.tsx` (the route tree as `SidebarMenu*` entries with controlled `Collapsible` sub-menus). Keep `client/components/ui/sidebar.tsx` as the shadcn CLI writes it and change the sidebar from these two files: the widths are set through the provider's `style` in spacing units (`--sidebar-width`, `--sidebar-width-icon`) so they follow the density preset; the phone sheet is rendered in `app-sidebar.tsx` with a translated title instead of the primitive's own; and the provider's Ctrl/Cmd+B shortcut is stopped by a `document` keydown listener, so the key stays with editors.
11
- - The desktop sidebar can collapse to icons: leaf entries then show their label in a tooltip without delay and groups open in a popover on hover or keyboard focus, keeping the filtered entries, parent-page links, nested groups and the highlight of the group holding the current page. The collapsed state is shared through `useSidebarPreference` under `nocobase:sidebar:collapsed` by every application on the same origin, while whether the phone sheet is open stays local to each layout.
9
+ - Collapsible navigation groups keep their expanded or collapsed state while the navigation tree stays mounted; opening a new page expands its ancestor groups without collapsing the others.
10
+ - The sidebar is shadcn's `Sidebar`, composed in `client/layouts/components/app-sidebar.tsx` (provider, desktop sidebar, phone sheet, header toggle) and `navigation-menu.tsx` (the route tree as `SidebarMenu*` entries: a top-level group with no page is a section under a heading, its entries always shown; clickable parents and nested groups are controlled `Collapsible` sub-menus; counts beside entries come from the layout through its `badges`, [`page.md`](page.md#a-count-beside-an-entry)). Keep `client/components/ui/sidebar.tsx` as the shadcn CLI writes it and change the sidebar from these two files: the widths are set through the provider's `style` in spacing units (`--sidebar-width`, `--sidebar-width-icon`) so they follow the density preset; the phone sheet is rendered in `app-sidebar.tsx` with a translated title instead of the primitive's own; and the provider's Ctrl/Cmd+B shortcut is stopped by a `document` keydown listener, so the key stays with editors.
11
+ - The desktop sidebar can collapse to icons: leaf entries then show their label in a tooltip without delay and section headings hide and their entries keep their icons, collapsible groups open in a popover on hover or keyboard focus, keeping the filtered entries, parent-page links, nested groups and the highlight of the group holding the current page. The collapsed state is shared through `useSidebarPreference` under `nocobase:sidebar:collapsed` by every application on the same origin, while whether the phone sheet is open stays local to each layout.
12
12
  - The authorization provider clears the permission snapshot before rendering a new session; route navigation and page guards subscribe to the authorization revision, so account switches and permission changes take effect without a reload.
13
13
  - When signing out, the account menu checks the result from Better Auth and shows a localized error message on failure; do not treat navigating away as having signed out.
14
14
 
@@ -327,6 +327,7 @@ export function DeleteProjectButton({
327
327
  - Status data needs text; do not rely on color alone to tell values apart.
328
328
  - Make each enum (for example project status) one component, shared by the list and the detail view (`ProjectStatusBadge`, see [`i18n.md`](i18n.md)).
329
329
  - Icons in a Badge also get `data-icon`; to render it as a link, use `render={<Link … />}`.
330
+ - A badge has two sizes, which `client/styles.css` draws for every `Badge`, the plugins' included. The default one stands on its own: a status in a table's column or among a record's particulars. The small one, `data-size='sm'` (`size='sm'` on `StatusBadge`), sits beside a title or a name, on a card or a board's card, or several to a dense row. Choose between them with the attribute rather than with `h-*`, `px-*` or a `text-[11px]` on the badge, which the stylesheet overrides.
330
331
 
331
332
  ## 10. Icons
332
333
 
@@ -339,6 +340,9 @@ export function DeleteProjectButton({
339
340
  - **The application must look like one product.** Before writing a component, look at how neighboring pages handle the same problem: spacing scale, heading sizes, cards or flat sections, where actions go. Follow them.
340
341
  - **When a different look is genuinely needed, change it globally.** Change the tokens in `client/theme/themes/*.css` ([`theme.md`](theme.md)), or change the component all pages share, so the whole application changes together.
341
342
  - **Do not change only the part you are working on.** A page with its own spacing, button styling, or color scheme is a defect. If you think the application's style should change, raise it and change it globally; do not let one page's look diverge.
343
+ - **Whatever may be clicked shows the pointer.** `client/styles.css` gives buttons, links, menu items, options, tabs, checkboxes, radios, switches, comboboxes, `summary`, `select`, `label[for]` and native checkbox, radio and file inputs the pointer cursor unless disabled. Prefer those elements; something clickable that is none of them, such as a card whose click handler sits on a `div`, adds `cursor-pointer` itself, and a disabled one keeps the arrow.
344
+ - **A card that opens something lifts under the pointer.** It rises half a unit, takes `shadow-md` and the `--hover` grey: `transition-[translate,box-shadow,background-color] duration-200 ease-out hover:-translate-y-0.5 hover:bg-hover hover:shadow-md motion-reduce:transition-none motion-reduce:hover:translate-y-0` (the `group-hover:` forms when the card sits inside the clickable element, as the template homepage's capability cards do). The card's own frame stays as it is; an icon tile inside it takes a frame of the general border, `ring-1 ring-transparent group-hover:ring-border`. A card that only shows content does not react to the pointer, and a row in a list or table takes the `--hover` grey without lifting: the template's stylesheet gives it to every `table` row that keeps the primitive's own hover, and a list item you build takes `hover:bg-hover`.
345
+ - **Every control shares one focus.** `client/styles.css` gives fields (the `input`, `textarea`, `select-trigger` and `input-group` slots), buttons, links, tabs, menu items, checkboxes, switches and radios, the plugins' copies included, a half-strength `--ring` border and a 2px halo at a fifth of `--ring` when focused, in place of the 3px ring the primitives draw; an invalid field keeps its red and a destructive button its own color. It is unlayered, so it wins over a control's own `focus-visible:` utilities: do not add `focus-visible:ring-*` or `focus-visible:border-*` classes to restyle one control's focus, and change the shared rule instead when the focus should look different. To give focus another color, change `--ring` in the theme ([`theme.md`](theme.md)), not the rule.
342
346
 
343
347
  ## 12. Dark mode
344
348
 
@@ -30,7 +30,7 @@ The template ships two presets. They share every color, font and shadow and diff
30
30
 
31
31
  | id | Label (en-US / zh-CN) | Role | `--spacing` | `--radius` | Line heights |
32
32
  | --------- | --------------------- | --------------------------------------------------- | ----------- | ---------- | ----------------------- |
33
- | `compact` | Compact / 紧凑 | First in the registry: the default and the fallback | `0.2rem` | `0.375rem` | Tighter than Tailwind's |
33
+ | `compact` | Compact / 紧凑 | First in the registry: the default and the fallback | `0.225rem` | `0.5rem` | Tighter than Tailwind's |
34
34
  | `default` | Spacious / 宽松 | The roomier alternative | `0.25rem` | `0.5rem` | Tailwind's defaults |
35
35
 
36
36
  The id `default` dates from when that preset was the default. It keeps the id because ids are saved in browsers and named in `config.yml`, and it is labeled Spacious so that the label does not claim it is the default selection. Do not relabel it "Default".
@@ -40,37 +40,39 @@ The id `default` dates from when that preset was the default. It keeps the id be
40
40
  ### Colors
41
41
 
42
42
  - Values are complete CSS colors, normally OKLCH, not HSL channels. Do not wrap them in `hsl()`.
43
- - Define all 31 color tokens in both the light and the dark rule.
43
+ - Define all 32 color tokens in both the light and the dark rule.
44
44
  - Surfaces and foregrounds come in pairs: a background and the text or icons on it. A pair does not guarantee enough contrast; measure it (guideline A5 in [`../ui-guidelines.md`](../ui-guidelines.md)).
45
45
 
46
- | Tokens | Meaning and consumers |
47
- | --------------------------------------------------- | ---------------------------------------------------------------- |
48
- | `--background`, `--foreground` | Page surface and default text |
49
- | `--card`, `--card-foreground` | Cards and panels |
50
- | `--popover`, `--popover-foreground` | Floating surfaces: menus, popovers, dialogs |
51
- | `--primary`, `--primary-foreground` | Primary actions |
52
- | `--secondary`, `--secondary-foreground` | Secondary actions |
53
- | `--muted`, `--muted-foreground` | Subtle surfaces and supporting text |
54
- | `--accent`, `--accent-foreground` | Interactive highlighted surfaces (hovered or focused menu items) |
55
- | `--destructive` | Destructive actions and errors |
56
- | `--border`, `--input`, `--ring` | General borders; input borders and surfaces; focus indicators |
57
- | `--chart-1` through `--chart-5` | Five chart series colors |
58
- | `--sidebar`, `--sidebar-foreground` | Navigation surface and text |
59
- | `--sidebar-primary`, `--sidebar-primary-foreground` | Selected navigation item surface and text |
60
- | `--sidebar-accent`, `--sidebar-accent-foreground` | Hovered navigation item surface and text |
61
- | `--sidebar-border`, `--sidebar-ring` | Navigation dividers and focus indicators |
46
+ | Tokens | Meaning and consumers |
47
+ | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
48
+ | `--background`, `--foreground` | Page surface and default text |
49
+ | `--card`, `--card-foreground` | Cards and panels |
50
+ | `--popover`, `--popover-foreground` | Floating surfaces: menus, popovers, dialogs |
51
+ | `--primary`, `--primary-foreground` | Primary actions |
52
+ | `--secondary`, `--secondary-foreground` | Secondary actions |
53
+ | `--muted`, `--muted-foreground` | Subtle surfaces and supporting text |
54
+ | `--accent`, `--accent-foreground` | Interactive highlighted surfaces (hovered or focused menu items) |
55
+ | `--hover` | The light grey of what is picked out: a hovered row or button, the menu's current and hovered entries, a table's header |
56
+ | `--destructive` | Destructive actions and errors |
57
+ | `--border`, `--input`, `--ring` | General borders; input borders and surfaces; focus indicators |
58
+ | `--chart-1` through `--chart-5` | Five chart series colors |
59
+ | `--sidebar`, `--sidebar-foreground` | Navigation surface and text |
60
+ | `--sidebar-primary`, `--sidebar-primary-foreground` | Selected navigation item surface and text |
61
+ | `--sidebar-accent`, `--sidebar-accent-foreground` | Hovered navigation item surface and text |
62
+ | `--sidebar-border`, `--sidebar-ring` | Navigation dividers and focus indicators |
62
63
 
63
64
  The matching classes are `bg-card text-card-foreground`, `border-input`, `ring-ring`, `bg-sidebar text-sidebar-foreground` and so on. Charts must reference the series explicitly with `fill-chart-1`, `stroke-chart-2` or `var(--chart-1)`; a chart library does not pick these variables up on its own.
64
65
 
65
66
  There is no `--destructive-foreground`. The primitives draw destructive buttons and badges as `text-destructive` on a `bg-destructive/10` tint (`/20` in dark), so `--destructive` must read as text on the page, card and popover surfaces and on its own tint.
66
67
 
67
- The template palette is neutral: every color has zero chroma except `--destructive` and the five chart series.
68
+ The template's grounds, text and lines are neutral, with zero chroma: `--background`, `--card`, `--popover`, `--muted`, `--secondary`, `--hover`, `--border`, `--input` and the sidebar's grounds. Its color sits in `--primary` (the NocoBase blue) and what follows it — `--accent`, `--ring`, the current navigation entry's words — and in `--destructive`, the status colors and the five chart series.
68
69
 
69
70
  **Surface and outline tokens carry structure, not decoration.** A preset that forgets this reads as a color clash rather than as a style:
70
71
 
71
72
  - Keep `--card` and `--popover` in the hue family of `--background`, so a panel lifts off the page instead of changing color.
72
73
  - Keep `--muted` a tint close to the background.
73
74
  - Keep `--border` and `--input` low-chroma hairlines, not a second statement of `--primary`.
75
+ - Keep `--border` fainter than `--input`. General borders — cards, tables, dividers, the sidebar's and header's rules, overlays — are the faint line that separates surfaces, so the template sets the light `--border` to `--input`'s color at 60% opacity, and the dark rule likewise keeps `--border` below `--input`. Form fields keep the firmer `--input`, so a person can still see where to type. Do not darken a border with `border-foreground/…` or a fixed color to make one panel stand out, and do not give fields `border-border`. Because that line is translucent, it is tuned to the template's very light `--background`: a preset that darkens `--background` fades its borders with it, so make `--border` opaque there (`oklch(0.9 0 0)`, `--input`'s color) or darker in step, and check a card's frame on the page before keeping the change.
74
76
  - Put the preset's actual color in `--primary`, `--secondary`, `--accent` and the chart series, which appear on small, deliberate areas.
75
77
  - Check a preset on a page that stacks several panels and dozens of dividers, not on one that shows a single card.
76
78
 
@@ -83,15 +85,17 @@ Sidebar tokens may reference the preset's general colors, as both template prese
83
85
  /* … */
84
86
  --sidebar: var(--card);
85
87
  --sidebar-foreground: var(--card-foreground);
86
- --sidebar-primary: color-mix(in oklch, var(--primary) 10%, var(--sidebar));
88
+ --sidebar-primary: color-mix(in srgb, var(--primary) 8%, var(--sidebar));
87
89
  --sidebar-primary-foreground: var(--primary);
88
- --sidebar-accent: var(--muted);
89
- --sidebar-accent-foreground: var(--foreground);
90
+ --sidebar-accent: var(--hover);
91
+ --sidebar-accent-foreground: var(--sidebar-foreground);
90
92
  --sidebar-border: var(--border);
91
93
  --sidebar-ring: var(--ring);
92
94
  }
93
95
  ```
94
96
 
97
+ The current entry sits on a faint tint of `--primary` with its words and icon in `--primary`; a hovered entry takes `--hover`, the grey a table's header also takes, and keeps the menu's words. Keep the tint faint, so a menu of many entries stays quiet and the current one still stands out.
98
+
95
99
  They remain independently configurable: to change the sidebar, change these tokens. Do not redefine general colors such as `--card` on the sidebar to change its appearance.
96
100
 
97
101
  ### Fonts
@@ -155,14 +159,14 @@ The Spacious line heights are Tailwind's defaults.
155
159
 
156
160
  ### Spacing
157
161
 
158
- - `--spacing` is a positive CSS length: `0.2rem` in Compact and `0.25rem`, Tailwind's default, in Spacious. Numeric classes such as `p-4`, `gap-2`, `h-8`, `size-4` and `w-64` multiply it by their suffix, so `h-8` is 1.6rem in Compact and 2rem in Spacious.
162
+ - `--spacing` is a positive CSS length: `0.225rem` in Compact and `0.25rem`, Tailwind's default, in Spacious. Numeric classes such as `p-4`, `gap-2`, `h-8`, `size-4` and `w-64` multiply it by their suffix, so `h-8` is 1.8rem in Compact and 2rem in Spacious.
159
163
  - Changing it moves padding, gaps, control and icon sizes and the navigation width together; the sidebar's widths are `--sidebar-width` and `--sidebar-width-icon`, set in spacing units (64 and 12) in `client/layouts/components/app-sidebar.tsx`. Check typography and spacing together: text must not be clipped, and targets must stay usable.
160
164
  - Percentages, viewport units, container widths such as `max-w-2xl` or `w-xs`, and arbitrary values such as `mt-[7px]` do not use this scale. Breakpoints do not change.
161
165
  - Use numeric classes for ordinary spacing and sizes. Keep deliberate constraints that should not scale, such as viewport limits, images and separators. Do not change the root font size to simulate density, and do not add ad hoc height tokens.
162
166
 
163
167
  ### Radius
164
168
 
165
- `--radius` is a nonnegative CSS length: `0.375rem` in Compact and `0.5rem` in Spacious. The `@theme inline` block in `client/styles.css` derives the public corner classes from it:
169
+ `--radius` is a nonnegative CSS length: `0.5rem` in both presets. The `@theme inline` block in `client/styles.css` derives the public corner classes from it:
166
170
 
167
171
  | Class | Multiplier |
168
172
  | ------------- | ---------- |
@@ -214,7 +218,7 @@ Some values stay fixed on purpose. Know which ones, and keep your own explicit.
214
218
 
215
219
  ### Constraints from the token test
216
220
 
217
- `tests/logic/theme-tokens.test.ts` requires `compact.css` and `default.css` to be identical, in both the light and the dark rule, except for `--spacing`, `--radius` and the `--text-*` variables, and it requires Compact's `--spacing` to be smaller than Spacious'. Today the two differ in spacing, radius and line heights; the text sizes are the same. So:
221
+ `tests/logic/theme-tokens.test.ts` requires `compact.css` and `default.css` to be identical, in both the light and the dark rule, except for `--spacing`, `--radius` and the `--text-*` variables, and it requires Compact's `--spacing` to be smaller than Spacious'. Today the two differ in spacing and line heights; the radius and the text sizes are the same. So:
218
222
 
219
223
  - A change to colors, fonts or shadows goes into both files, light and dark rules alike.
220
224
  - Density (spacing, radius, text sizes and line heights) may differ between the two.
@@ -225,7 +229,7 @@ Some values stay fixed on purpose. Know which ones, and keep your own explicit.
225
229
  The steps below add a preset with the id `forest`.
226
230
 
227
231
  1. **Copy a file.** Copy the preset whose density the new one should share to `client/theme/themes/forest.css`: `compact.css` for the application's default density, `default.css` for the spacious one. Use a stable id of lowercase letters, digits and hyphens, and name the file after it: the token test loads `client/theme/themes/<id>.css` for every registered id.
228
- 2. **Set the selectors and tokens.** Light uses `:root[data-theme='forest'], .theme-preview[data-theme='forest']`; dark uses `:root.dark[data-theme='forest'], :root.dark .theme-preview[data-theme='forest']`. Keep the single quotes: the token test looks the selectors up by their exact text. If you copied `default.css`, delete its bare `:root` and `:root.dark` selectors. Only `default.css` may carry them; whichever file is imported last would otherwise take over the fallback. Set `--radius` and all 31 colors, keep the fonts, sizes, spacing and shadows unless the preset is meant to change them, and repeat every color in the dark rule.
232
+ 2. **Set the selectors and tokens.** Light uses `:root[data-theme='forest'], .theme-preview[data-theme='forest']`; dark uses `:root.dark[data-theme='forest'], :root.dark .theme-preview[data-theme='forest']`. Keep the single quotes: the token test looks the selectors up by their exact text. If you copied `default.css`, delete its bare `:root` and `:root.dark` selectors. Only `default.css` may carry them; whichever file is imported last would otherwise take over the fallback. Set `--radius` and all 32 colors, keep the fonts, sizes, spacing and shadows unless the preset is meant to change them, and repeat every color in the dark rule.
229
233
 
230
234
  ```css
231
235
  /* client/theme/themes/forest.css */
@@ -239,7 +243,7 @@ The steps below add a preset with the id `forest`.
239
243
  ui-sans-serif, -apple-system, BlinkMacSystemFont, 'Segoe UI',
240
244
  'PingFang SC', 'Microsoft YaHei', sans-serif;
241
245
  /* … --font-serif through --shadow-2xl: copied from compact.css unchanged */
242
- --radius: 0.375rem;
246
+ --radius: 0.5rem;
243
247
  --background: oklch(0.985 0.005 150);
244
248
  --foreground: oklch(0.2 0.02 150);
245
249
  --card: oklch(0.995 0.003 150);
@@ -254,8 +258,9 @@ The steps below add a preset with the id `forest`.
254
258
  --muted-foreground: oklch(0.5 0.02 150);
255
259
  --accent: oklch(0.93 0.04 130);
256
260
  --accent-foreground: oklch(0.25 0.04 150);
261
+ --hover: color-mix(in srgb, var(--muted) 70%, var(--card));
257
262
  --destructive: oklch(0.577 0.245 27.325);
258
- --border: oklch(0.9 0.01 150);
263
+ --border: oklch(0.9 0.01 150 / 60%);
259
264
  --input: oklch(0.9 0.01 150);
260
265
  --ring: oklch(0.55 0.1 150);
261
266
  --chart-1: oklch(0.55 0.13 150);
@@ -265,10 +270,10 @@ The steps below add a preset with the id `forest`.
265
270
  --chart-5: oklch(0.8 0.12 90);
266
271
  --sidebar: var(--card);
267
272
  --sidebar-foreground: var(--card-foreground);
268
- --sidebar-primary: color-mix(in oklch, var(--primary) 10%, var(--sidebar));
273
+ --sidebar-primary: color-mix(in srgb, var(--primary) 8%, var(--sidebar));
269
274
  --sidebar-primary-foreground: var(--primary);
270
- --sidebar-accent: var(--muted);
271
- --sidebar-accent-foreground: var(--foreground);
275
+ --sidebar-accent: var(--hover);
276
+ --sidebar-accent-foreground: var(--sidebar-foreground);
272
277
  --sidebar-border: var(--border);
273
278
  --sidebar-ring: var(--ring);
274
279
  }
@@ -289,6 +294,7 @@ The steps below add a preset with the id `forest`.
289
294
  --muted-foreground: oklch(0.7 0.02 150);
290
295
  --accent: oklch(0.3 0.04 140);
291
296
  --accent-foreground: oklch(0.97 0.005 150);
297
+ --hover: color-mix(in srgb, var(--muted) 70%, var(--card));
292
298
  --destructive: oklch(0.704 0.191 22.216);
293
299
  --border: oklch(1 0 0 / 10%);
294
300
  --input: oklch(1 0 0 / 15%);
@@ -300,10 +306,10 @@ The steps below add a preset with the id `forest`.
300
306
  --chart-5: oklch(0.82 0.12 90);
301
307
  --sidebar: var(--card);
302
308
  --sidebar-foreground: var(--card-foreground);
303
- --sidebar-primary: color-mix(in oklch, var(--primary) 10%, var(--sidebar));
309
+ --sidebar-primary: color-mix(in srgb, var(--primary) 8%, var(--sidebar));
304
310
  --sidebar-primary-foreground: var(--primary);
305
- --sidebar-accent: var(--muted);
306
- --sidebar-accent-foreground: var(--foreground);
311
+ --sidebar-accent: var(--hover);
312
+ --sidebar-accent-foreground: var(--sidebar-foreground);
307
313
  --sidebar-border: var(--border);
308
314
  --sidebar-ring: var(--ring);
309
315
  }
@@ -426,7 +432,7 @@ Run the theme tests:
426
432
  pnpm exec vitest run tests/logic/theme-tokens.test.ts tests/logic/theme-preferences.test.ts tests/logic/client-theme.test.tsx
427
433
  ```
428
434
 
429
- - `theme-tokens.test.ts` checks that every registered preset defines all 31 colors and every non-color token in its light rule and every color in its dark rule, with the same declarations on the preview selectors; that Compact and Spacious differ only in dimensions, with Compact's spacing smaller; and, by compiling `client/styles.css` with Tailwind, that the color, font, size, line height, spacing, radius and shadow classes and the `body`, `h1` and `code` fonts still read the runtime variables.
435
+ - `theme-tokens.test.ts` checks that every registered preset defines all 32 colors and every non-color token in its light rule and every color in its dark rule, with the same declarations on the preview selectors; that Compact and Spacious differ only in dimensions, with Compact's spacing smaller; and, by compiling `client/styles.css` with Tailwind, that the color, font, size, line height, spacing, radius and shadow classes and the `body`, `h1` and `code` fonts still read the runtime variables.
430
436
  - `theme-preferences.test.ts` checks that Compact is first, the storage keys for each base path, restoring both choices at startup without reading another application's keys, and the fallbacks for invalid values, removed presets and unavailable storage.
431
437
  - `client-theme.test.tsx` checks the provider and the popover: labels in en-US and zh-CN, choosing and saving, configured defaults against saved choices, startup and provider agreeing, clearing and syncing across tabs, invalid values, and unavailable storage.
432
438
 
@@ -30,7 +30,7 @@ An agent's runs on one subject: a compact side-column log with a live timer, an
30
30
 
31
31
  ### agent-composer
32
32
 
33
- The message box for talking to an agent: page-context chips inside it, files to send (attach, paste, drop, uploaded before sending), Enter to send, Stop while the agent works, and a toolbar slot for a model or mode picker. Use it wherever a person writes to an agent. Presentational: context chips, drafts and focus come from the agents plugin's chat hooks (@nocobase/app-plugin-agents/client/chat) through optional props.
33
+ The message box for talking to an agent: page-context chips inside it, files to send (attach, paste, drop, uploaded before sending), Enter to send, Stop while the agent works, and a toolbar slot for a picker such as the agent's. Use it wherever a person writes to an agent. Presentational: context chips, drafts and focus come from the agents plugin's chat hooks (@nocobase/app-plugin-agents/client/chat) through optional props.
34
34
 
35
35
  - Kind: component
36
36
  - Install: `yes n | pnpm exec shadcn add @nocobase/agent-composer`
@@ -41,18 +41,18 @@ The message box for talking to an agent: page-context chips inside it, files to
41
41
 
42
42
  ### agent-picker
43
43
 
44
- The one way to pick an agent: a trigger with the agent's avatar (availability dot on its corner) and name, and a menu of the agents grouped by type (Online, Runner) with their default and personal tags and availability. Two appearances: field, which looks like a form's select, for forms and settings; toolbar, compact with the mode tag, for a composer. Presentational: pass ChatAgent records from @nocobase/app-plugin-agents/shared/conversations.
44
+ The one way to pick an agent: a trigger with the agent's avatar (availability dot on its corner) and name, and a menu of every enabled agent with what it is good at, its default and "personal runners only" tags, and why one cannot answer the viewer now (it cannot be picked then). Two appearances: field, which looks like a form's select, for forms and settings; toolbar, compact, for a composer. Presentational: pass ChatAgent records from @nocobase/app-plugin-agents/shared/conversations.
45
45
 
46
46
  - Kind: component
47
47
  - Install: `yes n | pnpm exec shadcn add @nocobase/agent-picker`
48
48
  - Installs to: `client/components/agent-picker.tsx`
49
49
  - Plugin dependencies: `@nocobase/app-plugin-agents`
50
50
  - Example: `@nocobase/agent-picker-demo` (`pnpm exec shadcn view @nocobase/agent-picker-demo`)
51
- - After installing: Pass the agents (useChatAgents from @nocobase/app-plugin-agents/client/chat for chat, or useAgentOptions().agents from @nocobase/app-plugin-agents/client/kit for a form), value and onSelect. appearance is field by default (type filters to Online or Runner, noneOption offers no agent, placeholder, disabled, id for a label); appearance='toolbar' fits a composer, and bound marks an existing conversation, whose agent cannot change. Also exports AgentIdentity (avatar, dot and name as one row, for a picker that lists agents among people), AvailabilityDot, ModeTag, AgentTags and AgentTag. Every word comes from the labels prop, English by default.
51
+ - After installing: Pass the agents (useChatAgents from @nocobase/app-plugin-agents/client/chat for chat, or useAgentOptions().agents from @nocobase/app-plugin-agents/client/kit for a form), value and onSelect. appearance is field by default (noneOption offers no agent, placeholder, disabled, id for a label); appearance='toolbar' fits a composer, and bound marks an existing conversation, whose agent cannot change. Also exports AgentIdentity (avatar, dot and name as one row, for a picker that lists agents among people), AvailabilityDot, AgentTags and AgentTag. Every word comes from the labels prop, English by default.
52
52
 
53
53
  ### agent-chat
54
54
 
55
- The agents' chat: a side panel beside the content area with the conversation, live steps, a composer with page-context chips and files to send (attach, paste, drop), model and agent pickers, the history, a full-page conversation view, and header, floating and Ask agent launchers. Use it to let people talk to agents from any page. Wired to the headless hooks of @nocobase/app-plugin-agents/client/chat.
55
+ The agents' chat: a side panel beside the content area with the conversation, live steps, a composer with page-context chips and files to send (attach, paste, drop), the agent picker, the history, a full-page conversation view, and header, floating and Ask agent launchers. Use it to let people talk to agents from any page. Wired to the headless hooks of @nocobase/app-plugin-agents/client/chat.
56
56
 
57
57
  - Kind: block
58
58
  - Install: `yes n | pnpm exec shadcn add @nocobase/agent-chat`
@@ -169,6 +169,17 @@ Markdown rendered as compact prose for descriptions and comments, with mention c
169
169
  - Example: `@nocobase/markdown-view-demo` (`pnpm exec shadcn view @nocobase/markdown-view-demo`)
170
170
  - After installing: Pass the Markdown as content. renderCodeBlock draws a fenced block itself, such as a mermaid diagram; mentionIcon picks a mention chip's icon by its kind. remarkCjkAutolink ends a bare URL at CJK text or full-width punctuation; add it after remark-gfm wherever else you render the same Markdown.
171
171
 
172
+ ### long-text
173
+
174
+ A long text shown in part, the last line fading out instead of an ellipsis. LongText is for where there is room, such as the description under a page's title or a comment: five lines that unfold in place on a click. LongTextPreview is for a narrow column, such as a record's introduction or address beside its page: three muted lines whose whole text opens in a pop-up, so the column never grows. Neither reacts unless the text overflows.
175
+
176
+ - Kind: component
177
+ - Install: `yes n | pnpm exec shadcn add @nocobase/long-text`
178
+ - Installs to: `client/components/long-text.tsx`
179
+ - Plugin dependencies: none
180
+ - Example: `@nocobase/long-text-demo` (`pnpm exec shadcn view @nocobase/long-text-demo`)
181
+ - After installing: Pass the text as children; a string keeps its line breaks, and rendered content such as MarkdownView works too. LongTextPreview needs a label, the heading of the pop-up that shows the text whole.
182
+
172
183
  ### comment-thread
173
184
 
174
185
  A record's activity line: comment threads with reactions, reply, edit, delete and resolve, the consumer's own entries between them, and a composer with modes and files. Use it for a record's discussion, such as an issue's comments from @nocobase/app-plugin-projects.
@@ -196,14 +207,15 @@ Files on a record or a message: image thumbnails and file chips with download, t
196
207
 
197
208
  ### property-fields
198
209
 
199
- The fields of a record's property card: the titled card, label and value rows, a select, chips with creation, a date, a number, a person as a value, and a row of avatars. Use it for the side column of a detail page.
210
+ The fields of a record's property card: the titled card, label and value rows, a select, chips with creation, a date, a number, a line of text, a long text, a link, a person as a value, and a row of avatars. Use it for the side column of a detail page. PropertyCard draws its fields one of two ways: variant form shows every value in its control, and variant inline reads first, each value plain text that a double-click, Enter or F2 edits, shaded under the pointer, with a copy button on hover; a long text opens whole on a click, and a link, which a click opens, is edited from a pencil.
200
211
 
201
212
  - Kind: component
202
213
  - Install: `yes n | pnpm exec shadcn add @nocobase/property-fields`
203
214
  - Installs to: `client/components/property-fields.tsx`
204
215
  - Plugin dependencies: none
216
+ - Also installs: `@nocobase/long-text`
205
217
  - Example: `@nocobase/property-fields-demo` (`pnpm exec shadcn view @nocobase/property-fields-demo`)
206
- - After installing: Values in, changes out: each field reports a change through onChange. Pass PropertyFieldLabels built from your locale resources for the words the fields show themselves.
218
+ - After installing: Values in, changes out: each field reports a change through onChange. Pass PropertyFieldLabels built from your locale resources for the words the fields show themselves. Set variant='inline' on PropertyCard for the read-first card, and give each field an aria-label, its name while it shows as text.
207
219
 
208
220
  ### rich-text-editor
209
221
 
@@ -328,7 +340,7 @@ One issue, compact: identifier, title, status in its workflow colour, priority,
328
340
 
329
341
  ### issue-detail
330
342
 
331
- An issue's page as presentational parts: the two-column frame of cards on the page background, the header and description opening the body card, an add bar under it, the secondary parts (checklist, approvals, sub-issues, dependencies with an issue search, files) as sections sharing one heading pattern and hidden while empty, files dropped or pasted on the body, and the side column over property-fields. Use it for an issue detail page over the hooks of @nocobase/app-plugin-projects/client/issues.
343
+ An issue's page as presentational parts: the two-column frame of cards on the page background, the header and description opening the body card, an add bar under it, the secondary parts (sub-issues, dependencies with an issue search, files) as sections sharing one heading pattern and hidden while empty, files dropped or pasted on the body, and the side column over property-fields. Use it for an issue detail page over the hooks of @nocobase/app-plugin-projects/client/issues.
332
344
 
333
345
  - Kind: block
334
346
  - Install: `yes n | pnpm exec shadcn add @nocobase/issue-detail`
@@ -42,6 +42,8 @@ These are this application's UI design guidelines: foundations, page structure,
42
42
 
43
43
  **L7 [Must] The primary action appears in exactly one place**: while a list is empty it is only inside the empty state (S2); once the list has rows it is only in the page header. Decide from loaded data, so the header shows no action while the list loads rather than one that disappears. A search or filter that matches nothing is not an empty list (S3): the header keeps its action. A primary action that opens a `DropdownMenu` aligns the menu with its trigger, `align='end'` in the header and `align='center'` in the empty state; each item is an icon and a name on one line with the `DropdownMenuItem` defaults, no sub-label.
44
44
 
45
+ **L8 [Should] A count beside a menu entry is what waits on the viewer**: unread messages, requests to decide, work assigned to them and not yet done. Never a total of records ("Leads 18"), which the page itself shows. Zero shows nothing. Work under way the viewer may want to follow, such as runs in progress, is a live count with words of its own ("2 running"). One thing is counted in one place: an entry and a header button, such as the inbox button, do not both count the same items. See ["A count beside an entry" in `references/page.md`](references/page.md#a-count-beside-an-entry).
46
+
45
47
  ## T Page templates
46
48
 
47
49
  ### T1 List page: browse, find and manage one kind of record
@@ -68,6 +70,7 @@ Structure, top to bottom: PageHeader (primary action "New X") → toolbar (searc
68
70
  - **T2.2 [Must]** The top of the drawer or detail page shows the record name. Actions on the record (edit, delete) sit in a fixed position at the top or the bottom, grouped together, not one on the left and one on the right.
69
71
  - **T2.3 [Must]** The detail view can be opened directly by URL, and a refresh still shows the same record (see I6).
70
72
  - **T2.4 [Must]** Fields are laid out in two columns, "label — value", and an empty value shows "—"; multi-line text keeps its line breaks; very long values (emails, URLs) may wrap and must not break the layout.
73
+ - **T2.5 [Should] Particulars read first and edit in place**: a record's particulars in the side column of its page, or in its drawer, use the UI Library `property-fields` card with `variant='inline'`: each value is plain text, shaded under the pointer when the user may change it, edited on a double-click (Enter or F2 from the keyboard) and saved on the pick or when it loses focus, Escape leaving it as it was. A single click never enters editing, so a value can be selected and copied. A value people copy — an email, a phone number, an address, a website — gets a copy button on hover (`copyable`). A long text opens beside the column in a pop-up on a click and is edited there with a double-click, so the column keeps its height; a link, which a click opens, is edited from a pencil shown on hover, so following it never starts an edit. A value the user may not change is plain text, with no shading and no pencil. A form filled in at once, such as a create dialog, keeps every value in its control (the card's default `variant='form'`, or T3).
71
74
 
72
75
  ### T3 Form: create and edit
73
76
 
@@ -152,6 +155,8 @@ Do not show raw backend error messages (untranslated exception messages, stack t
152
155
 
153
156
  **I13 [Must] Menus on icon triggers size to their items**: the shadcn `DropdownMenuContent` defaults to its trigger's width, so the menu of an icon button (a row's "…", a card's "More") is as narrow as the icon and wraps every item. Every `DropdownMenuContent` whose trigger is an icon button, or any trigger narrower than its items, gets `className='w-auto min-w-40'`: as wide as its longest item, and never narrower than `min-w-40`. Keep the class on the call site rather than in a wrapper component, beside positioning props such as `align='end'`. A menu whose trigger is at least as wide as its items, such as a labelled button, keeps the default.
154
157
 
158
+ **I14 [Must] Long text shows in part, by where it sits**: a description, an introduction, a note or a comment never ends in an ellipsis mid-sentence, and never pushes a narrow column longer than its neighbours. Where there is room, such as the description under a page's title or a comment in a timeline, show up to five lines and unfold the rest in place on a click (`LongText`). In a narrow column, such as a record's particulars beside its page or a card, show up to three muted lines and open the whole text in a pop-up beside it (`LongTextPreview`), so the column keeps its height. The last line fades out, and a text that fits is shown plainly, with nothing to click. Both come from the UI Library item `@nocobase/long-text` ([`references/ui-library.md`](references/ui-library.md)). A table cell or a list item's one-line summary keeps `truncate` or `line-clamp-1`, where the row opens the record.
159
+
155
160
  ## R Data freshness
156
161
 
157
162
  **R1 [Must] Never write from stale data**: edit, delete and similar actions work from the record's latest data (see T3.8). Take particular care when the backend replaces fields wholesale; otherwise the write overwrites changes that someone else, or the same user, just made.
@@ -200,7 +205,7 @@ The design review and the acceptance review both go through this checklist item
200
205
 
201
206
  - [ ] The page template and overlay choices are correct, and stacking follows the rules (T1–T5, I1)
202
207
  - [ ] Page structure: PageContainer, PageHeader, one primary button per view, actions in the right places, a back button on a page below another one, which returns to that other page with its search and filters unchanged, and the primary action in exactly one place: the empty state while the list is empty, the header once it has rows (L1, L2, L5, L6, L7)
203
- - [ ] Navigation is consistent: entries in one group all carry an icon or none does, and a group's own icon does not repeat its first child's (`page.md` §6)
208
+ - [ ] Navigation is consistent: entries in one group all carry an icon or none does, a group's own icon does not repeat its first child's, and a count beside an entry is only what waits on the viewer (`page.md` §6, L8)
204
209
  - [ ] All states are covered: loading, empty, no results, load failed, submitting, a block the user may not see; whether a failure offers a retry follows S4 (S1–S6)
205
210
  - [ ] List: search placeholder, filters and clearing them, first column, enum Badges, row actions, formatting, date and number columns sortable, all four states, result cap notice, a cut-off cell ending in an ellipsis with its full content on hover (T1.1–T1.6, T1.8–T1.11)
206
211
  - [ ] Detail view: drawer or page, record name and grouped actions, opens by URL, label–value layout with "—" for empty values (T2.1–T2.4)
@@ -213,6 +218,8 @@ The design review and the acceptance review both go through this checklist item
213
218
  - [ ] Overlays and their state have URLs; every record and overlay opens over the view the user is on — a filtered list, a dashboard, a board, a drawer, the tab being shown — at that view's URL plus its own segments, and closing returns to exactly that URL, checked from a view other than the first one too: a tab other than the default, a list with a filter applied (I6, I9)
214
219
  - [ ] Each overlay has the component, width and structure I1 gives what it holds, confirmations are AlertDialogs, and a dialog that can outgrow the screen caps its height at `calc(100dvh-2rem)` with a fixed footer and a scrolling body (I1)
215
220
  - [ ] Dates are picked from a Calendar in a Popover, never a native date input, and a range has presets; a drawer holding a form or details is medium width; select popups grow with their options and wrap long ones; menus on icon triggers size to their items (I10–I13)
221
+ - [ ] A record's particulars read as text and edit on a double-click, with copy on hover and a pencil for links (T2.5)
222
+ - [ ] Long text fades after five lines and unfolds in place where there is room, and after three muted lines opening in a pop-up in a narrow column, never an ellipsis mid-sentence (I14)
216
223
  - [ ] Actions without permission are hidden and unavailable ones disabled with a reason; everything works with the keyboard (I7, I8)
217
224
  - [ ] Color, font size, spacing, radius and icons use only tokens, scales and lucide-react, and fixed sizes are explained (F1–F5, F7)
218
225
  - [ ] Copy exists in every language `client/locales/index.ts` offers, wording is consistent, and button and title copy follows the rules (C1–C4, C6, C7)
@@ -0,0 +1,95 @@
1
+ # Configurable lifecycle parameters
2
+
3
+ Use this when administrators need to adjust approval departments, reviewers, thresholds, reopening windows or other business values while developers keep the workflow in source. Read [record lifecycles](lifecycle.md) first. This capability belongs to `@nocobase/lifecycle`; verify that the installed package exports `StoredLifecycleParameters` and `normalizeReviewerSelections` before using it. An older installation needs a compatible release upgrade rather than invented APIs.
4
+
5
+ ## Code declaration and storage
6
+
7
+ Declare defaults in `parameters` and a code-owned `parameterConfiguration` with groups. Every group has key, title, schemaVersion and fields; every field has type, title and a parse function returning its complete normalized JSON value. Optional field bindings name a state or transition. The flow declares readMode and snapshotTransition, and individual fields can override readMode. Groups can declare a validate function and sameReadMode arrays for joint invariants.
8
+
9
+ ```ts
10
+ import { StoredLifecycleParameters, type ParameterGroup } from '@nocobase/lifecycle';
11
+ import { z } from 'zod';
12
+
13
+ const thresholds: ParameterGroup = {
14
+ key: 'approvalThresholds', title: 'Approval thresholds', schemaVersion: 1,
15
+ fields: {
16
+ automaticLimit: {
17
+ type: 'number', title: 'Automatic approval limit',
18
+ parse: (value) => z.number().finite().nonnegative().parse(value),
19
+ bindings: [{ transition: 'submit' }],
20
+ },
21
+ financeLimit: {
22
+ type: 'number', title: 'Finance review limit',
23
+ parse: (value) => z.number().finite().nonnegative().parse(value),
24
+ bindings: [{ state: 'financeReview' }],
25
+ },
26
+ },
27
+ sameReadMode: [['automaticLimit', 'financeLimit']],
28
+ validate: (values) => {
29
+ if (Number(values.automaticLimit) > Number(values.financeLimit))
30
+ throw new Error('Automatic approval cannot exceed the finance limit.');
31
+ },
32
+ };
33
+
34
+ // In the definition:
35
+ parameters: { automaticLimit: 500, financeLimit: 5000 },
36
+ parameterConfiguration: {
37
+ readMode: 'snapshot', snapshotTransition: 'submit', groups: [thresholds],
38
+ },
39
+
40
+ // Register on the application's existing lifecycle runtime:
41
+ runtime.register(expenseLifecycle, {
42
+ parameterConfiguration: {
43
+ store: new StoredLifecycleParameters(lifecycleStore, collectionNames),
44
+ scope: ({ record }) => scopeFromAuthoritativeRecord(record),
45
+ legacyRecord: (record) => record.parameterContract !== 1,
46
+ snapshotRequired: (record) => record.status !== 'draft',
47
+ },
48
+ });
49
+ ```
50
+
51
+ Create six collections with an immutable migration, using application-owned names: heads (string id, scope, groupKey, status, integer revision; unique scope/groupKey); versions (string id, JSON payload, JSON selectionCounts); selections (string id, versionId, ruleKey, integer group, type, referenceId; index versionId); requests (string id, actorId, text fingerprint, integer revision); snapshots (string id, JSON payload); usages (string id, JSON payload, recordKey, zoned timestamp at; index recordKey/at/id). Pass names as `{ heads, versions, selections, requests, snapshots, usages }`. Existing LifecycleStore implementations are unchanged; custom parameter adapters implement the separate LifecycleParameterStore interface, including read/save/snapshot/saveSnapshot/usage/saveUsage/listUsage.
52
+
53
+ Resolve scope and record identity from server-owned context. Authenticate and authorize configuration read/write before validators or record lookup. In the save transaction validate referenced entities in that scope, then call `store.save({ scope, group, values, expectedRevision, requestId, actorId, at }, transactionHandle)`. Save exactly the complete declared group: never accept undeclared fields, schemaVersion, modes, workflow structure or client-provided effective values. A stale revision is a 409 configuration conflict; the same request and values replay its immutable version. Reused request IDs with different input fail. Only an absent configuration uses code defaults; read errors and incompatible schemas fail.
54
+
55
+ ## Snapshot, live and execution consistency
56
+
57
+ Snapshot fixes all declared snapshot fields at the first successful formal submission, before routing, setters and hooks, in the business transaction. Draft preview writes nothing. Return, withdrawal and resubmission keep the original snapshot. Snapshot rules fix their choices, not organization membership. New snapshot fields missing from an old submitted record require a migration; never fabricate historical values using current settings. Define an explicit legacyRecord policy when introducing the contract to existing records, and use a version marker on newly created records.
58
+
59
+ Live reads current complete values for every execution, effect retry and continuation transition. A same-record execution shares one resolution through guard, execute, route, set, hooks and nested tx.fire calls; different records have independent resolutions. For business actions use `runtime.withParameterExecution(name, recordId, async (parameters, tx) => { ... }, { actionId, transaction })` after the application's action replay check. This helper writes an identified action's usage fact but does not deduplicate the business action. Query services in guards and callbacks must use tx.handle.
60
+
61
+ Use `runtime.view()` for record availability and effective parameterValues from one authoritative preview. Use `lifecycleDescriptionViewAsync(runtime, name, { record: null, purpose: 'preview', transactionHandle: undefined })` for an authorized current configuration description. Record-aware previews pass the authoritative record. Preview is informative; actual execution rechecks guards.
62
+
63
+ Transitions, identified actions and each effect attempt record actual values and per-field revision/schema/origin/mode. Effect facts persist before external execution and are fenced against the active attempt. `store.snapshot()`, `store.usage()` and `store.listUsage(scope, lifecycle, recordId)` expose history. Pruning effect runs preserves configuration facts. Display “Not recorded” for missing historical usage and show current effective values separately.
64
+
65
+ Do not change payment amounts, accounts or recipients through live configuration while retaining an effect run's idempotency key. Those identities come from persisted business facts. Simulated notification copy is a safe demonstration of fresh live values on retry. Trigger timeouts remain code-owned.
66
+
67
+ ## Reviewer rules and task boundaries
68
+
69
+ Use `type: 'reviewers'`, parsed with `normalizeReviewerSelections(value, ['department', 'role', 'user'])`. Persist flat choices `{ group, type, referenceId }`, never arbitrary expression JSON or scripts. Same-group conditions intersect, separate groups union and deduplicate. Alternative people belong in separate groups.
70
+
71
+ Register selectors with `resolveReviewerSelections(choices, { scope, applicantId, transactionHandle }, { selectors, eligible })`. Each selector returns IDs for its code-declared reference type; eligible uniformly filters every result, including explicit users. Departments use exact membership unless code explicitly provides another named selector, roles respect scope, and inactive users and the applicant are filtered. Code determines a zero-candidate failure and the node's decision policy. Custom types may resolve positions, contextual department references or named queries without accepting arbitrary scripts.
72
+
73
+ On task creation resolve the snapshot or live rule against current organization data and persist candidates on the task. Existing candidates stay fixed. A single approver field is not a multi-person approval system. To demonstrate multiple candidates, declare a separate finite “any candidate can decide” workflow and use version checks so only one concurrent decision succeeds. Real approval plugins need their own compatibility verification for action replay, settings previews, task construction and opinion reuse; fixed current-round tasks or inherited opinions cannot stand in for rule configuration.
74
+
75
+ ## Optional user interfaces
76
+
77
+ Respect the user's existing UI and scope. API-only work needs no configuration page or diagram. An existing settings page can embed a form. Offer a central page or optional bound diagram entry only when useful. Do not add a mandatory diagram or a second workflow-design system.
78
+
79
+ When building a page with configurable parameters tied to business process nodes, prefer an editing entry on the corresponding diagram node or transition. For example, clicking a finance-review node can open a dialog for its reviewer rules and approval threshold, so users can adjust those values in their process context. If the page already includes a diagram, incorporate this entry as part of the page design; if a diagram has not been requested, suggest this interaction when discussing the process interface. Parameters with no node or transition relationship can stay in an embedded form or settings page.
80
+
81
+ For save request IDs, follow the [browser request ID guidance](lifecycle.md#5-the-page): use an HTTP-compatible generator and retain the key for retries of the same save.
82
+
83
+ The example plugin exports `ParameterEditor`, `parameterApi` and `boundParameterGroups` from `@nocobase/app-plugin-lifecycle-example/client`. They illustrate a shared editor with an injected API, complete-version CAS saves, read-only mode and preserved drafts on conflicts. They are example exports, not an automatically installed platform settings service. Applications can implement the same contracts in their own UI.
84
+
85
+ For a working reference in the NocoBase source repository, inspect `packages/examples/app-plugin-lifecycle-example/client/pages/parameters.tsx` and `client/components/parameter-binding-editor.tsx` in the same package: `useParameterBindingEditor` connects diagram bindings to a dialog containing the shared `ParameterEditor` and refreshes the page after saving. Reuse the same editor and save contract for diagram and settings entries when both exist.
86
+
87
+ For click-to-edit diagrams, derive groups from description.parameterConfiguration.groups and bindings referencing the clicked state or transition name. One entry can bind several fields or groups. Intercept only bound entries; unbound entries retain the component's ordinary details. In the example, ProcessDiagram's onParameterBinding(kind, name) returns true when the shared editor handles the click. Clicking opens configuration and never fires a transition. Use the diagram component's actual node/edge callbacks rather than assuming an event API.
88
+
89
+ Show field titles, units, validation, read mode and effective timing. Snapshot changes affect new submissions; live changes affect subsequent executions/retries. Read-only viewers see disabled fields and no save control. On 409 keep draft inputs, fetch the current revision and values, then require a deliberate retry against that revision. Label an editor opened from history as current configuration; never rewrite an old snapshot, actual usage fact or candidate list.
90
+
91
+ ## Validate the integration
92
+
93
+ Test complete schemas and cross-field constraints, CAS/replay, reference scope and authorization before validation. Prove draft previews create no facts, first submission freezes every snapshot field, failed transactions/savepoints remove it, resubmission retains it, and missing historical fields fail. Check same-record actions/nested transitions share values while different records do not. Prove fresh live retries preserve business idempotency and record each attempt's facts.
94
+
95
+ Exercise reviewer intersections/unions, duplicate and inactive/applicant filtering, changed department choices, changed organization membership and fixed existing candidates. Test simultaneous decisions. For chosen UI entry points verify shared save behavior, read-only rendering, preserved conflict drafts, multi-field bindings, untouched unbound entries and distinct current/history labels in the running application. Use the normal testing helpers and run skills sync after installation so this reference is reachable from the normal Skill entry.
@@ -2,6 +2,8 @@
2
2
 
3
3
  Use `@nocobase/lifecycle` when a business record moves through stages that developers define in source: an expense report, a ticket, a contract, an order, a leave request. The record keeps its state in one of its own fields, every change is a transition declared in a definition, and the work a transition owes outside the database — mail, payments, calls to other systems — runs as effects after the transaction commits. There is no separate process instance, so the state is never kept in two places.
4
4
 
5
+ Administrators can adjust code-declared business parameters without editing workflow structure. For configurable approval departments, reviewer choices, thresholds, snapshot/live reads and optional configuration editors, read [configurable lifecycle parameters](lifecycle-parameters.md).
6
+
5
7
  ## Choose it or something else
6
8
 
7
9
  | The requirement | Use |
@@ -14,6 +16,12 @@ Use `@nocobase/lifecycle` when a business record moves through stages that devel
14
16
 
15
17
  A parent and its children can each have a lifecycle and point at each other by foreign key, such as a document and the tasks it distributes; a child's last transition can move the parent on in the same transaction.
16
18
 
19
+ ## Ask about the process UI
20
+
21
+ When developing a lifecycle, ask whether the user wants to display a flowchart or a related process interface, unless they have already stated their preference. For example, ask in the user's language: “Would you like this process to include a flowchart or a process interface showing its current state, available actions and history? If yes, we can render it with the flow diagram components from our UI Library.”
22
+
23
+ If the user chooses yes, use the UI Library's `@nocobase/lifecycle-diagram` to render the lifecycle definition and record progress; `@nocobase/flow-diagram` is available for generic process graphs. Follow [the diagram integration guidance](#draw-an-interactive-lifecycle-diagram) and [the frontend workflow](frontend/ui-workflow.md) for the surrounding process interface. Respect separate preferences: a user may want state, action buttons and history without a diagram. If they decline both a diagram and a process interface, continue implementing the lifecycle without adding either.
24
+
17
25
  ## Rules that are never broken
18
26
 
19
27
  1. **The state lives only in the record's own field.** Query, filter and count on it like any other column; keep no copy elsewhere.
@@ -376,6 +384,8 @@ return view.available.map((transition) => (
376
384
 
377
385
  Render the buttons from `view.available`, never from a hard-coded state check, so the page and the server use the same judgement. Translate titles and blocker messages by their stable `name` and `code`, as every user-visible string goes through a translation key. `fire` sends a fresh `requestId` and the version on screen; on `CONFLICT` tell the person the record changed and reload rather than retrying. On `INVALID_INPUT`, mark the fields in `error.problems`. The hook refreshes every 4 seconds by default; `refreshMs` changes it. Follow [the frontend workflow](frontend/ui-workflow.md) for the page itself.
378
386
 
387
+ For browser request IDs, prefer the built-in lifecycle client, which already handles environments without `crypto.randomUUID()`. Custom submissions and parameter saves must not call it unconditionally: it requires a secure context and can be unavailable on HTTP test hosts. Use a shared helper that falls back to `crypto.getRandomValues(new Uint8Array(16))`, encoded as hex, or an existing HTTP-compatible ID utility. Generate one key per logical operation and reuse it with the same payload for transport retries; changed input or a new decision needs a new key. Verify submission with `randomUUID` unavailable, not only on localhost or HTTPS.
388
+
379
389
  ## 6. Tests
380
390
 
381
391
  Unit-test the definition with the test kit — a memory store, a fake clock and in-process effects — so waits, retries and refusals need no database:
@@ -429,10 +439,21 @@ The installed package's README lists its entries; the full guide, design notes a
429
439
 
430
440
  ## Draw an interactive lifecycle diagram
431
441
 
442
+ When building a process page whose configurable business parameters relate to nodes or transitions, prefer an entry on the corresponding diagram element that opens a parameter-editing dialog. Map the clicked state's or transition's stable name through code-declared parameter bindings and open the same editor used by the settings page or embedded form, if present. A bound entry can expose several groups; unbound entries keep their ordinary details. Read [configurable lifecycle parameters](lifecycle-parameters.md#optional-user-interfaces) for the working example, authorization, CAS conflicts and current-versus-historical values.
443
+
432
444
  When a page needs a lifecycle diagram, use the UI Library's `@nocobase/lifecycle-diagram` component (React Flow + ELK) instead of building a canvas or turning Mermaid source into an interactive view. Read `pnpm exec shadcn view @nocobase/lifecycle-diagram-demo`, then install with `yes n | pnpm exec shadcn add @nocobase/lifecycle-diagram` and format the created files. It includes `@nocobase/flow-diagram`, which is also available alone for a generic directed graph. Follow [the UI Library guidance](frontend/references/styling.md#3-use-shadcn) and its [offline catalog](frontend/references/ui-library.md) for discovery and installation.
433
445
 
434
446
  Import `LifecycleDiagram` from `#components/lifecycle-diagram`. Pass the hook's `description.description`, an `ariaLabel`, `currentState: view.record.status` (use the lifecycle's own state field), and `availableTransitions: view.available.filter((item) => item.allowed).map((item) => item.name)`. Translate labels by stable state/transition names with `stateLabel` and `transitionLabel`; add the shared `flowDiagram` keys to your locale resources. Use `onStateClick` and `onTransitionClick` to open details, including effects, triggers and continuations from the description. Definitions remain in source and clicking the diagram never fires a transition; action buttons still follow `view.available`. Pass `history={view.history.transitions}` for visited paths; the component matches the exact transition, source and destination, including retries. `visitedStates` supplements node highlights only; never infer a traversed edge from the current state or visited endpoints. Pass a translated `endLabel` to display a separate decorative end marker after each explicit final state, without treating every state lacking outgoing transitions as final. Keep `toMermaid()` for documentation and export.
435
447
 
436
448
  For detailed page diagrams, prefer `direction="DOWN" autoHeight`: the canvas grows with the full layout, including outer routes and labels. A wide graph fitted into a short fixed-height panel makes its labels unreadable. Check the actual lifecycle definition in the target page, rather than judging a simple preview alone.
437
449
 
450
+ The label callbacks receive description objects, not name strings. Read `state.name` in `stateLabel` and `transition.name` in `transitionLabel` when building translation keys:
451
+
452
+ ```tsx
453
+ stateLabel={(state) => t(`leaves.states.${state.name}`)}
454
+ transitionLabel={(transition) => t(`leaves.transitions.${transition.name}`)}
455
+ ```
456
+
457
+ Adapt the translation key prefix to the feature.
458
+
438
459
  Preserve the component’s application theme tokens: `--primary` for current, visited and available highlights, subdued neutral strokes for other edges, and card/foreground/border tokens for the canvas and labels. Current nodes have a stronger fill and ring, visited nodes a light fill, with no extra “visited” label. Labels stay on the routes; automatic transitions remain solid and may show `⚙` through `transitionLabel`. Do not introduce a separate palette or hard-coded accent color. Check light/dark themes and a changed application primary color when customizing the rendering.
@@ -233,6 +233,21 @@ export function createOrderRoutes(options: CreateOrderRoutesOptions): Hono {
233
233
 
234
234
  Do not write a helper that mutates a router passed in by its caller. Returning a router you own keeps the security boundary inside the thing being tested.
235
235
 
236
+ ## Lists and statistics: a fixed number of queries
237
+
238
+ A route that answers many rows or figures reads them with a fixed number of queries, whatever the row count. The database API is in the `nocobase-db` Skill.
239
+
240
+ - Read each kind of data once for all rows: one query with `IN (...)` over the row ids, then join the results in memory. Never call a per-item function or Repository read inside a loop or a `Promise.all` over rows.
241
+ - A list row carries only what the row shows. Expensive per-item work — diagnostics, "why is this waiting", full histories — belongs to the item's own detail endpoint.
242
+ - A component that needs one small fact, such as whether the viewer follows an item, gets a small endpoint answering that fact rather than reading a whole list or overview.
243
+ - Aggregate in the database: `COUNT`, `SUM`, `GROUP BY` through the Repository's `count`/`groupBy` or the query builder. Never load rows to count or sum them in JavaScript.
244
+ - One chart is one request, so charts load, fail, refresh and cache on their own. Each chart's request computes its figures with a fixed number of aggregate queries: one `GROUP BY` day, not a query per day or per item.
245
+ - Bound every statistic by a time range or a limit. A column a large table is filtered or grouped by needs an index — see [migrations](migrations.md).
246
+ - An aggregate that is expensive and read often is cached briefly with the application's cache (`cachingToken` from `@nocobase/app-server/caching`) rather than recomputed per request.
247
+ - Test it: the number of queries a list or statistics endpoint makes stays the same when the rows or groups grow. See [testing](testing.md#what-to-test-by-change).
248
+
249
+ The browser side — refreshing such a list or chart from realtime events — is in [client API requests](frontend/references/api.md#keeping-lists-and-charts-live).
250
+
236
251
  ## Keep the layers apart
237
252
 
238
253
  Routes handle HTTP: parsing input, checking permission, shaping the response and status. Domain logic goes in a service under `server/providers/` — see [services and jobs](services-and-jobs.md). A service should not read a Hono context or decide status codes.
@@ -265,3 +280,4 @@ In React components and custom Hooks, use `useApiClient()` from `@nocobase/app-c
265
280
  - Middleware does not leak into other routes.
266
281
  - Every `/api` route is declared: after `app.start()`, `findUndeclaredApiRoutes(app)` is empty, and the route appears in `GET /api/swagger` with its `operationId`. See the Verify section of [HTTP API design](http-api.md#verify).
267
282
  - A public route rejects missing and invalid signatures, and handles duplicate delivery.
283
+ - A list or statistics route makes the same number of queries for ten rows as for a thousand.
@@ -16,15 +16,16 @@ Templates ship their tests into generated applications. Keep them runnable from
16
16
 
17
17
  ## What to test, by change
18
18
 
19
- | You changed | Test at least |
20
- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------- |
21
- | A server route | Anonymous → `401`, authenticated but unpermitted → `403`, permitted → expected payload; the route is declared in the API document |
22
- | A public webhook | Missing signature, invalid signature, valid signature, duplicate delivery |
23
- | A migration | `up` produces the expected schema; `down` reverses it; against a real database |
24
- | A seed | First run, run against existing data, repeat run |
25
- | A service | Its domain behavior, with its dependencies supplied directly |
26
- | A job | `execute()` with a realistic payload; a second run is harmless; failures behave as intended |
27
- | Frontend code | See [frontend tests](frontend/references/testing.md): pages, components, route declarations, copy |
19
+ | You changed | Test at least |
20
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
21
+ | A server route | Anonymous → `401`, authenticated but unpermitted → `403`, permitted → expected payload; the route is declared in the API document |
22
+ | A list or stats route | Its query count does not grow with the number of rows or groups: count the reads for a few rows and for many, and assert they are equal |
23
+ | A public webhook | Missing signature, invalid signature, valid signature, duplicate delivery |
24
+ | A migration | `up` produces the expected schema; `down` reverses it; against a real database |
25
+ | A seed | First run, run against existing data, repeat run |
26
+ | A service | Its domain behavior, with its dependencies supplied directly |
27
+ | A job | `execute()` with a realistic payload; a second run is harmless; failures behave as intended |
28
+ | Frontend code | See [frontend tests](frontend/references/testing.md): pages, components, route declarations, copy |
28
29
 
29
30
  ## Testing a route
30
31
 
@@ -94,6 +94,8 @@ diff -rq "$WORK/$BASE" "$WORK/$TARGET"
94
94
 
95
95
  `Files ... differ` is modified, `Only in TARGET` added, `Only in BASE` removed. Read the substantive ones with `diff -u`. Use the actual BASE → TARGET changes and the project's current state to decide what applies. The target template's `@nocobase/app-skills` dependency identifies the shared guidance shipped for that release; inspect that package's relevant references when a changed framework contract needs explanation. Check [edge cases](references/edge-cases.md) for generated configuration, synchronized Skills, and migration history that the template diff cannot describe.
96
96
 
97
+ When the upgrade changes application migrations or registered plugins that supply migrations, read [database upgrades](references/database-upgrades.md) during planning, before starting the target application. Review the affected packages' upgrade notes as well as the template diff: a dependency update can change database behavior without adding a migration file to the application. Include any documented checksum correction, data prerequisite, and irreversible migration in the upgrade and recovery plan. A Git branch protects source, not the database.
98
+
97
99
  Then ask the project which of those files it has also touched:
98
100
 
99
101
  ```bash
@@ -155,7 +157,7 @@ pnpm typecheck && pnpm test && pnpm lint && pnpm build
155
157
 
156
158
  `pnpm install` can retain older transitive dependencies in `pnpm-lock.yaml` even after the template raises a direct dependency. Run `pnpm dedupe` to refresh compatible resolutions before synchronizing Skills from the final `node_modules`. Review and include the resulting lockfile changes in the upgrade. If type checking still reports incompatible types from two versions of the same package, follow [dependency resolution conflicts](references/edge-cases.md#dependency-resolution-conflicts) before changing application code.
157
159
 
158
- `typecheck` is doing real work here — it catches the broken import a removal left behind. Then run the application and check what the delta touched: sign-in, the user's pages, navigation, locale switching, any new migration. Passing commands are not evidence the application still behaves. For a theme or shell change, also complete the [theme upgrade checks](references/theme-upgrade.md); token changes alone do not verify the application-owned consumers.
160
+ `typecheck` is doing real work here — it catches the broken import a removal left behind. Before starting the application against retained data, complete the applicable [database upgrade checks](references/database-upgrades.md); startup may apply migrations automatically. Then run the application and check what the delta touched: sign-in, the user's pages, navigation, locale switching, any new migration. Passing commands are not evidence the application still behaves. For a theme or shell change, also complete the [theme upgrade checks](references/theme-upgrade.md); token changes alone do not verify the application-owned consumers.
159
161
 
160
162
  Report the range merged, how each contested file was decided, any manual actions and their validation, and how to roll back.
161
163
 
@@ -0,0 +1,64 @@
1
+ # Database upgrades
2
+
3
+ Use this procedure when a template or dependency upgrade changes migrations, or when an upgrade reports checksum drift. Read the target versions' changelogs and upgrade notes for the application and its registered plugins. The template source diff alone does not show plugin migrations. Match each instruction to the installed versions, configured dialect, connection, and execution history; do not replay every historical upgrade instruction.
4
+
5
+ ## Before applying migrations
6
+
7
+ Identify the database the target application will use and whether startup applies migrations or seeds automatically. Finish the applicable checks before starting it against retained data. A source branch, an older archive, or a successful build is not a database backup: have a restorable database backup and coordinate files or object storage when the upgrade affects their references. Record any irreversible migrations and whether the previous runtime can use the resulting schema.
8
+
9
+ Use the CLI from the target packages with the intended application's configuration and environment. In a source project, invoke `pnpm nocobase`; for a built application, use `node dist/cli/index.js` in its deployment context, preserving its config, environment, and storage paths. Do not run a development checkout against production as a shortcut. For an app-installer installation, retain the installer's lifecycle and configuration handling; if its supported workflow cannot perform a required release-specific preparation, establish that procedure before retrying the upgrade.
10
+
11
+ Preview pending work with the target CLI:
12
+
13
+ ```bash
14
+ pnpm nocobase db apply --dry-run --json
15
+ ```
16
+
17
+ The default connection is selected unless `--connection <name>` or `--all` is supplied. Keep preview, repair, and apply scoped to the same intended managed connections; plugins contribute to the default connection. An apply dry run discovers pending tasks by comparing their names with execution history. It does not check recorded checksums, even with `onChecksumMismatch: error`, and does not execute migration bodies or validate existing data against new constraints. A successful preview is therefore not evidence that checksums or data prerequisites are satisfied.
18
+
19
+ ## Review checksum drift
20
+
21
+ Before applying target migrations or starting the target application against retained data, inspect checksums independently with the target CLI, even when release notes mention no historical corrections and the apply preview succeeds:
22
+
23
+ ```bash
24
+ pnpm nocobase db repair --dry-run --json
25
+ ```
26
+
27
+ This preview is read-only and checks both executed migrations and seeds. If it proposes no checksum changes, skip the actual repair command and continue with the pending tasks and data prerequisites. Writing repaired checksums remains conditional on reviewing and authorizing the changes below.
28
+
29
+ Match every proposed change to its owning package, migration or seed name, and the documented source change. `db repair` updates all mismatching executed migration and seed checksums in the selected connections; it has no per-migration allowlist. An unexplained entry means investigate before repairing that connection, even when other entries are expected. Do not weaken the checksum policy, edit migration sources or history by hand, or use `db reset` or `db redo` to bypass the failure.
30
+
31
+ Before writing any repair, stop the application and other writers and take a restorable backup that includes the original migration and seed history. Keep that backup paired with the previous runtime. Once every proposed checksum change is explained and the operation is within the authorized upgrade scope, acknowledge it with the same target sources and connection selection:
32
+
33
+ ```bash
34
+ pnpm nocobase db repair --json
35
+ ```
36
+
37
+ The CLI confirms before writing; non-interactive execution requires `--force`. Use that flag only for the reviewed repair already authorized by the user. Repair changes recorded checksums only: it does not rerun migrations, change schema or business data, or make a failed migration count as successful. An upstream fix that changes an old schema still needs its forward migration after repair. This procedure does not authorize editing merged migrations yourself.
38
+
39
+ For an app-installer installation, do not run actual repair as preparation for a subsequent ordinary `upgrade`: the installer takes its SQLite backup after stopping the application, so that backup would already contain the repaired history. On failure it can restore checksums that the previous runtime rejects under `onChecksumMismatch: error`, even without a schema change. Establish a supported maintenance procedure that backs up before repair and restores that same backup before starting the old runtime on failure. Merely keeping an extra pre-repair backup does not make the installer's automatic rollback select it. If the selected installer cannot coordinate these steps, complete only the read-only checks until that procedure is available.
40
+
41
+ ## Apply and verify
42
+
43
+ For a source application, after completing the independent checksum check, any required repair, and the documented data preparation, review the pending tasks again with the apply preview and execute `pnpm nocobase db apply --json` within the authorized upgrade scope. For a deployment, keep backup, repair, migration, and recovery inside the established maintenance procedure; use the ordinary installer upgrade directly when no repair is needed. Check the command result and relevant application behavior, including reads and writes affected by the migration; a running process alone is insufficient. Keep the reviewed checksum changes, migration results, and recovery path in the upgrade report.
44
+
45
+ If a migration rejects existing data, preserve it and resolve the reported records under a data migration plan before retrying. For example, shortening a stored archive key without moving the corresponding archive breaks downloads. Do not silently truncate data to make a constraint pass.
46
+
47
+ MySQL DDL can leave partial tables or indexes after a failed migration without a successful history entry. Checksum repair cannot reconcile those objects. Preserve a database containing application data and diagnose the partial schema before retrying. A new empty database is appropriate only when the failed installation is confirmed disposable; never infer that from a missing history entry.
48
+
49
+ ## Recovery after a schema change
50
+
51
+ A code rollback does not run migration `down()` methods. If the applied correction is irreversible and the old runtime requires the old schema, restore a compatible backup together with the matching runtime, configuration, and file storage. Account for writes since the backup. Do not promise that `db rollback` or `db redo` can reverse an irreversible migration.
52
+
53
+ app-installer can restore the SQLite databases it backed up. It does not back up or restore external MySQL, PostgreSQL, or SQL Server databases; `--backup-done` acknowledges an operator backup, not automatic restoration. An exit reporting that the previous release is running does not prove an external database was restored. Use `--no-restore` only when retaining the upgraded schema is an intentional, verified compatible choice.
54
+
55
+ ## Known correction: agents and releases MySQL indexes
56
+
57
+ When the installed plugins cross the index correction described in the [agents upgrade notes](https://github.com/nocobase/nocobase/blob/943a9a8a80cc1f76c7a01ecd4965a2a0c51be1eb/packages/plugins/app-plugin-agents/docs/mysql-installation-upgrade.md) or [releases upgrade notes](https://github.com/nocobase/nocobase/blob/943a9a8a80cc1f76c7a01ecd4965a2a0c51be1eb/packages/plugins/app-plugin-releases/docs/mysql-installation-upgrade.md), check these task identities against the target sources and database history:
58
+
59
+ | Registered plugin | Corrected creation migration | Forward correction |
60
+ | ------------------------------- | -------------------------------- | -------------------------------------- |
61
+ | `@nocobase/app-plugin-agents` | `202610020003_ag_create_runs` | `202610260001_ag_drop_directory_index` |
62
+ | `@nocobase/app-plugin-releases` | `202610020001_rel_create_tables` | `202610260002_rel_bound_artifact_keys` |
63
+
64
+ The documented checksum changes apply to installations that executed the old creation sources on any supported dialect, not only MySQL. Only installed plugins are relevant. New databases that run the corrected sources need no checksum acknowledgment; their forward corrections may skip without a history entry. Existing old schemas require the forward corrections, which are irreversible when applied. The releases correction rejects archive keys longer than 172 characters before changing the schema; follow the release notes for data handling rather than rewriting keys independently of stored archives. Treat any other checksum difference as separate evidence to investigate.
@@ -98,11 +98,11 @@ Apply the agreed outcome to the manifest and composition roots together, then ve
98
98
 
99
99
  ## Migrations
100
100
 
101
- A release can ship a migration under `database/`. Copy it in like any added file, then `pnpm nocobase db apply`.
101
+ A release can ship a migration under `database/`, and updated plugins can supply migrations without any application file changing. Copy new application migrations in like other added files, then follow [database upgrades](database-upgrades.md) before applying them or starting the application against retained data.
102
102
 
103
103
  Never edit a migration that arrives this way, and never edit one already run — a correction goes in a new migration. The user's own migrations and seeds stay byte for byte where they are; an upgrade never rewrites them.
104
104
 
105
- Template cleanup does not authorize deleting previously executed application migrations or seeds, even when they originally came from the template. Preserve their original package owner, paths, contents, and history; do not reset checksums, drop tables, or repoint history to another template. For directory or connection changes, follow [existing application migration rules](../../nocobase-app-development/references/migrations.md#existing-applications) and verify the original sources remain available in the deployment.
105
+ Template cleanup does not authorize deleting previously executed application migrations or seeds, even when they originally came from the template. Preserve their original package owner, paths, contents, and history; do not reset checksums to hide unexplained drift, drop tables, or repoint history to another template. A documented upstream correction requires the separate checksum review in [database upgrades](database-upgrades.md#review-checksum-drift). For directory or connection changes, follow [existing application migration rules](../../nocobase-app-development/references/migrations.md#existing-applications) and verify the original sources remain available in the deployment.
106
106
 
107
107
  Unregistering a plugin leaves its records and migration history intact. Do not roll back a retired plugin's migrations after removing its sources; an intentional rollback requires restoring the original plugin version first.
108
108
 
@@ -26,6 +26,7 @@ If the user explicitly requests the new default theme, replace only the agreed t
26
26
 
27
27
  - Compare theme presets and `client/styles.css` together with shell wrappers, background assets, sidebar navigation, authentication forms, table components, overlays, toast configuration, and loading adapters affected by the target delta. Class names and `data-slot` selectors must match the application's installed component version.
28
28
  - Preserve the application's branding, locale namespace, font choices, mobile navigation, login handlers, registration policy, plugin registrations, and business pages. Adapt presentation to its existing framework contracts rather than copying imports or APIs unavailable in its installed SDK.
29
+ - Merge a token together with everything that uses it. When BASE → TARGET adds a token, such as a `--hover` grey that components draw as `bg-hover`, give it a value in every preset PROJECT keeps, its own presets included, and map it in `client/styles.css` where TARGET does: a utility whose variable is undefined draws nothing, without an error, so a merged component quietly loses its hover or its ground. When TARGET removes or renames a token, such as `--overlay-backdrop`, search PROJECT for every remaining use, its own pages and components included, and move each to what TARGET draws instead. Treat a new global rule keyed by an attribute, such as a badge's `data-size`, the same way: a component that sets the attribute only looks right once the rule has been merged too.
29
30
  - Check both first-level and nested navigation. A first-level row-height override does not affect `sidebar-menu-sub-button`; inspect row height, vertical gaps, long labels, scrolling, active state, collapsed rail, and keyboard focus in compact and spacious modes. Derive spacing from theme tokens, and preserve the primitive's collapsed/hidden behavior.
30
31
  - Check authentication controls as a group: identifier input, password container, submit button, pending state, and forgot-password position. Keep registration hidden where the application disables it; do not add a sign-up link merely to match a template screenshot.
31
32
  - Verify table headers on an actual business table, including header background, text contrast, sorting, alignment, and density. Verify shell gradients or watermarks outside an example homepage; preserve mobile layouts and ensure decorative layers cannot intercept clicks or obscure content.
@@ -62,6 +62,8 @@ A deployment package carries code and production dependencies, not business data
62
62
 
63
63
  Before an update that can change schema, take a database and file backup and confirm the restore path. Ensure the database account can perform the configured migration and seed operations. Do not point a new instance at an empty database and describe the result as a data migration.
64
64
 
65
+ Read [database upgrades](../nocobase-app-upgrade/references/database-upgrades.md) when the update changes migrations or reports checksum drift, before starting the new runtime. It covers target-version upgrade notes, reviewed checksum repair, data prerequisites, and irreversible changes, including plugin migrations that the application's source diff does not show. `db repair` acknowledges source checksums only; it does not upgrade schema or recover a partially failed installation.
66
+
65
67
  The default configuration uses managed schema migrations and automatic seeds. Determine whether the deployment should run them on startup. If migrations or seeds are run separately, set the corresponding automatic options to `false` and execute the supported CLI operation before starting the application. Record the migration and seed result; a successful process start alone is insufficient.
66
68
 
67
69
  ## Build and review production configuration