diff --git a/.agents/skills/how-to-write-component/SKILL.md b/.agents/skills/how-to-write-component/SKILL.md index bf523070740..4a5a73088ec 100644 --- a/.agents/skills/how-to-write-component/SKILL.md +++ b/.agents/skills/how-to-write-component/SKILL.md @@ -1,71 +1,59 @@ --- name: how-to-write-component -description: React/TypeScript component style guide. Use when writing, refactoring, or reviewing React components, especially around abstraction choices, props typing, state boundaries, shared local state with Jotai atoms, API types, query/mutation contracts, navigation, memoization, wrappers, and empty-state handling. +description: Use when writing, refactoring, or reviewing React/TypeScript components in Dify web, especially decisions about component ownership, props/types, URL/query state, Jotai state, async state, generated API contracts, queries/mutations, overlays, effects, navigation, performance, and empty states. --- # How To Write A Component -Use this as the decision guide for React/TypeScript component structure. Existing code is reference material, not automatic precedent; when it conflicts with these rules, adapt the approach instead of reproducing the violation. +Use this as the component decision guide for Dify web. Existing code is reference material, not automatic precedent; if touched code violates these rules, adapt it and fix equivalent patterns in the same feature branch. + +## First Decisions + +| Question | Default | Promote or extract only when | +| --- | --- | --- | +| Where should code live? | Keep it local to the feature workflow, route, or owner. | Multiple verticals need the same stable primitive. | +| Who owns state, data, and handlers? | The lowest component that uses them. | A parent coordinates shared loading, errors, empty UI, selection, submission, navigation, or one consistent snapshot. | +| Should this become Jotai state? | Keep synchronous UI/form state in component or DOM state. | Siblings need one source of truth, the value drives atoms, or scoped workflow state must survive hidden/unmounted steps. | +| Should URL state enter Jotai? | Let Next.js route params and `nuqs` own URL state and updates. | Query atoms or shared derived atoms need a read-only bridge hydrated at the route/surface boundary. | +| Should this query/mutation become an atom? | Use TanStack Query hooks at the lowest owner. | It reads atom state, feeds derived atoms, or participates in shared Jotai workflow orchestration. | +| Should this be a helper/wrapper? | Prefer direct readable code at the use site. | The name captures a stable domain rule or the wrapper owns real behavior, validation, state, error handling, or semantics. | +| Is an Effect needed? | No. Derive during render or handle the user action in the event handler. | It synchronizes with an external system such as browser APIs, subscriptions, timers, analytics, or imperative DOM/non-React widgets. | ## Core Defaults -- Search before adding UI, hooks, helpers, or styling patterns. Reuse existing base components, feature components, hooks, utilities, and design styles when they fit. -- Group code by feature workflow, route, or ownership area: components, hooks, local types, query helpers, atoms, constants, and small utilities should live near the code that changes with them. -- Promote code to shared only when multiple verticals need the same stable primitive. Otherwise keep it local and compose shared primitives inside the owning feature. -- Prefer local code and purpose-named helpers over catch-all utility modules; do not group workflow-specific defaults, validation, payload shaping, or metadata merging in a generic utils file just because they share a DTO. -- Keep source/default selection, validation, and payload shaping close to the workflow that owns the behavior. Do not extract a shared helper just because two flows read the same DTO when their priority order, fallback behavior, or submit semantics differ. -- Prefer direct, readable conditionals at the use site for small branch-specific decisions, especially form source selection and request payload assembly. Extract only when the helper name captures a stable domain rule and removes repeated complexity without hiding flow-specific behavior. -- When fixing an invalid pattern, scan the touched feature or branch for equivalent patterns and fix them together. -- Follow Dify's CSS-first Tailwind v4 contract from `packages/dify-ui/README.md` and `packages/dify-ui/AGENTS.md`. Prefer design-system tokens, utilities, and radius mappings over generic Tailwind guidance. +- Search before adding UI, hooks, helpers, query utilities, or styling patterns. Reuse existing base components, feature components, hooks, utilities, and design styles when they fit. +- Follow Dify's CSS-first Tailwind v4 contract from `packages/dify-ui/README.md` and `packages/dify-ui/AGENTS.md`. Prefer design-system tokens, utilities, and radius mappings over generic Tailwind choices. +- Group feature code by workflow, route, or ownership area: components, hooks, local types, query helpers, atoms, constants, and small utilities should live near the code that changes with them. +- Keep source/default selection, validation, dirty checks, and payload shaping close to the workflow that owns submit behavior. Do not hide flow-specific priority order, fallback behavior, or submit semantics in generic utilities. +- Prefer direct conditionals for small branch-specific decisions, especially form source selection and request payload assembly. +- Loading states for page sections, cards, lists, tables, forms, and drawers should be skeletons scoped to the content being loaded. Use spinners only for small inline busy indicators. -## Feature Workflow Layout +## Layout And Ownership -- State-heavy wizards, drawers, modals, and secondary workflows work best as a small feature surface with route/entry files, a single feature-local state file, and feature-local UI. -- Keep `ui/` shallow with owner files that map to the workflow's real composition boundaries and major visual regions. -- Owner files contain the section components, field components, skeletons, and one-off helper components that belong to their visual region. -- Folders represent groups of related files with a shared owner and a stable reason to change together. -- The entry file handles route integration, provider wiring, close behavior, and feature surface mounting. The composition owner handles high-level workflow branching, and the closest visual owner handles section branching. +- State-heavy wizards, drawers, modals, and secondary workflows can be a small feature surface: an entry file, one feature-local state file when Jotai is actually needed, and shallow `ui/` owners that match real visual regions. +- The entry file handles route integration, provider wiring, close behavior, and surface mounting. The composition owner handles high-level workflow branching. The closest visual owner handles section branching. +- Repeated TanStack query calls in sibling components are acceptable when each component independently consumes the data; TanStack Query deduplicates and shares cache. +- Pass stable domain identity across boundaries. Do not forward derived presentation state when the receiver can derive it from its own data source. +- A component that owns a visual surface should also own data access, loading, empty, and error states for content rendered inside it unless a parent truly coordinates that state. +- Avoid prop drilling. One pass-through layer is acceptable; repeated forwarding means ownership should move down or into feature-scoped Jotai UI state. Keep server/cache state in Query and API flow. +- Do not replace prop drilling with one large view-model hook threaded through section props. Move each hook, query, derived value, and handler to the concrete section that consumes it. +- Keep callbacks in a parent only for workflow coordination such as form submission, shared selection, batch behavior, or navigation. Otherwise let the child, menu, or row own the action. -## Ownership +## Feature-Scoped Jotai -- Put local state, queries, mutations, handlers, and derived UI data in the lowest component that uses them. Extract a purpose-built owner component only when the logic has no natural home. -- Repeated TanStack query calls in sibling components are acceptable when each component independently consumes the data. Do not hoist a query only because it is duplicated; TanStack Query handles deduplication and cache sharing. -- Hoist state, queries, or callbacks to a parent only when the parent consumes the data, coordinates shared loading/error/empty UI, needs one consistent snapshot, or owns a workflow spanning children. -- Pass stable domain identity across boundaries; avoid forwarding derived presentation state when the receiver can derive it from its own data source. A component that owns a visual surface should also own the data access, loading, empty, and error states for content rendered inside it unless a parent truly coordinates that state. -- Loading states for visual surfaces should use skeleton placeholders scoped to the content that is actually loading, with shape, density, and dimensions close to the final UI. Avoid generic loading text or centered spinners for page sections, cards, lists, tables, forms, and drawers; reserve spinners for small inline busy indicators such as an in-progress status icon. -- Avoid prop drilling. One pass-through layer is acceptable; repeated forwarding means ownership should move down or into feature-scoped Jotai UI state. Keep server/cache state in query and API data flow. -- Do not replace prop drilling with one top-level hook that returns a large view model and then thread that object through section props. Move each hook, query, derived value, and handler to the concrete section that consumes it, or use feature-scoped Jotai atoms for simple shared form/UI state when siblings need the same source of truth. -- When using feature-scoped Jotai state for a form, drawer, or other secondary surface, scope the store to that surface instance when stale cross-instance state is possible. Initialize stable config at the owning boundary, then let descendants read only the atoms or purpose-named hooks they actually need. -- For Jotai-backed surfaces, put shared query atoms, mutation atoms, derived state, and write actions in the feature state file when they coordinate multiple descendants. Do not create a query or mutation atom only because the surrounding feature uses Jotai. If the query or mutation does not read atom state, feed another atom, or participate in shared workflow orchestration, use `useQuery` or `useMutation` directly at the lowest owner. -- For repeated row/menu action surfaces that need reset, hydrate the stable identity at the surface entry and scope only the primitives that truly need per-instance reset, such as open flags, drafts, or selected local options. -- Keep callbacks in a parent only for workflow coordination such as form submission, shared selection, batch behavior, or navigation. Otherwise let the child or row own its action. -- Default to uncontrolled form and DOM state. Add controlled props or atom-backed drafts only when live cross-component reactions, multi-step persistence, or external synchronization require them. - -## Feature-Scoped Jotai State - -- A module's feature-local state lives in one state file for Jotai-backed features: primitive atoms, shared query atoms, derived atoms, write-only action atoms, shared mutation atoms, submission orchestration, provider exports, and optional scope configuration. -- Keep synchronous UI state local when one component owns it, even inside Jotai-backed features. Dialog open flags, menu/popover visibility, confirmation visibility, form/input drafts, and selected local options usually belong in component state. -- Do not put simple form drafts in Jotai atoms. For edit/create forms whose fields are only read at submit time, use uncontrolled `@langgenius/dify-ui/form` and `@langgenius/dify-ui/field` controls with `defaultValue`, browser/form validation, and keyed remounts for query-backed initial values. -- Promote form state to Jotai only when another component must react to in-progress field changes, the draft must survive unmount/remount within the same scoped workflow, or multiple steps/surfaces share the same editable draft before submit. -- Keep submit-time normalization, dirty checks, and payload shaping beside the form submit handler. Do not create form atoms, field atoms, or derived can-save atoms only to mirror uncontrolled form values or disable a submit button. -- In Jotai-backed feature surfaces, never hand-roll async loading, error, or in-flight guards with `useState` or `useRef`. For async work that depends on atom state, feeds derived atoms, or participates in shared submission orchestration, model the work with `atomWithQuery` or `atomWithMutation`; write atoms should only update the inputs that drive those atoms. For component-owned remote work that does not participate in atom state, use TanStack Query hooks directly. -- Row-local async state should belong to the row owner. Use `useQuery` or `useMutation` directly for row actions that do not depend on atom state and are not consumed by other atoms. Use a per-instance query or mutation atom only when the row action participates in a Jotai-backed shared workflow or needs atom-scoped reset semantics. -- Promote UI state to an atom only when siblings need the same source of truth, the value drives a query or mutation atom, a parent workflow coordinates the state, or the state intentionally persists across hidden or unmounted descendants within a scoped surface. -- Reflect atom-backed surface-wide locks or invariants in every affected trigger. If only one row, menu, or dialog should be disabled, keep the pending or lock scope local to that row, menu, or dialog with the lowest-owner query/mutation hook unless it genuinely participates in shared atom state. -- Atom order in the state file follows the dependency graph: types/constants, editable primitives, query atoms, query-data derived atoms, readiness/business derived atoms, write actions, mutation atoms, submission orchestration, provider exports. -- Derived atom names read as business facts. Write atom names read as user or workflow commands. -- UI components read and write the exact atom they use with `useAtomValue` or `useSetAtom`. Repeated workflow semantics live in named derived atoms or write atoms. -- Non-query derived atoms return a narrow value with a clear domain name; avoid pass-through aliases or bundling unrelated UI facts. Query atoms expose the TanStack Query result object so loading, error, fetch, and pagination state stay attached to the query contract. -- Write-only atoms own synchronous state transitions that update multiple primitives, reset dependent state, or advance the workflow. Async work with loading, error, caching, retry, stale-result, or in-flight concerns should be modeled as query or mutation atoms, with write atoms only changing the inputs that drive them. -- Avoid feature hooks that aggregate form values, query results, derived state, and commands for sibling components. Prefer named derived atoms and write atoms so UI components read the exact shared fact or command they need. -- When a form library owns validation, keep submit orchestration in feature state when post-submit result or error state is shared by the surface. Avoid duplicating validation gates or request shaping in UI hooks. -- `jotai-tanstack-query` atoms use the same QueryClient as the React Query provider. Query atoms belong in feature state only when they need atom inputs, provide data to derived atoms, or coordinate a shared Jotai-backed workflow. -- Jotai scope is an optional instance-isolation tool for secondary surfaces with independent local state. Query and mutation atoms keep shared cache behavior through the shared QueryClient. -- Do not put `atomWithQuery`, `atomWithInfiniteQuery`, `atomWithMutation`, or broad derived orchestration atoms in a `ScopeProvider` just to reset a surface. Scoped derived atoms implicitly scope their dependencies, which can duplicate query client access and break shared invalidation. Leave query/mutation atoms unscoped; let them read scoped primitive inputs. -- Scope providers should list resettable primitive atoms and explicit hydration tuples. If a derived atom must be scoped, confirm that every dependency it implicitly scopes is meant to be private to that surface. -- For scoped primitives that are always hydrated by a `ScopeProvider` tuple, prefer `atomWithLazy(() => { throw new Error(...) })` when consumers should see a non-null type. This keeps missing provider hydration as a runtime invariant without leaking `T | undefined` or adding pass-through "required" derived atoms only for narrowing. -- Keep independent dialog lifecycles separate. Avoid a single discriminated "current action dialog" atom when edit, delete, and other dialogs have their own open state, loading guard, or reset behavior. -- Route-derived stable identities that do not need instance reset or scoped isolation can be hydrated at the route or layout boundary into a feature route atom. Use scoped atoms only when stale cross-instance state or per-surface reset semantics are needed. +- A Jotai-backed feature has one feature-local state file for shared primitive atoms, query atoms, derived atoms, write-only actions, mutation atoms, submission orchestration, provider exports, and optional scope configuration. +- Keep component-owned synchronous UI state local even inside Jotai features: dialog open flags, menus/popovers, confirmations, field drafts, and selected local options usually belong in component state. +- Use uncontrolled `@langgenius/dify-ui/form` and `@langgenius/dify-ui/field` controls for edit/create forms whose fields are read only at submit time. Initialize query-backed defaults with `defaultValue` and keyed remounts. +- Promote form state to atoms only when another component must react to in-progress values, a draft must survive unmount/remount in the scoped workflow, or multiple steps share the same editable draft before submit. +- Treat `useParams`, route args, and `nuqs` query state as framework-owned state. When atom logic needs those values, hydrate primitive atoms at the route or surface boundary, such as with `useHydrateAtoms(..., { dangerouslyForceHydrate: true })`; keep URL updates in the route/query-state APIs instead of write atoms. +- For async work tied to atom state, use `atomWithQuery` or `atomWithMutation`; write atoms should update only the inputs that drive those atoms. This applies to pure frontend async work as well as network requests, so do not hand-roll loading/error/in-flight state with `useState` or `useRef` for atom-orchestrated async behavior. For component-owned remote work, use `useQuery` or `useMutation` directly. +- Row-local async state belongs to the row owner unless it participates in a shared Jotai workflow or needs atom-scoped reset semantics. +- Leave query and mutation atoms unscoped so they keep shared QueryClient cache and invalidation behavior. Scope resettable primitives and explicit hydration tuples; scope a derived atom only when every dependency should be private to that surface. +- For scoped primitives that are always hydrated by `ScopeProvider`, prefer `atomWithLazy(() => { throw new Error(...) })` when consumers should see a non-null type. +- Order state files by dependency graph: types/constants, primitives, query atoms, query-data derived atoms, business/readiness derived atoms, write actions, mutation atoms, submission orchestration, provider exports. +- Name derived atoms as business facts and write atoms as user or workflow commands. Components should read or write the exact atom they need with `useAtomValue` or `useSetAtom`. +- Menu/dialog `open` state usually stays local, but a scoped atom is acceptable when a composed menu plus secondary surface would otherwise pass confusing `open`/`onClose` props through unrelated layers. Scope that primitive with the surface instance so reset behavior stays local. +- Keep independent dialog lifecycles separate. Avoid one discriminated "current action dialog" atom when dialogs have separate open state, loading guards, or reset behavior. ## Components, Props, And Types @@ -74,86 +62,56 @@ Use this as the decision guide for React/TypeScript component structure. Existin - Prefer named exports. Use default exports only where the framework requires them, such as Next.js route files. - Type simple one-off props inline. Use a named `Props` type only when reused, exported, complex, or clearer. - Use API-generated or API-returned types at component boundaries. Keep small UI conversion helpers and one-off UI extensions beside the component that needs them. -- Do not create type aliases that only rename another type. Use an alias only when it encodes a real UI concept, refinement, or reusable local contract. -- Name values by their domain role and backend API contract, and keep that name stable across the call chain, especially persistent IDs and route params. Normalize framework or route params at the boundary. -- Keep fallback and invariant checks at the lowest component that already handles that state; avoid defensive fallbacks that mask impossible states. -- Do not extract fallback helpers whose only behavior is hiding missing display data. The component that renders the surface owns the empty, disabled, hidden, or placeholder state. +- Do not create type aliases that only rename another type. Use aliases only for real UI concepts, refinements, or reusable local contracts. +- Name values by their domain role and backend API contract, especially persistent IDs and route params. Normalize framework or route params at the boundary. +- Put fallback and invariant checks in the lowest component that already handles that state. Do not extract helpers whose only behavior is hiding missing display data. -## Generated API Contracts +## Generated API And Nullable Data - Treat generated contracts as authoritative at API, query, mutation, cache, and service boundaries. For enterprise APIs, use `packages/contracts/generated/enterprise/*`. -- Do not hand-write local request/response/reply/page/cache-data types that mirror generated DTOs. Import or infer the generated type. -- Do not widen generated fields or enums for compatibility. Normalize legacy input at the boundary, then return the generated field type. -- Do not repair generated or API-returned contract fields in components unless the API contract or product requirement says they need normalization. Treat enums, statuses, and presence flags as exact contract values. -- Use generated enum objects and union types directly in props, comparisons, status logic, and i18n keys. Do not add local enum constants or parallel frontend enum/status layers unless they model real product state not represented by the API. Presentation-only tone maps should be keyed by the generated enum. -- Normalize or coerce only at a real boundary, such as user-entered forms, search, URL/query params, file names, DOM IDs, or legacy adapters. Preserve user-entered values when whitespace or formatting can be meaningful. -- Do not coerce nullable or optional API strings to `''` in query, derived model, or payload-building code. Keep `undefined` or `null` until the final boundary that requires a string. -- Do not use `value || undefined` for mutation payload fields where an empty string means "clear this value". Trim or normalize at the form boundary, then preserve `''` when the API contract treats it as an intentional update. -- Local UI models are fine for presentation, form state, select options, or guarded required-field refinements. Name them as UI concepts, not generated DTO mirrors. -- Required-value refinements are allowed only after same-branch filtering or early return. Prefer nullable-tolerant props for render-only data. -- When a component needs a stricter shape than a generated DTO, refine once at the API/query-to-UI boundary into a purpose-named UI type instead of hiding missing fields with generic fallback or coercion helpers. - -## Nullable API Data - -- Prefer nullable-tolerant call boundaries. Pass API-returned types through for render-only rows, and let the component render fallback, disabled state, or nothing. -- Narrow only where a real value is required, such as mutation params, route hrefs, select values, or query input. Build that target model with `flatMap`, a local loop, or an early return so the required value is captured in the same branch. -- If design says a field is the display value, use that field. Only the final component should decide whether a nullable display value renders a placeholder, hides content, or disables an action. -- Do not wrap required arrays or fields in null-fallback helpers. Use empty collection fallbacks only for not-yet-loaded query data or genuinely nullable collections at the owning render boundary. -- Do not drop rows only to satisfy props or React keys; use a stable fallback key when possible. -- Use conditional spreads or explicit pushes for conditional array items instead of `undefined` placeholders followed by a narrowing filter. -- Avoid truthiness type guards, `filter(Boolean)`, `filter(item => item.id)`, and `!` after those filters. -- Use type guards only for meaningful domain or runtime validation, such as enum membership, object shape, or a reusable business invariant. +- Do not hand-write DTO mirrors, widen generated fields/enums, or add parallel frontend enum/status layers unless they model product state not represented by the API. +- Use generated enum objects and union types directly in props, comparisons, status logic, and i18n keys. Presentation-only tone maps should be keyed by generated enums. +- Normalize or coerce only at real boundaries: user-entered forms, search, URL/query params, file names, DOM IDs, or legacy adapters. +- Do not coerce nullable or optional API strings to `''` in query, derived model, or payload-building code. Keep `null` or `undefined` until the final boundary requiring a string. +- Do not use `value || undefined` for mutation fields where `''` means "clear this value". Trim or normalize at the form boundary, then preserve intentional empty strings. +- Prefer nullable-tolerant render props for API-returned rows. Narrow only where a real value is required, such as mutation params, route hrefs, select values, query input, or required React keys. +- Build required values in the same branch that proves them, using `flatMap`, a local loop, or an early return. Avoid truthiness guards, `filter(Boolean)`, `filter(item => item.id)`, and `!` after filters. +- Use conditional spreads or explicit pushes for conditional array items instead of `undefined` placeholders followed by narrowing filters. +- Empty collection fallbacks are for not-yet-loaded query data or genuinely nullable collections at the owning render boundary, not for hiding required API fields. ## Queries And Mutations -- Keep `web/contract/*` as the single source of truth for API shape; follow existing domain/router patterns and the `{ params, query?, body? }` input shape. -- Consume queries directly with `useQuery(consoleQuery.xxx.queryOptions(...))` or `useQuery(marketplaceQuery.xxx.queryOptions(...))`. -- Do not promote a query or mutation to an atom just because the feature already has a state file. Use `atomWithQuery` or `atomWithMutation` only when the query/mutation reads atom state, is consumed by another atom, or is part of shared workflow orchestration. -- In `atomWithQuery` and `atomWithInfiniteQuery`, return generated `queryOptions()` or `infiniteOptions()` directly. Pass `enabled`, `retry`, `placeholderData`, `select`, and pagination options into that call instead of spreading generated options into a hand-built object. -- When prefetch and render consume the same server request, extract local query options or a query-options atom so `queryClient.prefetchQuery(...)` and `useQuery`/`atomWithQuery` share the exact generated query options. -- In `atomWithMutation`, return generated `mutationOptions()` directly when using generated clients. Put request shaping and submit orchestration in write atoms; do not rebuild mutation option objects just to pass through the generated mutation function. -- For custom query functions that do not come from generated clients, wrap the options object with TanStack `queryOptions(...)` so query atoms still return a query options contract. -- Avoid pass-through hooks and thin `web/service/use-*` wrappers that only rename `queryOptions()` or `mutationOptions()`. Extract a small `queryOptions` helper only when repeated call-site options justify it. -- Keep feature hooks for real orchestration, workflow state, or shared domain behavior. -- For TanStack cache data, use generated or query-derived types; do not create local wrappers for `getQueryData` or `getQueriesData`. -- For generated oRPC `queryOptions()` / `infiniteOptions()`, keep returning the generated options directly. When required input is missing, use a whole-input branch such as `input: condition ? validInput : skipToken` together with `enabled: Boolean(condition)` so no request runs and no fake payload is built. -- Do not put `skipToken` inside a nested placeholder payload, such as `{ params: { appInstanceId: skipToken } }`. Do not create hand-written "missing queryOptions" objects or coerce required IDs to `''`. -- Consume mutations directly with `useMutation(consoleQuery.xxx.mutationOptions(...))` or `useMutation(marketplaceQuery.xxx.mutationOptions(...))` when the mutation is owned by one component, menu, dialog, or row and its pending/error state is not consumed by feature atoms. In Jotai-backed workflow orchestration, expose mutations from feature state with `atomWithMutation` so pending/error state stays attached to the mutation atom. For component-owned custom mutation functions, use `useMutation(mutationOptions(...))` at the owner. -- Put shared cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`; components may add UI feedback callbacks, but should not own shared invalidation rules. -- Component or atom mutation callbacks can handle local UI feedback such as toasts, closing dialogs, or navigation. They should not replace shared invalidation or add local cache patches for shared server state. -- For overlays that may open a heavier secondary surface, prefetch server data from the trigger/menu open event with `queryClient.prefetchQuery(queryOptions)` when the primitive exposes `onOpenChange`. Do not mount a hidden component or subscribe to a query only to warm the cache. Do not make an otherwise uncontrolled menu controlled only for prefetching. +- Keep `web/contract/*` as the API shape source of truth and follow the `{ params, query?, body? }` input shape. +- Consume generated queries with `useQuery(consoleQuery.xxx.queryOptions(...))` or `useQuery(marketplaceQuery.xxx.queryOptions(...))`. +- Consume owner-local mutations with `useMutation(consoleQuery.xxx.mutationOptions(...))` or `useMutation(marketplaceQuery.xxx.mutationOptions(...))` when pending/error state is not consumed by feature atoms. +- In `atomWithQuery`, `atomWithInfiniteQuery`, and `atomWithMutation`, return generated `queryOptions()`, `infiniteOptions()`, or `mutationOptions()` directly. Pass `enabled`, `retry`, `placeholderData`, `select`, and pagination options into the generated call instead of spreading options into a hand-built object. +- For generated oRPC options with missing required input, branch the whole input with `input: condition ? validInput : skipToken` and `enabled: Boolean(condition)`. Never place `skipToken` inside a nested placeholder payload or coerce required IDs to `''`. +- When prefetch and render use the same request, extract local query options or a query-options atom so `prefetchQuery` and `useQuery`/`atomWithQuery` share the exact options. +- For custom query or mutation functions, wrap options with TanStack `queryOptions(...)` or `mutationOptions(...)`. +- Avoid pass-through hooks and thin `web/service/use-*` wrappers that only rename generated options. Keep feature hooks for real orchestration, workflow state, or shared domain behavior. +- Put shared cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`. Component or atom callbacks may handle local toasts, closing dialogs, and navigation, but should not replace shared invalidation or patch shared server state locally. +- For overlays that may open heavier secondary content, prefetch from the trigger/menu open event with `queryClient.prefetchQuery(queryOptions)` when `onOpenChange` is available. Do not mount hidden subscribers just to warm cache. - Do not use deprecated `useInvalid` or `useReset`. - Prefer `mutate(...)`; use `mutateAsync(...)` only when Promise semantics are required, and wrap awaited calls in `try/catch`. -## Component Boundaries +## Boundaries And Overlays -- Use the first level below a page or tab to organize independent page sections when it adds real structure. This layer is layout/semantic first, not automatically the data owner. -- Treat component names, semantic roles, and user- or design-marked visual regions as boundary constraints. Do not expand a child component's responsibility just because its data is useful nearby; keep adjacent UI as a sibling owner or introduce a correctly named broader owner. -- Split deeper components by the data and state each layer actually needs. Each component should access only necessary data, and ownership should stay at the lowest consumer. +- Use the first level below a page or tab to organize independent page sections when it adds structure. This layer is layout/semantic first, not automatically the data owner. +- Treat component names, semantic roles, and user- or design-marked visual regions as boundary constraints. Keep adjacent UI as a sibling owner or introduce a correctly named broader owner. - Keep cohesive forms, menu bodies, and one-off helpers local unless they need their own state, reuse, or semantic boundary. -- Separate hidden secondary surfaces from the trigger's main flow. For dialogs, dropdowns, popovers, and similar branches, extract a small local component that owns the trigger, open state, and hidden content when it would obscure the parent flow. -- Preserve composability by separating behavior ownership from layout ownership. A dropdown action may own its trigger, open state, and menu content; the caller owns placement such as slots, offsets, and alignment. -- When a dialog, dropdown, or popover component already accepts controlled `open` state, mount the surface unconditionally unless unmounting is required for performance or reset semantics. Use keyed scope or local state reset for reset behavior instead of `{open && }` wrappers. -- When opening a dialog from a menu item, keep the menu and dialog as sibling surfaces. Let the menu item command open the dialog through local state or scoped atoms, and mount the dialog outside the menu popup content. Avoid wrapping menu items with dialog triggers when the menu primitive already owns item activation and dismissal behavior. -- For dialogs and alert dialogs, keep the root component responsible for `open` wiring and put query/mutation hooks inside the content component when the work should only mount after the overlay opens. Do not put closed-surface remote work in the root just because the root owns the open atom. -- Prefer uncontrolled overlay roots when the library can own their open state. Use `onOpenChange` for side effects such as prefetching, and CSS/data selectors for visual open-state styling instead of adding controlled state only for observation. -- Avoid unnecessary DOM hierarchy. Do not add wrapper elements unless they provide layout, semantics, accessibility, state ownership, or integration with a library API; prefer fragments or styling an existing element when possible. -- Avoid shallow wrappers, hook-to-props adapter components, layout-only render-prop wrappers, children-as-pass-through composition, and prop renaming unless the wrapper adds validation, orchestration, error handling, state ownership, or a real semantic boundary. If a component only calls a hook, forwards props, or passes trigger/content through to one child, move the logic into that child or make the wrapper own a real surface. +- Separate hidden secondary surfaces from the trigger's main flow. For dialogs, dropdowns, popovers, and similar branches, extract a small local component when hidden content would obscure the parent. +- Preserve composability by separating behavior ownership from placement ownership: an action can own trigger/open/menu content while the caller owns slots, offsets, and alignment. +- When a dialog, dropdown, or popover accepts controlled `open`, mount it unconditionally unless unmounting is required for performance or reset semantics. Use keyed scope or local state reset instead of `{open && }` wrappers. +- When opening a dialog from a menu item, keep the menu and dialog as sibling surfaces. Let the menu command open the dialog, and mount the dialog outside menu popup content. +- For dialogs and alert dialogs, keep the root responsible for `open` wiring and put query/mutation hooks inside the content component when work should mount only after the overlay opens. +- Prefer uncontrolled overlay roots when the library can own open state. Use `onOpenChange` for side effects and CSS/data selectors for open-state styling. +- Avoid wrapper DOM unless it provides layout, semantics, accessibility, state ownership, or library integration. Avoid shallow wrappers, hook-to-props adapters, layout-only render props, children pass-through wrappers, and prop renaming unless they add real behavior or a real boundary. -## You Might Not Need An Effect - -- Use Effects only to synchronize with external systems such as browser APIs, non-React widgets, subscriptions, timers, analytics that must run because the component was shown, or imperative DOM integration. -- Do not use Effects to transform props or state for rendering. Calculate derived values during render, and use `useMemo` only when the calculation is actually expensive. -- Do not use Effects to handle user actions. Put action-specific logic in the event handler where the cause is known. -- Do not use Effects to copy one state value into another state value representing the same concept. Pick one source of truth and derive the rest during render. -- Do not reset or adjust state from props with an Effect. Prefer a `key` reset, storing a stable ID and deriving the selected object, or guarded same-component render-time adjustment when truly necessary. -- For forms initialized from query data, prefer keyed remounts or surface-entry hydration of form/field atoms over an Effect that copies query data into form state. -- Prefer framework data APIs or TanStack Query for data fetching instead of writing request Effects in components. -- If an Effect still seems necessary, first name the external system it synchronizes with. If there is no external system, remove the Effect and restructure the state or event flow. - -## Navigation And Performance +## Effects, Navigation, And Performance +- Use Effects only to synchronize with external systems. Do not use Effects to transform props/state for rendering, handle user actions, copy state, reset state from props, or fetch data. +- For forms initialized from query data, prefer keyed remounts or surface-entry atom hydration over Effects that copy query data into form state. +- Prefer framework data APIs or TanStack Query for data fetching. - Prefer `Link` for normal navigation. Use router APIs only for command-flow side effects such as mutation success, guarded redirects, or form submission. -- Before reaching for `memo`, first try moving changing state down to the smallest component that actually uses it so unrelated sibling trees stay untouched. -- If changing state must wrap other content, lift the unchanged content up and pass it as `children` so the stateful wrapper can update without React visiting that subtree. +- Before using `memo`, move changing state down to the smallest component that uses it. If state must wrap stable content, lift the stable content up and pass it as `children`. - Avoid `memo`, `useMemo`, and `useCallback` unless there is a clear performance reason. diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index e4c686adb31..c80e1f3d2be 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -105,6 +105,10 @@ jobs: if: steps.changed-files.outputs.any_changed == 'true' run: vp run knip + - name: Web dead code check production + if: steps.changed-files.outputs.any_changed == 'true' + run: vp run knip:production + ts-common-style: name: TS Common runs-on: depot-ubuntu-24.04 diff --git a/api/controllers/console/app/agent_app_feature.py b/api/controllers/console/app/agent_app_feature.py index d155dae6ac3..358e552beb0 100644 --- a/api/controllers/console/app/agent_app_feature.py +++ b/api/controllers/console/app/agent_app_feature.py @@ -91,7 +91,10 @@ class AgentAppFeatureConfigResource(Resource): args = AgentAppFeaturesPayload.model_validate(console_ns.payload or {}) new_app_model_config = AgentAppFeatureConfigService.update_features( - app_model=app_model, account=current_user, config=args.model_dump(exclude_none=True), session=db.session + app_model=app_model, + account=current_user, + config=args.model_dump(exclude_none=True), + session=db.session, ) app_model_config_was_updated.send(app_model, app_model_config=new_app_model_config) diff --git a/api/controllers/inner_api/knowledge/retrieval.py b/api/controllers/inner_api/knowledge/retrieval.py index 1c1320fde42..e34dedea286 100644 --- a/api/controllers/inner_api/knowledge/retrieval.py +++ b/api/controllers/inner_api/knowledge/retrieval.py @@ -14,6 +14,7 @@ from controllers.common.schema import register_response_schema_models, register_ from controllers.inner_api import inner_api_ns from controllers.inner_api.wraps import plugin_inner_api_only from core.workflow.nodes.knowledge_retrieval import exc as retrieval_exc +from extensions.ext_database import db from libs.exception import BaseHTTPException from services.entities.knowledge_retrieval_inner import InnerKnowledgeRetrieveRequest, InnerKnowledgeRetrieveResponse from services.errors.knowledge_retrieval import ExternalKnowledgeRetrievalError, InnerKnowledgeRetrievalServiceError @@ -81,7 +82,7 @@ class InnerKnowledgeRetrieveApi(Resource): ) from exc try: - response = InnerKnowledgeRetrievalService().retrieve(payload) + response = InnerKnowledgeRetrievalService().retrieve(payload, session=db.session) except InnerKnowledgeRetrievalServiceError as exc: raise InnerKnowledgeRetrievalHttpError( error_code=exc.error_code, diff --git a/api/services/agent_app_feature_service.py b/api/services/agent_app_feature_service.py index b8e98653c8e..5fd794bb10f 100644 --- a/api/services/agent_app_feature_service.py +++ b/api/services/agent_app_feature_service.py @@ -69,7 +69,12 @@ class AgentAppFeatureConfigService: @classmethod def update_features( - cls, *, app_model: App, account: Account, config: dict[str, Any], session: scoped_session + cls, + *, + app_model: App, + account: Account, + config: dict[str, Any], + session: scoped_session, ) -> AppModelConfig: """Persist the presentation features as a new app_model_config version. diff --git a/api/services/knowledge_retrieval_inner_service.py b/api/services/knowledge_retrieval_inner_service.py index fccc81c4a29..8759413f533 100644 --- a/api/services/knowledge_retrieval_inner_service.py +++ b/api/services/knowledge_retrieval_inner_service.py @@ -13,11 +13,11 @@ of a separate validation error. """ from sqlalchemy import select +from sqlalchemy.orm import scoped_session from core.rag.entities.metadata_entities import Condition, MetadataFilteringCondition from core.rag.retrieval.dataset_retrieval import DatasetRetrieval from core.workflow.nodes.knowledge_retrieval.retrieval import KnowledgeRetrievalRequest -from extensions.ext_database import db from graphon.model_runtime.utils.encoders import jsonable_encoder from graphon.nodes.llm.entities import ModelConfig from models.dataset import Dataset @@ -38,7 +38,11 @@ from services.errors.knowledge_retrieval import ( class InnerKnowledgeRetrievalService: """Validate inner caller scope and delegate to workflow dataset retrieval.""" - def retrieve(self, request: InnerKnowledgeRetrieveRequest) -> InnerKnowledgeRetrieveResponse: + def retrieve( + self, + request: InnerKnowledgeRetrieveRequest, + session: scoped_session, + ) -> InnerKnowledgeRetrieveResponse: """Run tenant-scoped retrieval for a trusted internal caller. This method only rejects caller app existence/tenant mismatches and @@ -56,8 +60,8 @@ class InnerKnowledgeRetrievalService: InnerKnowledgeRetrieveDatasetTenantMismatchError: At least one requested dataset is outside the caller tenant. """ - self._validate_caller_app(tenant_id=request.caller.tenant_id, app_id=request.caller.app_id) - self._validate_datasets(tenant_id=request.caller.tenant_id, dataset_ids=request.dataset_ids) + self._validate_caller_app(tenant_id=request.caller.tenant_id, app_id=request.caller.app_id, session=session) + self._validate_datasets(tenant_id=request.caller.tenant_id, dataset_ids=request.dataset_ids, session=session) rag = DatasetRetrieval() results = rag.knowledge_retrieval(request=self._to_rag_request(request)) @@ -66,8 +70,8 @@ class InnerKnowledgeRetrievalService: usage=InnerKnowledgeRetrieveUsage.model_validate(jsonable_encoder(rag.llm_usage)), ) - def _validate_caller_app(self, *, tenant_id: str, app_id: str) -> None: - app = db.session.scalar(select(App).where(App.id == app_id).limit(1)) + def _validate_caller_app(self, *, tenant_id: str, app_id: str, session: scoped_session) -> None: + app = session.scalar(select(App).where(App.id == app_id).limit(1)) if app is None: raise InnerKnowledgeRetrieveAppNotFoundError(f"App '{app_id}' not found") if app.tenant_id != tenant_id: @@ -75,8 +79,8 @@ class InnerKnowledgeRetrievalService: f"App '{app_id}' does not belong to tenant '{tenant_id}'" ) - def _validate_datasets(self, *, tenant_id: str, dataset_ids: list[str]) -> None: - datasets = db.session.scalars(select(Dataset).where(Dataset.id.in_(dataset_ids))).all() + def _validate_datasets(self, *, tenant_id: str, dataset_ids: list[str], session: scoped_session) -> None: + datasets = session.scalars(select(Dataset).where(Dataset.id.in_(dataset_ids))).all() found_ids = {dataset.id for dataset in datasets} missing_ids = sorted(set(dataset_ids) - found_ids) diff --git a/api/tests/test_containers_integration_tests/services/test_webhook_service_relationships.py b/api/tests/test_containers_integration_tests/services/test_webhook_service_relationships.py index 69cde847f8e..f37dc328b02 100644 --- a/api/tests/test_containers_integration_tests/services/test_webhook_service_relationships.py +++ b/api/tests/test_containers_integration_tests/services/test_webhook_service_relationships.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import logging from types import SimpleNamespace from unittest.mock import MagicMock, patch from uuid import uuid4 @@ -355,7 +356,10 @@ class TestWebhookServiceTriggerExecutionWithContainers: mock_mark_rate_limited.assert_called_once_with(tenant.id) def test_trigger_workflow_execution_logs_and_reraises_unexpected_errors( - self, db_session_with_containers: Session, flask_app_with_containers: Flask + self, + db_session_with_containers: Session, + flask_app_with_containers: Flask, + caplog: pytest.LogCaptureFixture, ): del flask_app_with_containers factory = WebhookServiceRelationshipFactory @@ -367,13 +371,11 @@ class TestWebhookServiceTriggerExecutionWithContainers: webhook_trigger = factory.create_webhook_trigger( db_session_with_containers, app=app, account=account, node_id="node-1" ) + caplog.set_level(logging.ERROR, logger="services.trigger.webhook_service") - with ( - patch( - "services.trigger.webhook_service.EndUserService.get_or_create_end_user_by_type", - side_effect=RuntimeError("boom"), - ), - patch("services.trigger.webhook_service.logger.exception") as mock_logger_exception, + with patch( + "services.trigger.webhook_service.EndUserService.get_or_create_end_user_by_type", + side_effect=RuntimeError("boom"), ): with pytest.raises(RuntimeError, match="boom"): WebhookService.trigger_workflow_execution( @@ -382,7 +384,7 @@ class TestWebhookServiceTriggerExecutionWithContainers: workflow, ) - mock_logger_exception.assert_called_once() + assert caplog.messages.count(f"Failed to trigger workflow for webhook {webhook_trigger.webhook_id}") == 1 class TestWebhookServiceRelationshipSyncWithContainers: @@ -482,7 +484,10 @@ class TestWebhookServiceRelationshipSyncWithContainers: assert cached_payload["webhook_id"] == "cache-webhook-id-00001" def test_sync_webhook_relationships_logs_when_lock_release_fails( - self, db_session_with_containers: Session, flask_app_with_containers: Flask + self, + db_session_with_containers: Session, + flask_app_with_containers: Flask, + caplog: pytest.LogCaptureFixture, ): del flask_app_with_containers factory = WebhookServiceRelationshipFactory @@ -494,14 +499,12 @@ class TestWebhookServiceRelationshipSyncWithContainers: lock = MagicMock() lock.acquire.return_value = True lock.release.side_effect = RuntimeError("release failed") + caplog.set_level(logging.ERROR, logger="services.trigger.webhook_service") - with ( - patch("services.trigger.webhook_service.redis_client.lock", return_value=lock), - patch("services.trigger.webhook_service.logger.exception") as mock_logger_exception, - ): + with patch("services.trigger.webhook_service.redis_client.lock", return_value=lock): WebhookService.sync_webhook_relationships(app, workflow) - mock_logger_exception.assert_called_once() + assert caplog.messages.count(f"Failed to release lock for webhook sync, app {app.id}") == 1 def _read_cache(cache_key: str) -> dict[str, str] | None: diff --git a/api/tests/test_containers_integration_tests/tasks/test_disable_segments_from_index_task.py b/api/tests/test_containers_integration_tests/tasks/test_disable_segments_from_index_task.py index cb5fb5483c8..19611bd6ff2 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_disable_segments_from_index_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_disable_segments_from_index_task.py @@ -6,9 +6,11 @@ using TestContainers to ensure realistic database interactions and proper isolat The task is responsible for removing document segments from the search index when they are disabled. """ +import logging from unittest.mock import MagicMock, patch from uuid import uuid4 +import pytest from faker import Faker from sqlalchemy import select from sqlalchemy.orm import Session @@ -533,7 +535,9 @@ class TestDisableSegmentsFromIndexTask: assert result is None # Task should complete without returning a value mock_factory.assert_called_with(doc_form) - def test_disable_segments_performance_timing(self, db_session_with_containers: Session): + def test_disable_segments_performance_timing( + self, db_session_with_containers: Session, caplog: pytest.LogCaptureFixture + ): """ Test that the task properly measures and logs performance timing. @@ -562,21 +566,18 @@ class TestDisableSegmentsFromIndexTask: # Mock time.perf_counter to control timing with patch("tasks.disable_segments_from_index_task.time.perf_counter") as mock_perf_counter: mock_perf_counter.side_effect = [1000.0, 1000.5] # 0.5 seconds execution time + caplog.set_level(logging.INFO, logger="tasks.disable_segments_from_index_task") - # Mock logger to capture log messages - with patch("tasks.disable_segments_from_index_task.logger") as mock_logger: - # Act - result = disable_segments_from_index_task(segment_ids, dataset.id, document.id) + # Act + result = disable_segments_from_index_task(segment_ids, dataset.id, document.id) - # Assert - assert result is None # Task should complete without returning a value + # Assert + assert result is None # Task should complete without returning a value - # Verify performance logging - mock_logger.info.assert_called() - log_calls = [call[0][0] for call in mock_logger.info.call_args_list] - performance_log = next((call for call in log_calls if "latency" in call), None) - assert performance_log is not None - assert "0.5" in performance_log # Should log the execution time + # Verify performance logging + performance_log = next((message for message in caplog.messages if "latency" in message), None) + assert performance_log is not None + assert "0.5" in performance_log # Should log the execution time def test_disable_segments_redis_cache_cleanup(self, db_session_with_containers: Session): """ diff --git a/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py b/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py index 0eec166fe2f..567bd44b930 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_mail_email_code_login_task.py @@ -10,6 +10,7 @@ All tests use the testcontainers infrastructure to ensure proper database isolat and realistic testing scenarios with actual PostgreSQL and Redis instances. """ +import logging from unittest.mock import MagicMock, patch import pytest @@ -543,7 +544,10 @@ class TestSendEmailCodeLoginMailTask: redis_client.delete(cache_key) def test_send_email_code_login_mail_task_error_handling_comprehensive( - self, db_session_with_containers: Session, mock_external_service_dependencies + self, + db_session_with_containers: Session, + mock_external_service_dependencies, + caplog: pytest.LogCaptureFixture, ): """ Test comprehensive error handling for email code login mail task. @@ -559,6 +563,7 @@ class TestSendEmailCodeLoginMailTask: test_email = fake.email() test_code = "123456" test_language = "en-US" + caplog.set_level(logging.ERROR, logger="tasks.mail_email_code_login") # Test different exception types exception_types = [ @@ -571,31 +576,26 @@ class TestSendEmailCodeLoginMailTask: for error_name, exception in exception_types: # Reset mocks for each test case + caplog.clear() mock_email_service_instance = mock_external_service_dependencies["email_service_instance"] mock_email_service_instance.reset_mock() mock_email_service_instance.send_email.side_effect = exception - # Mock logging to capture error messages - with patch("tasks.mail_email_code_login.logger", autospec=True) as mock_logger: - # Act: Execute the task - it should handle the exception gracefully - send_email_code_login_mail_task( - language=test_language, - to=test_email, - code=test_code, - ) + # Act: Execute the task - it should handle the exception gracefully + send_email_code_login_mail_task( + language=test_language, + to=test_email, + code=test_code, + ) - # Assert: Verify error handling - # Verify email service was called (and failed) - mock_email_service_instance.send_email.assert_called_once() + # Assert: Verify error handling + # Verify email service was called (and failed) + mock_email_service_instance.send_email.assert_called_once() - # Verify error was logged - error_calls = [ - call - for call in mock_logger.exception.call_args_list - if f"Send email code login mail to {test_email} failed" in str(call) - ] - # Check if any exception call was made (the exact message format may vary) - assert mock_logger.exception.call_count >= 1, f"Error should be logged for {error_name}" + # Verify error was logged + assert f"Send email code login mail to {test_email} failed" in caplog.messages, ( + f"Error should be logged for {error_name}" + ) # Reset side effect for next iteration mock_email_service_instance.send_email.side_effect = None diff --git a/api/tests/test_containers_integration_tests/tasks/test_mail_invite_member_task.py b/api/tests/test_containers_integration_tests/tasks/test_mail_invite_member_task.py index de15d4cc772..507e674e5af 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_mail_invite_member_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_mail_invite_member_task.py @@ -11,6 +11,7 @@ and realistic testing scenarios with actual PostgreSQL and Redis instances. """ import json +import logging import uuid from datetime import UTC, datetime from unittest.mock import MagicMock, patch @@ -295,7 +296,10 @@ class TestMailInviteMemberTask: mock_email_service.send_email.assert_not_called() def test_send_invite_member_mail_email_service_exception( - self, db_session_with_containers: Session, mock_external_service_dependencies + self, + db_session_with_containers: Session, + mock_external_service_dependencies, + caplog: pytest.LogCaptureFixture, ): """ Test error handling when email service raises an exception. @@ -308,21 +312,19 @@ class TestMailInviteMemberTask: # Arrange: Setup email service to raise exception mock_email_service = mock_external_service_dependencies["email_service"] mock_email_service.send_email.side_effect = Exception("Email service failed") + caplog.set_level(logging.ERROR, logger="tasks.mail_invite_member_task") # Act & Assert: Execute task and verify exception is handled - with patch("tasks.mail_invite_member_task.logger", autospec=True) as mock_logger: - send_invite_member_mail_task( - language="en-US", - to="test@example.com", - token="test-token", - inviter_name="Test User", - workspace_name="Test Workspace", - ) + send_invite_member_mail_task( + language="en-US", + to="test@example.com", + token="test-token", + inviter_name="Test User", + workspace_name="Test Workspace", + ) - # Verify error was logged - mock_logger.exception.assert_called_once() - error_call = mock_logger.exception.call_args[0][0] - assert "Send invite member mail to %s failed" in error_call + # Verify error was logged + assert caplog.messages.count("Send invite member mail to test@example.com failed") == 1 def test_send_invite_member_mail_template_context_validation( self, db_session_with_containers: Session, mock_external_service_dependencies diff --git a/api/tests/test_containers_integration_tests/tasks/test_mail_register_task.py b/api/tests/test_containers_integration_tests/tasks/test_mail_register_task.py index c74b451b4b6..685c1617bb0 100644 --- a/api/tests/test_containers_integration_tests/tasks/test_mail_register_task.py +++ b/api/tests/test_containers_integration_tests/tasks/test_mail_register_task.py @@ -5,6 +5,7 @@ This module provides integration tests for email registration tasks using TestContainers to ensure real database and service interactions. """ +import logging from unittest.mock import patch import pytest @@ -68,7 +69,10 @@ class TestMailRegisterTask: mock_mail_dependencies["email_service"].send_email.assert_not_called() def test_send_email_register_mail_task_exception_handling( - self, db_session_with_containers: Session, mock_mail_dependencies + self, + db_session_with_containers: Session, + mock_mail_dependencies, + caplog: pytest.LogCaptureFixture, ): """Test email registration task exception handling.""" mock_mail_dependencies["email_service"].send_email.side_effect = Exception("Email service error") @@ -76,10 +80,11 @@ class TestMailRegisterTask: fake = Faker() to_email = fake.email() code = fake.numerify("######") + caplog.set_level(logging.ERROR, logger="tasks.mail_register_task") - with patch("tasks.mail_register_task.logger", autospec=True) as mock_logger: - send_email_register_mail_task(language="en-US", to=to_email, code=code) - mock_logger.exception.assert_called_once_with("Send email register mail to %s failed", to_email) + send_email_register_mail_task(language="en-US", to=to_email, code=code) + + assert caplog.messages.count(f"Send email register mail to {to_email} failed") == 1 def test_send_email_register_mail_task_when_account_exist_success( self, db_session_with_containers: Session, mock_mail_dependencies @@ -121,7 +126,10 @@ class TestMailRegisterTask: mock_mail_dependencies["email_service"].send_email.assert_not_called() def test_send_email_register_mail_task_when_account_exist_exception_handling( - self, db_session_with_containers: Session, mock_mail_dependencies + self, + db_session_with_containers: Session, + mock_mail_dependencies, + caplog: pytest.LogCaptureFixture, ): """Test account exist email task exception handling.""" mock_mail_dependencies["email_service"].send_email.side_effect = Exception("Email service error") @@ -129,7 +137,8 @@ class TestMailRegisterTask: fake = Faker() to_email = fake.email() account_name = fake.name() + caplog.set_level(logging.ERROR, logger="tasks.mail_register_task") - with patch("tasks.mail_register_task.logger", autospec=True) as mock_logger: - send_email_register_mail_task_when_account_exist(language="en-US", to=to_email, account_name=account_name) - mock_logger.exception.assert_called_once_with("Send email register mail to %s failed", to_email) + send_email_register_mail_task_when_account_exist(language="en-US", to=to_email, account_name=account_name) + + assert caplog.messages.count(f"Send email register mail to {to_email} failed") == 1 diff --git a/api/tests/unit_tests/core/entities/test_entities_provider_configuration.py b/api/tests/unit_tests/core/entities/test_entities_provider_configuration.py index 07ba9314977..dbc8f4969dc 100644 --- a/api/tests/unit_tests/core/entities/test_entities_provider_configuration.py +++ b/api/tests/unit_tests/core/entities/test_entities_provider_configuration.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging from contextlib import contextmanager from types import SimpleNamespace from typing import Any @@ -1704,13 +1705,14 @@ def test_get_specific_provider_credential_decrypts_and_obfuscates_credentials() assert credentials == {"openai_api_key": "raw-secret", "region": "us"} -def test_get_specific_provider_credential_logs_when_decrypt_fails() -> None: +def test_get_specific_provider_credential_logs_when_decrypt_fails(caplog: pytest.LogCaptureFixture) -> None: configuration = _build_provider_configuration() configuration.provider.provider_credential_schema = _build_secret_provider_schema() session = Mock() session.execute.return_value.scalar_one_or_none.return_value = SimpleNamespace( encrypted_config='{"openai_api_key":"enc-secret"}' ) + caplog.set_level(logging.ERROR, logger="core.entities.provider_configuration") with _patched_session(session): with patch.object(ProviderConfiguration, "_get_provider_record", return_value=None): @@ -1718,16 +1720,15 @@ def test_get_specific_provider_credential_logs_when_decrypt_fails() -> None: "core.entities.provider_configuration.encrypter.decrypt_token", side_effect=RuntimeError("boom"), ): - with patch("core.entities.provider_configuration.logger.exception") as mock_logger: - with patch.object( - ProviderConfiguration, - "obfuscated_credentials", - side_effect=lambda credentials, credential_form_schemas: credentials, - ): - credentials = configuration._get_specific_provider_credential("cred-1") + with patch.object( + ProviderConfiguration, + "obfuscated_credentials", + side_effect=lambda credentials, credential_form_schemas: credentials, + ): + credentials = configuration._get_specific_provider_credential("cred-1") assert credentials == {"openai_api_key": "enc-secret"} - mock_logger.assert_called_once() + assert caplog.messages.count("Failed to decrypt credential secret variable openai_api_key") == 1 def test_validate_provider_credentials_uses_empty_original_when_record_missing() -> None: @@ -1831,7 +1832,7 @@ def test_switch_active_provider_credential_rolls_back_on_error() -> None: session.rollback.assert_called_once() -def test_get_specific_custom_model_credential_logs_when_decrypt_fails() -> None: +def test_get_specific_custom_model_credential_logs_when_decrypt_fails(caplog: pytest.LogCaptureFixture) -> None: configuration = _build_provider_configuration() configuration.provider.model_credential_schema = _build_secret_model_schema() session = Mock() @@ -1840,19 +1841,19 @@ def test_get_specific_custom_model_credential_logs_when_decrypt_fails() -> None: credential_name="Main", encrypted_config='{"openai_api_key":"enc-secret"}', ) + caplog.set_level(logging.ERROR, logger="core.entities.provider_configuration") with _patched_session(session): with patch("core.entities.provider_configuration.encrypter.decrypt_token", side_effect=RuntimeError("boom")): - with patch("core.entities.provider_configuration.logger.exception") as mock_logger: - with patch.object( - ProviderConfiguration, - "obfuscated_credentials", - side_effect=lambda credentials, credential_form_schemas: credentials, - ): - result = configuration._get_specific_custom_model_credential(ModelType.LLM, "gpt-4o", "cred-1") + with patch.object( + ProviderConfiguration, + "obfuscated_credentials", + side_effect=lambda credentials, credential_form_schemas: credentials, + ): + result = configuration._get_specific_custom_model_credential(ModelType.LLM, "gpt-4o", "cred-1") assert result["credentials"] == {"openai_api_key": "enc-secret"} - mock_logger.assert_called_once() + assert caplog.messages.count("Failed to decrypt model credential secret variable openai_api_key") == 1 def test_validate_custom_model_credentials_handles_invalid_original_json() -> None: diff --git a/api/tests/unit_tests/core/rag/embedding/test_embedding_service.py b/api/tests/unit_tests/core/rag/embedding/test_embedding_service.py index 42d5ea4a393..168d0e466d4 100644 --- a/api/tests/unit_tests/core/rag/embedding/test_embedding_service.py +++ b/api/tests/unit_tests/core/rag/embedding/test_embedding_service.py @@ -407,7 +407,7 @@ class TestCacheEmbeddingDocuments: assert len(calls[1].kwargs["texts"]) == 10 assert len(calls[2].kwargs["texts"]) == 5 - def test_embed_documents_nan_handling(self, mock_model_instance, caplog): + def test_embed_documents_nan_handling(self, mock_model_instance, caplog: pytest.LogCaptureFixture): """Test handling of NaN values in embeddings. Verifies: diff --git a/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py b/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py index d2154f138a7..302ababb48f 100644 --- a/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py +++ b/api/tests/unit_tests/core/rag/indexing/processor/test_paragraph_index_processor.py @@ -385,7 +385,7 @@ class TestParagraphIndexProcessor: with pytest.raises(ValueError, match="model_name and model_provider_name"): ParagraphIndexProcessor.generate_summary("tenant-1", "text", {"enable": True}) - def test_generate_summary_text_only_flow(self, caplog) -> None: + def test_generate_summary_text_only_flow(self, caplog: pytest.LogCaptureFixture) -> None: model_instance = Mock() model_instance.credentials = {"k": "v"} model_instance.model_type_instance.get_model_schema.return_value = SimpleNamespace(features=[]) @@ -459,7 +459,7 @@ class TestParagraphIndexProcessor: assert summary == "vision summary" mock_extract_text.assert_not_called() - def test_generate_summary_fallbacks_for_prompt_and_result_types(self, caplog) -> None: + def test_generate_summary_fallbacks_for_prompt_and_result_types(self, caplog: pytest.LogCaptureFixture) -> None: model_instance = Mock() model_instance.credentials = {"k": "v"} model_instance.model_type_instance.get_model_schema.return_value = SimpleNamespace( @@ -503,7 +503,7 @@ class TestParagraphIndexProcessor: "Failed to convert image file to prompt message content" in record.message for record in caplog.records ) - def test_extract_images_from_text_handles_patterns_and_build_errors(self, caplog) -> None: + def test_extract_images_from_text_handles_patterns_and_build_errors(self, caplog: pytest.LogCaptureFixture) -> None: text = ( "![img](/files/11111111-1111-1111-1111-111111111111/image-preview) " "![img2](/files/22222222-2222-2222-2222-222222222222/file-preview) " @@ -554,7 +554,7 @@ class TestParagraphIndexProcessor: session.scalars.return_value = scalars_result assert ParagraphIndexProcessor._extract_images_from_text("tenant-1", "no images here", session) == [] - def test_extract_images_from_text_logs_when_build_fails(self, caplog) -> None: + def test_extract_images_from_text_logs_when_build_fails(self, caplog: pytest.LogCaptureFixture) -> None: text = "![img](/files/11111111-1111-1111-1111-111111111111/image-preview)" image_upload = SimpleNamespace( id="11111111-1111-1111-1111-111111111111", @@ -583,7 +583,7 @@ class TestParagraphIndexProcessor: assert files == [] assert sum(1 for r in caplog.records if r.levelno == logging.WARNING) == 1 - def test_extract_images_from_segment_attachments(self, caplog) -> None: + def test_extract_images_from_segment_attachments(self, caplog: pytest.LogCaptureFixture) -> None: image_upload = SimpleNamespace( id="file-1", name="image", diff --git a/api/tests/unit_tests/core/rag/indexing/processor/test_qa_index_processor.py b/api/tests/unit_tests/core/rag/indexing/processor/test_qa_index_processor.py index 4ffd0a76433..6e5a4fabbb0 100644 --- a/api/tests/unit_tests/core/rag/indexing/processor/test_qa_index_processor.py +++ b/api/tests/unit_tests/core/rag/indexing/processor/test_qa_index_processor.py @@ -351,7 +351,9 @@ class TestQAIndexProcessor: assert all_qa_documents[0].metadata["answer"] == "A test." assert all_qa_documents[1].metadata["answer"] == "Coverage." - def test_format_qa_document_logs_errors(self, processor: QAIndexProcessor, fake_flask_app, caplog) -> None: + def test_format_qa_document_logs_errors( + self, processor: QAIndexProcessor, fake_flask_app, caplog: pytest.LogCaptureFixture + ) -> None: all_qa_documents: list[Document] = [] source_document = Document(page_content="source text", metadata={"origin": "doc-1"}) diff --git a/api/tests/unit_tests/core/workflow/graph_engine/layers/test_llm_quota.py b/api/tests/unit_tests/core/workflow/graph_engine/layers/test_llm_quota.py index 12c7f8113c7..97d7e4a937b 100644 --- a/api/tests/unit_tests/core/workflow/graph_engine/layers/test_llm_quota.py +++ b/api/tests/unit_tests/core/workflow/graph_engine/layers/test_llm_quota.py @@ -4,6 +4,8 @@ from datetime import datetime from types import SimpleNamespace from unittest.mock import MagicMock, patch +import pytest + from core.app.workflow.layers.llm_quota import LLMQuotaLayer from core.errors.error import QuotaExceededError from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus @@ -122,7 +124,7 @@ def test_precheck_ignores_non_quota_node() -> None: mock_check.assert_not_called() -def test_quota_error_is_handled_in_layer(caplog) -> None: +def test_quota_error_is_handled_in_layer(caplog: pytest.LogCaptureFixture) -> None: layer = LLMQuotaLayer(tenant_id="tenant-id") stop_event = threading.Event() layer.command_channel = MagicMock() diff --git a/api/tests/unit_tests/enterprise/telemetry/test_exporter.py b/api/tests/unit_tests/enterprise/telemetry/test_exporter.py index 674a2026131..e04046a1f0d 100644 --- a/api/tests/unit_tests/enterprise/telemetry/test_exporter.py +++ b/api/tests/unit_tests/enterprise/telemetry/test_exporter.py @@ -7,6 +7,8 @@ from datetime import UTC, datetime from types import SimpleNamespace from unittest.mock import MagicMock, patch +import pytest + from configs.enterprise import EnterpriseTelemetryConfig from enterprise.telemetry.entities import EnterpriseTelemetryCounter, EnterpriseTelemetryHistogram from enterprise.telemetry.exporter import EnterpriseExporter, _datetime_to_ns, _parse_otlp_headers @@ -533,7 +535,7 @@ def test_export_span_cross_workflow_parent_context() -> None: assert kwargs["context"] is not None -def test_export_span_logs_exception_on_error(caplog) -> None: +def test_export_span_logs_exception_on_error(caplog: pytest.LogCaptureFixture) -> None: """If the span block raises, the exception is logged and context is still cleared.""" exporter, mock_tracer, mock_span = _make_exporter_with_mock_tracer() @@ -546,7 +548,7 @@ def test_export_span_logs_exception_on_error(caplog) -> None: assert "bad.span" in caplog.text -def test_export_span_invalid_trace_correlation_logs_warning(caplog) -> None: +def test_export_span_invalid_trace_correlation_logs_warning(caplog: pytest.LogCaptureFixture) -> None: """Invalid UUID for trace_correlation_override triggers a warning log.""" exporter, mock_tracer, mock_span = _make_exporter_with_mock_tracer() diff --git a/api/tests/unit_tests/events/test_update_provider_when_message_created.py b/api/tests/unit_tests/events/test_update_provider_when_message_created.py index 4b2a6438f44..f9ac5d9678e 100644 --- a/api/tests/unit_tests/events/test_update_provider_when_message_created.py +++ b/api/tests/unit_tests/events/test_update_provider_when_message_created.py @@ -4,6 +4,7 @@ from types import SimpleNamespace from unittest.mock import patch from uuid import uuid4 +import pytest from sqlalchemy import create_engine, select from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker @@ -122,7 +123,9 @@ def test_message_created_paid_credit_accounting_uses_paid_pool() -> None: ) -def test_capped_credit_pool_accounting_skips_exhaustion_warning_when_full_amount_is_deducted(caplog) -> None: +def test_capped_credit_pool_accounting_skips_exhaustion_warning_when_full_amount_is_deducted( + caplog: pytest.LogCaptureFixture, +) -> None: with patch( "services.credit_pool_service.CreditPoolService.deduct_credits_capped", return_value=3, diff --git a/api/tests/unit_tests/extensions/test_ext_request_logging.py b/api/tests/unit_tests/extensions/test_ext_request_logging.py index 3d2f8541f63..70e80707882 100644 --- a/api/tests/unit_tests/extensions/test_ext_request_logging.py +++ b/api/tests/unit_tests/extensions/test_ext_request_logging.py @@ -56,18 +56,19 @@ def mock_response_receiver(monkeypatch: pytest.MonkeyPatch) -> mock.Mock: return mock_log_request_finished -@pytest.fixture -def mock_logger(monkeypatch: pytest.MonkeyPatch) -> logging.Logger: - _logger = mock.MagicMock(spec=logging.Logger) - monkeypatch.setattr(ext_request_logging, "logger", _logger) - return _logger - - @pytest.fixture def enable_request_logging(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(dify_config, "ENABLE_REQUEST_LOGGING", True) +def _captured_records(caplog: pytest.LogCaptureFixture, level: int) -> list[logging.LogRecord]: + return [ + record + for record in caplog.records + if record.name == ext_request_logging.logger.name and record.levelno == level + ] + + class TestRequestLoggingExtension: def test_receiver_should_not_be_invoked_if_configuration_is_disabled( self, @@ -108,67 +109,74 @@ class TestRequestLoggingExtension: class TestLoggingLevel: @pytest.mark.usefixtures("enable_request_logging") - def test_logging_should_be_skipped_if_level_is_above_debug(self, enable_request_logging, mock_logger): - mock_logger.isEnabledFor.return_value = False + def test_logging_should_be_skipped_if_level_is_above_debug( + self, enable_request_logging, caplog: pytest.LogCaptureFixture + ): + caplog.set_level(logging.INFO, logger=ext_request_logging.logger.name) app = _get_test_app() init_app(app) with app.test_client() as client: client.post("/", json={_KEY_NEEDLE: _VALUE_NEEDLE}) - mock_logger.debug.assert_not_called() + assert not _captured_records(caplog, logging.DEBUG) class TestRequestReceiverLogging: @pytest.mark.usefixtures("enable_request_logging") - def test_non_json_request(self, enable_request_logging, mock_logger, mock_response_receiver): - mock_logger.isEnabledFor.return_value = True + def test_non_json_request(self, enable_request_logging, caplog: pytest.LogCaptureFixture, mock_response_receiver): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() init_app(app) with app.test_client() as client: client.post("/", data="plain text") - assert mock_logger.debug.call_count == 1 - call_args = mock_logger.debug.call_args[0] - assert "Received Request" in call_args[0] - assert call_args[1] == "POST" - assert call_args[2] == "/" - assert "Request Body" not in call_args[0] + debug_records = _captured_records(caplog, logging.DEBUG) + assert len(debug_records) == 1 + record = debug_records[0] + assert "Received Request" in record.msg + assert record.args == ("POST", "/") + assert "Request Body" not in record.msg @pytest.mark.usefixtures("enable_request_logging") - def test_json_request(self, enable_request_logging, mock_logger, mock_response_receiver): - mock_logger.isEnabledFor.return_value = True + def test_json_request(self, enable_request_logging, caplog: pytest.LogCaptureFixture, mock_response_receiver): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() init_app(app) with app.test_client() as client: client.post("/", json={_KEY_NEEDLE: _VALUE_NEEDLE}) - assert mock_logger.debug.call_count == 1 - call_args = mock_logger.debug.call_args[0] - assert "Received Request" in call_args[0] - assert "Request Body" in call_args[0] - assert call_args[1] == "POST" - assert call_args[2] == "/" - assert _KEY_NEEDLE in call_args[3] + debug_records = _captured_records(caplog, logging.DEBUG) + assert len(debug_records) == 1 + record = debug_records[0] + assert "Received Request" in record.msg + assert "Request Body" in record.msg + assert record.args[0] == "POST" + assert record.args[1] == "/" + assert _KEY_NEEDLE in record.args[2] @pytest.mark.usefixtures("enable_request_logging") - def test_json_request_with_empty_body(self, enable_request_logging, mock_logger, mock_response_receiver): - mock_logger.isEnabledFor.return_value = True + def test_json_request_with_empty_body( + self, enable_request_logging, caplog: pytest.LogCaptureFixture, mock_response_receiver + ): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() init_app(app) with app.test_client() as client: client.post("/", headers={"Content-Type": "application/json"}) - assert mock_logger.debug.call_count == 1 - call_args = mock_logger.debug.call_args[0] - assert "Received Request" in call_args[0] - assert "Request Body" not in call_args[0] - assert call_args[1] == "POST" - assert call_args[2] == "/" + debug_records = _captured_records(caplog, logging.DEBUG) + assert len(debug_records) == 1 + record = debug_records[0] + assert "Received Request" in record.msg + assert "Request Body" not in record.msg + assert record.args == ("POST", "/") @pytest.mark.usefixtures("enable_request_logging") - def test_json_request_with_invalid_json_as_body(self, enable_request_logging, mock_logger, mock_response_receiver): - mock_logger.isEnabledFor.return_value = True + def test_json_request_with_invalid_json_as_body( + self, enable_request_logging, caplog: pytest.LogCaptureFixture, mock_response_receiver + ): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() init_app(app) @@ -178,50 +186,53 @@ class TestRequestReceiverLogging: headers={"Content-Type": "application/json"}, data="{", ) - assert mock_logger.debug.call_count == 0 - assert mock_logger.exception.call_count == 1 - - exception_call_args = mock_logger.exception.call_args[0] - assert exception_call_args[0] == "Failed to parse JSON request" + assert not _captured_records(caplog, logging.DEBUG) + error_records = _captured_records(caplog, logging.ERROR) + assert len(error_records) == 1 + assert error_records[0].message == "Failed to parse JSON request" class TestResponseReceiverLogging: @pytest.mark.usefixtures("enable_request_logging") - def test_non_json_response(self, enable_request_logging, mock_logger): - mock_logger.isEnabledFor.return_value = True + def test_non_json_response(self, enable_request_logging, caplog: pytest.LogCaptureFixture): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() response = Response( "OK", headers={"Content-Type": "text/plain"}, ) _log_request_finished(app, response) - assert mock_logger.debug.call_count == 1 - call_args = mock_logger.debug.call_args[0] - assert "Response" in call_args[0] - assert "200" in call_args[1] - assert call_args[2] == "text/plain" - assert "Response Body" not in call_args[0] + debug_records = _captured_records(caplog, logging.DEBUG) + assert len(debug_records) == 1 + record = debug_records[0] + assert "Response" in record.msg + assert "200" in record.args[0] + assert record.args[1] == "text/plain" + assert "Response Body" not in record.msg @pytest.mark.usefixtures("enable_request_logging") - def test_json_response(self, enable_request_logging, mock_logger, mock_response_receiver): - mock_logger.isEnabledFor.return_value = True + def test_json_response(self, enable_request_logging, caplog: pytest.LogCaptureFixture, mock_response_receiver): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() response = Response( json.dumps({_KEY_NEEDLE: _VALUE_NEEDLE}), headers={"Content-Type": "application/json"}, ) _log_request_finished(app, response) - assert mock_logger.debug.call_count == 1 - call_args = mock_logger.debug.call_args[0] - assert "Response" in call_args[0] - assert "Response Body" in call_args[0] - assert "200" in call_args[1] - assert call_args[2] == "application/json" - assert _KEY_NEEDLE in call_args[3] + debug_records = _captured_records(caplog, logging.DEBUG) + assert len(debug_records) == 1 + record = debug_records[0] + assert "Response" in record.msg + assert "Response Body" in record.msg + assert "200" in record.args[0] + assert record.args[1] == "application/json" + assert _KEY_NEEDLE in record.args[2] @pytest.mark.usefixtures("enable_request_logging") - def test_json_request_with_invalid_json_as_body(self, enable_request_logging, mock_logger, mock_response_receiver): - mock_logger.isEnabledFor.return_value = True + def test_json_request_with_invalid_json_as_body( + self, enable_request_logging, caplog: pytest.LogCaptureFixture, mock_response_receiver + ): + caplog.set_level(logging.DEBUG, logger=ext_request_logging.logger.name) app = _get_test_app() response = Response( @@ -229,11 +240,10 @@ class TestResponseReceiverLogging: headers={"Content-Type": "application/json"}, ) _log_request_finished(app, response) - assert mock_logger.debug.call_count == 0 - assert mock_logger.exception.call_count == 1 - - exception_call_args = mock_logger.exception.call_args[0] - assert exception_call_args[0] == "Failed to parse JSON response" + assert not _captured_records(caplog, logging.DEBUG) + error_records = _captured_records(caplog, logging.ERROR) + assert len(error_records) == 1 + assert error_records[0].message == "Failed to parse JSON response" class TestResponseUnmodified: @@ -267,7 +277,7 @@ class TestResponseUnmodified: class TestRequestFinishedInfoAccessLine: def test_info_access_log_includes_method_path_status_duration_trace_id( - self, monkeypatch: pytest.MonkeyPatch, caplog + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ): """Ensure INFO access line contains expected fields with computed duration and trace id.""" app = _get_test_app() diff --git a/api/tests/unit_tests/services/enterprise/test_plugin_manager_service.py b/api/tests/unit_tests/services/enterprise/test_plugin_manager_service.py index 759d9079348..b0db3bc248b 100644 --- a/api/tests/unit_tests/services/enterprise/test_plugin_manager_service.py +++ b/api/tests/unit_tests/services/enterprise/test_plugin_manager_service.py @@ -5,6 +5,7 @@ This module covers the pre-uninstall plugin hook behavior: - API failure: soft-fail (logs and does not re-raise) """ +import logging from unittest.mock import patch import pytest @@ -43,18 +44,16 @@ class TestTryPreUninstallPlugin: timeout=dify_config.ENTERPRISE_REQUEST_TIMEOUT, ) - def test_try_pre_uninstall_plugin_http_error_soft_fails(self): + def test_try_pre_uninstall_plugin_http_error_soft_fails(self, caplog: pytest.LogCaptureFixture): body = PreUninstallPluginRequest( tenant_id="tenant-456", plugin_unique_identifier="com.example.other_plugin", ) + caplog.set_level(logging.ERROR, logger="services.enterprise.plugin_manager_service") - with ( - patch( - "services.enterprise.plugin_manager_service.EnterprisePluginManagerRequest.send_request" - ) as mock_send_request, - patch("services.enterprise.plugin_manager_service.logger") as mock_logger, - ): + with patch( + "services.enterprise.plugin_manager_service.EnterprisePluginManagerRequest.send_request" + ) as mock_send_request: mock_send_request.side_effect = HTTPStatusError( "502 Bad Gateway", request=None, @@ -69,20 +68,22 @@ class TestTryPreUninstallPlugin: json={"tenant_id": "tenant-456", "plugin_unique_identifier": "com.example.other_plugin"}, timeout=dify_config.ENTERPRISE_REQUEST_TIMEOUT, ) - mock_logger.exception.assert_called_once() + assert len(caplog.records) == 1 + assert caplog.messages[0] == ( + "failed to perform pre uninstall plugin hook. tenant_id: tenant-456, " + "plugin_unique_identifier: com.example.other_plugin" + ) - def test_try_pre_uninstall_plugin_generic_exception_soft_fails(self): + def test_try_pre_uninstall_plugin_generic_exception_soft_fails(self, caplog: pytest.LogCaptureFixture): body = PreUninstallPluginRequest( tenant_id="tenant-789", plugin_unique_identifier="com.example.failing_plugin", ) + caplog.set_level(logging.ERROR, logger="services.enterprise.plugin_manager_service") - with ( - patch( - "services.enterprise.plugin_manager_service.EnterprisePluginManagerRequest.send_request" - ) as mock_send_request, - patch("services.enterprise.plugin_manager_service.logger") as mock_logger, - ): + with patch( + "services.enterprise.plugin_manager_service.EnterprisePluginManagerRequest.send_request" + ) as mock_send_request: mock_send_request.side_effect = ConnectionError("network unreachable") PluginManagerService.try_pre_uninstall_plugin(body) @@ -93,7 +94,11 @@ class TestTryPreUninstallPlugin: json={"tenant_id": "tenant-789", "plugin_unique_identifier": "com.example.failing_plugin"}, timeout=dify_config.ENTERPRISE_REQUEST_TIMEOUT, ) - mock_logger.exception.assert_called_once() + assert len(caplog.records) == 1 + assert caplog.messages[0] == ( + "failed to perform pre uninstall plugin hook. tenant_id: tenant-789, " + "plugin_unique_identifier: com.example.failing_plugin" + ) class TestCheckCredentialPolicyCompliance: diff --git a/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py b/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py index 628e4e594dd..4768215210e 100644 --- a/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py +++ b/api/tests/unit_tests/services/retention/workflow_run/test_restore_archived_workflow_run.py @@ -8,6 +8,7 @@ and both positive and negative test scenarios. import io import json +import logging import zipfile from datetime import datetime from unittest.mock import Mock, create_autospec, patch @@ -312,16 +313,16 @@ class TestGetSchemaVersion: result = restore._get_schema_version(manifest) assert result == "1.0" - def test_missing_schema_version_defaults_to_1_0(self): + def test_missing_schema_version_defaults_to_1_0(self, caplog: pytest.LogCaptureFixture): """Should default to 1.0 when schema_version is missing.""" restore = WorkflowRunRestore() manifest = {"tables": {}} + caplog.set_level(logging.WARNING, logger="services.retention.workflow_run.restore_archived_workflow_run") - with patch("services.retention.workflow_run.restore_archived_workflow_run.logger") as mock_logger: - result = restore._get_schema_version(manifest) + result = restore._get_schema_version(manifest) assert result == "1.0" - mock_logger.warning.assert_called_once_with("Manifest missing schema_version; defaulting to 1.0") + assert "Manifest missing schema_version; defaulting to 1.0" in caplog.messages def test_unsupported_schema_version_raises_error(self): """Should raise ValueError for unsupported schema version.""" @@ -492,19 +493,19 @@ class TestRestoreTableRecords: """Tests for WorkflowRunRestore._restore_table_records method.""" @patch("services.retention.workflow_run.restore_archived_workflow_run.TABLE_MODELS") - def test_unknown_table_returns_zero(self, mock_table_models): + def test_unknown_table_returns_zero(self, mock_table_models, caplog: pytest.LogCaptureFixture): """Should return 0 for unknown table.""" restore = WorkflowRunRestore() mock_table_models.get.return_value = None mock_session = Mock() records = [{"id": "test"}] + caplog.set_level(logging.WARNING, logger="services.retention.workflow_run.restore_archived_workflow_run") - with patch("services.retention.workflow_run.restore_archived_workflow_run.logger") as mock_logger: - result = restore._restore_table_records(mock_session, "unknown_table", records, schema_version="1.0") + result = restore._restore_table_records(mock_session, "unknown_table", records, schema_version="1.0") assert result == 0 - mock_logger.warning.assert_called_once_with("Unknown table: %s", "unknown_table") + assert "Unknown table: unknown_table" in caplog.messages def test_empty_records_returns_zero(self): """Should return 0 for empty records list.""" diff --git a/api/tests/unit_tests/services/test_human_input_service.py b/api/tests/unit_tests/services/test_human_input_service.py index d9d81d66566..5c26a9ef57d 100644 --- a/api/tests/unit_tests/services/test_human_input_service.py +++ b/api/tests/unit_tests/services/test_human_input_service.py @@ -673,7 +673,7 @@ def test_enqueue_resume_workflow_not_found(mocker: MockerFixture, mock_session_f assert "WorkflowRun not found" in str(excinfo.value) -def test_enqueue_resume_app_not_found(mocker, mock_session_factory, caplog): +def test_enqueue_resume_app_not_found(mocker, mock_session_factory, caplog: pytest.LogCaptureFixture): session_factory, session = mock_session_factory service = HumanInputService(session_factory) diff --git a/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py b/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py index 11f9dfedc1a..321b1a7c046 100644 --- a/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py +++ b/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py @@ -74,14 +74,14 @@ def _build_source() -> Source: class TestInnerKnowledgeRetrievalService: @patch("services.knowledge_retrieval_inner_service.DatasetRetrieval") - @patch("services.knowledge_retrieval_inner_service.db") - def test_retrieve_maps_multiple_request_and_skips_enable_api_check(self, mock_db, mock_rag_cls): + def test_retrieve_maps_multiple_request_and_skips_enable_api_check(self, mock_rag_cls): request = _build_request() + mock_session = MagicMock() mock_app = MagicMock(id="app-1", tenant_id="tenant-1") dataset_1 = MagicMock(id="dataset-1", tenant_id="tenant-1", enable_api=False) dataset_2 = MagicMock(id="dataset-2", tenant_id="tenant-1", enable_api=True) - mock_db.session.scalar.return_value = mock_app - mock_db.session.scalars.return_value.all.return_value = [dataset_1, dataset_2] + mock_session.scalar.return_value = mock_app + mock_session.scalars.return_value.all.return_value = [dataset_1, dataset_2] rag = MagicMock() rag.knowledge_retrieval.return_value = [_build_source()] @@ -103,7 +103,7 @@ class TestInnerKnowledgeRetrievalService: } mock_rag_cls.return_value = rag - response = InnerKnowledgeRetrievalService().retrieve(request) + response = InnerKnowledgeRetrievalService().retrieve(request, mock_session) rag_request = rag.knowledge_retrieval.call_args.kwargs["request"] assert rag_request.tenant_id == "tenant-1" @@ -129,8 +129,7 @@ class TestInnerKnowledgeRetrievalService: assert response.usage.currency == "USD" @patch("services.knowledge_retrieval_inner_service.DatasetRetrieval") - @patch("services.knowledge_retrieval_inner_service.db") - def test_retrieve_maps_single_request(self, mock_db, mock_rag_cls): + def test_retrieve_maps_single_request(self, mock_rag_cls): request = _build_request( dataset_ids=["dataset-1"], retrieval={ @@ -153,8 +152,9 @@ class TestInnerKnowledgeRetrievalService: }, attachment_ids=[], ) - mock_db.session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-1") - mock_db.session.scalars.return_value.all.return_value = [MagicMock(id="dataset-1", tenant_id="tenant-1")] + mock_session = MagicMock() + mock_session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-1") + mock_session.scalars.return_value.all.return_value = [MagicMock(id="dataset-1", tenant_id="tenant-1")] rag = MagicMock() rag.knowledge_retrieval.return_value = [] @@ -174,7 +174,7 @@ class TestInnerKnowledgeRetrievalService: } mock_rag_cls.return_value = rag - InnerKnowledgeRetrievalService().retrieve(request) + InnerKnowledgeRetrievalService().retrieve(request, mock_session) rag_request = rag.knowledge_retrieval.call_args.kwargs["request"] assert rag_request.retrieval_mode == "single" @@ -186,35 +186,35 @@ class TestInnerKnowledgeRetrievalService: assert rag_request.metadata_model_config is not None assert rag_request.metadata_model_config.provider == "openai" - @patch("services.knowledge_retrieval_inner_service.db") - def test_retrieve_raises_when_app_missing(self, mock_db): - mock_db.session.scalar.return_value = None + def test_retrieve_raises_when_app_missing(self): + mock_session = MagicMock() + mock_session.scalar.return_value = None with pytest.raises(InnerKnowledgeRetrieveAppNotFoundError): - InnerKnowledgeRetrievalService().retrieve(_build_request()) + InnerKnowledgeRetrievalService().retrieve(_build_request(), mock_session) - @patch("services.knowledge_retrieval_inner_service.db") - def test_retrieve_raises_when_app_belongs_to_other_tenant(self, mock_db): - mock_db.session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-2") + def test_retrieve_raises_when_app_belongs_to_other_tenant(self): + mock_session = MagicMock() + mock_session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-2") with pytest.raises(InnerKnowledgeRetrieveAppTenantMismatchError): - InnerKnowledgeRetrievalService().retrieve(_build_request()) + InnerKnowledgeRetrievalService().retrieve(_build_request(), mock_session) - @patch("services.knowledge_retrieval_inner_service.db") - def test_retrieve_raises_when_dataset_missing(self, mock_db): - mock_db.session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-1") - mock_db.session.scalars.return_value.all.return_value = [MagicMock(id="dataset-1", tenant_id="tenant-1")] + def test_retrieve_raises_when_dataset_missing(self): + mock_session = MagicMock() + mock_session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-1") + mock_session.scalars.return_value.all.return_value = [MagicMock(id="dataset-1", tenant_id="tenant-1")] with pytest.raises(InnerKnowledgeRetrieveDatasetNotFoundError): - InnerKnowledgeRetrievalService().retrieve(_build_request()) + InnerKnowledgeRetrievalService().retrieve(_build_request(), mock_session) - @patch("services.knowledge_retrieval_inner_service.db") - def test_retrieve_raises_when_dataset_belongs_to_other_tenant(self, mock_db): - mock_db.session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-1") - mock_db.session.scalars.return_value.all.return_value = [ + def test_retrieve_raises_when_dataset_belongs_to_other_tenant(self): + mock_session = MagicMock() + mock_session.scalar.return_value = MagicMock(id="app-1", tenant_id="tenant-1") + mock_session.scalars.return_value.all.return_value = [ MagicMock(id="dataset-1", tenant_id="tenant-1"), MagicMock(id="dataset-2", tenant_id="tenant-2"), ] with pytest.raises(InnerKnowledgeRetrieveDatasetTenantMismatchError): - InnerKnowledgeRetrievalService().retrieve(_build_request()) + InnerKnowledgeRetrievalService().retrieve(_build_request(), mock_session) diff --git a/api/tests/unit_tests/services/test_webhook_service.py b/api/tests/unit_tests/services/test_webhook_service.py index a2b56fe7771..d36c45d7777 100644 --- a/api/tests/unit_tests/services/test_webhook_service.py +++ b/api/tests/unit_tests/services/test_webhook_service.py @@ -1,3 +1,4 @@ +import logging from io import BytesIO from unittest.mock import MagicMock, patch @@ -159,7 +160,9 @@ class TestWebhookServiceUnit: assert result == "application/octet-stream" - def test_detect_binary_mimetype_handles_magic_exception(self, monkeypatch: pytest.MonkeyPatch): + def test_detect_binary_mimetype_handles_magic_exception( + self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ): """Fallback MIME type should be used when python-magic raises an exception.""" try: import magic as real_magic @@ -169,12 +172,12 @@ class TestWebhookServiceUnit: fake_magic = MagicMock() fake_magic.from_buffer.side_effect = real_magic.MagicException("magic error") monkeypatch.setattr("services.trigger.webhook_service.magic", fake_magic) + caplog.set_level(logging.DEBUG, logger="services.trigger.webhook_service") - with patch("services.trigger.webhook_service.logger", autospec=True) as mock_logger: - result = WebhookService._detect_binary_mimetype(b"binary data") + result = WebhookService._detect_binary_mimetype(b"binary data") - assert result == "application/octet-stream" - mock_logger.debug.assert_called_once() + assert result == "application/octet-stream" + assert "python-magic detection failed for octet-stream payload" in caplog.messages def test_extract_webhook_data_invalid_json(self): """Test webhook data extraction with invalid JSON.""" diff --git a/eslint-suppressions.json b/eslint-suppressions.json index abb273edb6c..4b2ad6864dc 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -121,11 +121,6 @@ "count": 3 } }, - "web/__tests__/navigation-utils.test.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/__tests__/plugin-tool-workflow-error.test.tsx": { "ts/no-explicit-any": { "count": 2 @@ -343,14 +338,6 @@ "count": 4 } }, - "web/app/components/app-sidebar/app-sidebar-dropdown.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -559,14 +546,6 @@ "count": 1 } }, - "web/app/components/app/configuration/config-var/select-type-item/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/app/configuration/config-var/select-var-type.tsx": { "ts/no-explicit-any": { "count": 1 @@ -616,17 +595,6 @@ "count": 4 } }, - "web/app/components/app/configuration/config/assistant-type-picker/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - }, - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/app/configuration/config/automatic/get-automatic-res.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -808,11 +776,6 @@ "count": 1 } }, - "web/app/components/app/configuration/prompt-value-panel/utils.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/app/create-app-dialog/app-list/index.tsx": { "no-restricted-imports": { "count": 1 @@ -996,11 +959,6 @@ "count": 1 } }, - "web/app/components/apps/new-app-card.tsx": { - "react/set-state-in-effect": { - "count": 3 - } - }, "web/app/components/apps/starred-app-card.tsx": { "jsx-a11y/no-noninteractive-element-to-interactive-role": { "count": 1 @@ -1617,17 +1575,6 @@ "count": 2 } }, - "web/app/components/base/form/components/field/mixed-variable-text-input/placeholder.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 2 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 2 - }, - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/base/form/components/field/variable-selector.tsx": { "no-console": { "count": 1 @@ -1643,22 +1590,12 @@ "count": 1 } }, - "web/app/components/base/form/form-scenarios/base/index.tsx": { - "react/static-components": { - "count": 2 - } - }, "web/app/components/base/form/form-scenarios/base/types.ts": { "erasable-syntax-only/enums": { "count": 1 }, "ts/no-explicit-any": { - "count": 3 - } - }, - "web/app/components/base/form/form-scenarios/demo/index.tsx": { - "no-console": { - "count": 2 + "count": 1 } }, "web/app/components/base/form/form-scenarios/input-field/__tests__/field.spec.tsx": { @@ -1679,24 +1616,6 @@ "count": 2 } }, - "web/app/components/base/form/form-scenarios/node-panel/__tests__/field.spec.tsx": { - "react/static-components": { - "count": 2 - } - }, - "web/app/components/base/form/form-scenarios/node-panel/field.tsx": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/base/form/form-scenarios/node-panel/types.ts": { - "erasable-syntax-only/enums": { - "count": 1 - }, - "ts/no-explicit-any": { - "count": 2 - } - }, "web/app/components/base/form/hooks/index.ts": { "no-barrel-files/no-barrel-files": { "count": 3 @@ -1802,7 +1721,7 @@ }, "web/app/components/base/icons/src/vender/line/arrows/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 6 + "count": 5 } }, "web/app/components/base/icons/src/vender/line/communication/index.ts": { @@ -1827,7 +1746,7 @@ }, "web/app/components/base/icons/src/vender/line/files/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 6 + "count": 4 } }, "web/app/components/base/icons/src/vender/line/financeAndECommerce/index.ts": { @@ -1837,7 +1756,7 @@ }, "web/app/components/base/icons/src/vender/line/general/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 11 + "count": 10 } }, "web/app/components/base/icons/src/vender/line/images/index.ts": { @@ -1845,11 +1764,6 @@ "count": 1 } }, - "web/app/components/base/icons/src/vender/line/layout/index.ts": { - "no-barrel-files/no-barrel-files": { - "count": 1 - } - }, "web/app/components/base/icons/src/vender/line/mediaAndDevices/index.ts": { "no-barrel-files/no-barrel-files": { "count": 2 @@ -1912,7 +1826,7 @@ }, "web/app/components/base/icons/src/vender/solid/education/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 3 + "count": 2 } }, "web/app/components/base/icons/src/vender/solid/files/index.ts": { @@ -1981,17 +1895,6 @@ "count": 3 } }, - "web/app/components/base/image-uploader/audio-preview.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/media-has-caption": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/base/image-uploader/hooks.ts": { "ts/no-explicit-any": { "count": 4 @@ -2029,17 +1932,6 @@ "count": 2 } }, - "web/app/components/base/image-uploader/video-preview.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/media-has-caption": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/base/inline-delete-confirm/index.stories.tsx": { "no-console": { "count": 2 @@ -2589,27 +2481,6 @@ "count": 4 } }, - "web/app/components/base/with-input-validation/index.stories.tsx": { - "jsx-a11y/aria-role": { - "count": 7 - }, - "no-console": { - "count": 1 - } - }, - "web/app/components/base/with-input-validation/index.tsx": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/billing/header-billing-btn/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/billing/plan/assets/index.tsx": { "no-barrel-files/no-barrel-files": { "count": 4 @@ -2887,14 +2758,6 @@ "count": 3 } }, - "web/app/components/datasets/create/step-two/preview-item/index.tsx": { - "erasable-syntax-only/enums": { - "count": 1 - }, - "react-refresh/only-export-components": { - "count": 1 - } - }, "web/app/components/datasets/create/website/base/crawled-result-item.tsx": { "jsx-a11y/label-has-associated-control": { "count": 1 @@ -3359,14 +3222,6 @@ "count": 1 } }, - "web/app/components/datasets/list/dataset-card/operation-item.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/datasets/metadata/edit-metadata-batch/add-row.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -3650,24 +3505,6 @@ "count": 2 } }, - "web/app/components/header/account-setting/key-validator/Operate.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 4 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 4 - } - }, - "web/app/components/header/account-setting/key-validator/declarations.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/header/account-setting/language-page/__tests__/index.spec.tsx": { - "jsx-a11y/role-has-required-aria-props": { - "count": 1 - } - }, "web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx": { "jsx-a11y/no-autofocus": { "count": 1 @@ -3900,14 +3737,6 @@ "count": 1 } }, - "web/app/components/header/nav/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/main-nav/components/workspace-switcher.tsx": { "jsx-a11y/no-autofocus": { "count": 1 @@ -4044,11 +3873,6 @@ "count": 2 } }, - "web/app/components/plugins/plugin-auth/utils.ts": { - "ts/no-explicit-any": { - "count": 2 - } - }, "web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -4212,17 +4036,9 @@ "count": 1 } }, - "web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 5 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 5 - } - }, "web/app/components/plugins/plugin-detail-panel/tool-selector/components/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 7 + "count": 6 } }, "web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx": { @@ -4252,11 +4068,6 @@ "count": 3 } }, - "web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/index.ts": { - "no-barrel-files/no-barrel-files": { - "count": 2 - } - }, "web/app/components/plugins/plugin-detail-panel/tool-selector/index.tsx": { "no-restricted-imports": { "count": 1 @@ -4297,14 +4108,6 @@ "count": 1 } }, - "web/app/components/plugins/plugin-page/filter-management/__tests__/index.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/plugins/plugin-page/filter-management/category-filter.tsx": { "no-restricted-imports": { "count": 1 @@ -4629,11 +4432,6 @@ "count": 1 } }, - "web/app/components/share/utils.ts": { - "ts/no-explicit-any": { - "count": 2 - } - }, "web/app/components/snippet-list/components/snippet-card.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -4971,11 +4769,6 @@ "count": 4 } }, - "web/app/components/workflow/block-selector/use-check-vertical-scrollbar.ts": { - "react/set-state-in-effect": { - "count": 1 - } - }, "web/app/components/workflow/block-selector/use-sticky-scroll.ts": { "erasable-syntax-only/enums": { "count": 1 @@ -5342,30 +5135,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/_base/components/mixed-variable-text-input/__tests__/placeholder.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, - "web/app/components/workflow/nodes/_base/components/mixed-variable-text-input/index.tsx": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/workflow/nodes/_base/components/mixed-variable-text-input/placeholder.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 2 - }, - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/nodes/_base/components/next-step/operator.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 2 @@ -5421,14 +5190,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/_base/components/support-var-input/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -5627,11 +5388,6 @@ "count": 7 } }, - "web/app/components/workflow/nodes/agent/use-single-run-form-params.ts": { - "ts/no-explicit-any": { - "count": 3 - } - }, "web/app/components/workflow/nodes/answer/default.ts": { "ts/no-explicit-any": { "count": 1 @@ -5675,20 +5431,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/code/dependency-picker.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-autofocus": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - }, - "no-restricted-imports": { - "count": 1 - } - }, "web/app/components/workflow/nodes/code/types.ts": { "erasable-syntax-only/enums": { "count": 1 @@ -5784,14 +5526,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/http/components/key-value/bulk-edit/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/nodes/http/components/key-value/key-value-edit/index.tsx": { "ts/no-explicit-any": { "count": 2 @@ -6385,11 +6119,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/tool/components/input-var-list.tsx": { - "ts/no-explicit-any": { - "count": 7 - } - }, "web/app/components/workflow/nodes/tool/components/mixed-variable-text-input/index.tsx": { "ts/no-explicit-any": { "count": 1 @@ -6487,11 +6216,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/trigger-plugin/utils/form-helpers.ts": { - "ts/no-explicit-any": { - "count": 7 - } - }, "web/app/components/workflow/nodes/trigger-schedule/default.ts": { "regexp/no-unused-capturing-group": { "count": 2 @@ -6843,14 +6567,6 @@ "count": 1 } }, - "web/app/components/workflow/run/__tests__/loop-result-panel.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/run/__tests__/special-result-panel.spec.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -6938,14 +6654,6 @@ "count": 2 } }, - "web/app/components/workflow/run/loop-result-panel.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/run/node.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -7022,26 +6730,11 @@ "count": 11 } }, - "web/app/components/workflow/run/utils/format-log/graph-to-log-struct.ts": { - "ts/no-explicit-any": { - "count": 7 - } - }, "web/app/components/workflow/run/utils/format-log/index.ts": { "ts/no-explicit-any": { "count": 2 } }, - "web/app/components/workflow/run/utils/format-log/iteration/index.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/workflow/run/utils/format-log/loop/index.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/run/utils/format-log/parallel/index.ts": { "no-console": { "count": 4 @@ -7091,11 +6784,6 @@ "count": 1 } }, - "web/app/components/workflow/utils/debug.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/utils/index.ts": { "no-barrel-files/no-barrel-files": { "count": 10 @@ -7924,11 +7612,6 @@ "count": 6 } }, - "web/utils/navigation.spec.ts": { - "ts/no-explicit-any": { - "count": 4 - } - }, "web/utils/tool-call.spec.ts": { "ts/no-explicit-any": { "count": 1 diff --git a/packages/dify-ui/src/themes/dark.css b/packages/dify-ui/src/themes/dark.css index 1b24e8fb489..3f4a163a725 100644 --- a/packages/dify-ui/src/themes/dark.css +++ b/packages/dify-ui/src/themes/dark.css @@ -162,6 +162,7 @@ html[data-theme="dark"] { --color-components-main-nav-glass-surface-middle-2: #0033ff1a; --color-components-main-nav-glass-surface-end: #0033ff14; --color-components-main-nav-glass-edge-highlight-first: #fffffffa; + --color-components-main-nav-glass-edge-highlight-middle: #ffffff00; --color-components-main-nav-glass-edge-highlight-end: #ffffff6b; --color-components-main-nav-glass-edge-reflection-first: #0033ff00; --color-components-main-nav-glass-edge-reflection-middle: #0033ff99; diff --git a/packages/dify-ui/src/themes/light.css b/packages/dify-ui/src/themes/light.css index 3feb4afb47f..dd3252f3614 100644 --- a/packages/dify-ui/src/themes/light.css +++ b/packages/dify-ui/src/themes/light.css @@ -162,6 +162,7 @@ html[data-theme="light"] { --color-components-main-nav-glass-surface-middle-2: #0033ff1a; --color-components-main-nav-glass-surface-end: #0033ff14; --color-components-main-nav-glass-edge-highlight-first: #fffffffa; + --color-components-main-nav-glass-edge-highlight-middle: #ffffff00; --color-components-main-nav-glass-edge-highlight-end: #ffffff6b; --color-components-main-nav-glass-edge-reflection-first: #0033ff00; --color-components-main-nav-glass-edge-reflection-middle: #0033ff99; diff --git a/packages/dify-ui/src/themes/theme.css b/packages/dify-ui/src/themes/theme.css index 3e35feb8eb8..c14e54ea549 100644 --- a/packages/dify-ui/src/themes/theme.css +++ b/packages/dify-ui/src/themes/theme.css @@ -169,6 +169,7 @@ --color-components-main-nav-glass-surface-middle-2: var(--color-components-main-nav-glass-surface-middle-2); --color-components-main-nav-glass-surface-end: var(--color-components-main-nav-glass-surface-end); --color-components-main-nav-glass-edge-highlight-first: var(--color-components-main-nav-glass-edge-highlight-first); + --color-components-main-nav-glass-edge-highlight-middle: var(--color-components-main-nav-glass-edge-highlight-middle); --color-components-main-nav-glass-edge-highlight-end: var(--color-components-main-nav-glass-edge-highlight-end); --color-components-main-nav-glass-edge-reflection-first: var(--color-components-main-nav-glass-edge-reflection-first); --color-components-main-nav-glass-edge-reflection-middle: var(--color-components-main-nav-glass-edge-reflection-middle); diff --git a/web/.storybook/utils/form-story-wrapper.tsx b/web/.storybook/utils/form-story-wrapper.tsx deleted file mode 100644 index 7503e9905d3..00000000000 --- a/web/.storybook/utils/form-story-wrapper.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import type { ReactNode } from 'react' -import { useStore } from '@tanstack/react-form' -import { useState } from 'react' -import { useAppForm } from '@/app/components/base/form' - -type UseAppFormOptions = Parameters[0] -type AppFormInstance = ReturnType - -type FormStoryWrapperProps = { - options?: UseAppFormOptions - children: (form: AppFormInstance) => ReactNode - title?: string - subtitle?: string -} - -export const FormStoryWrapper = ({ - options, - children, - title, - subtitle, -}: FormStoryWrapperProps) => { - const [lastSubmitted, setLastSubmitted] = useState(null) - const [submitCount, setSubmitCount] = useState(0) - - const form = useAppForm({ - ...options, - onSubmit: (context) => { - setSubmitCount(count => count + 1) - setLastSubmitted(context.value) - options?.onSubmit?.(context) - }, - }) - - const values = useStore(form.store, state => state.values) - const isSubmitting = useStore(form.store, state => state.isSubmitting) - const canSubmit = useStore(form.store, state => state.canSubmit) - - return ( -
-
- {(title || subtitle) && ( -
- {title &&

{title}

} - {subtitle &&

{subtitle}

} -
- )} - {children(form)} -
- -
- ) -} - -export type FormStoryRender = (form: AppFormInstance) => ReactNode diff --git a/web/__tests__/app-sidebar/sidebar-shell-flow.test.tsx b/web/__tests__/app-sidebar/sidebar-shell-flow.test.tsx deleted file mode 100644 index c1f3a1c62d4..00000000000 --- a/web/__tests__/app-sidebar/sidebar-shell-flow.test.tsx +++ /dev/null @@ -1,151 +0,0 @@ -import type { SVGProps } from 'react' -import { fireEvent, render, screen } from '@testing-library/react' -import * as React from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import AppDetailNav from '@/app/components/app-sidebar' - -const mockSetDetailSidebarMode = vi.fn() - -let mockDetailSidebarMode = 'expand' -let mockPathname = '/app/app-1/logs' -let mockSelectedSegment = 'logs' -let mockIsHovering = true -let hotkeyHandler: ((event: { preventDefault: () => void }) => void) | null = null - -vi.mock('react-i18next', () => ({ - useTranslation: () => ({ - t: (key: string) => key, - }), -})) - -vi.mock('@/app/components/main-nav/storage', () => ({ - useDetailSidebarMode: () => [mockDetailSidebarMode, mockSetDetailSidebarMode], -})) - -vi.mock('@/next/navigation', () => ({ - usePathname: () => mockPathname, - useSelectedLayoutSegment: () => mockSelectedSegment, -})) - -vi.mock('@/next/link', () => ({ - default: ({ - href, - children, - className, - title, - }: { - href: string - children?: React.ReactNode - className?: string - title?: string - }) => ( - - {children} - - ), -})) - -vi.mock('ahooks', () => ({ - useHover: () => mockIsHovering, -})) - -vi.mock('@tanstack/react-hotkeys', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - useHotkey: (_hotkey: string, handler: (event: { preventDefault: () => void }) => void) => { - hotkeyHandler = handler - }, - } -}) - -vi.mock('@/hooks/use-breakpoints', () => ({ - default: () => 'desktop', - MediaType: { - mobile: 'mobile', - desktop: 'desktop', - }, -})) - -vi.mock('@/context/event-emitter', () => ({ - useEventEmitterContextContext: () => ({ - eventEmitter: { - useSubscription: vi.fn(), - }, - }), -})) - -vi.mock('@/context/app-context', () => ({ - useAppContext: () => ({ - isCurrentWorkspaceEditor: true, - }), -})) - -vi.mock('@langgenius/dify-ui/dropdown-menu', () => import('@/__mocks__/base-ui-dropdown-menu')) -vi.mock('@langgenius/dify-ui/tooltip', () => import('@/__mocks__/base-ui-tooltip')) - -vi.mock('@/app/components/app-sidebar/app-info', () => ({ - default: ({ - expand, - onlyShowDetail, - openState, - }: { - expand: boolean - onlyShowDetail?: boolean - openState?: boolean - }) => ( -
- ), -})) - -const MockIcon = (props: SVGProps) => - -const navigation = [ - { name: 'Overview', href: '/app/app-1/overview', icon: MockIcon, selectedIcon: MockIcon }, - { name: 'Logs', href: '/app/app-1/logs', icon: MockIcon, selectedIcon: MockIcon }, -] - -describe('App Sidebar Shell Flow', () => { - beforeEach(() => { - vi.clearAllMocks() - localStorage.clear() - mockDetailSidebarMode = 'expand' - mockPathname = '/app/app-1/logs' - mockSelectedSegment = 'logs' - mockIsHovering = true - hotkeyHandler = null - }) - - it('renders the expanded sidebar, marks the active nav item, and toggles collapse by click and shortcut', () => { - render() - - expect(screen.getByTestId('app-info')).toHaveAttribute('data-expand', 'true') - - const logsLink = screen.getByRole('link', { name: /Logs/i }) - expect(logsLink.className).toContain('bg-components-menu-item-bg-active') - - fireEvent.click(screen.getByRole('button')) - expect(mockSetDetailSidebarMode).toHaveBeenCalledWith('collapse') - - const preventDefault = vi.fn() - hotkeyHandler?.({ preventDefault }) - - expect(preventDefault).toHaveBeenCalled() - expect(mockSetDetailSidebarMode).toHaveBeenCalledWith('collapse') - }) - - it('keeps the normal sidebar on workflow routes', () => { - mockPathname = '/app/app-1/workflow' - mockSelectedSegment = 'workflow' - - render() - - expect(screen.getByTestId('app-info')).toBeInTheDocument() - expect(screen.getByRole('link', { name: /Overview/i })).toBeInTheDocument() - expect(screen.getByRole('link', { name: /Logs/i })).toBeInTheDocument() - }) -}) diff --git a/web/__tests__/base/form-demo-flow.test.tsx b/web/__tests__/base/form-demo-flow.test.tsx deleted file mode 100644 index afb36528c0f..00000000000 --- a/web/__tests__/base/form-demo-flow.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { render, screen, waitFor, within } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import DemoForm from '@/app/components/base/form/form-scenarios/demo' - -describe('Base Form Demo Flow', () => { - const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - beforeEach(() => { - vi.clearAllMocks() - }) - - it('reveals contact fields and submits the composed form values through the shared form actions', async () => { - const user = userEvent.setup() - render() - - expect(screen.queryByRole('heading', { name: /contacts/i })).not.toBeInTheDocument() - - await user.type(screen.getByRole('textbox', { name: /^name$/i }), 'Alice') - await user.type(screen.getByRole('textbox', { name: /^surname$/i }), 'Smith') - await user.click(screen.getByText(/i accept the terms and conditions/i)) - - expect(await screen.findByRole('heading', { name: /contacts/i })).toBeInTheDocument() - - await user.type(screen.getByRole('textbox', { name: /^email$/i }), 'alice@example.com') - - const preferredMethodLabel = screen.getByText('Preferred Contact Method') - const preferredMethodField = preferredMethodLabel.parentElement?.parentElement - expect(preferredMethodField).toBeTruthy() - - await user.click(within(preferredMethodField as HTMLElement).getByText('Email')) - await user.click(screen.getByText('Whatsapp')) - - const submitButton = screen.getByRole('button', { name: /operation\.submit/i }) - expect(submitButton).toBeEnabled() - await user.click(submitButton) - - await waitFor(() => { - expect(consoleLogSpy).toHaveBeenCalledWith('Form submitted:', expect.objectContaining({ - name: 'Alice', - surname: 'Smith', - isAcceptingTerms: true, - contact: expect.objectContaining({ - email: 'alice@example.com', - preferredContactMethod: 'whatsapp', - }), - })) - }) - }) - - it('removes the nested contact section again when the name field is cleared', async () => { - const user = userEvent.setup() - render() - - const nameInput = screen.getByRole('textbox', { name: /^name$/i }) - await user.type(nameInput, 'Alice') - expect(await screen.findByRole('heading', { name: /contacts/i })).toBeInTheDocument() - - await user.clear(nameInput) - - await waitFor(() => { - expect(screen.queryByRole('heading', { name: /contacts/i })).not.toBeInTheDocument() - }) - }) -}) diff --git a/web/__tests__/billing/billing-integration.test.tsx b/web/__tests__/billing/billing-integration.test.tsx index 2fde9b506f4..e82a6d8eac2 100644 --- a/web/__tests__/billing/billing-integration.test.tsx +++ b/web/__tests__/billing/billing-integration.test.tsx @@ -7,7 +7,6 @@ import AnnotationFullModal from '@/app/components/billing/annotation-full/modal' import AppsFull from '@/app/components/billing/apps-full-in-dialog' import Billing from '@/app/components/billing/billing-page' import { defaultPlan, NUM_INFINITE } from '@/app/components/billing/config' -import HeaderBillingBtn from '@/app/components/billing/header-billing-btn' import PlanComp from '@/app/components/billing/plan' import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal' import PriorityLabel from '@/app/components/billing/priority-label' @@ -696,83 +695,7 @@ describe('Capacity Full Components Integration', () => { }) // ═══════════════════════════════════════════════════════════════════════════ -// 5. Header Billing Button Integration -// Tests HeaderBillingBtn behavior for different plan states -// ═══════════════════════════════════════════════════════════════════════════ -describe('Header Billing Button Integration', () => { - beforeEach(() => { - vi.clearAllMocks() - setupAppContext() - }) - - it('should render UpgradeBtn (premium badge) for sandbox plan', () => { - setupProviderContext({ type: Plan.sandbox }) - - render() - - expect(screen.getByText(/upgradeBtn\.encourageShort/i)).toBeInTheDocument() - }) - - it('should render "pro" badge for professional plan', () => { - setupProviderContext({ type: Plan.professional }) - - render() - - expect(screen.getByText('pro')).toBeInTheDocument() - expect(screen.queryByText(/upgradeBtn/i)).not.toBeInTheDocument() - }) - - it('should render "team" badge for team plan', () => { - setupProviderContext({ type: Plan.team }) - - render() - - expect(screen.getByText('team')).toBeInTheDocument() - }) - - it('should return null when billing is disabled', () => { - setupProviderContext({ type: Plan.sandbox }, { enableBilling: false }) - - const { container } = render() - - expect(container.innerHTML).toBe('') - }) - - it('should return null when plan is not fetched yet', () => { - setupProviderContext({ type: Plan.sandbox }, { isFetchedPlan: false }) - - const { container } = render() - - expect(container.innerHTML).toBe('') - }) - - it('should call onClick when clicking pro/team badge in non-display-only mode', async () => { - const user = userEvent.setup() - const onClick = vi.fn() - setupProviderContext({ type: Plan.professional }) - - render() - - await user.click(screen.getByText('pro')) - - expect(onClick).toHaveBeenCalledTimes(1) - }) - - it('should not call onClick when isDisplayOnly is true', async () => { - const user = userEvent.setup() - const onClick = vi.fn() - setupProviderContext({ type: Plan.professional }) - - render() - - await user.click(screen.getByText('pro')) - - expect(onClick).not.toHaveBeenCalled() - }) -}) - -// ═══════════════════════════════════════════════════════════════════════════ -// 6. PriorityLabel Integration +// 5. PriorityLabel Integration // Tests priority badge display for different plan types // ═══════════════════════════════════════════════════════════════════════════ describe('PriorityLabel Integration', () => { diff --git a/web/__tests__/header/nav-flow.test.tsx b/web/__tests__/header/nav-flow.test.tsx deleted file mode 100644 index 33927f19da4..00000000000 --- a/web/__tests__/header/nav-flow.test.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import { fireEvent, render, screen, waitFor } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import * as React from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import Nav from '@/app/components/header/nav' -import { AppModeEnum } from '@/types/app' - -const mockPush = vi.fn() -const mockSetAppDetail = vi.fn() -const mockOnCreate = vi.fn() -const mockOnLoadMore = vi.fn() - -let mockSelectedSegment = 'app' -let mockIsCurrentWorkspaceEditor = true - -vi.mock('react-i18next', () => ({ - useTranslation: () => ({ - t: (key: string) => key, - }), -})) - -vi.mock('@/next/navigation', () => ({ - useSelectedLayoutSegment: () => mockSelectedSegment, - useRouter: () => ({ - push: mockPush, - }), -})) - -vi.mock('@/next/link', () => ({ - default: ({ - href, - children, - }: { - href: string - children?: React.ReactNode - }) => {children}, -})) - -vi.mock('@/app/components/app/store', () => ({ - useStore: () => mockSetAppDetail, -})) - -vi.mock('@/context/app-context', () => ({ - useAppContext: () => ({ - isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor, - workspacePermissionKeys: mockIsCurrentWorkspaceEditor ? ['app.create_and_management'] : [], - }), -})) - -const navigationItems = [ - { - id: 'app-1', - name: 'Alpha', - link: '/app/app-1/configuration', - icon_type: 'emoji' as const, - icon: '🤖', - icon_background: '#FFEAD5', - icon_url: null, - mode: AppModeEnum.CHAT, - }, - { - id: 'app-2', - name: 'Bravo', - link: '/app/app-2/workflow', - icon_type: 'emoji' as const, - icon: '⚙️', - icon_background: '#E0F2FE', - icon_url: null, - mode: AppModeEnum.WORKFLOW, - }, -] - -const curNav = { - id: 'app-1', - name: 'Alpha', - icon_type: 'emoji' as const, - icon: '🤖', - icon_background: '#FFEAD5', - icon_url: null, - mode: AppModeEnum.CHAT, -} - -const renderNav = (nav = curNav) => { - return render( -