chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
# Bundle analysis in pull requests
The main CI calls **Web Bundle Analysis** when its Web style checks are required,
for both pull requests and merge queue entries. It builds the event's exact base
commit and the tested merge commit from `github.sha` in parallel. Both run the
complete `build:vinext` pipeline, including the unused translations check.
No SSR, reference-analysis, or standalone stage is skipped.
This replaces the separate Vinext build in Web Style. Static checks run alongside
the analysis workflow, and the existing **Web Style** required check succeeds only
when both complete successfully. Main CI owns change detection and duplicate-run
skipping. Target-branch updates alone do not rerun PRs.
The official Rolldown `bundleAnalyzerPlugin` is added only to the client environment
through a temporary Vite config wrapper. Each revision keeps its own application
config and lockfile. The plugin is already bundled with the repository's Vite+
runtime through `vite/rolldown/experimental`; no separate analyzer dependency is
installed. The experimental schema is validated and unsupported data fails the
job instead of appearing as savings.
## Reading the report
The full comparison always appears in the Actions summary. Same-repository PRs
receive an updated comment only when the absolute gzip change reaches at least
5 KiB for all client JS, 1 KiB for client CSS, or 2 KiB for any entry present in
both revisions. Increases and decreases both qualify. Raw sizes, package
attribution, and added/removed entry boundaries do not independently trigger a
comment. If a later run falls below every threshold, the existing report comment
is removed to avoid leaving stale results.
Merge queue runs receive the summary and artifacts without
a PR comment. Fork PRs receive the summary and artifacts without a
privileged build or comment token. Reports are informational: growth does not fail
the check; build, analysis, and reporting errors do.
- **All client JS:** actual bytes and per-file gzip of the chunks listed in the
official analyzer. Includes dynamically imported chunks.
- **Client CSS:** emitted CSS under `dist/client/_next/static`, excluding copied
public assets.
- **Entry static dependencies:** recursively follows static chunk edges, with
shared chunks counted once within an entry. Application source paths identify
entries independently of output hashes. Dynamic entries are measured when
loaded; these are not full-page first-load measurements. Entries overlap and
cannot be summed. The comment shows the 20 largest absolute gzip changes.
Added/removed entry boundaries appear separately and are not treated as size
changes from zero.
- **Package attribution:** groups module sizes from the official analyzer by npm
package. This is attribution, not compressed output size; the comment shows the
15 largest absolute changes.
This measures Vinext/Rolldown output, not Next.js/Turbopack production output or
browser network timings. Compiler versions are recorded in both snapshots.
Both revisions upload the official JSON and Markdown reports, build logs, and
size snapshots for 14 days. The summary links to these artifacts; no local viewer
is required. We do not rely on Vite DevTools' incomplete static Session Compare.
See the [Rolldown analyzer documentation].
## Local collection
The `instrument` command renames `vite.config.ts` and writes a temporary wrapper.
Use it only in a disposable checkout, as CI does:
```sh
node web/scripts/bundle-analysis.ts instrument web
pnpm --dir web run build:vinext
node web/scripts/bundle-analysis.ts collect web "$(git rev-parse HEAD)" /tmp/current.json
node web/scripts/bundle-analysis.ts compare /tmp/base.json /tmp/current.json /tmp/report.md
```
## Next.js / Turbopack analysis
The Web `analyze` script uses Next.js's built-in Turbopack analyzer:
```sh
pnpm --dir web analyze --output
```
Save `web/.next/diagnostics/analyze` before changing code, then collect another
report with the same compiler version and environment. Omit `--output` to open
the interactive analyzer and inspect route-specific client/server import chains.
These reports are separate from the Vinext snapshots above.
If analysis panics inside `next-api/src/nft.rs`, move
`web/.next/cache/turbopack` outside `.next` and retry before changing production
configuration. A stale filesystem cache caused this failure locally with
Next.js 16.3.6; rebuilding the cache let the unchanged configuration complete.
Check import chains before adding configuration. Next.js already optimizes
imports from libraries such as `ahooks` and Heroicons. `serverExternalPackages`
affects server bundling; it does not remove dependencies from browser bundles.
A lazy component can still have eager dependencies if shared utilities import
its SDK statically. Console analytics keeps its initialization state and event
helpers lightweight, loading Amplitude and session replay only after analytics
is enabled and consent is granted. Keep SDK imports in shared helpers type-only
and use the initialized client for events. When changing this boundary, verify
revocation and unmount during loading, concurrent initialization, and failure
recovery as well as entry static dependencies and total emitted bytes.
[Rolldown analyzer documentation]: https://rolldown.rs/builtin-plugins/bundle-analyzer
+124
View File
@@ -0,0 +1,124 @@
# Keyboard Commands
Use TanStack Hotkeys for application commands. Keep registration, business actions, and
availability with the feature owner; keep text editing, widget navigation, and dismissal with
their existing editor or Dify UI primitive. Do not add a generic shortcut wrapper.
The official [React guide] owns library options and [defaults], including input filtering,
keyboard layouts, composition matching, and repeats. This document adds Dify's integration
contracts. Check the installed declarations when an API differs from the latest documentation.
## Registration and availability
For commands belonging to mounted popup content, pass the actual owner's ref:
```tsx
const PUBLISH_HOTKEY = 'Mod+Shift+P' satisfies HotkeyChord
const popupRef = useRef<HTMLDivElement>(null)
useHotkey(PUBLISH_HOTKEY, publish, {
target: popupRef,
enabled: canPublish,
requireReset: true,
})
```
Attach the ref to the Popup. Import the hook and type from `@tanstack/react-hotkeys` and
`useRef` from React. Call the button's action, including its validation and permission checks.
- Use `enabled` when an unavailable command should release the key entirely. A disabled
registration does not consume the event. If the browser action must remain suppressed,
keep the registration enabled and guard the business action inside its callback instead.
- Use default input filtering unless the feature requires otherwise. Form submission may need
`ignoreInputs: false`; canvas commands use `true` to preserve editing. See [defaults].
- Use `requireReset: true` for one-shot commands with default consumption; allow continuous
actions such as zoom to repeat. Conditional event owners follow the rules below.
- Pass a ref, not `ref.current`. An empty ref skips registration; a bare null target falls back
to document. Ref mutation does not re-render the owner: put the hook in mounted content or
use the actual Form's `onKeyDown` when it mounts later. Lexical root replacement can use its
root subscription with element state; disable registration while that element is null.
- For form commands, call `event.currentTarget.requestSubmit()` to share native submission and
validation. React events from nested portals follow React ancestry; check DOM containment
when those portals must be excluded. The Skills file tree intentionally includes its menus.
## Bindings and display
| Boundary | Contract |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| One command / a group | `useHotkey` / `useHotkeys`; preserve feature command IDs. |
| Chord-only strings / objects | `HotkeyChord` / `RawHotkeyChord`; use `satisfies` for constants. |
| Both chord forms | `RegisterableHotkeyChord`; `Hotkey` / `RegisterableHotkey` also admit sequences. |
| Existing React handler | `matchesKeyboardEvent(event.nativeEvent, chord)` matches one chord only. |
| Keycaps | Share the binding with registration; use `formatForDisplay(..., { parts: true })` and Dify UI `Kbd` / `KbdGroup`. |
Use `DisplayHotkeyChord` for chord-only display boundaries. Sequence formatting returns groups
of keycaps; do not widen a chord renderer without implementing that UI. Follow [formatting] for
logical/physical keys, validation, and labels. Preserve the initial platform through hydration,
as navigation search does. `aria-keyshortcuts` uses `Meta+K` or `Control+K`, not glyphs or `Mod`.
Local constants are the default. Use native [app hotkeys] when a product needs app-wide discovery
or remapping: declarations contain no callbacks; business callbacks stay with their feature.
Recording, sequences, and modifier hints are optional capabilities, not migration requirements.
## Event ownership and scopes
A DOM target limits event origin; a [scope] controls whether TanStack registrations are active.
Neither replaces editor handling or Dify UI dismissal. Use a scoped provider above its hook
consumers, with a unique name for independently mounted surfaces. Same-scope matches may all
run; `conflictBehavior: 'replace'` is not a restoring stack, and metadata is not activation.
Use `exclusive` when a modal feature must suspend background application commands. Activate it
with the interactive content, not a permanently mounted Root. Content may retain exclusivity
through its closing transition; hidden retained content needs explicit `enabled` handling.
Preserve commands needed inside the modal: GotoAnything consumes repeated `Mod+K` inside its
scope while the global opener is suspended. Scope precedence and exceptions belong to [scope].
Use normal library consumption unless the owner must decide whether to claim an event:
- An element's native listener can precede child React handlers. When children must go first,
handle React bubbling, or use document bubble plus owner containment as Workflow does.
`capture: true` is for an intentional requirement to precede descendants, not a general fix.
- The manager does not skip `defaultPrevented`. Conditional owners set `preventDefault: false`
and `stopPropagation: false`, check scope and `defaultPrevented`, then consume accepted events.
Consume repeats before returning on `event.repeat`; leave `requireReset` unset in this mode
so its callback latch cannot bypass that consumption. `stopPropagation()` does not stop
another callback on the same manager target.
- Keep IME protection for custom submission and logical Enter/Escape, including existing
composition-end handling. Library composition filtering does not cover those named keys.
- A container delegating child events retains its real semantics. Explain a necessary lint
exception instead of adding a fake button role or tab stop.
[Character shortcuts], including Shift plus a character, must be disableable, remappable to
include a non-character key, or limited to focus within their owning component. Input filtering
or an active page-wide scope alone is insufficient.
## Workflow boundaries
| Owner | Responsibility |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Canvas | `WorkflowCanvas` supplies the ReactFlow root ref. `useWorkflowHotkeys` runs after child React handlers and accepts only events within that subtree. |
| Graph actions | Existing graph hooks own permissions, mutations, history, and persistence. Keyboard commands invoke them. |
| Editors and nodes | ReactFlow, local handlers, Lexical, CodeMirror, and forms own navigation, undo, suggestions, and submission. |
| Portalled menus | Match displayed commands and act on the actual node, edge, or selection. |
| Run and history | Header features own page commands; header focus is unnecessary. |
| Comments | Focused draft/thread dismissal runs after suggestions. Active pointer-following placement owns Escape without taking focus. |
The outer Workflow container includes unrelated panels; use the canvas root for graph scope.
Restore canvas focus after deleting its focused object or applying graph undo/redo. Use Popup
`finalFocus` when a menu action deletes its return target. Hold-to-dim combines held-key state
with canvas focus and clears on focus loss; held-key state alone does not establish ownership.
## Verification
Follow [Web testing]. Use the real matcher/manager to verify affected scope, availability,
mount/reopen behavior, child priority, IME flags, and repeats. Check native editing, focus, and
selection in a browser, and both platform modifiers for binding or hint changes. State the
limits of simulated IME and mocked business actions.
[Character shortcuts]: https://www.w3.org/WAI/WCAG22/Understanding/character-key-shortcuts.html
[React guide]: https://tanstack.com/hotkeys/latest/docs/framework/react/guides/hotkeys
[Web testing]: test.md
[app hotkeys]: https://tanstack.com/hotkeys/latest/docs/framework/react/guides/app-hotkeys
[defaults]: https://tanstack.com/hotkeys/latest/docs/guides/sensible-defaults
[formatting]: https://tanstack.com/hotkeys/latest/docs/framework/react/guides/formatting-display
[scope]: https://tanstack.com/hotkeys/latest/docs/framework/react/guides/hotkeys-provider-and-scopes
+57
View File
@@ -0,0 +1,57 @@
# Page Landmarks
Web owns landmark composition across route layouts and feature components. Use the
[W3C landmark guide] for role semantics and the Dify UI [naming contract] for accessible
names. This guide records how those contracts apply to Web pages.
## Page Ownership
- Place perceivable page content in meaningful landmark regions and check coverage after
composing the layout and its children.
- Trace the parent layouts before adding a page-level landmark. Inspect the composed
page, including parallel route slots and portals, rather than judging a component alone.
- [MainNavLayout] provides the console's `main` and skip-navigation target. Descendant
pages and editors must not create another `main`. Hiding the main navigation does not
remove this wrapper. A route outside this layout must establish its own main-content
boundary in its owning layout or page.
- Keep the skip link and its target under the same layout owner. Preserve the target ID
and focus behavior when changing wrappers; a landmark role alone does not move focus.
- Keep page and section headings meaningful inside these boundaries. A heading does not
create a landmark or automatically name its surrounding section.
## Choose Roles by Content
- Use `nav` for a meaningful group of navigation links. A grid of resource cards is not
automatically navigation merely because its cards can open detail pages.
- A visual sidebar is not automatically complementary content. File controls, editors,
and builder or version panels are parts of the current task. Use ordinary containers
or named sections according to their navigation value. Follow APG's recommendation
to keep genuine complementary landmarks at the top level.
- Reserve named `section` regions for content useful to reach directly. Avoid turning
every wrapper, card, or modal body into a landmark. Prefer an existing visible heading
as the naming source, following the [naming contract].
- Give repeated landmarks distinct names by purpose unless their content and purpose
are identical. Keep names localized and avoid repeating the role in the name.
- Page-level `header` and `footer` can expose `banner` and `contentinfo`. Their implicit
roles depend on ancestors; local panel headers and footers do not necessarily expose
those landmarks. Check the composed context before adding explicit roles.
## Verify the Composed Page
- Check the main-content boundary, landmark hierarchy, names, and heading relationships
in the relevant loaded, empty, collapsed, and open-overlay states. Exclude hidden
skeletons from the exposed landmark inventory. Check that label references still
resolve when conditional content changes.
- When changing a semantic element, inspect affected unit tests and E2E locators,
including CSS selectors such as `closest('main')`. Locate the intended feature or
control instead of relying on an extra page landmark or positional selection among
duplicate landmarks.
- Follow [Web testing policy] for regression coverage. At composition boundaries, keep
the components that own landmark semantics real; a mocked sidebar cannot prove the
real sidebar's role. Distinguish DOM assertions and Cucumber dry-runs from actual
browser or assistive-technology verification.
[MainNavLayout]: ../app/components/main-nav/layout.tsx
[W3C landmark guide]: https://www.w3.org/WAI/ARIA/apg/practices/landmark-regions
[Web testing policy]: test.md
[naming contract]: ../../packages/dify-ui/docs/accessible-names-and-descriptions.md
+5
View File
@@ -0,0 +1,5 @@
# Static Check Guide
See the [repository tooling guide] for linting, formatting, static checks, and custom rule maintenance.
[repository tooling guide]: ../../packages/tooling/README.md
+186
View File
@@ -0,0 +1,186 @@
# Frontend Testing Guide
This document is the single source of truth for automated frontend tests under `web/`. Tests should protect product behavior and make refactoring safer. They are not a file-by-file completion exercise. Dify UI owns its package-specific test boundary in the [Dify UI testing contract].
## Testing Mindset
Write or update a test when a change affects a stable, observable contract:
- User interactions and resulting UI state.
- Navigation, URL state, persistence, permissions, or data flow.
- Loading, success, error, and empty states that users can actually reach.
- Accessibility semantics, keyboard behavior, focus management, or disabled state.
- Business logic or a reusable utility with meaningful input/output behavior.
- A bug fix whose regression can be reproduced through a public boundary.
Do not add tests merely for file/prop coverage, render-without-crashing checks, React implementation choices, or inputs excluded by TypeScript and the product contract.
Decide whether a regression needs lasting automated coverage before choosing its boundary or runtime. Check existing tests first. For visual-only changes, default to reviewing the real UI at representative widths and states; record the result without adding a permanent test. Automate a stable visual requirement or meaningful regression risk, not every design adjustment. Do not move a low-value test to another runner or a screenshot suite merely to keep coverage.
### Coverage
Coverage is a diagnostic signal, not a quality target. This guide defines no required percentage and reviewers should not request tests solely to increase coverage. Use a report to find suspicious gaps, then decide whether each gap represents a product risk worth protecting.
The unit coverage report includes authored JavaScript and TypeScript throughout `web/`, including runtime entry points, scripts, plugins, and files that no test imports. It excludes test infrastructure, stories, declarations, generated sources, tool configuration, build output, and vendored static code. TypeScript modules containing only erased types have no executable statements and are not meaningful zero-coverage findings. Local coverage runs also produce an HTML report at `coverage/index.html`.
Run the full `unit` project before using coverage to identify untested modules. A focused run measures only the selected tests. CI collects Browser Mode coverage separately and combines it with unit coverage under the same Codecov `web` flag. Zero unit coverage does not imply that Browser Mode or E2E never exercises the file; E2E does not contribute to the coverage report. Anonymous VM scripts and subprocesses can also execute code without attributing coverage to its source file. Check existing tests and separate product modules from development tooling when prioritizing the findings.
## Choose the Right Boundary
Use the smallest boundary that includes the behavior owner and proves the product contract without coupling the test to implementation:
- Test pure transformations and business rules as unit tests.
- Test hooks directly only when the hook itself exposes a reusable public contract. Otherwise, exercise the hook through its owning component or feature.
- Exercise component and feature behavior through rendered DOM or external side effects.
- Use integration tests for behavior that crosses meaningful module boundaries.
- Default rendered component and feature tests to the `browser` project under [Browser Mode Admission]. Keep non-DOM logic in `unit`.
- Follow the [Dify UI testing contract] for the Storybook and Vitest boundary of Dify UI primitives.
Test the behavior owner. Barrel exports, pass-through wrappers, and purely presentational children do not need separate tests when the owning feature already proves their contract. Do not repeat generic behavior already owned by Base UI, React Aria, or the browser; test Dify's integration, overrides, and known regressions.
### Browser Mode Admission
Rendered React component and feature tests default to the `browser` project in Playwright Chromium. This includes dialogs, forms, pages, editors, canvas, and hooks exercised through a rendered owner. Use `*.browser.spec.{ts,tsx}` under `{app,features}/**`; one scenario belongs to one project. Do not duplicate unit cases in Browser Mode.
Keep `unit` in `happy-dom` when a browser adds no useful evidence: pure functions, types and schemas, request builders, stores or hooks without DOM, and Node or build tooling. Files outside the browser project's include paths also remain in `unit`. If a required capability is unavailable in Browser Mode, explain the concrete blocker in the PR and propose the missing infrastructure instead of emulating browser behavior or weakening the test.
The runtime does not make a weak test valuable. Every retained scenario must still protect a user-visible contract at its faithful production owner. Use the smallest journey that proves that contract with real rendering and interaction. Do not repeat a state matrix merely because a browser fixture exists; each viewport, theme, key, or variant row needs a distinct failure mode. Primitive and native defaults need no separate Dify tests unless Dify's integration or overrides are the contract.
When migrating an existing spec, rewrite happy-dom workarounds into browser behavior: use public close/reopen or prop-change journeys, real layout, native input and semantic locators. Drop zero-size canvas expectations, fake geometry, CSS-class visibility proofs and aria-hiding assertions that stand in for actual removal. Do not merely rename a file or move low-value cases to another runner to preserve coverage. Use the [Vitest Interactivity API] when native gestures, capture or event ordering are the contract.
Do not add permanent tests solely to freeze decorative spacing, radii, or artwork dimensions from a one-off visual adjustment. Geometry and computed styles are appropriate when they prove the chosen contract, such as readable content, unobstructed controls, or visible keyboard focus. Visual baselines need an explicit stable requirement and controlled rendering environment.
Each `*.browser.spec.{ts,tsx}` must make its behavioral contract and browser evidence clear from its scenario and assertions; add a short explanation only when needed. Do not use forced interaction, fixed sleeps, private DOM assertions, or real network requests.
Browser input is real and nothing waits between keys. Split a `userEvent.keyboard` sequence wherever a later key depends on state an earlier key produces, such as an opened menu or moved focus, and await that state with `expect.element` before continuing.
Browser Mode remains a focused component or feature test and currently proves Chromium only. Use the end-to-end suite for a running application, authentication, real routing, backend APIs, persistence, or complete journeys.
## Assert Behavior, Not Implementation
- Set initial state through render-time inputs (props, `initialStoreState`, seeded query data), not `store.setState` or internal setters after render. Drive mid-test transitions through user actions or public APIs, including prop and URL updates. Seed a reachable non-empty state before testing reset or clear.
- Assert rendered UI, ARIA state, navigation, persistence, network-boundary calls, or another observable result.
- For a reset-or-persistence regression in a hidden surface, exercise the public transition: open, modify, close and wait for the surface to disappear, then reopen. Assert the intended behavior without coupling the test to hook placement, component names, keys, or private mount structure.
- Do not inspect React state, refs, hook call order, effect dependencies, or private DOM structure.
- Test referential identity only when identity is itself a documented public contract.
- One test should describe one behavior. It may contain multiple assertions when they jointly prove that behavior.
- Test only input states supported by the type and product contract. Do not manufacture `null`, `undefined`, or extreme values without a reachable scenario.
- Do not assert CSS class names or mechanically translate them into computed-style assertions. Assert the required outcome; use visual review for incidental styling.
- Use DOM or data snapshots only when serialized output is itself an intentionally public, stable contract. Visual baselines follow Browser Mode Admission.
- Never accept both correct and suspicious results, such as parsing again when a value is still a string. Assert the correct contract; if production violates it, mark the case `it.fails` with a tracking issue link and fix production separately.
## Queries, Interaction, and Accessibility
Prefer selectors in this order:
1. `getByRole` with an accessible name.
1. `getByLabelText` for labeled form controls.
1. `getByText`, `getByPlaceholderText`, or other user-visible queries when appropriate.
1. `getByTestId` only for boundaries with no useful DOM semantics, such as canvas output, editor shims, or mocked non-visual integrations.
When repeated content creates ambiguity, narrow to a semantic container, then query within it with `within` in React Testing Library or locator chaining in Browser Mode.
If an interactive control cannot be found semantically, first check whether the production markup needs a real button, link, label, landmark, or accessible name.
- In React Testing Library tests, use a `userEvent.setup()` instance inside the test. Use `fireEvent` only when the low-level event itself is the contract.
- In Browser Mode, interact through awaited locators. Use `.element()` only for DOM APIs that locators do not expose; it does not wait, so await the element with `expect.element` first.
- Semantic queries and automated checks do not constitute complete accessibility conformance.
- Exact copy assertions are valid when the copy or translation key is the contract; otherwise prefer a semantic query or resilient match.
- In React Testing Library, use `queryBy*` for synchronous absence, `findBy*` for asynchronous appearance, and `waitForElementToBeRemoved` or `waitFor` for asynchronous disappearance. In Browser Mode, use `expect.element` for eventual assertions.
## Mock at Real Boundaries
Keep the production code that owns or transforms the asserted behavior real. Mock only dependencies outside the target contract, where isolation improves the signal:
- Service and network boundaries.
- Next.js navigation or browser APIs not provided by the test environment.
- External SDKs and expensive providers.
- Independently tested child boundaries that do not own or transform the asserted behavior and whose setup would otherwise dominate the owner test.
Mocks must preserve the public contract needed by the test. A mock must not reimplement the owner's transformation, state, or subscription. A child double that only records props or manually invokes captured callbacks does not prove the real control exists or submits valid values; render the real child and drive it, or keep the double at an external SDK or service boundary. Do not mock interactive Dify UI primitives or feature-owned wrappers around them. Keep their semantic roles, state attributes, portals, focus behavior, and `render(props, state)` contract real; mock only service or external-data boundaries needed to reach the scenario.
- Never make real network requests.
- Reset shared mock state before each test that mutates it.
- Create a fresh TanStack Query client for tests that exercise query behavior.
- Prefer typed builders with valid defaults for complex data. Add overrides only for fields relevant to the scenario.
- Keep local mocks local. Move a mock helper to `web/__mocks__/` only when multiple suites genuinely share it.
## Async, Time, and Isolation
- Await user interactions, promises, `findBy*`, and `waitFor`.
- Wait for observable state changes. Keep side effects outside `waitFor`. For filtering or refresh, await the intended new result before asserting excluded items are absent.
- When a production debounce or delay is the contract, use fake timers and advance the full window, including before asserting something did not happen. Restore real timers after the test. Otherwise, use real timers and await the visible result; do not lengthen timeouts, use fixed sleeps, or add broad retries to hide incorrect timing.
- Control time, randomness, network responses, and shared stores so tests are deterministic.
- `web/vitest.setup.ts` already runs Testing Library cleanup and resets Zustand stores after each test.
- Vitest 5 clears mock call history before each test. This does not reset mock implementations or external state; set those up explicitly for each case. Do not use `afterEach` to prepare the next test.
## Dify Test Setup
- Following [Vite+ testing configuration], tests under `web/` use two explicit projects; rendered component and feature tests default to `browser`, and non-DOM logic stays in `unit`. Both projects are configured in `web/vite.config.ts`. Supported commands and CI select one project explicitly: `unit` runs in `happy-dom` and loads `web/vitest.setup.ts`, while `browser` runs matching `{app,features}/**/*.browser.spec.{ts,tsx}` files in Playwright Chromium and loads `web/vitest.browser.setup.ts`. Bare `vp test` runs both registered projects.
- Browser string locators use Vitest 5's exact, case-sensitive matching. Use a regular expression or a per-locator `{ exact: false }` only when partial matching protects the intended behavior. Node tests use `@testing-library/jest-dom/vitest`; a regular-expression check against rendered text can use `expect(element.textContent).toMatch(pattern)` when the Vitest 5 browser matcher types conflict with jest-dom's `toHaveTextContent` overload.
- Tests in one browser file share a page. `web/vitest.browser.setup.ts` resets the viewport and pointer before each test; set the viewport a test depends on inside that test.
- Browser failures keep screenshots and Playwright traces under `web/.vitest-browser/`. CI uploads that directory only when failure artifacts exist; Browser Mode does not own coverage or report merging.
- New component and feature specs should generally use a sibling `__tests__/` directory. Existing colocated utility and hook specs may follow their owning module's convention. Cross-feature integration specs belong in `web/__tests__/`.
- Shared test helpers must have no import-time side effects: no `beforeEach`/`afterEach` registration, global or fetch stubbing, or assertions. Render helpers accept initial store state and injected props and return the real stores and query client. When two or more specs need the same query-cache seed, extract a side-effect-free preset under `web/test/`, distinct from `__mocks__`, that seeds only the client passed in.
- The shared `react-i18next` mock is loaded globally. Use `createReactI18nextMock` from `web/test/i18n-mock` only when a test needs custom translations.
- For `nuqs` behavior, use the helpers in `web/test/nuqs-testing.tsx` and assert URL updates. Mock `nuqs` only when URL synchronization is explicitly outside the test contract.
- Do not add another test runner, DOM environment, or network interception library without a demonstrated project-level need.
## Workflow
Use the behavior owner and nearby tests to identify a realistic regression and the assertion that would catch it. For a behavior change or bug fix, establish the failing case first when practical. Remove redundant tests and assertions as readily as adding missing coverage. When an old test reached a race, rollback, or sync scenario by mutating internals, rewrite it through a real entry point (socket event, refetch, user action) before deleting it. Internal mutation alone does not prove the scenario is unreachable.
Run the focused spec and the affected suite when it adds coverage beyond that spec, plus the required [static checks]. Once these pass, broaden or repeat verification only for new changes, failures, or unresolved concerns. Diagnose CI-only failures from the failing job and reproduce them locally when possible; reruns do not replace diagnosis or reporting.
## Commands
Run from `web/`:
```bash
# happy-dom; omit the path to run the full unit project
vp test run --project unit path/to/spec-or-directory
# Browser Mode; omit the path to run the full browser project
vp test run --project browser path/to/spec.browser.spec.tsx
# Watch mode; select browser instead for Browser Mode
vp test watch --project unit path/to/spec
# Diagnostic coverage report for the unit project; not an acceptance target
vp test run --project unit --coverage path/to/spec-or-directory
```
Always pass `--project unit` or `--project browser`. Bare `vp test` runs both registered projects and is not the standard Web test command.
## References
- [Vitest documentation]
- [Vitest test projects]
- [Why Browser Mode]
- [Vitest Browser Mode documentation]
- [Vitest Browser Mode locators]
- [Vitest Browser Mode traces]
- [Storybook Vitest addon]
- [Testing Library guiding principles]
- [React Testing Library documentation]
- [Testing Library query guidance]
- [Testing Library user-event guidance]
- [Testing Library user-event convenience APIs]
[Browser Mode Admission]: #browser-mode-admission
[Dify UI testing contract]: ../../packages/dify-ui/docs/testing.md
[React Testing Library documentation]: https://testing-library.com/docs/react-testing-library/intro
[Storybook Vitest addon]: https://storybook.js.org/docs/writing-tests/integrations/vitest-addon
[Testing Library guiding principles]: https://testing-library.com/docs/guiding-principles
[Testing Library query guidance]: https://testing-library.com/docs/queries/about
[Testing Library user-event convenience APIs]: https://testing-library.com/docs/user-event/convenience
[Testing Library user-event guidance]: https://testing-library.com/docs/user-event/intro
[Vite+ testing configuration]: https://viteplus.dev/guide/test
[Vitest Browser Mode documentation]: https://vitest.dev/guide/browser
[Vitest Browser Mode locators]: https://vitest.dev/api/browser/locators
[Vitest Browser Mode traces]: https://vitest.dev/guide/browser/trace-view
[Vitest Interactivity API]: https://vitest.dev/api/browser/interactivity
[Vitest documentation]: https://vitest.dev/guide
[Vitest test projects]: https://vitest.dev/guide/projects
[Why Browser Mode]: https://vitest.dev/guide/browser/why
[static checks]: lint.md
+53
View File
@@ -0,0 +1,53 @@
# Toasts
A toast reports a result the user cannot see where they acted. It is the last choice for feedback, not the default completion signal of a mutation.
## Choose the Feedback Owner
Before adding a toast, check in order:
1. If the result is already visible where the user acted, add nothing.
1. If the feedback can live at the trigger, such as a button state, an inline message, or a field error, put it there.
1. Otherwise a toast is appropriate.
Show at most one toast for one user action. When an action succeeds with a warning, show the warning and not a separate success message.
## Choose the Type
The type says whether the thing the user asked for happened.
| Type | Meaning | Example |
| --------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------- |
| `success` | It happened as asked, and the result is not on screen. | An export finished; reindexing started. |
| `warning` | It happened, but incompletely or with a side effect the user should know about. | An import completed with warnings. |
| `error` | It did not happen. | A request failed. |
| `info` | Something the user did not trigger happened, and it needs no response from the user. | A collaborator restored a version of the shared workflow. |
A toast is not the place to explain why an action is unavailable. When a precondition is not met, such as missing permission, a response still in progress, or a feature that is not available, prevent the action at the control instead: disable it, keep it focusable, and give the reason in a tooltip or inline text next to it.
## Success
Do not show a success toast when:
- A switch, select, segmented control, checkbox, toggle, or rating control shows the new value itself. After a failed request the control must show the server value again.
- A button copies content. Show the copied state on the button. For an icon button use [CopyFeedback], which changes the icon, the tooltip, and the accessible name.
- The created, changed, or removed item is visible on the current surface, whether the action ran inline, from a menu, or through a dialog that closed.
- The action navigates to the item it just created, or the page reloads right after.
A success toast is appropriate when the result is not on screen: a background job started, an import, export, or download finished, a save left the page looking the same, or the action left the page that showed its subject, such as deleting an item from its detail page. The message must name what happened. Do not use generic messages such as “Action succeeded” or “Modified successfully” in new code.
## Errors
- When a request fails and the server returns an error message, the request layer shows that message unless the request is `silent`; see `afterResponseErrorCode` in [request layer]. Do not add a second toast for the same failure in `catch` or `onError`.
- When a business flow owns the error feedback, make its requests `silent` (`{ context: { silent: true } }` for generated clients) and present the failure once at that business boundary. Prefer inline errors; use a business-specific toast only when the feedback cannot live where the user acted. For multi-request actions, let the business flow choose one message for the overall result. A `silent` request with no other error presentation fails without any feedback.
- Failures that never reach the request layer, such as a rejected clipboard write or a client-side exception, still need their own feedback.
- When choosing the business error, preserve the actionable reason. Prefer a localized message for a known domain error, then the server's error message; use a generic failure message only as a fallback. Making a request silent must not hide details such as name conflicts, quota limits, unsupported file types, or permission requirements.
- Client-side validation belongs at the field through the [form contract], never in a toast.
## Existing Code
Many existing calls predate these rules and are migrated in batches. Do not copy them into new code, and do not remove an error toast without confirming the request layer covers that failure.
[CopyFeedback]: ../app/components/base/copy-feedback/index.tsx
[form contract]: ../../packages/dify-ui/docs/forms.md
[request layer]: ../service/fetch.ts
@@ -0,0 +1,81 @@
# Truncated Text Disclosure
Treat native `title` as an opt-in, supplemental product behavior. Do not treat it as a mechanical companion to `truncate`, `text-overflow`, or `line-clamp-*`.
Browser-rendered title tooltips are exempt from the author-controlled hover and focus behavior in [WCAG 1.4.13], but that exception is not an accessibility endorsement. [MDN] documents unreliable access for touch, keyboard, and assistive-technology users. The classifications below decide whether to add `title`; they do not establish WCAG conformance for the surrounding interaction.
Missing `title` is not by itself an accessibility defect. Native title tooltips must not:
- be the only way to access essential information;
- replace a visible label, accessible name, or accessible description;
- compete with an existing hover, focus, pointer, expand, copy, or detail interaction.
For automated `title` additions, trace the displayed value, final DOM element, and existing disclosure owner. Apply `SKIP`, `COVERED`, `AUTO`, and `REVIEW` in that order; add `title` only for `AUTO` candidates.
These classifications limit automatic `title` additions. For a requested disclosure fix, continue with the appropriate feature-owned interaction. `REVIEW` calls for resolving the disclosure design; it does not require stopping an already authorized fix or asking for approval of routine implementation choices.
## AUTO
Automatically add `title` only when every condition below is satisfied:
- The target is a native, non-editable, pointer-reachable text container whose own hit area receives the pointer, or a documented component that forwards `title` unchanged to that final DOM element.
- The final element intentionally implements single-line truncation. A truncation-related class alone is not sufficient evidence.
- The full content is a bounded, non-sensitive, single-line plain string.
- The truncated portion is supplemental; users do not need it to understand, distinguish, or complete the current task.
- “Bounded” means fixed text, an enum, or a value with an explicit owner-level maximum length.
- The exact already-evaluated display value can be reused without repeating a function call, getter, conversion, mutation, async operation, or other potentially effectful expression.
- The final rendered element does not already receive an equivalent title through its props, wrapper, child component, or covering interaction target.
- No Tooltip, Popover, expandable content, “show more” action, detail view, copy/reveal action, or other full-content owner exists. A PreviewCard counts only under the `COVERED` rule below.
- The native tooltip will not compete with another hover, focus, pointer, or keyboard interaction.
## COVERED
Classify as `COVERED` and make no change when the full content is already available through the current content, an accessible interaction, or a linked destination. An overlay is not automatically a disclosure owner:
- a Tooltip only when it duplicates non-essential full text already available from its trigger's readable text or accessible name;
- a [PreviewCard] whose trigger is a real destination link and whose destination contains the equivalent full content; the preview popup itself is only a visual enhancement, not the disclosure owner;
- a Popover that exposes the full content through pointer, keyboard, touch, and assistive technology;
- expandable or “show more” content;
- a detail view opened from the current surface;
- a copy or reveal action;
- a parent or covering interaction target that already provides the equivalent title.
## SKIP
Classify as `SKIP` and make no change when any condition below applies:
- The value contains or may contain a secret, token, API key, password, credential, or other sensitive data.
- The value is unbounded user content, multiline content, a comment, prompt, generated output, log body, or another potentially large string.
- The visible content is JSX, `ReactNode`, structured content, or would require a stringification helper.
- Producing the title would repeat or relocate evaluation of a function call, getter, conversion, mutation, async operation, or other potentially effectful expression.
- The element is an input, textarea, editable surface, `pointer-events-none`, covered by another element, or not the actual pointer target.
- An existing `title`, including `title=""`, would need to be overwritten or removed.
## REVIEW
Classify a proposed automatic `title` addition as `REVIEW` and explain the unresolved disclosure requirement when:
- the correct disclosure owner is ambiguous or product-specific;
- users need the full value to understand, distinguish, or complete the task, but no cross-input disclosure owner exists;
- the value bound or sensitivity cannot be proven;
- the final DOM element or pointer owner cannot be traced;
- the component is interactive;
- Tooltip or PreviewCard content would be the only path to the full content, or a PreviewCard trigger is not a destination link;
- a Popover or other disclosure cannot be reached across pointer, keyboard, touch, and assistive technology;
- the content uses `line-clamp-*` without an existing full-content path;
- actual truncation or the intended product behavior cannot be established from the owner contract.
Before adding `title` to a custom component, inspect its implementation and trace the prop to the final DOM element. A `value`, `label`, or similar prop may already provide the native title; do not add a duplicate at the call site.
Do not introduce:
- a repository-wide missing-title lint error;
- a mass autofix or migration;
- a `ReactNode`-to-string helper;
- suppressions for candidates outside the allowlist.
Test the feature-owned disclosure behavior through its public interface. Assert native `title` only when it is an explicitly accepted product contract. Do not use `getByTitle` or `toHaveAttribute('title', ...)` merely to prove a migration, and do not use title-based selectors to test unrelated interactions.
[MDN]: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/title#accessibility_concerns
[PreviewCard]: ../../packages/dify-ui/docs/overlays.md#primitive-semantics
[WCAG 1.4.13]: https://www.w3.org/WAI/WCAG22/Understanding/content-on-hover-or-focus.html
@@ -0,0 +1,18 @@
# WebApp document availability gate
The optional Proxy gate checks default `/chat/:code`, `/chatbot/:code`, `/workflow/:code`, `/completion/:code`, and `/agent/:code` addresses before Next starts rendering. It does not replace Gateway checks on subsequent API requests. Environment/Enterprise address routing is unchanged.
Configure both server-only variables:
- `WEBAPP_ACCESS_PREFLIGHT_URL`: the fixed internal Gateway `/api/webapp/access-mode` endpoint. Do not point it at Core or a public redirecting origin.
- `WEBAPP_ACCESS_PREFLIGHT_PROXY_SECRET`: a random shared ingress secret. Do not use a `NEXT_PUBLIC_` variable, commit its value, include it in logs, or expose it in a response.
Every ingress location that forwards documents to Web must **overwrite**, not append or preserve, `X-Dify-Webapp-Client-Ip` with its validated visitor address and `X-Dify-Webapp-Proxy-Secret` with this secret. The ingress must itself have an explicit trusted-proxy policy; an arbitrary inbound XFF/CF header is not evidence of visitor identity. Web should not have an unprotected public port.
Web verifies the proof with a constant-time comparison and validates a single IP, then creates a fresh Gateway request with only `Accept` and a one-address `X-Forwarded-For`. Gateway must trust the Web peer's network and resolve the forwarded address using its existing trusted-hop policy. Original XFF, Forwarded, CF headers, Authorization, Cookie, and ingress proof are not forwarded. The URL is configuration-owned; request queries cannot select another upstream or supply an IP.
An unset URL leaves self-hosted routing unchanged. Once configured, missing/invalid attestation, timeout, redirects, invalid payloads, and dependency failures produce a non-cacheable 503. They are not application-not-found responses. Only the canonical Gateway/Core `404 app_not_found` produces the existing generic unavailable page, with a 404 status fixed before rendering and `Cache-Control: no-store`. The allow path retains existing rendering and authentication behavior.
The internal `/webapp-unavailable` destination has no application lookup, uses no caller-supplied query state, and is always a 404. Proxy clears its internal IP header on every request, including direct visits. Only a verified denial can populate that header. Locale resources are provided for server rendering; the existing error-page UI remains the owner of language selection, appearance, and navigation.
Validation must include real Next HTTP requests, not only an assertion on `NextResponse.status`: verify document status, absence of redirect, non-cacheability, matching missing/denied body, and unchanged allowed rendering. API availability and the edge trust configuration must be deployed before enabling these variables. Do not enable them globally in an environment whose Gateway does not route `/api`.