From 8e8a3c54145f9d3d66388e53ba4c2d2602ddd10d Mon Sep 17 00:00:00 2001 From: Stephen Zhou Date: Wed, 9 Sep 2026 07:58:29 +0000 Subject: [PATCH 01/28] chore(lint): respect gitignore in ESLint flat config (#42065) --- eslint.config.mjs | 7 +++++++ package.json | 1 + pnpm-lock.yaml | 32 ++++++++++++++++++++++++++++++++ pnpm-workspace.yaml | 1 + 4 files changed, 41 insertions(+) diff --git a/eslint.config.mjs b/eslint.config.mjs index f069b6910bc..9b72b129bd9 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,6 +1,8 @@ // @ts-check +/// import markdown from '@eslint/markdown' +import gitignore from 'eslint-config-flat-gitignore' import md from 'eslint-markdown' import jsonc from 'eslint-plugin-jsonc' import markdownPreferences from 'eslint-plugin-markdown-preferences' @@ -213,6 +215,11 @@ export default defineConfig([ ], 'Project lint scope', ), + gitignore({ + cwd: import.meta.dirname, + root: true, + recursive: { skipDirs: ['.venv', 'volumes'] }, + }), globalIgnores([codeFiles], 'Migration tradeoff: code files are handled by Oxlint only'), globalIgnores( [ diff --git a/package.json b/package.json index f396fceefe2..d1d4762c2fe 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "@typescript/native": "catalog:", "concurrently": "catalog:", "eslint": "catalog:", + "eslint-config-flat-gitignore": "catalog:", "eslint-markdown": "catalog:", "eslint-plugin-antfu": "catalog:", "eslint-plugin-better-tailwindcss": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c9cdb62e766..b2452f6e462 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -413,6 +413,9 @@ catalogs: eslint: specifier: 10.9.1 version: 10.9.1 + eslint-config-flat-gitignore: + specifier: 2.4.0 + version: 2.4.0 eslint-markdown: specifier: 0.12.1 version: 0.12.1 @@ -771,6 +774,9 @@ importers: eslint: specifier: 'catalog:' version: 10.9.1(jiti@2.7.0)(supports-color@11.0.0) + eslint-config-flat-gitignore: + specifier: 'catalog:' + version: 2.4.0(eslint@10.9.1(jiti@2.7.0)(supports-color@11.0.0)) eslint-markdown: specifier: 'catalog:' version: 0.12.1(eslint@10.9.1(jiti@2.7.0)(supports-color@11.0.0))(supports-color@11.0.0) @@ -2287,6 +2293,15 @@ packages: eslint: '*' typescript: '*' + '@eslint/compat@2.1.1': + resolution: {integrity: sha512-rMcy8GSrwNzcISX/BlTDY/GLB4eCopEuy9woIls3To+15OLxykZrxxq+WUcylCPCQ6F4MujjBM1DX5V1aqI3Vw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + peerDependencies: + eslint: ^8.40 || 9 || 10 + peerDependenciesMeta: + eslint: + optional: true + '@eslint/config-array@0.23.5': resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} @@ -6196,6 +6211,11 @@ packages: peerDependencies: eslint: '>=6.0.0' + eslint-config-flat-gitignore@2.4.0: + resolution: {integrity: sha512-JhYC+V7qEDiCDsbJcVP8fxNc62fk4+i91YLP/YvmVHlkaQ8Xo99olYN8MO5COdxl7onGlsrfZVONe5NYsZP1UA==} + peerDependencies: + eslint: ^9.5.0 || ^10.0.0 + eslint-json-compat-utils@0.2.3: resolution: {integrity: sha512-RbBmDFyu7FqnjE8F0ZxPNzx5UaptdeS9Uu50r7A+D7s/+FCX+ybiyViYEgFUaFIFqSWJgZRTpL5d8Kanxxl2lQ==} engines: {node: '>=12'} @@ -10066,6 +10086,12 @@ snapshots: transitivePeerDependencies: - supports-color + '@eslint/compat@2.1.1(eslint@10.9.1(jiti@2.7.0)(supports-color@11.0.0))': + dependencies: + '@eslint/core': 1.2.1 + optionalDependencies: + eslint: 10.9.1(jiti@2.7.0)(supports-color@11.0.0) + '@eslint/config-array@0.23.5(supports-color@11.0.0)': dependencies: '@eslint/object-schema': 3.0.5 @@ -13565,6 +13591,11 @@ snapshots: eslint: 10.9.1(jiti@2.7.0)(supports-color@11.0.0) semver: 7.8.5 + eslint-config-flat-gitignore@2.4.0(eslint@10.9.1(jiti@2.7.0)(supports-color@11.0.0)): + dependencies: + '@eslint/compat': 2.1.1(eslint@10.9.1(jiti@2.7.0)(supports-color@11.0.0)) + eslint: 10.9.1(jiti@2.7.0)(supports-color@11.0.0) + eslint-json-compat-utils@0.2.3(eslint@10.9.1(jiti@2.7.0)(supports-color@11.0.0))(jsonc-eslint-parser@3.3.0): dependencies: eslint: 10.9.1(jiti@2.7.0)(supports-color@11.0.0) @@ -17433,6 +17464,7 @@ time: embla-carousel-react@8.6.0: '2025-04-04T17:37:53.976Z' emoji-mart@5.6.0: '2024-04-25T14:22:21.440Z' es-toolkit@1.52.0: '2026-08-28T07:22:17.687Z' + eslint-config-flat-gitignore@2.4.0: '2026-08-27T07:24:43.063Z' eslint-markdown@0.12.1: '2026-07-10T23:35:26.055Z' eslint-plugin-antfu@3.2.3: '2026-05-11T02:24:38.348Z' eslint-plugin-better-tailwindcss@4.7.0: '2026-07-19T13:26:01.366Z' diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 9964cb41475..02e54426222 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -153,6 +153,7 @@ catalog: emoji-mart: 5.6.0 es-toolkit: 1.52.0 eslint: 10.9.1 + eslint-config-flat-gitignore: 2.4.0 eslint-markdown: 0.12.1 eslint-plugin-antfu: 3.2.3 eslint-plugin-better-tailwindcss: 4.7.0 From a7cc6913af4620f4ace8213c45297793d4189764 Mon Sep 17 00:00:00 2001 From: Yunlu Wen Date: Wed, 9 Sep 2026 08:47:09 +0000 Subject: [PATCH 02/28] chore(deps): bump unstructured from 0.21.5 to 0.27.5 in /api (#42053) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- api/pyproject.toml | 3 +++ api/uv.lock | 59 +++++++++++++++++++++++++++++++++------------- 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/api/pyproject.toml b/api/pyproject.toml index 76d67eb2523..2ca877a8bd5 100644 --- a/api/pyproject.toml +++ b/api/pyproject.toml @@ -114,6 +114,9 @@ override-dependencies = [ "pyarrow>=23.0.1,<24.0.0", "cryptography>=50.0.0,<51.0.0", "setuptools>=80.10.2,<81", + # `tos` hard-pins `wrapt==1.16.0` without importing it, which blocks + # `unstructured>=0.24.0` (requires `wrapt>=2.1.1`). + "wrapt>=2.1.1,<3.0.0", ] [dependency-groups] diff --git a/api/uv.lock b/api/uv.lock index 9debbf825c2..0ce5ce844a4 100644 --- a/api/uv.lock +++ b/api/uv.lock @@ -55,6 +55,7 @@ overrides = [ { name = "litellm", specifier = ">=1.83.10,<2.0.0" }, { name = "pyarrow", specifier = ">=23.0.1,<24.0.0" }, { name = "setuptools", specifier = ">=80.10.2,<81" }, + { name = "wrapt", specifier = ">=2.1.1,<3.0.0" }, ] [[package]] @@ -4216,6 +4217,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/07/c7/d64168da60332c17d24c0d2f08bdf3987e8d1ae9d84b5bbd0eec2eb26a55/networkx-3.6-py3-none-any.whl", hash = "sha256:cdb395b105806062473d3be36458d8f1459a4e4b98e236a66c3a48996e07684f", size = 2063713, upload-time = "2025-11-24T03:03:45.21Z" }, ] +[[package]] +name = "nh3" +version = "0.3.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/2f/022b27146d52d24b1b353b003359134788ecbcd6fcdf6283adbd57c0fbc8/nh3-0.3.7.tar.gz", hash = "sha256:71860d01c16f4d8c72e334e0674beb2b0899dbd0bf760de18932ef4390303848", size = 25662, upload-time = "2026-08-23T14:26:30.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/0d/c257754bf57f829f307aa226bbe136d3a1356b5a0d08324c7b6bd2a8aacd/nh3-0.3.7-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:6c3aa50eb26e9228238271db9f983cbc3b006dfbfeca2d4dc34c33ddc6ac5ea5", size = 1493959, upload-time = "2026-08-23T14:26:09.025Z" }, + { url = "https://files.pythonhosted.org/packages/07/42/a687e7091928806e514f89fa2666f25ec9bfe0a902fc4402b25e51ce408b/nh3-0.3.7-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f266d3f1b3647449923a8e406524632220dd5d8b647078dfe45b885d33d10479", size = 859615, upload-time = "2026-08-23T14:26:10.606Z" }, + { url = "https://files.pythonhosted.org/packages/85/05/b0e6bef633549a23347d5462aa288fcc42381e7918482062ca3cb456242a/nh3-0.3.7-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e8fd1ab205258b29254f72db377d99e2c96aa7653ef3b015ccab0420b094b506", size = 839872, upload-time = "2026-08-23T14:26:12.037Z" }, + { url = "https://files.pythonhosted.org/packages/17/40/2a0921d45b20828708bcb56887e47dcf8cae13818de5bf9a01308d348712/nh3-0.3.7-cp38-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:19f288c938ec6eef1f5d2c6cab47838e71fef8097e1c1233802be5a6230ba086", size = 1091325, upload-time = "2026-08-23T14:26:13.34Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d1/9d70e0e418a48280ec0ddc6c1b08b4b1136ebcc31a1625e57ff5c665fa51/nh3-0.3.7-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de2b2aab32ea303405debefdcfc58043d3e635fa3f67b9eb140d2b0e0c0d2563", size = 1042482, upload-time = "2026-08-23T14:26:14.667Z" }, + { url = "https://files.pythonhosted.org/packages/93/a7/02dd159d4e71f98607d8d4249cddb7561e77be1a8e4dec77d76e1b68fc99/nh3-0.3.7-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b7279d43323a25225df23576af6594a16693f61431170848b8b2ac21ad4f174", size = 946868, upload-time = "2026-08-23T14:26:16.094Z" }, + { url = "https://files.pythonhosted.org/packages/a6/ed/c5510c615dce55b6fcc364aa1838142f938beed64f5e4927490dfcaf4405/nh3-0.3.7-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70f5ac8626e899a4bab0ef74ca2f5bd602f49c7b739e6e5026b4afc6d63dac42", size = 832161, upload-time = "2026-08-23T14:26:17.272Z" }, + { url = "https://files.pythonhosted.org/packages/7b/e3/3212c1a5b5745245d7f18885207bbddb34c56075f34dd682bd539aad55cc/nh3-0.3.7-cp38-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:5ffdfcb9a686ffb12765376bcfb6b5b55728516d3c0ee317d29982381ded3df8", size = 849791, upload-time = "2026-08-23T14:26:18.498Z" }, + { url = "https://files.pythonhosted.org/packages/20/64/9e36594efad6c290de4240d02cb2bd80c339a4ab1c4de66e599ffa6d9d81/nh3-0.3.7-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bc42bb1193c1e28a1e74c2cabaca178e118a7103e8832699fef8a2b3e2496493", size = 875473, upload-time = "2026-08-23T14:26:19.908Z" }, + { url = "https://files.pythonhosted.org/packages/00/0c/1a8985fd43fea5530c0ac890b6f0b423770ee72f111b70b7a77f2dec243a/nh3-0.3.7-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:d56e76bd3cadb09b6b0cef364850811663734b348a25f5f587a2819c495367bd", size = 1036463, upload-time = "2026-08-23T14:26:21.536Z" }, + { url = "https://files.pythonhosted.org/packages/b2/5d/891e533b716cf00df76ad0ba6485dcfd14d59a6430a3cc99057c4c04004e/nh3-0.3.7-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:fd4a70efb45d5372174f718878eb7a35c12677626a63b2f103b23b833457dcac", size = 1116029, upload-time = "2026-08-23T14:26:22.907Z" }, + { url = "https://files.pythonhosted.org/packages/42/e5/ae8c0782fce74fb6fcf7234bb3d4017f37ce181b4f9d29369eab21c50a04/nh3-0.3.7-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:15f5fbf090f5c88d61c820e1fc1fceecb6520cca9fe85649c06b57ef9dc9ff62", size = 1076589, upload-time = "2026-08-23T14:26:24.302Z" }, + { url = "https://files.pythonhosted.org/packages/26/a4/c3423351e8d864ad756e85e15f0c01433361f14d34e4ed156482c0518f2a/nh3-0.3.7-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6698a822132beedab80f131c08d8d0ac5a178ddeb488d02ca4b67716ecfac7af", size = 1058871, upload-time = "2026-08-23T14:26:25.674Z" }, + { url = "https://files.pythonhosted.org/packages/4b/6a/478f153f1d7c0baaa3d1e8bb5fdcee3a6235f90fe44ea969a9d4e2b8c47a/nh3-0.3.7-cp38-abi3-win32.whl", hash = "sha256:6e4280115d44c3b278eef712a86748c1a723105cd79feec46952383117ab4e59", size = 630729, upload-time = "2026-08-23T14:26:26.932Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b9/34433ccb1f0fe6968dabbb7d4bf5721c6221878ef07832748c06655a6a80/nh3-0.3.7-cp38-abi3-win_amd64.whl", hash = "sha256:618e3059caf41ccdf5dcccb3fa9df4cf6e4efe23d1382a8bbfca272a8a4f8bfc", size = 644462, upload-time = "2026-08-23T14:26:28.294Z" }, + { url = "https://files.pythonhosted.org/packages/f9/70/e140dffff6e808dc6343598df76e7e2407fd0f581de3524c75fba2e0cf24/nh3-0.3.7-cp38-abi3-win_arm64.whl", hash = "sha256:f04b7d333b27f13ca439da3cf1c75c2fba34f104969f6ce4ac8e7079699c2f4a", size = 621867, upload-time = "2026-08-23T14:26:29.547Z" }, +] + [[package]] name = "nltk" version = "3.10.3" @@ -7258,7 +7283,7 @@ wheels = [ [[package]] name = "unstructured" -version = "0.21.5" +version = "0.27.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "beautifulsoup4" }, @@ -7270,6 +7295,7 @@ dependencies = [ { name = "installer" }, { name = "langdetect" }, { name = "lxml" }, + { name = "nh3" }, { name = "numba" }, { name = "numpy" }, { name = "psutil" }, @@ -7285,9 +7311,9 @@ dependencies = [ { name = "unstructured-client" }, { name = "wrapt" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b3/e6/fbef61517d130af1def3b81681e253a5679f19de2f04e439afbbf1f021e0/unstructured-0.21.5.tar.gz", hash = "sha256:3e220d0c2b9c8ec12c99767162b95ab0acfca75e979b82c66c15ca15caa60139", size = 1501811, upload-time = "2026-02-24T15:29:27.84Z" } +sdist = { url = "https://files.pythonhosted.org/packages/54/89/40ba552526ae54b80bc8daeea048b8cd7e409fec5795f6e70ce3207eb430/unstructured-0.27.5.tar.gz", hash = "sha256:68c72b9ea17fb34e0037126d3eca23f76290b9e5171b221d6d078dcff2ffd77d", size = 1560203, upload-time = "2026-08-28T21:18:29.131Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b8/b6/7e6dd60bde81d5a4d4ddf426f566a5d1b4c30490053caed69e47f55c676f/unstructured-0.21.5-py3-none-any.whl", hash = "sha256:d88a277c368462b69a8843b9cb22476f3cc4d0a58455536520359387224b3366", size = 1554925, upload-time = "2026-02-24T15:29:26.009Z" }, + { url = "https://files.pythonhosted.org/packages/c8/56/3eb070e467178d763a27587f40a3a8fa8277ef7b087d13b286a5ec25d711/unstructured-0.27.5-py3-none-any.whl", hash = "sha256:4624145cb102296425ed0c4917711f8068746680f73718ac819b54568a5d293e", size = 1620083, upload-time = "2026-08-28T21:18:26.983Z" }, ] [package.optional-dependencies] @@ -7655,21 +7681,22 @@ wheels = [ [[package]] name = "wrapt" -version = "1.16.0" +version = "2.4.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/95/4c/063a912e20bcef7124e0df97282a8af3ff3e4b603ce84c481d6d7346be0a/wrapt-1.16.0.tar.gz", hash = "sha256:5f370f952971e7d17c7d1ead40e49f32345a7f7a5373571ef44d800d06b1899d", size = 53972, upload-time = "2023-11-09T06:33:30.191Z" } +sdist = { url = "https://files.pythonhosted.org/packages/65/ba/8dc25478ed234dacc7d83c671634f347d0bdfb65bf0502f41879cf2f15a9/wrapt-2.4.0.tar.gz", hash = "sha256:7082fc1f94b020ac275870c4af71b09cff22876fe6e9c4c0ad01ea21d217b288", size = 161179, upload-time = "2026-08-30T04:41:51.424Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/92/17/224132494c1e23521868cdd57cd1e903f3b6a7ba6996b7b8f077ff8ac7fe/wrapt-1.16.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:5eb404d89131ec9b4f748fa5cfb5346802e5ee8836f57d516576e61f304f3b7b", size = 37614, upload-time = "2023-11-09T06:32:08.859Z" }, - { url = "https://files.pythonhosted.org/packages/6a/d7/cfcd73e8f4858079ac59d9db1ec5a1349bc486ae8e9ba55698cc1f4a1dff/wrapt-1.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9090c9e676d5236a6948330e83cb89969f433b1943a558968f659ead07cb3b36", size = 38316, upload-time = "2023-11-09T06:32:10.719Z" }, - { url = "https://files.pythonhosted.org/packages/7e/79/5ff0a5c54bda5aec75b36453d06be4f83d5cd4932cc84b7cb2b52cee23e2/wrapt-1.16.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:94265b00870aa407bd0cbcfd536f17ecde43b94fb8d228560a1e9d3041462d73", size = 86322, upload-time = "2023-11-09T06:32:12.592Z" }, - { url = "https://files.pythonhosted.org/packages/c4/81/e799bf5d419f422d8712108837c1d9bf6ebe3cb2a81ad94413449543a923/wrapt-1.16.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f2058f813d4f2b5e3a9eb2eb3faf8f1d99b81c3e51aeda4b168406443e8ba809", size = 79055, upload-time = "2023-11-09T06:32:14.394Z" }, - { url = "https://files.pythonhosted.org/packages/62/62/30ca2405de6a20448ee557ab2cd61ab9c5900be7cbd18a2639db595f0b98/wrapt-1.16.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98b5e1f498a8ca1858a1cdbffb023bfd954da4e3fa2c0cb5853d40014557248b", size = 87291, upload-time = "2023-11-09T06:32:16.201Z" }, - { url = "https://files.pythonhosted.org/packages/49/4e/5d2f6d7b57fc9956bf06e944eb00463551f7d52fc73ca35cfc4c2cdb7aed/wrapt-1.16.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:14d7dc606219cdd7405133c713f2c218d4252f2a469003f8c46bb92d5d095d81", size = 90374, upload-time = "2023-11-09T06:32:18.052Z" }, - { url = "https://files.pythonhosted.org/packages/a6/9b/c2c21b44ff5b9bf14a83252a8b973fb84923764ff63db3e6dfc3895cf2e0/wrapt-1.16.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:49aac49dc4782cb04f58986e81ea0b4768e4ff197b57324dcbd7699c5dfb40b9", size = 83896, upload-time = "2023-11-09T06:32:19.533Z" }, - { url = "https://files.pythonhosted.org/packages/14/26/93a9fa02c6f257df54d7570dfe8011995138118d11939a4ecd82cb849613/wrapt-1.16.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:418abb18146475c310d7a6dc71143d6f7adec5b004ac9ce08dc7a34e2babdc5c", size = 91738, upload-time = "2023-11-09T06:32:20.989Z" }, - { url = "https://files.pythonhosted.org/packages/a2/5b/4660897233eb2c8c4de3dc7cefed114c61bacb3c28327e64150dc44ee2f6/wrapt-1.16.0-cp312-cp312-win32.whl", hash = "sha256:685f568fa5e627e93f3b52fda002c7ed2fa1800b50ce51f6ed1d572d8ab3e7fc", size = 35568, upload-time = "2023-11-09T06:32:22.715Z" }, - { url = "https://files.pythonhosted.org/packages/5c/cc/8297f9658506b224aa4bd71906447dea6bb0ba629861a758c28f67428b91/wrapt-1.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:dcdba5c86e368442528f7060039eda390cc4091bfd1dca41e8046af7c910dda8", size = 37653, upload-time = "2023-11-09T06:32:24.533Z" }, - { url = "https://files.pythonhosted.org/packages/ff/21/abdedb4cdf6ff41ebf01a74087740a709e2edb146490e4d9beea054b0b7a/wrapt-1.16.0-py3-none-any.whl", hash = "sha256:6906c4100a8fcbf2fa735f6059214bb13b97f75b1a61777fcf6432121ef12ef1", size = 23362, upload-time = "2023-11-09T06:33:28.271Z" }, + { url = "https://files.pythonhosted.org/packages/f0/22/581a0b44349d5babe526c958f365b8126e0fbd8fc2810e80446c47358050/wrapt-2.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef4e2d6e399ce6eecc80179a6b9ef6544f121288f95fc132bc36c9d9503903af", size = 96374, upload-time = "2026-08-30T04:39:42.335Z" }, + { url = "https://files.pythonhosted.org/packages/5d/90/095984648cec62a786bb27c0b50f6cfa5856d1e073ba1006fe148d190084/wrapt-2.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6b9b32d5e4f0a179cef5075cc79b79d6d3482c44c434c12969e48c6719e06d95", size = 96178, upload-time = "2026-08-30T04:39:43.789Z" }, + { url = "https://files.pythonhosted.org/packages/f8/fd/b20e3cb3cab35131b515edf18e8cd777dff680fc76fc00919481f4e536af/wrapt-2.4.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d7dbbdbfdacb85c2d962fa52db791c77943fd777d600d74c95af2d53b32f5a94", size = 227806, upload-time = "2026-08-30T04:39:45.264Z" }, + { url = "https://files.pythonhosted.org/packages/08/75/c8dfba5e0caf17cd0718a0cbbe76cb85e637a2d65183fb728232419f6fca/wrapt-2.4.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:39cd68df4dff79f5336f9c745c06259d204bcb42d504040c9c91eac9e2abb39c", size = 229004, upload-time = "2026-08-30T04:39:47.068Z" }, + { url = "https://files.pythonhosted.org/packages/42/05/d4853fbd33e5860b10d5aec690f563547a92a82e61fb8bb2d4ece1ce3570/wrapt-2.4.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2a9f1a2f75bb95257cc5744e255e10a5a86e923f328b40ad3dbf9d8d03430013", size = 208934, upload-time = "2026-08-30T04:39:48.73Z" }, + { url = "https://files.pythonhosted.org/packages/a3/66/23d0e8de9b411fd198af5121627587563657370c8d509fbe5ea8adb3df79/wrapt-2.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8763ad01e3725b7751a4575f38bbcc19c0aa0822fec91c5c5bd21ce3ce7e1d2b", size = 225709, upload-time = "2026-08-30T04:39:50.287Z" }, + { url = "https://files.pythonhosted.org/packages/01/37/3b357bc90530d510ae59ae7ac48265c482ae899e47637ca4436645688b40/wrapt-2.4.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:9125c6dbe8b88c00dd8ef4fc1e55757e8eb4720b6b2b2cc610a45bd32bd28c57", size = 207090, upload-time = "2026-08-30T04:39:51.78Z" }, + { url = "https://files.pythonhosted.org/packages/6d/0c/d8a5c6dbcc2d221308223bcea4130c6332454a855cb4dbd5dcb2360b13b2/wrapt-2.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:28f5de1526831b8f173889a436e289fe181ede8c66c9feb669d1aca8fd602eaf", size = 216269, upload-time = "2026-08-30T04:39:53.641Z" }, + { url = "https://files.pythonhosted.org/packages/92/93/cc9fc8fef1d3d25edaa1c2dc2337b556dc1d0613ddc1c4a6fe9ee08ad705/wrapt-2.4.0-cp312-cp312-win32.whl", hash = "sha256:a9ca1cdb3f7facb4990c7739ea5afbaceeb6728d066feedde03a4cfe83b29b03", size = 91187, upload-time = "2026-08-30T04:39:55.38Z" }, + { url = "https://files.pythonhosted.org/packages/ad/ec/a7b10705172bdb669b9687a8ff68bbe5f566437d2a49ad6d976af48b6d10/wrapt-2.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:8b464316489fb2fca0669ea0f8f07290054a0f26fc72982d3e4cf95469628ba9", size = 96423, upload-time = "2026-08-30T04:39:56.81Z" }, + { url = "https://files.pythonhosted.org/packages/83/7a/e838ac6463a1a1a1817b2f184ee2aa20c54692b80368c5063403c8d2461c/wrapt-2.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:db1285071ea09a7767fac608e7b5c7b03c09833b06186875a359905fbc659d29", size = 93003, upload-time = "2026-08-30T04:39:58.237Z" }, + { url = "https://files.pythonhosted.org/packages/79/c8/fafe0002f572ced999c792cfe8b05d39269c63d8193d15d25bd828bcad7a/wrapt-2.4.0-py3-none-any.whl", hash = "sha256:18aabd9301d06026f5900538051773d6f87f65ae02cdc60de482df978513dc0a", size = 73713, upload-time = "2026-08-30T04:41:49.805Z" }, ] [[package]] From a062155841498c0829122e277b46b447fea9bf6c Mon Sep 17 00:00:00 2001 From: Asuka Minato Date: Wed, 9 Sep 2026 08:47:46 +0000 Subject: [PATCH 03/28] test: migrate console app response sessions and ORM models to SQLite (#40562) --- api/controllers/console/app/app.py | 97 ++--- api/services/app_dsl_service.py | 51 +++ .../console/app/test_app_response_models.py | 392 ++++++++++-------- .../console/app/test_message_api.py | 146 ++++--- .../services/test_app_dsl_service.py | 88 +++- 5 files changed, 491 insertions(+), 283 deletions(-) diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.py index a750dc4bd96..ad6961ef074 100644 --- a/api/controllers/console/app/app.py +++ b/api/controllers/console/app/app.py @@ -63,7 +63,7 @@ from services.app_service import ( ) from services.enterprise import rbac_service as enterprise_rbac_service from services.enterprise.enterprise_service import EnterpriseService -from services.entities.dsl_entities import DslImportWarning, ImportMode, ImportStatus +from services.entities.dsl_entities import DslImportWarning, ImportStatus from services.entities.knowledge_entities.knowledge_entities import ( DataSource, InfoList, @@ -972,66 +972,53 @@ class AppCopyApi(Resource): @rbac_permission_required(RBACCheck(RBACPermission.APP_CREATE_AND_MANAGEMENT, PlainApp())) @with_current_user @with_current_tenant_id + @with_session @get_app_model(mode=None) @model_validate(CopyAppPayload) - def post(self, req_data: CopyAppPayload, current_tenant_id: str, current_user: Account, app_model: App): + def post( + self, + req_data: CopyAppPayload, + session: Session, + current_tenant_id: str, + current_user: Account, + app_model: App, + ): """Copy app""" # The role of the current user in the ta table must be admin, owner, or editor - with Session(db.engine, expire_on_commit=False) as session: - import_service = AppDslService(session) - yaml_content = import_service.export_dsl(app_model=app_model, session=session, include_secret=True) - try: - result = import_service.import_app( - account=current_user, - import_mode=ImportMode.YAML_CONTENT, - yaml_content=yaml_content, - name=req_data.name, - description=req_data.description, - icon_type=req_data.icon_type, - icon=req_data.icon, - icon_background=req_data.icon_background, - ) - except NoPermissionError as e: - raise Forbidden(str(e)) - if result.status == ImportStatus.FAILED: - session.rollback() - return dump_response(AppImportResponse, result), 400 - if result.status == ImportStatus.PENDING: - session.rollback() - return dump_response(AppImportResponse, result), 202 - session.commit() - - # Inherit web app permission from original app - if result.app_id and SystemFeatureService.is_webapp_auth_enabled(): - try: - # Get the original app's access mode - original_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_model.id) - access_mode = original_settings.access_mode - except Exception: - # If original app has no settings (old app), default to public to match fallback behavior - access_mode = "public" - - # Apply the same access mode to the copied app - EnterpriseService.WebAppAuth.update_app_access_mode(result.app_id, access_mode) - - stmt = select(App).where(App.id == result.app_id) - app = session.scalar(stmt) - if not app: - raise NotFound("App not found") - - permission_keys_map = enterprise_rbac_service.RBACService.AppPermissions.batch_get( - current_tenant_id, - current_user.id, - [str(app.id)], - session=session, + import_service = AppDslService(session) + try: + result, app = import_service.copy_app( + app_model=app_model, + account=current_user, + tenant_id=current_tenant_id, + name=req_data.name, + description=req_data.description, + icon_type=req_data.icon_type, + icon=req_data.icon, + icon_background=req_data.icon_background, ) - response_model = AppDetailWithSite.model_validate( - app, - from_attributes=True, - context={"session": session}, - ).model_copy(update={"permission_keys": permission_keys_map.get(str(app.id), [])}) - return response_model.model_dump(mode="json"), 201 + except NoPermissionError as e: + raise Forbidden(str(e)) + if result.status == ImportStatus.FAILED: + return dump_response(AppImportResponse, result), 400 + if result.status == ImportStatus.PENDING: + return dump_response(AppImportResponse, result), 202 + if not app: + raise NotFound("App not found") + + permission_keys_map = enterprise_rbac_service.RBACService.AppPermissions.batch_get( + current_tenant_id, + current_user.id, + [str(app.id)], + session=session, + ) + response_model = AppDetailWithSite.model_validate( + app, + from_attributes=True, + context={"session": session}, + ).model_copy(update={"permission_keys": permission_keys_map.get(str(app.id), [])}) + return response_model.model_dump(mode="json"), 201 @console_ns.route("/apps//export") diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.py index 9bc467fcd6a..c312e6a8c2b 100644 --- a/api/services/app_dsl_service.py +++ b/api/services/app_dsl_service.py @@ -52,6 +52,7 @@ from services.agent.retirement_service import WorkflowAgentRetirementService from services.agent.workflow_publish_service import WorkflowAgentPublishService from services.dsl_content import DSL_MAX_SIZE, dsl_content_size from services.dsl_version import check_version_compatibility +from services.enterprise.enterprise_service import EnterpriseService from services.enterprise.rbac_service import RBACService from services.entities.dsl_entities import ( CheckDependenciesResult, @@ -68,6 +69,7 @@ from services.icon_configuration import ( is_valid_image_icon, ) from services.plugin.dependencies_analysis import DependenciesAnalysisService +from services.system_feature_service import SystemFeatureService from services.workflow_draft_variable_service import WorkflowDraftVariableService from services.workflow_service import WorkflowService @@ -114,6 +116,55 @@ class AppDslService: self._session = session self._warnings = [] + def copy_app( + self, + *, + app_model: App, + account: Account, + tenant_id: str, + name: str | None = None, + description: str | None = None, + icon_type: str | None = None, + icon: str | None = None, + icon_background: str | None = None, + ) -> tuple[Import, App | None]: + """Copy an app, finalizing the import before inheriting external access settings. + + Failed and pending imports roll back the current transaction. Completed + imports commit before external I/O, then load the copy in the caller's tenant. + """ + if app_model.tenant_id != tenant_id or account.current_tenant_id != tenant_id: + raise NoPermissionError("App does not belong to the current workspace") + + original_app_id = app_model.id + yaml_content = self.export_dsl(app_model=app_model, session=self._session, include_secret=True) + result = self.import_app( + account=account, + import_mode=ImportMode.YAML_CONTENT, + yaml_content=yaml_content, + name=name, + description=description, + icon_type=icon_type, + icon=icon, + icon_background=icon_background, + ) + if result.status in {ImportStatus.FAILED, ImportStatus.PENDING}: + self._session.rollback() + return result, None + self._session.commit() + + if result.app_id and SystemFeatureService.is_webapp_auth_enabled(): + try: + original_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(original_app_id) + access_mode = original_settings.access_mode + except Exception: + # Old apps without settings default to public, matching the access fallback. + access_mode = "public" + EnterpriseService.WebAppAuth.update_app_access_mode(result.app_id, access_mode) + + app = self._session.scalar(select(App).where(App.id == result.app_id, App.tenant_id == tenant_id)) + return result, app + def import_app( self, *, diff --git a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py b/api/tests/unit_tests/controllers/console/app/test_app_response_models.py index 2c7a6ca9e90..b1cfa160f60 100644 --- a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py +++ b/api/tests/unit_tests/controllers/console/app/test_app_response_models.py @@ -14,12 +14,14 @@ import pytest from flask import Flask from flask.views import MethodView from pydantic import ValidationError -from sqlalchemy.engine import Engine from sqlalchemy.orm import Session from werkzeug.datastructures import MultiDict -from models.model import App, AppMode, IconType +from models.account import Account +from models.enums import CustomizeTokenStrategy, TagType +from models.model import App, AppMode, AppModelConfig, IconType, Site, Tag, TagBinding from models.workflow import Workflow, WorkflowType +from services.app_service import RecentAppListItem # kombu references MethodView as a global when importing celery/kombu pools. if not hasattr(builtins, "MethodView"): @@ -126,6 +128,8 @@ def app_module(): "OpsTraceManager": _OpsTraceManager, "TraceQueueManager": object, "TraceTask": object, + "TracingProviderConfigEntry": dict, + "provider_config_map": {}, }, ) @@ -180,27 +184,113 @@ def _ts(hour: int = 12) -> datetime: return datetime(2024, 1, 1, hour, 0, 0) -def _dummy_model_config(): - return SimpleNamespace( - model_dict={"provider": "openai", "name": "gpt-4o"}, - pre_prompt="hello", - created_by="config-author", - created_at=_ts(9), - updated_by="config-editor", - updated_at=_ts(10), +TENANT_ID = "00000000-0000-0000-0000-000000000001" +APP_ID = "00000000-0000-0000-0000-000000000101" +ACCOUNT_ID = "00000000-0000-0000-0000-000000000201" +CONFIG_ID = "00000000-0000-0000-0000-000000000301" +WORKFLOW_ID = "00000000-0000-0000-0000-000000000401" +SITE_ID = "00000000-0000-0000-0000-000000000501" +TAG_ID = "00000000-0000-0000-0000-000000000601" + + +def _account(*, account_id: str = ACCOUNT_ID) -> Account: + account = Account(name="Creator", email=f"{account_id}@example.com") + account.id = account_id + return account + + +def _app( + *, + app_id: str = APP_ID, + tenant_id: str = TENANT_ID, + name: str = "My App", + description: str = "Summary", + mode: AppMode = AppMode.CHAT, + icon_type: IconType | None = IconType.IMAGE, + icon: str | None = "icon-key", + created_at: datetime | None = None, +) -> App: + timestamp = created_at or _ts() + return App( + id=app_id, + tenant_id=tenant_id, + name=name, + description=description, + mode=mode, + icon_type=icon_type, + icon=icon, + icon_background="#fff", + enable_site=True, + enable_api=True, + max_active_requests=0, + created_at=timestamp, + updated_at=timestamp, ) -def _dummy_workflow(): - return SimpleNamespace( - id="wf-1", - created_by="workflow-author", +def _workflow(*, app_id: str = APP_ID, tenant_id: str = TENANT_ID) -> Workflow: + return Workflow( + id=WORKFLOW_ID, + tenant_id=tenant_id, + app_id=app_id, + type=WorkflowType.CHAT, + version=Workflow.VERSION_DRAFT, + graph=json.dumps({"nodes": [], "edges": []}), + features=json.dumps({}), + created_by=ACCOUNT_ID, created_at=_ts(8), - updated_by="workflow-editor", + updated_by=ACCOUNT_ID, updated_at=_ts(9), + environment_variables=[], + conversation_variables=[], ) +def _persist_response_graph(session: Session) -> App: + app = _app(description="Description") + app.created_by = ACCOUNT_ID + app.app_model_config_id = CONFIG_ID + app.workflow_id = WORKFLOW_ID + app.access_mode = "private" + app.create_user_name = "Creator" + app.has_draft_trigger = True + app.permission_keys = ["app.acl.view_layout"] + + model_config = AppModelConfig( + app_id=APP_ID, + model=json.dumps({"provider": "openai", "name": "gpt-4o"}), + pre_prompt="hello", + created_by=ACCOUNT_ID, + updated_by=ACCOUNT_ID, + ) + model_config.id = CONFIG_ID + model_config.created_at = _ts(9) + model_config.updated_at = _ts(10) + + site = Site( + id=SITE_ID, + app_id=APP_ID, + code="site-code", + title="Public Site", + icon_type=IconType.IMAGE, + icon="site-icon", + icon_background="#fff", + description="Site description", + default_language="en-US", + input_placeholder="Ask anything", + customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW, + ) + site.created_at = _ts(14) + site.updated_at = _ts(14) + tag = Tag(tenant_id=TENANT_ID, type=TagType.APP, name="Utilities", created_by=ACCOUNT_ID) + tag.id = TAG_ID + binding = TagBinding(tenant_id=TENANT_ID, tag_id=TAG_ID, target_id=APP_ID, created_by=ACCOUNT_ID) + + session.add_all([_account(), app, model_config, _workflow(), site, tag, binding]) + session.commit() + return app + + def test_app_list_query_reads_repeated_tag_ids(app_module): first_tag_id = "8c4ef3d1-58a1-4d94-8a1c-1c171d889e08" second_tag_id = "3c39395b-6d1f-4030-8b17-eaa7cc85221c" @@ -336,175 +426,128 @@ def test_create_app_endpoint_rejects_agent_mode(app_module): app_module.CreateAppPayload.model_validate({"name": "Iris", "mode": "agent", "description": "Agent app"}) -def test_app_partial_serialization_uses_aliases(app_models): +def test_app_partial_serialization_uses_aliases(app_models, sqlite_session: Session): AppPartial = app_models.AppPartial - created_at = _ts() - app_obj = SimpleNamespace( - id="app-1", - name="My App", - desc_or_prompt="Prompt snippet", - mode_compatible_with_agent="chat", - icon_type="image", - icon="icon-key", - icon_background="#fff", - app_model_config=_dummy_model_config(), - workflow=_dummy_workflow(), - created_by="creator", - created_at=created_at, - updated_by="editor", - updated_at=created_at, - tags=[SimpleNamespace(id="tag-1", name="Utilities", type="app")], - access_mode="private", - create_user_name="Creator", - author_name="Author", - has_draft_trigger=True, - permission_keys=["app.acl.view_layout"], - role="Should stay agent-only", - ) + app_obj = _persist_response_graph(sqlite_session) + app_obj.description = "Prompt snippet" - serialized = AppPartial.model_validate(app_obj, from_attributes=True).model_dump(mode="json") + serialized = AppPartial.model_validate( + app_obj, + from_attributes=True, + context={"session": sqlite_session}, + ).model_dump(mode="json") assert serialized["description"] == "Prompt snippet" assert serialized["mode"] == "chat" assert serialized["icon_url"] == "signed:icon-key" - assert serialized["created_at"] == int(created_at.timestamp()) - assert serialized["updated_at"] == int(created_at.timestamp()) + assert serialized["created_at"] == int(app_obj.created_at.timestamp()) + assert serialized["updated_at"] == int(app_obj.updated_at.timestamp()) assert serialized["model_config"]["model"] == {"provider": "openai", "name": "gpt-4o"} - assert serialized["workflow"]["id"] == "wf-1" + assert serialized["workflow"]["id"] == WORKFLOW_ID assert serialized["tags"][0]["name"] == "Utilities" assert serialized["permission_keys"] == ["app.acl.view_layout"] assert "role" not in serialized -def test_app_detail_with_site_includes_nested_serialization(app_models): +def test_app_detail_with_site_includes_nested_serialization( + app: Flask, + app_models, + monkeypatch: pytest.MonkeyPatch, + sqlite_session: Session, +): AppDetailWithSite = app_models.AppDetailWithSite - timestamp = _ts(14) - site = SimpleNamespace( - code="site-code", - title="Public Site", - icon_type="image", - icon="site-icon", - input_placeholder="Ask anything", - created_at=timestamp, - updated_at=timestamp, - ) - app_obj = SimpleNamespace( - id="app-2", - name="Detailed App", - description="Desc", - mode_compatible_with_agent="advanced-chat", - icon_type="image", - icon="detail-icon", - icon_background="#123456", - enable_site=True, - enable_api=True, - app_model_config={ - "opening_statement": "hi", - "model": {"provider": "openai", "name": "gpt-4o"}, - "retriever_resource": {"enabled": True}, - }, - workflow=_dummy_workflow(), - tracing={"enabled": True}, - use_icon_as_answer_icon=True, - created_by="creator", - created_at=timestamp, - updated_by="editor", - updated_at=timestamp, - access_mode="public", - tags=[SimpleNamespace(id="tag-2", name="Prod", type="app")], - permission_keys=["app.acl.view_layout", "app.acl.edit"], - api_base_url="https://api.example.com/v1", - max_active_requests=5, - deleted_tools=[{"type": "api", "tool_name": "search", "provider_id": "prov"}], - site=site, - bound_agent_id="agent-1", - role="Should stay agent-only", - ) + app_obj = _persist_response_graph(sqlite_session) + app_obj.name = "Detailed App" + app_obj.description = "Desc" + app_obj.mode = AppMode.ADVANCED_CHAT + app_obj.icon = "detail-icon" + app_obj.icon_background = "#123456" + app_obj.use_icon_as_answer_icon = True + app_obj.max_active_requests = 5 + app_obj.access_mode = "public" + app_obj.permission_keys = ["app.acl.view_layout", "app.acl.edit"] + model_config = sqlite_session.get(AppModelConfig, CONFIG_ID) + assert model_config is not None + model_config.opening_statement = "hi" + model_config.retriever_resource = json.dumps({"enabled": True}) + monkeypatch.setattr("services.app_service.load_annotation_reply_config", lambda _session, _app_id: {}) - serialized = AppDetailWithSite.model_validate(app_obj, from_attributes=True).model_dump(mode="json") + with app.test_request_context("/"): + serialized = AppDetailWithSite.model_validate( + app_obj, + from_attributes=True, + context={"session": sqlite_session}, + ).model_dump(mode="json") assert serialized["icon_url"] == "signed:detail-icon" assert serialized["model_config"]["retriever_resource"] == {"enabled": True} - assert serialized["deleted_tools"][0]["tool_name"] == "search" + assert serialized["deleted_tools"] == [] assert serialized["site"]["icon_url"] == "signed:site-icon" assert serialized["site"]["input_placeholder"] == "Ask anything" - assert serialized["site"]["created_at"] == int(timestamp.timestamp()) + assert serialized["site"]["created_at"] == int(_ts(14).timestamp()) assert serialized["permission_keys"] == ["app.acl.view_layout", "app.acl.edit"] - assert serialized["bound_agent_id"] == "agent-1" + assert serialized["bound_agent_id"] is None assert "role" not in serialized def test_app_response_view_uses_the_caller_session_for_query_backed_fields( - app_module, monkeypatch, unbound_session: Session + app_module, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session ): - app_obj = MagicMock() - app_model_config = SimpleNamespace(app_id="app-1") - app_obj.desc_or_prompt_with_session.return_value = "Description" - app_obj.site_with_session.return_value = SimpleNamespace(id="site-1") - app_obj.app_model_config_with_session.return_value = app_model_config - app_obj.workflow_with_session.return_value = SimpleNamespace(id="workflow-1") - app_obj.bound_agent_id_with_session.return_value = "agent-1" - app_obj.mode_compatible_with_agent_with_session.return_value = "agent" - app_obj.deleted_tools_with_session.return_value = [] - app_obj.tags_with_session.return_value = [] - app_obj.author_name_with_session.return_value = "Author" + app_obj = _persist_response_graph(sqlite_session) + decoy_tenant_id = "00000000-0000-0000-0000-000000000002" + decoy_tag = Tag(tenant_id=decoy_tenant_id, type=TagType.APP, name="Decoy", created_by=ACCOUNT_ID) + decoy_tag.id = "00000000-0000-0000-0000-000000000602" + sqlite_session.add_all( + [ + decoy_tag, + TagBinding( + tenant_id=decoy_tenant_id, + tag_id=decoy_tag.id, + target_id=APP_ID, + created_by=ACCOUNT_ID, + ), + ] + ) + sqlite_session.commit() load_annotation_reply = MagicMock(return_value={"enabled": False}) monkeypatch.setattr("services.app_service.load_annotation_reply_config", load_annotation_reply) - view = app_module.AppResponseView(app_obj, session=unbound_session) + view = app_module.AppResponseView(app_obj, session=sqlite_session) site = view.site workflow = view.workflow model_config = view.app_model_config assert view.desc_or_prompt == "Description" assert site is not None - assert site.id == "site-1" + assert site.id == SITE_ID assert workflow is not None - assert workflow.id == "workflow-1" - assert view.bound_agent_id == "agent-1" - assert view.mode_compatible_with_agent == "agent" + assert workflow.id == WORKFLOW_ID + assert view.bound_agent_id is None + assert view.mode_compatible_with_agent == "chat" assert view.deleted_tools == [] - assert view.tags == [] - assert view.author_name == "Author" + assert [tag.name for tag in view.tags] == ["Utilities"] + assert view.author_name == "Creator" assert model_config is not None assert model_config.annotation_reply_dict == {"enabled": False} - for method in ( - app_obj.desc_or_prompt_with_session, - app_obj.site_with_session, - app_obj.app_model_config_with_session, - app_obj.workflow_with_session, - app_obj.bound_agent_id_with_session, - app_obj.mode_compatible_with_agent_with_session, - app_obj.deleted_tools_with_session, - app_obj.tags_with_session, - app_obj.author_name_with_session, - ): - method.assert_called_once_with(session=unbound_session) - load_annotation_reply.assert_called_once_with(unbound_session, "app-1") + load_annotation_reply.assert_called_once_with(sqlite_session, APP_ID) -def test_app_pagination_aliases_per_page_and_has_next(app_models): +def test_app_pagination_aliases_per_page_and_has_next(app_models, sqlite_session: Session): AppPagination = app_models.AppPagination - item_one = SimpleNamespace( - id="app-10", + item_one = _app( + app_id="00000000-0000-0000-0000-000000000110", name="Paginated One", - desc_or_prompt="Summary", - mode_compatible_with_agent="chat", - icon_type="image", icon="first-icon", created_at=_ts(15), - updated_at=_ts(15), - permission_keys=["app.acl.edit"], ) - item_two = SimpleNamespace( - id="app-11", + item_one.permission_keys = ["app.acl.edit"] + item_two = _app( + app_id="00000000-0000-0000-0000-000000000111", name="Paginated Two", - desc_or_prompt="Summary", - mode_compatible_with_agent="agent-chat", - icon_type="emoji", + mode=AppMode.AGENT_CHAT, + icon_type=IconType.EMOJI, icon="🙂", created_at=_ts(16), - updated_at=_ts(16), ) pagination = SimpleNamespace( page=2, @@ -514,7 +557,11 @@ def test_app_pagination_aliases_per_page_and_has_next(app_models): items=[item_one, item_two], ) - serialized = AppPagination.model_validate(pagination, from_attributes=True).model_dump(mode="json") + serialized = AppPagination.model_validate( + pagination, + from_attributes=True, + context={"session": sqlite_session}, + ).model_dump(mode="json") assert serialized["page"] == 2 assert serialized["limit"] == 10 @@ -529,16 +576,14 @@ def test_app_list_uses_injected_session_for_draft_workflows( app_module: ModuleType, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session, - unbound_session: Session, ) -> None: api = app_module.AppListApi() method = _unwrap(api.get) - app_item = SimpleNamespace( - id="app-1", + app_item = _app( + app_id="app-1", + tenant_id="tenant-1", name="Workflow App", - desc_or_prompt="Summary", - mode="workflow", - mode_compatible_with_agent="workflow", + mode=AppMode.WORKFLOW, ) app_pagination = SimpleNamespace(page=1, per_page=20, total=1, has_next=False, items=[app_item]) workflow = Workflow( @@ -583,8 +628,6 @@ def test_app_list_uses_injected_session_for_draft_workflows( "get", get_permissions, ) - monkeypatch.setattr(app_module, "db", SimpleNamespace(session=unbound_session)) - with app.test_request_context("/console/api/apps?page=1&limit=20", method="GET"): response, status = method("tenant-1", "user-1", sqlite_session) @@ -595,21 +638,19 @@ def test_app_list_uses_injected_session_for_draft_workflows( def test_app_create_api_attaches_permission_keys( - app, app_module, unbound_session: Session, config_overrides: Callable[..., None] + app, app_module, sqlite_session: Session, config_overrides: Callable[..., None] ): config_overrides(RBAC_ENABLED=True) method = app_module.AppListApi.post while hasattr(method, "__wrapped__"): method = method.__wrapped__ - app_obj = SimpleNamespace( - id="app-new", + app_obj = _app( + app_id="app-new", + tenant_id="tenant-1", name="Created App", description="Summary", - mode_compatible_with_agent="advanced-chat", - enable_site=True, - enable_api=True, - permission_keys=[], + mode=AppMode.ADVANCED_CHAT, ) with app.test_request_context("/apps", method="POST", json={}): @@ -642,9 +683,9 @@ def test_app_create_api_attaches_permission_keys( description="Summary", mode="advanced-chat", ), - unbound_session, + sqlite_session, "tenant-1", - SimpleNamespace(id="acct-1"), + _account(account_id="acct-1"), ) assert status == 201 @@ -659,15 +700,11 @@ def test_app_list_api_attaches_permission_keys( while hasattr(method, "__wrapped__"): method = method.__wrapped__ - app_obj = SimpleNamespace( - id="app-1", + app_obj = _app( + app_id="app-1", + tenant_id="tenant-1", name="List App", - desc_or_prompt="Summary", - mode_compatible_with_agent="chat", - mode="chat", created_at=_ts(15), - updated_at=_ts(15), - permission_keys=[], ) pagination = SimpleNamespace(page=1, per_page=20, total=1, has_next=False, items=[app_obj]) get_paginate_apps = MagicMock(return_value=pagination) @@ -725,10 +762,10 @@ def test_recent_app_list_api_returns_only_home_card_fields( while hasattr(method, "__wrapped__"): method = method.__wrapped__ - recent_app = SimpleNamespace( + recent_app = RecentAppListItem( id="app-1", name="Recent App", - icon_type="emoji", + icon_type=IconType.EMOJI, icon="🚀", icon_background="#FFFFFF", mode="chat", @@ -974,21 +1011,18 @@ def test_app_list_api_returns_no_apps_without_workspace_or_resource_view_permiss def test_app_detail_api_attaches_current_user_permission_keys( - app, app_module, unbound_session: Session, config_overrides: Callable[..., None] + app, app_module, sqlite_session: Session, config_overrides: Callable[..., None] ): config_overrides(RBAC_ENABLED=True) method = app_module.AppApi.get while hasattr(method, "__wrapped__"): method = method.__wrapped__ - app_obj = SimpleNamespace( - id="app-1", + app_obj = _app( + app_id="app-1", + tenant_id="tenant-1", name="Detail App", description="Summary", - mode_compatible_with_agent="chat", - enable_site=True, - enable_api=True, - permission_keys=[], ) with app.test_request_context("/apps/app-1"): @@ -1025,14 +1059,14 @@ def test_app_detail_api_attaches_current_user_permission_keys( resp = method( app_module.AppApi(), - unbound_session, + sqlite_session, "tenant-1", - SimpleNamespace(id="acct-1"), + _account(account_id="acct-1"), app_model=app_obj, ) - get_app.assert_called_once_with(app_obj, session=unbound_session) - get_permissions.assert_called_once_with("tenant-1", "acct-1", app_id="app-1", session=unbound_session) + get_app.assert_called_once_with(app_obj, session=sqlite_session) + get_permissions.assert_called_once_with("tenant-1", "acct-1", app_id="app-1", session=sqlite_session) assert resp["permission_keys"] == [ "app.acl.view_layout", "app.acl.edit", @@ -1045,7 +1079,6 @@ def test_app_copy_api_attaches_permission_keys( app, app_module, sqlite_session: Session, - sqlite_engine: Engine, config_overrides: Callable[..., None], ): config_overrides(RBAC_ENABLED=True) @@ -1076,8 +1109,7 @@ def test_app_copy_api_attaches_permission_keys( app_module, "AppDslService", lambda *_args, **_kwargs: SimpleNamespace( - export_dsl=lambda **_kwargs: "dsl", - import_app=lambda **_kwargs: import_result, + copy_app=lambda **_kwargs: (import_result, app_obj), ), ) monkeypatch.setattr( @@ -1085,7 +1117,6 @@ def test_app_copy_api_attaches_permission_keys( "is_webapp_auth_enabled", lambda: False, ) - monkeypatch.setattr(app_module, "db", SimpleNamespace(engine=sqlite_engine)) monkeypatch.setattr( app_module.enterprise_rbac_service.RBACService.AppPermissions, "batch_get", @@ -1095,9 +1126,10 @@ def test_app_copy_api_attaches_permission_keys( resp, status = method( app_module.AppCopyApi(), app_module.CopyAppPayload(), + sqlite_session, "tenant-1", - SimpleNamespace(id="acct-1"), - app_model=SimpleNamespace(id="app-original"), + _account(account_id="acct-1"), + app_model=_app(app_id="app-original", tenant_id="tenant-1"), ) assert status == 201 diff --git a/api/tests/unit_tests/controllers/console/app/test_message_api.py b/api/tests/unit_tests/controllers/console/app/test_message_api.py index bc797ef75e5..237f02402ab 100644 --- a/api/tests/unit_tests/controllers/console/app/test_message_api.py +++ b/api/tests/unit_tests/controllers/console/app/test_message_api.py @@ -2,7 +2,6 @@ from __future__ import annotations from datetime import UTC, datetime from inspect import unwrap -from types import SimpleNamespace from unittest.mock import MagicMock import pytest @@ -12,8 +11,37 @@ from sqlalchemy.orm import Session from controllers.console.app import message as message_module from core.app.entities.app_invoke_entities import InvokeFrom -from models.enums import ConversationFromSource -from models.model import AppMode, Conversation, Message +from models.account import Account +from models.enums import ConversationFromSource, CreatorUserRole, FeedbackFromSource, FeedbackRating +from models.model import ( + App, + AppAnnotationHitHistory, + AppMode, + Conversation, + Message, + MessageAgentThought, + MessageAnnotation, + MessageFeedback, +) + + +def _account() -> Account: + account = Account(name="Account", email="account@example.com") + account.id = "account-1" + return account + + +def _app(*, app_id: str = "app-1") -> App: + return App( + id=app_id, + tenant_id="tenant-1", + name="Chat App", + description="", + mode=AppMode.CHAT, + enable_site=True, + enable_api=True, + max_active_requests=0, + ) def _persist_message(session: Session, *, message_id: str, app_id: str = "app-1") -> Message: @@ -59,7 +87,7 @@ def _persist_message(session: Session, *, message_id: str, app_id: str = "app-1" app_mode=AppMode.CHAT, ) message.id = message_id - session.add_all([conversation, message]) + session.add_all([_account(), _app(app_id=app_id), conversation, message]) session.flush() return message @@ -68,8 +96,8 @@ def test_app_message_routes_pass_injected_session( app: Flask, monkeypatch: pytest.MonkeyPatch, unbound_session: Session ) -> None: session = unbound_session - current_user = SimpleNamespace(id="account-1") - app_model = SimpleNamespace(id="app-1", mode="chat") + current_user = _account() + app_model = _app() message_id = "550e8400-e29b-41d4-a716-446655440000" list_messages = MagicMock(return_value={"data": []}) update_feedback = MagicMock(return_value={"result": "success"}) @@ -109,10 +137,17 @@ def test_app_message_routes_pass_injected_session( def test_update_message_feedback_commits_injected_session(app: Flask, sqlite_session: Session) -> None: message_id = "550e8400-e29b-41d4-a716-446655440000" - feedback = SimpleNamespace(rating="dislike", content=None) - get_admin_feedback = MagicMock(return_value=feedback) message = _persist_message(sqlite_session, message_id=message_id) - message.admin_feedback_with_session = get_admin_feedback + feedback = MessageFeedback( + app_id=message.app_id, + conversation_id=message.conversation_id, + message_id=message.id, + rating=FeedbackRating.DISLIKE, + from_source=FeedbackFromSource.ADMIN, + from_account_id="account-1", + ) + sqlite_session.add(feedback) + sqlite_session.commit() session = sqlite_session commits: list[str] = [] event.listen(session, "after_commit", lambda _session: commits.append("commit")) @@ -125,14 +160,15 @@ def test_update_message_feedback_commits_injected_session(app: Flask, sqlite_ses content="helpful", ), session=session, - current_user=SimpleNamespace(id="account-1"), - app_model=SimpleNamespace(id="app-1"), + current_user=_account(), + app_model=_app(), ) assert result == {"result": "success"} - assert feedback.rating == "like" - assert feedback.content == "helpful" - get_admin_feedback.assert_called_once_with(session=session) + updated_feedback = sqlite_session.get(MessageFeedback, feedback.id) + assert updated_feedback is not None + assert updated_feedback.rating == FeedbackRating.LIKE + assert updated_feedback.content == "helpful" assert commits == ["commit"] @@ -148,7 +184,7 @@ def test_get_message_detail_uses_injected_session(monkeypatch: pytest.MonkeyPatc result = message_module._get_message_detail( session=session, - app_model=SimpleNamespace(id="app-1"), + app_model=_app(), message_id=message_id, ) @@ -156,48 +192,64 @@ def test_get_message_detail_uses_injected_session(monkeypatch: pytest.MonkeyPatc response_source_factory.assert_called_once_with(message, session=session) -def test_message_response_source_uses_caller_session_for_nested_fields(unbound_session: Session) -> None: - session = unbound_session - account = object() - feedback = MagicMock() - feedback.from_account_with_session.return_value = account - annotation = MagicMock() - annotation.account_with_session.return_value = account - annotation.annotation_create_account_with_session.return_value = account - thought = object() - message_file = {"id": "file-1"} - message = MagicMock() - message.inputs_with_session.return_value = {"topic": "support"} - message.user_feedback_with_session.return_value = feedback - message.feedbacks_with_session.return_value = [feedback] - message.annotation_with_session.return_value = annotation - message.annotation_hit_history_with_session.return_value = annotation - message.agent_thoughts_with_session.return_value = [thought] - message.message_files_with_session.return_value = [message_file] +def test_message_response_source_uses_caller_session_for_nested_fields(sqlite_session: Session) -> None: + session = sqlite_session + message_id = "550e8400-e29b-41d4-a716-446655440000" + message = _persist_message(sqlite_session, message_id=message_id) + message.inputs = {"topic": "support"} + feedback = MessageFeedback( + app_id=message.app_id, + conversation_id=message.conversation_id, + message_id=message.id, + rating=FeedbackRating.LIKE, + from_source=FeedbackFromSource.USER, + from_account_id="account-1", + ) + annotation = MessageAnnotation( + app_id=message.app_id, + question="Question", + content="Answer", + account_id="account-1", + conversation_id=message.conversation_id, + message_id=message.id, + ) + annotation.id = "annotation-1" + annotation_hit = AppAnnotationHitHistory( + app_id=message.app_id, + annotation_id=annotation.id, + source="annotation", + question="Question", + account_id="account-1", + score=0.0, + message_id=message.id, + annotation_question="Question", + annotation_content="Answer", + ) + thought = MessageAgentThought( + message_id=message.id, + position=1, + created_by_role=CreatorUserRole.ACCOUNT, + created_by="account-1", + thought="Consider the request", + tool_labels_str="{}", + tool_meta_str="{}", + ) + sqlite_session.add_all([feedback, annotation, annotation_hit, thought]) + sqlite_session.commit() source = message_module.MessageResponseSource(message, session=session) assert source.inputs == {"topic": "support"} assert source.user_feedback is feedback - assert source.feedbacks[0].from_account is account + assert source.feedbacks[0].from_account.id == "account-1" annotation_source = source.annotation assert annotation_source is not None - assert annotation_source.account is account + assert annotation_source.account.id == "account-1" annotation_hit_history_source = source.annotation_hit_history assert annotation_hit_history_source is not None - assert annotation_hit_history_source.annotation_create_account is account + assert annotation_hit_history_source.annotation_create_account.id == "account-1" assert source.agent_thoughts == [thought] - assert source.message_files == [message_file] - message.inputs_with_session.assert_called_once_with(session=session) - message.user_feedback_with_session.assert_called_once_with(session=session) - message.feedbacks_with_session.assert_called_once_with(session=session) - message.annotation_with_session.assert_called_once_with(session=session) - message.annotation_hit_history_with_session.assert_called_once_with(session=session) - message.agent_thoughts_with_session.assert_called_once_with(session=session) - message.message_files_with_session.assert_called_once_with(session=session) - feedback.from_account_with_session.assert_called_once_with(session=session) - annotation.account_with_session.assert_called_once_with(session=session) - annotation.annotation_create_account_with_session.assert_called_once_with(session=session) + assert source.message_files == [] def test_chat_messages_query_valid(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py index d736e14bbc4..b4cbd5cfb46 100644 --- a/api/tests/unit_tests/services/test_app_dsl_service.py +++ b/api/tests/unit_tests/services/test_app_dsl_service.py @@ -14,10 +14,12 @@ from core.workflow.llm_environment_variable import LLMEnvironmentVariable from models import Account, App, AppMode, Tenant from models.model import AppModelConfig, AppModelConfigDict, IconType from models.workflow import Workflow, WorkflowType -from services.app_dsl_service import AppDslService, PendingData +from services.app_dsl_service import AppDslService, Import, PendingData +from services.enterprise.enterprise_service import EnterpriseService from services.entities.dsl_entities import ImportStatus from services.errors.account import NoPermissionError from services.errors.app import WorkflowNotFoundError +from services.system_feature_service import SystemFeatureService from tests.unit_tests.config_override import apply_config_overrides _OVERWRITE_APP_ID = "11111111-1111-4111-8111-111111111111" @@ -105,6 +107,90 @@ def _workflow( return workflow +@pytest.mark.parametrize("status", [ImportStatus.FAILED, ImportStatus.PENDING]) +def test_copy_app_rolls_back_incomplete_import( + sqlite_session: Session, monkeypatch: pytest.MonkeyPatch, status: ImportStatus +) -> None: + original = _persist_overwrite_target(sqlite_session) + service = AppDslService(sqlite_session) + monkeypatch.setattr(service, "export_dsl", Mock(return_value="dsl")) + + def import_app(**_kwargs: object) -> Import: + original.name = "Uncommitted change" + sqlite_session.flush() + return Import(id="import-1", status=status) + + monkeypatch.setattr(service, "import_app", import_app) + auth_enabled = Mock() + monkeypatch.setattr(SystemFeatureService, "is_webapp_auth_enabled", auth_enabled) + + result, copied = service.copy_app(app_model=original, account=_account(tenant_id=_TENANT_ID), tenant_id=_TENANT_ID) + + assert result.status == status + assert copied is None + assert original.name == "Target" + auth_enabled.assert_not_called() + + +@pytest.mark.parametrize("status", [ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS]) +@pytest.mark.parametrize("missing_settings", [False, True]) +def test_copy_app_commits_before_inheriting_access( + sqlite_session: Session, monkeypatch: pytest.MonkeyPatch, status: ImportStatus, missing_settings: bool +) -> None: + original = _persist_overwrite_target(sqlite_session) + service = AppDslService(sqlite_session) + monkeypatch.setattr(service, "export_dsl", Mock(return_value="dsl")) + copied_id = "55555555-5555-4555-8555-555555555555" + + def import_app(**_kwargs: object) -> Import: + sqlite_session.add(_app(app_id=copied_id, tenant_id=_TENANT_ID)) + return Import(id="import-1", status=status, app_id=copied_id) + + def get_access_mode(app_id: str) -> SimpleNamespace: + assert not sqlite_session.in_transaction() + assert app_id == _OVERWRITE_APP_ID + if missing_settings: + raise ValueError("No settings") + return SimpleNamespace(access_mode="private") + + def update_access_mode(app_id: str, access_mode: str) -> None: + assert not sqlite_session.in_transaction() + assert app_id == copied_id + assert access_mode == ("public" if missing_settings else "private") + + monkeypatch.setattr(service, "import_app", import_app) + monkeypatch.setattr(SystemFeatureService, "is_webapp_auth_enabled", lambda: True) + monkeypatch.setattr(EnterpriseService.WebAppAuth, "get_app_access_mode_by_id", get_access_mode) + update_access = Mock(side_effect=update_access_mode) + monkeypatch.setattr(EnterpriseService.WebAppAuth, "update_app_access_mode", update_access) + + result, copied = service.copy_app(app_model=original, account=_account(tenant_id=_TENANT_ID), tenant_id=_TENANT_ID) + + assert result.status == status + assert copied is not None + assert copied.id == copied_id + update_access.assert_called_once() + + +def test_copy_app_scopes_result_to_current_tenant(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> None: + original = _persist_overwrite_target(sqlite_session) + foreign_app = _app(tenant_id="66666666-6666-4666-8666-666666666666", app_id=_OTHER_ACCOUNT_ID) + sqlite_session.add(foreign_app) + sqlite_session.commit() + service = AppDslService(sqlite_session) + monkeypatch.setattr(service, "export_dsl", Mock(return_value="dsl")) + monkeypatch.setattr( + service, + "import_app", + Mock(return_value=Import(id="import-1", status=ImportStatus.COMPLETED, app_id=foreign_app.id)), + ) + monkeypatch.setattr(SystemFeatureService, "is_webapp_auth_enabled", lambda: False) + + _, copied = service.copy_app(app_model=original, account=_account(tenant_id=_TENANT_ID), tenant_id=_TENANT_ID) + + assert copied is None + + def test_extract_workflow_dependencies_uses_llm_environment_variable_provider(monkeypatch: pytest.MonkeyPatch) -> None: workflow = _workflow( graph={ From f71047f31a30b6eb9a4d0196137aff0698943b89 Mon Sep 17 00:00:00 2001 From: Asuka Minato Date: Wed, 9 Sep 2026 08:50:02 +0000 Subject: [PATCH 04/28] test: migrate console workflow sessions and ORM models to SQLite (#40563) Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- api/controllers/console/app/workflow.py | 42 +-- .../console/app/workflow_trigger.py | 84 ++--- .../controllers/console/app/test_app_apis.py | 7 +- .../controllers/console/app/test_workflow.py | 319 ++++++++++-------- .../console/app/test_workflow_trigger_api.py | 34 +- 5 files changed, 263 insertions(+), 223 deletions(-) diff --git a/api/controllers/console/app/workflow.py b/api/controllers/console/app/workflow.py index 23cc11b8282..0597a4c2222 100644 --- a/api/controllers/console/app/workflow.py +++ b/api/controllers/console/app/workflow.py @@ -586,14 +586,14 @@ class DraftWorkflowApi(Resource): @account_initialization_required @edit_permission_required @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) + @with_session(write=False) @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) - def get(self, app_model: App): + def get(self, session: Session, app_model: App): """ Get draft workflow """ # fetch draft workflow by app_model workflow_service = WorkflowService() - session = db.session() workflow = workflow_service.get_draft_workflow(app_model=app_model, session=session) if not workflow: @@ -1489,11 +1489,12 @@ class PublishedAllWorkflowApi(Resource): @login_required @account_initialization_required @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) - @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @with_current_user @edit_permission_required + @with_session(write=False) + @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW]) @model_validate(WorkflowListQuery) - def get(self, args: WorkflowListQuery, current_user: Account, app_model: App): + def get(self, args: WorkflowListQuery, session: Session, current_user: Account, app_model: App): """ Get published workflows """ @@ -1508,23 +1509,22 @@ class PublishedAllWorkflowApi(Resource): raise Forbidden() workflow_service = WorkflowService() - with sessionmaker(db.engine).begin() as session: - workflows, has_more = workflow_service.get_all_published_workflow( - session=session, - app_model=app_model, - page=page, - limit=limit, - user_id=user_id, - named_only=named_only, - ) - return WorkflowPaginationResponse.model_validate( - { - "items": [WorkflowResponseSource(workflow, session=session) for workflow in workflows], - "page": page, - "limit": limit, - "has_more": has_more, - } - ).model_dump(mode="json") + workflows, has_more = workflow_service.get_all_published_workflow( + session=session, + app_model=app_model, + page=page, + limit=limit, + user_id=user_id, + named_only=named_only, + ) + return WorkflowPaginationResponse.model_validate( + { + "items": [WorkflowResponseSource(workflow, session=session) for workflow in workflows], + "page": page, + "limit": limit, + "has_more": has_more, + } + ).model_dump(mode="json") @console_ns.route("/apps//workflows//restore") diff --git a/api/controllers/console/app/workflow_trigger.py b/api/controllers/console/app/workflow_trigger.py index 98260b3734d..9e33e0a01ae 100644 --- a/api/controllers/console/app/workflow_trigger.py +++ b/api/controllers/console/app/workflow_trigger.py @@ -4,13 +4,13 @@ from datetime import datetime from flask_restx import Resource from pydantic import BaseModel, field_validator from sqlalchemy import select -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import Session from werkzeug.exceptions import NotFound from configs import dify_config from controllers.common.rbac import PlainApp, RBACCheck from controllers.common.schema import query_params_from_model, register_schema_models -from extensions.ext_database import db +from controllers.common.session import with_session from fields.base import ResponseModel from libs.helper import dump_response from libs.login import login_required @@ -101,28 +101,28 @@ class WebhookTriggerApi(Resource): @account_initialization_required @console_ns.response(200, "Success", console_ns.models[WebhookTriggerResponse.__name__]) @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) + @with_session(write=False) @get_app_model(mode=AppMode.WORKFLOW) @model_validate(Parser) - def get(self, req_data: Parser, app_model: App): + def get(self, req_data: Parser, session: Session, app_model: App): """Get webhook trigger for a node""" node_id = req_data.node_id - with sessionmaker(db.engine, expire_on_commit=False).begin() as session: - # Get webhook trigger for this app and node - webhook_trigger = session.scalar( - select(WorkflowWebhookTrigger) - .where( - WorkflowWebhookTrigger.app_id == app_model.id, - WorkflowWebhookTrigger.node_id == node_id, - ) - .limit(1) + # Get webhook trigger for this app and node + webhook_trigger = session.scalar( + select(WorkflowWebhookTrigger) + .where( + WorkflowWebhookTrigger.app_id == app_model.id, + WorkflowWebhookTrigger.node_id == node_id, ) + .limit(1) + ) - if not webhook_trigger: - raise NotFound("Webhook trigger not found for this node") + if not webhook_trigger: + raise NotFound("Webhook trigger not found for this node") - return dump_response(WebhookTriggerResponse, webhook_trigger) + return dump_response(WebhookTriggerResponse, webhook_trigger) @console_ns.route("/apps//triggers") @@ -135,23 +135,23 @@ class AppTriggersApi(Resource): @console_ns.response(200, "Success", console_ns.models[WorkflowTriggerListResponse.__name__]) @with_current_tenant_id @rbac_permission_required(RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())) + @with_session(write=False) @get_app_model(mode=AppMode.WORKFLOW) - def get(self, current_tenant_id: str, app_model: App): + def get(self, session: Session, current_tenant_id: str, app_model: App): """Get app triggers list""" - with sessionmaker(db.engine, expire_on_commit=False).begin() as session: - # Get all triggers for this app using select API - triggers = ( - session.execute( - select(AppTrigger) - .where( - AppTrigger.tenant_id == current_tenant_id, - AppTrigger.app_id == app_model.id, - ) - .order_by(AppTrigger.created_at.desc(), AppTrigger.id.desc()) + # Get all triggers for this app using select API + triggers = ( + session.execute( + select(AppTrigger) + .where( + AppTrigger.tenant_id == current_tenant_id, + AppTrigger.app_id == app_model.id, ) - .scalars() - .all() + .order_by(AppTrigger.created_at.desc(), AppTrigger.id.desc()) ) + .scalars() + .all() + ) # Add computed icon field for each trigger url_prefix = dify_config.CONSOLE_API_URL + "/console/api/workspaces/current/tool-provider/builtin/" @@ -174,27 +174,27 @@ class AppTriggerEnableApi(Resource): @rbac_permission_required(RBACCheck(RBACPermission.APP_EDIT, PlainApp())) @console_ns.response(200, "Success", console_ns.models[WorkflowTriggerResponse.__name__]) @with_current_tenant_id + @with_session @get_app_model(mode=AppMode.WORKFLOW) @model_validate(ParserEnable) - def post(self, req_data: ParserEnable, current_tenant_id: str, app_model: App): + def post(self, req_data: ParserEnable, session: Session, current_tenant_id: str, app_model: App): """Update app trigger (enable/disable)""" trigger_id = req_data.trigger_id - with sessionmaker(db.engine, expire_on_commit=False).begin() as session: - # Find the trigger using select - trigger = session.execute( - select(AppTrigger).where( - AppTrigger.id == trigger_id, - AppTrigger.tenant_id == current_tenant_id, - AppTrigger.app_id == app_model.id, - ) - ).scalar_one_or_none() + # Find the trigger using select + trigger = session.execute( + select(AppTrigger).where( + AppTrigger.id == trigger_id, + AppTrigger.tenant_id == current_tenant_id, + AppTrigger.app_id == app_model.id, + ) + ).scalar_one_or_none() - if not trigger: - raise NotFound("Trigger not found") + if not trigger: + raise NotFound("Trigger not found") - # Update status based on enable_trigger boolean - trigger.status = AppTriggerStatus.ENABLED if req_data.enable_trigger else AppTriggerStatus.DISABLED + # Update status based on enable_trigger boolean + trigger.status = AppTriggerStatus.ENABLED if req_data.enable_trigger else AppTriggerStatus.DISABLED # Add computed icon field url_prefix = dify_config.CONSOLE_API_URL + "/console/api/workspaces/current/tool-provider/builtin/" diff --git a/api/tests/unit_tests/controllers/console/app/test_app_apis.py b/api/tests/unit_tests/controllers/console/app/test_app_apis.py index 461afa9efd4..263f1d4d4dd 100644 --- a/api/tests/unit_tests/controllers/console/app/test_app_apis.py +++ b/api/tests/unit_tests/controllers/console/app/test_app_apis.py @@ -920,6 +920,7 @@ class TestWorkflowTriggerEndpoints: def test_webhook_trigger_api_get( self, database_app: Flask, + sqlite_session: Session, ) -> None: api = workflow_trigger_module.WebhookTriggerApi() method = unwrap(api.get) @@ -930,11 +931,11 @@ class TestWorkflowTriggerEndpoints: webhook_id="webhook-1", created_by=USER_ID, ) - db.session.add(trigger) - db.session.commit() + sqlite_session.add(trigger) + sqlite_session.commit() with database_app.test_request_context("/?node_id=node-1"): - result = method(api, Parser(node_id="node-1"), app_model=_make_app()) + result = method(api, Parser(node_id="node-1"), sqlite_session, app_model=_make_app()) assert isinstance(result, dict) assert {"id", "webhook_id", "webhook_url", "webhook_debug_url", "node_id", "created_at"} <= set(result.keys()) diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow.py b/api/tests/unit_tests/controllers/console/app/test_workflow.py index 5a5bf81336d..c55a923b22f 100644 --- a/api/tests/unit_tests/controllers/console/app/test_workflow.py +++ b/api/tests/unit_tests/controllers/console/app/test_workflow.py @@ -5,13 +5,11 @@ import json from contextlib import contextmanager, nullcontext from datetime import datetime from types import SimpleNamespace -from typing import cast from unittest.mock import Mock import pytest from flask import Flask from pydantic import ValidationError -from sqlalchemy import Engine from sqlalchemy.orm import Session from werkzeug.exceptions import HTTPException, NotFound @@ -22,65 +20,117 @@ from core.workflow.llm_environment_variable import LLMEnvironmentVariable from graphon.file import File, FileTransferMethod, FileType from graphon.variables import SecretVariable, StringVariable from graphon.variables.variables import RAGPipelineVariable +from models.account import Account +from models.model import App, AppMode +from models.workflow import Workflow, WorkflowType from tests.unit_tests.config_override import apply_config_overrides -def _make_workflow(**overrides): - workflow = SimpleNamespace( - id="workflow-1", - graph_dict={"nodes": [], "edges": []}, - features_dict={"file_upload": {"enabled": False}}, - unique_hash="hash-1", - version="1", - marked_name="Release 1", - marked_comment="Initial release", - created_by_account=SimpleNamespace(id="user-1", name="Alice", email="alice@example.com"), - created_at=datetime(2024, 1, 1, 12, 0, 0), - updated_by_account=None, - updated_at=datetime(2024, 1, 1, 12, 1, 0), - tool_published=False, - environment_variables=[ - { - "id": "env-1", - "name": "API_KEY", - "value": "[__HIDDEN__]", - "value_type": "secret", - "description": "API key", - } - ], - conversation_variables=[ - { - "id": "conv-1", - "name": "topic", - "value": "hello", - "value_type": "string", - "description": "Topic", - } - ], - rag_pipeline_variables=[ - { - "variable": "query", - "type": "text-input", - "label": "Query", - "belong_to_node_id": "shared", - "max_length": 0, - "required": False, - "unit": "", - "default_value": "", - "options": [], - "placeholder": "", - "tooltips": "", - "allowed_file_types": ["custom"], - "allowed_file_extensions": [".pdf"], - "allowed_file_upload_methods": ["local_file"], - } +@pytest.fixture(autouse=True) +def _identity_workflow_encryption(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep variable serialization focused on ORM behavior, not the external key provider.""" + + monkeypatch.setattr(workflow_module.encrypter, "encrypt_token", lambda *, tenant_id, token: token) + monkeypatch.setattr(workflow_module.encrypter, "decrypt_token", lambda *, tenant_id, token: token) + + +def _account() -> Account: + account = Account(name="Alice", email="alice@example.com") + account.id = "user-1" + return account + + +def _app(*, app_id: str = "app", tenant_id: str = "t1") -> App: + return App( + id=app_id, + tenant_id=tenant_id, + name="Workflow App", + description="", + mode=AppMode.WORKFLOW, + enable_site=True, + enable_api=True, + max_active_requests=0, + ) + + +def _make_workflow(**overrides) -> Workflow: + graph = overrides.pop("graph_dict", {"nodes": [], "edges": []}) + features = overrides.pop("features_dict", {"file_upload": {"enabled": False}}) + environment_variables = overrides.pop( + "environment_variables", + [ + SecretVariable( + id="env-1", + name="API_KEY", + value="plain-token", + selector=["env", "API_KEY"], + description="API key", + ) ], ) + conversation_variables = overrides.pop( + "conversation_variables", + [ + StringVariable( + id="conv-1", + name="topic", + value="hello", + selector=["conversation", "topic"], + description="Topic", + ) + ], + ) + rag_pipeline_variables = overrides.pop( + "rag_pipeline_variables", + [ + RAGPipelineVariable.model_validate( + { + "variable": "query", + "type": "text-input", + "label": "Query", + "belong_to_node_id": "shared", + "max_length": 0, + "required": False, + "unit": "", + "default_value": "", + "options": [], + "placeholder": "", + "tooltips": "", + "allowed_file_types": ["custom"], + "allowed_file_extensions": [".pdf"], + "allowed_file_upload_methods": ["local_file"], + } + ) + ], + ) + workflow = Workflow( + id="workflow-1", + tenant_id="t1", + app_id="app", + type=WorkflowType.WORKFLOW, + version="1", + graph=json.dumps(graph), + features=json.dumps(features), + marked_name="Release 1", + marked_comment="Initial release", + created_by="user-1", + created_at=datetime(2024, 1, 1, 12, 0, 0), + updated_by=None, + updated_at=datetime(2024, 1, 1, 12, 1, 0), + environment_variables=[], + conversation_variables=[], + rag_pipeline_variables=[], + ) + if environment_variables and isinstance(environment_variables[0], dict): + workflow._environment_variables = json.dumps( + {str(index): value for index, value in enumerate(environment_variables)} + ) + else: + workflow.environment_variables = environment_variables + workflow.conversation_variables = conversation_variables + workflow.rag_pipeline_variables = rag_pipeline_variables for key, value in overrides.items(): setattr(workflow, key, value) - workflow.get_created_by_account = Mock(return_value=workflow.created_by_account) - workflow.get_updated_by_account = Mock(return_value=workflow.updated_by_account) - workflow.get_tool_published = Mock(return_value=workflow.tool_published) return workflow @@ -180,9 +230,9 @@ def test_delete_workflow_retires_candidates_only_after_transaction_exit( def test_parse_file_no_config(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(workflow_module.FileUploadConfigManager, "convert", lambda *_args, **_kwargs: None) - workflow = SimpleNamespace(features_dict={}, tenant_id="t1") + workflow = _make_workflow(features_dict={}) - assert workflow_module._parse_file(cast(workflow_module.Workflow, workflow), files=[{"id": "f"}]) == [] + assert workflow_module._parse_file(workflow, files=[{"id": "f"}]) == [] def test_parse_file_with_config(monkeypatch: pytest.MonkeyPatch) -> None: @@ -199,8 +249,8 @@ def test_parse_file_with_config(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(workflow_module.FileUploadConfigManager, "convert", lambda *_args, **_kwargs: config) monkeypatch.setattr(workflow_module.file_factory, "build_from_mappings", build_mock) - workflow = SimpleNamespace(features_dict={}, tenant_id="t1") - result = workflow_module._parse_file(cast(workflow_module.Workflow, workflow), files=[{"id": "f"}]) + workflow = _make_workflow(features_dict={}) + result = workflow_module._parse_file(workflow, files=[{"id": "f"}]) assert result == file_list build_mock.assert_called_once() @@ -212,7 +262,7 @@ def test_sync_draft_workflow_invalid_content_type(app: Flask, monkeypatch: pytes with app.test_request_context("/apps/app/workflows/draft", method="POST", data="x", content_type="text/html"): with pytest.raises(HTTPException) as exc: - handler(api, "t1", app_model=SimpleNamespace(id="app")) + handler(api, _account(), app_model=_app()) assert exc.value.code == 415 @@ -227,18 +277,14 @@ def test_sync_draft_workflow_invalid_json(app: Flask, monkeypatch: pytest.Monkey data="[]", content_type="application/json", ): - response, status = handler(api, "t1", app_model=SimpleNamespace(id="app")) + response, status = handler(api, _account(), app_model=_app()) assert status == 400 assert response["message"] == "Invalid JSON data" def test_sync_draft_workflow_success(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: - workflow = SimpleNamespace( - unique_hash="h", - updated_at=None, - created_at=datetime(2024, 1, 1), - ) + workflow = _make_workflow(updated_at=None, created_at=datetime(2024, 1, 1)) monkeypatch.setattr( workflow_module.variable_factory, "build_environment_variable_from_mapping", lambda *_args: "env" @@ -259,7 +305,7 @@ def test_sync_draft_workflow_success(app: Flask, monkeypatch: pytest.MonkeyPatch method="POST", json={"graph": {}, "features": {}, "hash": "h"}, ): - response = handler(api, "t1", app_model=SimpleNamespace(id="app")) + response = handler(api, _account(), app_model=_app()) assert response["result"] == "success" assert sync_draft_workflow.call_args.kwargs["environment_variables"] == [] @@ -267,11 +313,7 @@ def test_sync_draft_workflow_success(app: Flask, monkeypatch: pytest.MonkeyPatch def test_sync_draft_workflow_passes_environment_patch(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: - workflow = SimpleNamespace( - unique_hash="next-hash", - updated_at=None, - created_at=datetime(2024, 1, 1), - ) + workflow = _make_workflow(updated_at=None, created_at=datetime(2024, 1, 1)) patched_variable = StringVariable( id="env-model", name="shared_model", @@ -313,7 +355,7 @@ def test_sync_draft_workflow_passes_environment_patch(app: Flask, monkeypatch: p }, }, ): - response = handler(api, "t1", app_model=SimpleNamespace(id="app")) + response = handler(api, _account(), app_model=_app()) assert response["result"] == "success" assert sync_draft_workflow.call_args.kwargs["preserve_environment_variables"] is True @@ -364,7 +406,7 @@ def test_sync_draft_workflow_hash_mismatch(app: Flask, monkeypatch: pytest.Monke json={"graph": {}, "features": {}, "hash": "h"}, ): with pytest.raises(DraftWorkflowNotSync): - handler(api, "t1", app_model=SimpleNamespace(id="app")) + handler(api, _account(), app_model=_app()) def test_sync_draft_workflow_variable_validation_error(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: @@ -385,18 +427,13 @@ def test_sync_draft_workflow_variable_validation_error(app: Flask, monkeypatch: json={"graph": {}, "features": {}, "hash": "h", "conversation_variables": [{"name": "topic"}]}, ): with pytest.raises(InvalidArgumentError) as exc: - handler(api, "t1", app_model=SimpleNamespace(id="app")) + handler(api, _account(), app_model=_app()) assert exc.value.description == "description too long" def test_restore_published_workflow_to_draft_success(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: - workflow = SimpleNamespace( - unique_hash="restored-hash", - updated_at=None, - created_at=datetime(2024, 1, 1), - ) - user = SimpleNamespace(id="account-1") + workflow = _make_workflow(updated_at=None, created_at=datetime(2024, 1, 1)) monkeypatch.setattr( workflow_module, @@ -413,13 +450,13 @@ def test_restore_published_workflow_to_draft_success(app: Flask, monkeypatch: py ): response = handler( api, - "t1", - app_model=SimpleNamespace(id="app", tenant_id="tenant-1"), + _account(), + app_model=_app(tenant_id="tenant-1"), workflow_id="published-workflow", ) assert response["result"] == "success" - assert response["hash"] == "restored-hash" + assert response["hash"] == workflow.unique_hash def test_restore_published_workflow_to_draft_not_found(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: @@ -443,8 +480,8 @@ def test_restore_published_workflow_to_draft_not_found(app: Flask, monkeypatch: with pytest.raises(NotFound): handler( api, - "t1", - app_model=SimpleNamespace(id="app", tenant_id="tenant-1"), + _account(), + app_model=_app(tenant_id="tenant-1"), workflow_id="published-workflow", ) @@ -475,8 +512,8 @@ def test_restore_published_workflow_to_draft_returns_400_for_draft_source( with pytest.raises(HTTPException) as exc: handler( api, - "t1", - app_model=SimpleNamespace(id="app", tenant_id="tenant-1"), + _account(), + app_model=_app(tenant_id="tenant-1"), workflow_id="draft-workflow", ) @@ -507,8 +544,8 @@ def test_restore_published_workflow_to_draft_returns_400_for_invalid_structure( with pytest.raises(HTTPException) as exc: handler( api, - "t1", - app_model=SimpleNamespace(id="app", tenant_id="tenant-1"), + _account(), + app_model=_app(tenant_id="tenant-1"), workflow_id="published-workflow", ) @@ -516,31 +553,19 @@ def test_restore_published_workflow_to_draft_returns_400_for_invalid_structure( assert exc.value.description == "invalid workflow graph" -def test_get_published_workflows_serializes_items_before_session_closes( - app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine +def test_get_published_workflows_uses_the_request_session( + app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session ) -> None: api = workflow_module.PublishedAllWorkflowApi() handler = inspect.unwrap(api.get) - - base_workflow = _make_workflow() - - class _Workflow: - def __init__(self, session: Session) -> None: - self._session = session - - def __getattr__(self, name): - return getattr(base_workflow, name) - - @property - def id(self): - assert self._session.in_transaction() - return "w1" + workflow = _make_workflow() + sqlite_session.add_all([_account(), workflow]) + sqlite_session.commit() def get_all_published_workflow(*, session: Session, **_kwargs): - assert isinstance(session, Session) - return [_Workflow(session)], False + assert session is sqlite_session + return [workflow], False - monkeypatch.setattr(workflow_module, "db", SimpleNamespace(engine=sqlite_engine)) monkeypatch.setattr( workflow_module, "WorkflowService", @@ -555,16 +580,18 @@ def test_get_published_workflows_serializes_items_before_session_closes( query = workflow_module.WorkflowListQuery.model_validate( {"page": "1", "limit": "10", "user_id": "", "named_only": "false"} ) - response = handler(api, query, "t1", app_model=SimpleNamespace(id="app", workflow_id="wf-1")) + response = handler(api, query, sqlite_session, _account(), app_model=_app()) - assert response["items"][0]["id"] == "w1" + assert response["items"][0]["id"] == "workflow-1" assert response["page"] == 1 assert response["limit"] == 10 assert response["has_more"] is False -def test_draft_workflow_get_serializes_response_model(monkeypatch: pytest.MonkeyPatch) -> None: +def test_draft_workflow_get_serializes_response_model(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None: workflow = _make_workflow() + sqlite_session.add_all([_account(), workflow]) + sqlite_session.commit() monkeypatch.setattr( workflow_module, "WorkflowService", lambda: SimpleNamespace(get_draft_workflow=lambda **_kwargs: workflow) ) @@ -572,12 +599,12 @@ def test_draft_workflow_get_serializes_response_model(monkeypatch: pytest.Monkey api = workflow_module.DraftWorkflowApi() handler = inspect.unwrap(api.get) - response = handler(api, app_model=SimpleNamespace(id="app")) + response = handler(api, sqlite_session, app_model=_app()) assert response["id"] == "workflow-1" assert response["graph"] == {"nodes": [], "edges": []} assert response["features"] == {"file_upload": {"enabled": False}} - assert response["hash"] == "hash-1" + assert response["hash"] == workflow.unique_hash assert response["created_by"] == {"id": "user-1", "name": "Alice", "email": "alice@example.com"} assert response["updated_by"] is None assert response["created_at"] == int(datetime(2024, 1, 1, 12, 0, 0).timestamp()) @@ -586,7 +613,7 @@ def test_draft_workflow_get_serializes_response_model(monkeypatch: pytest.Monkey { "id": "env-1", "name": "API_KEY", - "value": "[__HIDDEN__]", + "value": workflow_module.encrypter.full_mask_token(), "value_type": "secret", "description": "API key", } @@ -620,10 +647,13 @@ def test_draft_workflow_get_serializes_response_model(monkeypatch: pytest.Monkey ] -def test_published_workflow_get_uses_session_aware_response_source(monkeypatch: pytest.MonkeyPatch) -> None: +def test_published_workflow_get_uses_session_aware_response_source( + monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +) -> None: + sqlite_session.add(_account()) + sqlite_session.commit() workflow = _make_workflow() - session = Mock(spec=Session) - monkeypatch.setattr(workflow_module, "db", SimpleNamespace(session=Mock(return_value=session))) + monkeypatch.setattr(workflow_module.db, "session", lambda: sqlite_session) monkeypatch.setattr( workflow_module, "WorkflowService", lambda: SimpleNamespace(get_published_workflow=lambda **_kwargs: workflow) ) @@ -634,9 +664,9 @@ def test_published_workflow_get_uses_session_aware_response_source(monkeypatch: response = handler(api, app_model=SimpleNamespace(id="app")) assert response["id"] == "workflow-1" - workflow.get_created_by_account.assert_called_once_with(session=session) - workflow.get_updated_by_account.assert_called_once_with(session=session) - workflow.get_tool_published.assert_called_once_with(session=session) + assert response["created_by"] == {"id": "user-1", "name": "Alice", "email": "alice@example.com"} + assert response["updated_by"] is None + assert response["tool_published"] is False def test_pipeline_variable_response_accepts_legacy_file_field_names() -> None: @@ -690,15 +720,20 @@ def test_pipeline_variable_response_accepts_explicit_null_optional_fields() -> N assert response["allowed_file_upload_methods"] is None -def test_workflow_response_masks_secret_environment_variables() -> None: +def test_workflow_response_masks_secret_environment_variables(sqlite_session: Session) -> None: workflow = _make_workflow( environment_variables=[ SecretVariable(id="env-secret", name="API_KEY", value="plain-token", selector=["env", "API_KEY"]), StringVariable(id="env-string", name="REGION", value="us-east-1", selector=["env", "REGION"]), ] ) + sqlite_session.add_all([_account(), workflow]) + sqlite_session.commit() - response = workflow_module.WorkflowResponse.model_validate(workflow, from_attributes=True).model_dump(mode="json") + response = workflow_module.WorkflowResponse.model_validate( + workflow_module.WorkflowResponseSource(workflow, session=sqlite_session), + from_attributes=True, + ).model_dump(mode="json") assert response["environment_variables"] == [ { @@ -718,7 +753,7 @@ def test_workflow_response_masks_secret_environment_variables() -> None: ] -def test_workflow_response_preserves_llm_environment_variable_type() -> None: +def test_workflow_response_preserves_llm_environment_variable_type(sqlite_session: Session) -> None: workflow = _make_workflow( environment_variables=[ LLMEnvironmentVariable( @@ -729,8 +764,13 @@ def test_workflow_response_preserves_llm_environment_variable_type() -> None: ) ] ) + sqlite_session.add_all([_account(), workflow]) + sqlite_session.commit() - response = workflow_module.WorkflowResponse.model_validate(workflow, from_attributes=True).model_dump(mode="json") + response = workflow_module.WorkflowResponse.model_validate( + workflow_module.WorkflowResponseSource(workflow, session=sqlite_session), + from_attributes=True, + ).model_dump(mode="json") assert response["environment_variables"] == [ { @@ -743,14 +783,19 @@ def test_workflow_response_preserves_llm_environment_variable_type() -> None: ] -def test_workflow_response_rejects_invalid_environment_variable_dict() -> None: +def test_workflow_response_rejects_invalid_environment_variable_dict(sqlite_session: Session) -> None: workflow = _make_workflow(environment_variables=[{"value_type": "not-a-segment-type"}]) + sqlite_session.add_all([_account(), workflow]) + sqlite_session.commit() with pytest.raises(ValidationError): - workflow_module.WorkflowResponse.model_validate(workflow, from_attributes=True) + workflow_module.WorkflowResponse.model_validate( + workflow_module.WorkflowResponseSource(workflow, session=sqlite_session), + from_attributes=True, + ) -def test_draft_workflow_get_not_found(monkeypatch: pytest.MonkeyPatch) -> None: +def test_draft_workflow_get_not_found(monkeypatch: pytest.MonkeyPatch, unbound_session: Session) -> None: monkeypatch.setattr( workflow_module, "WorkflowService", lambda: SimpleNamespace(get_draft_workflow=lambda **_k: None) ) @@ -759,10 +804,12 @@ def test_draft_workflow_get_not_found(monkeypatch: pytest.MonkeyPatch) -> None: handler = inspect.unwrap(api.get) with pytest.raises(DraftWorkflowNotExist): - handler(api, app_model=SimpleNamespace(id="app")) + handler(api, unbound_session, app_model=_app()) -def test_draft_workflow_get_projects_agent_node_job_to_graph(monkeypatch: pytest.MonkeyPatch) -> None: +def test_draft_workflow_get_projects_agent_node_job_to_graph( + monkeypatch: pytest.MonkeyPatch, sqlite_session: Session +) -> None: workflow = _make_workflow( graph_dict={ "nodes": [ @@ -778,6 +825,8 @@ def test_draft_workflow_get_projects_agent_node_job_to_graph(monkeypatch: pytest "edges": [], } ) + sqlite_session.add_all([_account(), workflow]) + sqlite_session.commit() projected_graph = { "nodes": [ { @@ -811,12 +860,14 @@ def test_draft_workflow_get_projects_agent_node_job_to_graph(monkeypatch: pytest api = workflow_module.DraftWorkflowApi() handler = inspect.unwrap(api.get) - response = handler(api, app_model=SimpleNamespace(id="app")) + response = handler(api, sqlite_session, app_model=_app()) assert response["graph"] == projected_graph -def test_advanced_chat_run_conversation_not_exists(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None: +def test_advanced_chat_run_conversation_not_exists( + app: Flask, monkeypatch: pytest.MonkeyPatch, unbound_session: Session +) -> None: monkeypatch.setattr( workflow_module.AppGenerateService, "generate", @@ -835,7 +886,7 @@ def test_advanced_chat_run_conversation_not_exists(app: Flask, monkeypatch: pyte ): payload = workflow_module.AdvancedChatWorkflowRunPayload.model_validate({"inputs": {}}) with pytest.raises(NotFound): - handler(api, payload, Mock(), "t1", app_model=SimpleNamespace(id="app")) + handler(api, payload, unbound_session, _account(), app_model=_app()) @pytest.mark.parametrize( @@ -868,7 +919,7 @@ def test_trigger_run_loads_draft_with_request_session( lambda: SimpleNamespace(get_draft_workflow=get_draft_workflow), ) session = unbound_session - app_model = SimpleNamespace(id="app-1") + app_model = _app(app_id="app-1") handler = inspect.unwrap(resource.post) with app.test_request_context("/", method="POST", json=payload): @@ -877,7 +928,7 @@ def test_trigger_run_loads_draft_with_request_session( resource(), payload_model.model_validate(payload), session, - SimpleNamespace(id="account-1"), + _account(), app_model, ) diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_trigger_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_trigger_api.py index cb1ce0cf87f..1aaceaff3eb 100644 --- a/api/tests/unit_tests/controllers/console/app/test_workflow_trigger_api.py +++ b/api/tests/unit_tests/controllers/console/app/test_workflow_trigger_api.py @@ -3,32 +3,18 @@ from __future__ import annotations import inspect import uuid from datetime import UTC, datetime -from types import SimpleNamespace from unittest.mock import PropertyMock, patch -import pytest from flask import Flask -from sqlalchemy import Engine from sqlalchemy.orm import Session from controllers.console import console_ns from controllers.console.app import workflow_trigger as workflow_trigger_module -from models.base import TypeBase from models.enums import AppTriggerStatus, AppTriggerType from models.model import App, AppMode, IconType from models.trigger import AppTrigger -@pytest.fixture -def database_session(sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch): - models = (App, AppTrigger) - tables = [model.metadata.tables[model.__tablename__] for model in models] - TypeBase.metadata.create_all(sqlite_engine, tables=tables) - monkeypatch.setattr(workflow_trigger_module, "db", SimpleNamespace(engine=sqlite_engine)) - with Session(sqlite_engine, expire_on_commit=False) as session: - yield session - - def _persist_app_trigger( session: Session, *, @@ -107,8 +93,8 @@ def test_webhook_trigger_response_serializes_datetime(): assert payload["created_at"] == "2026-01-02T03:04:05Z" -def test_app_triggers_get_uses_injected_tenant_id(app: Flask, database_session: Session) -> None: - app_model, trigger = _persist_app_trigger(database_session) +def test_app_triggers_get_uses_injected_tenant_id(app: Flask, sqlite_session: Session) -> None: + app_model, trigger = _persist_app_trigger(sqlite_session) other_tenant_trigger = AppTrigger( tenant_id=str(uuid.uuid4()), app_id=app_model.id, @@ -118,21 +104,21 @@ def test_app_triggers_get_uses_injected_tenant_id(app: Flask, database_session: provider_name="provider", status=AppTriggerStatus.ENABLED, ) - database_session.add(other_tenant_trigger) - database_session.commit() + sqlite_session.add(other_tenant_trigger) + sqlite_session.commit() api = workflow_trigger_module.AppTriggersApi() method = inspect.unwrap(api.get) with app.test_request_context("/"): - response = method(api, app_model.tenant_id, app_model) + response = method(api, sqlite_session, app_model.tenant_id, app_model) assert [item["id"] for item in response["data"]] == [trigger.id] assert response["data"][0]["icon"].endswith("/provider/icon") -def test_app_trigger_enable_uses_injected_tenant_id(app: Flask, database_session: Session) -> None: - app_model, trigger = _persist_app_trigger(database_session, status=AppTriggerStatus.DISABLED) +def test_app_trigger_enable_uses_injected_tenant_id(app: Flask, sqlite_session: Session) -> None: + app_model, trigger = _persist_app_trigger(sqlite_session, status=AppTriggerStatus.DISABLED) payload = {"trigger_id": trigger.id, "enable_trigger": True} api = workflow_trigger_module.AppTriggerEnableApi() @@ -145,13 +131,15 @@ def test_app_trigger_enable_uses_injected_tenant_id(app: Flask, database_session response = method( api, workflow_trigger_module.ParserEnable(trigger_id=trigger.id, enable_trigger=True), + sqlite_session, app_model.tenant_id, app_model, ) assert response["id"] == trigger.id assert response["status"] == "enabled" - database_session.expire_all() - persisted_trigger = database_session.get(AppTrigger, trigger.id) + sqlite_session.flush() + sqlite_session.expire_all() + persisted_trigger = sqlite_session.get(AppTrigger, trigger.id) assert persisted_trigger is not None assert persisted_trigger.status == AppTriggerStatus.ENABLED From 677f2cf43f19e8304fde929c38ed03133d343ebd Mon Sep 17 00:00:00 2001 From: Asuka Minato Date: Wed, 9 Sep 2026 08:56:41 +0000 Subject: [PATCH 05/28] chore: example to add Mapped (#40374) --- api/models/model.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/api/models/model.py b/api/models/model.py index 216fed2be6a..4fb4cbf166e 100644 --- a/api/models/model.py +++ b/api/models/model.py @@ -1154,7 +1154,7 @@ class Conversation(Base): ) id: Mapped[str] = mapped_column(StringUUID, default=lambda: str(uuid4())) - app_id = mapped_column(StringUUID, nullable=False) + app_id: Mapped[str] = mapped_column(StringUUID, nullable=False) app_model_config_id = mapped_column(StringUUID, nullable=True) agent_workspace_binding_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True) model_provider = mapped_column(String(255), nullable=True) @@ -1164,8 +1164,8 @@ class Conversation(Base): name: Mapped[str] = mapped_column(String(255), nullable=False) summary = mapped_column(LongText) _inputs: Mapped[dict[str, Any]] = mapped_column("inputs", sa.JSON) - introduction = mapped_column(LongText) - system_instruction = mapped_column(LongText) + introduction: Mapped[str | None] = mapped_column(LongText, nullable=True) + system_instruction: Mapped[str | None] = mapped_column(LongText, nullable=True) system_instruction_tokens: Mapped[int] = mapped_column(sa.Integer, nullable=False, server_default=sa.text("0")) status: Mapped[ConversationStatus] = mapped_column( EnumText(ConversationStatus, length=255), nullable=False, default=ConversationStatus.NORMAL From ebb875e0a5285daf4a9b3504bf2f32757e93e4dc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 08:57:27 +0000 Subject: [PATCH 06/28] chore(deps): bump h2 from 4.3.0 to 4.4.1 in /dify-agent (#40119) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> From 57a6ccbd3b914c3943ad7650d0601061fb309cb8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 08:57:53 +0000 Subject: [PATCH 07/28] chore(i18n): sync translations with en-US (#42064) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: yyh <92089059+lyzno1@users.noreply.github.com> --- web/i18n/zh-Hans/permission.json | 8 ++++---- web/i18n/zh-Hant/permission.json | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/web/i18n/zh-Hans/permission.json b/web/i18n/zh-Hans/permission.json index 8a6ff1bdc6e..d835c66bdf3 100644 --- a/web/i18n/zh-Hans/permission.json +++ b/web/i18n/zh-Hans/permission.json @@ -56,20 +56,20 @@ "permissionSet.descriptionLabel": "描述", "permissionSet.descriptionPlaceholder": "描述此权限集授予的能力", "permissionSet.learnMore": "了解更多权限说明", - "permissionSet.modal.create.agent.description": "创建可在访问规则中引用的 Agent 权限集,以便快速授权。", - "permissionSet.modal.create.agent.title": "创建Agent 权限集", + "permissionSet.modal.create.agent.description": "创建可在访问规则中引用的 Agent 权限集,以便快速授权。", + "permissionSet.modal.create.agent.title": "创建 Agent 权限集", "permissionSet.modal.create.app.description": "创建可在访问规则中引用的应用权限集,以便快速授权。", "permissionSet.modal.create.app.title": "创建应用权限集", "permissionSet.modal.create.dataset.description": "创建可在访问规则中引用的知识库权限集,以便快速授权。", "permissionSet.modal.create.dataset.title": "创建知识库权限集", "permissionSet.modal.edit.agent.description": "修改此权限集的名称、描述和授予的权限。", - "permissionSet.modal.edit.agent.title": "编辑Agent 权限集", + "permissionSet.modal.edit.agent.title": "编辑 Agent 权限集", "permissionSet.modal.edit.app.description": "修改此权限集的名称、描述和授予的权限。", "permissionSet.modal.edit.app.title": "编辑应用权限集", "permissionSet.modal.edit.dataset.description": "修改此权限集的名称、描述和授予的权限。", "permissionSet.modal.edit.dataset.title": "编辑知识库权限集", "permissionSet.modal.view.agent.description": "查看此权限集的名称、描述和授予的权限。", - "permissionSet.modal.view.agent.title": "查看Agent 权限集", + "permissionSet.modal.view.agent.title": "查看 Agent 权限集", "permissionSet.modal.view.app.description": "查看此权限集的名称、描述和授予的权限。", "permissionSet.modal.view.app.title": "查看应用权限集", "permissionSet.modal.view.dataset.description": "查看此权限集的名称、描述和授予的权限。", diff --git a/web/i18n/zh-Hant/permission.json b/web/i18n/zh-Hant/permission.json index 38dbe610513..ff51213c763 100644 --- a/web/i18n/zh-Hant/permission.json +++ b/web/i18n/zh-Hant/permission.json @@ -56,20 +56,20 @@ "permissionSet.descriptionLabel": "描述", "permissionSet.descriptionPlaceholder": "描述此權限集授予的能力", "permissionSet.learnMore": "了解更多權限說明", - "permissionSet.modal.create.agent.description": "建立可在訪問規則中引用的 Agent 權限集,以便快速授權。", - "permissionSet.modal.create.agent.title": "建立Agent 權限集", + "permissionSet.modal.create.agent.description": "建立可在訪問規則中引用的 Agent 權限集,以便快速授權。", + "permissionSet.modal.create.agent.title": "建立 Agent 權限集", "permissionSet.modal.create.app.description": "建立可在訪問規則中引用的應用權限集,以便快速授權。", "permissionSet.modal.create.app.title": "建立應用權限集", "permissionSet.modal.create.dataset.description": "建立可在訪問規則中引用的知識庫權限集,以便快速授權。", "permissionSet.modal.create.dataset.title": "建立知識庫權限集", "permissionSet.modal.edit.agent.description": "修改此權限集的名稱、描述和授予的權限。", - "permissionSet.modal.edit.agent.title": "編輯Agent 權限集", + "permissionSet.modal.edit.agent.title": "編輯 Agent 權限集", "permissionSet.modal.edit.app.description": "修改此權限集的名稱、描述和授予的權限。", "permissionSet.modal.edit.app.title": "編輯應用權限集", "permissionSet.modal.edit.dataset.description": "修改此權限集的名稱、描述和授予的權限。", "permissionSet.modal.edit.dataset.title": "編輯知識庫權限集", "permissionSet.modal.view.agent.description": "查看此權限集的名稱、描述和授予的權限。", - "permissionSet.modal.view.agent.title": "查看Agent 權限集", + "permissionSet.modal.view.agent.title": "查看 Agent 權限集", "permissionSet.modal.view.app.description": "查看此權限集的名稱、描述和授予的權限。", "permissionSet.modal.view.app.title": "查看應用權限集", "permissionSet.modal.view.dataset.description": "查看此權限集的名稱、描述和授予的權限。", From adedbf1f12f9b1735d8d744d9de6a45d116a231b Mon Sep 17 00:00:00 2001 From: wangxiaolei Date: Wed, 9 Sep 2026 09:02:04 +0000 Subject: [PATCH 08/28] =?UTF-8?q?fix:=20fix=20undo=20delete=20operation=20?= =?UTF-8?q?for=20webhook=20trigger=20node=20lead=20the=20url=20=E2=80=A6?= =?UTF-8?q?=20(#42069)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sync_webhook_when_app_created.py | 14 ++- api/services/trigger/webhook_service.py | 19 ++-- .../test_sync_webhook_when_app_created.py | 32 +++++++ .../test_webhook_service_relationships.py | 94 +++++++++++++++++++ 4 files changed, 150 insertions(+), 9 deletions(-) create mode 100644 api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py create mode 100644 api/tests/unit_tests/services/test_webhook_service_relationships.py diff --git a/api/events/event_handlers/sync_webhook_when_app_created.py b/api/events/event_handlers/sync_webhook_when_app_created.py index 481561faa2f..7fd23a8dfa4 100644 --- a/api/events/event_handlers/sync_webhook_when_app_created.py +++ b/api/events/event_handlers/sync_webhook_when_app_created.py @@ -1,6 +1,6 @@ import logging -from events.app_event import app_draft_workflow_was_synced +from events.app_event import app_draft_workflow_was_synced, app_published_workflow_was_updated from models.model import App, AppMode from models.workflow import Workflow from services.trigger.webhook_service import WebhookService @@ -19,4 +19,14 @@ def handle(sender, synced_draft_workflow: Workflow, **kwargs): # only handle workflow app, chatflow is not supported yet return - WebhookService.sync_webhook_relationships(app, synced_draft_workflow) + WebhookService.sync_webhook_relationships(app, synced_draft_workflow, remove_stale=False) + + +@app_published_workflow_was_updated.connect +def handle_published(sender, published_workflow: Workflow, **kwargs): + """Remove stale webhook relationships after their node deletion is published.""" + app: App = sender + if app.mode != AppMode.WORKFLOW.value: + return + + WebhookService.sync_webhook_relationships(app, published_workflow, remove_stale=True) diff --git a/api/services/trigger/webhook_service.py b/api/services/trigger/webhook_service.py index 809693aa415..382fd1ed3d7 100644 --- a/api/services/trigger/webhook_service.py +++ b/api/services/trigger/webhook_service.py @@ -887,13 +887,17 @@ class WebhookService: return response_data, status_code @classmethod - def sync_webhook_relationships(cls, app: App, workflow: Workflow): + def sync_webhook_relationships(cls, app: App, workflow: Workflow, *, remove_stale: bool = True): """ Sync webhook relationships in DB. 1. Check if the workflow has any webhook trigger nodes 2. Fetch the nodes from DB, see if there were any webhook records already - 3. Diff the nodes and the webhook records, create/update/delete the webhook records as needed + 3. Diff the nodes and the webhook records, creating missing records and optionally deleting stale records + + Draft workflow synchronization preserves stale records so undo can restore a + webhook node without changing its URL. Published workflow synchronization + removes stale records after the deletion becomes effective. Approach: Frequent DB operations may cause performance issues, using Redis to cache it instead. @@ -969,11 +973,12 @@ class WebhookService: f"{cls.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:{node_id}", cache.model_dump_json(), ex=60 * 60 ) - # delete the nodes not found in the graph - for node_id in nodes_id_in_db: - if node_id not in nodes_id_in_graph: - session.delete(nodes_id_in_db[node_id]) - redis_client.delete(f"{cls.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:{node_id}") + if remove_stale: + # Delete relationships only when reconciling an effective published workflow. + for node_id in nodes_id_in_db: + if node_id not in nodes_id_in_graph: + session.delete(nodes_id_in_db[node_id]) + redis_client.delete(f"{cls.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:{node_id}") except Exception: logger.exception("Failed to sync webhook relationships for app %s", app.id) raise diff --git a/api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py b/api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py new file mode 100644 index 00000000000..9f450474ec0 --- /dev/null +++ b/api/tests/unit_tests/events/event_handlers/test_sync_webhook_when_app_created.py @@ -0,0 +1,32 @@ +from types import SimpleNamespace +from typing import cast +from unittest.mock import patch + +from events.event_handlers import sync_webhook_when_app_created +from events.event_handlers.sync_webhook_when_app_created import handle +from models.model import App +from models.workflow import Workflow + + +def test_draft_sync_preserves_stale_webhook_relationships() -> None: + app = cast(App, SimpleNamespace(mode="workflow")) + workflow = cast(Workflow, SimpleNamespace()) + + with patch( + "events.event_handlers.sync_webhook_when_app_created.WebhookService.sync_webhook_relationships" + ) as sync_webhook_relationships: + handle(app, synced_draft_workflow=workflow) + + sync_webhook_relationships.assert_called_once_with(app, workflow, remove_stale=False) + + +def test_published_sync_removes_stale_webhook_relationships() -> None: + app = cast(App, SimpleNamespace(mode="workflow")) + workflow = cast(Workflow, SimpleNamespace()) + + with patch( + "events.event_handlers.sync_webhook_when_app_created.WebhookService.sync_webhook_relationships" + ) as sync_webhook_relationships: + sync_webhook_when_app_created.handle_published(app, published_workflow=workflow) + + sync_webhook_relationships.assert_called_once_with(app, workflow, remove_stale=True) diff --git a/api/tests/unit_tests/services/test_webhook_service_relationships.py b/api/tests/unit_tests/services/test_webhook_service_relationships.py new file mode 100644 index 00000000000..ed22c91624a --- /dev/null +++ b/api/tests/unit_tests/services/test_webhook_service_relationships.py @@ -0,0 +1,94 @@ +from types import SimpleNamespace +from typing import cast +from unittest.mock import MagicMock + +import pytest +from sqlalchemy import Engine, Table, select +from sqlalchemy.orm import Session, sessionmaker + +from core.trigger.constants import TRIGGER_WEBHOOK_NODE_TYPE +from models.base import TypeBase +from models.model import App +from models.trigger import WorkflowWebhookTrigger +from models.workflow import Workflow +from services.trigger import webhook_service +from services.trigger.webhook_service import WebhookService + + +def test_draft_sync_preserves_webhook_id_when_deleted_node_is_restored( + monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine +) -> None: + webhook_trigger_table = cast(Table, WorkflowWebhookTrigger.__table__) + TypeBase.metadata.create_all(sqlite_engine, tables=[webhook_trigger_table]) + session_maker = sessionmaker(bind=sqlite_engine, expire_on_commit=False) + app = cast( + App, + SimpleNamespace(id="00000000-0000-0000-0000-000000000001", tenant_id="tenant-1", created_by="user-1"), + ) + webhook_trigger = WorkflowWebhookTrigger( + app_id=app.id, + tenant_id=app.tenant_id, + node_id="webhook-node", + webhook_id="stable-webhook-id", + created_by=app.created_by, + ) + with session_maker.begin() as session: + session.add(webhook_trigger) + original_record_id = webhook_trigger.id + + redis = MagicMock() + redis.get.return_value = None + redis.lock.return_value.acquire.return_value = True + monkeypatch.setattr(webhook_service, "db", SimpleNamespace(engine=sqlite_engine)) + monkeypatch.setattr(webhook_service, "redis_client", redis) + + deleted_draft = cast(Workflow, SimpleNamespace(walk_nodes=lambda _node_type: iter(()))) + WebhookService.sync_webhook_relationships(app, deleted_draft, remove_stale=False) + + restored_draft = cast( + Workflow, + SimpleNamespace(walk_nodes=lambda _node_type: iter([("webhook-node", {"type": TRIGGER_WEBHOOK_NODE_TYPE})])), + ) + WebhookService.sync_webhook_relationships(app, restored_draft, remove_stale=False) + + with Session(sqlite_engine) as session: + records = session.scalars(select(WorkflowWebhookTrigger)).all() + + assert len(records) == 1 + assert records[0].id == original_record_id + assert records[0].webhook_id == "stable-webhook-id" + + +def test_published_sync_removes_stale_webhook_relationships( + monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine +) -> None: + webhook_trigger_table = cast(Table, WorkflowWebhookTrigger.__table__) + TypeBase.metadata.create_all(sqlite_engine, tables=[webhook_trigger_table]) + session_maker = sessionmaker(bind=sqlite_engine, expire_on_commit=False) + app = cast( + App, + SimpleNamespace(id="00000000-0000-0000-0000-000000000001", tenant_id="tenant-1", created_by="user-1"), + ) + webhook_trigger = WorkflowWebhookTrigger( + app_id=app.id, + tenant_id=app.tenant_id, + node_id="deleted-webhook-node", + webhook_id="deleted-webhook-id", + created_by=app.created_by, + ) + with session_maker.begin() as session: + session.add(webhook_trigger) + + redis = MagicMock() + redis.get.return_value = None + redis.lock.return_value.acquire.return_value = True + monkeypatch.setattr(webhook_service, "db", SimpleNamespace(engine=sqlite_engine)) + monkeypatch.setattr(webhook_service, "redis_client", redis) + + published_workflow = cast(Workflow, SimpleNamespace(walk_nodes=lambda _node_type: iter(()))) + WebhookService.sync_webhook_relationships(app, published_workflow, remove_stale=True) + + with session_maker() as session: + records = session.scalars(select(WorkflowWebhookTrigger)).all() + assert records == [] + redis.delete.assert_called_once_with(f"{WebhookService.__WEBHOOK_NODE_CACHE_KEY__}:{app.id}:deleted-webhook-node") From 1007cf82944b313161f4559ff65e57c320a0bb49 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:15:16 +0000 Subject: [PATCH 09/28] chore(deps): bump httpx2 from 2.5.0 to 2.12.0 in /api (#42012) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- api/uv.lock | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/api/uv.lock b/api/uv.lock index 0ce5ce844a4..e35807e8b90 100644 --- a/api/uv.lock +++ b/api/uv.lock @@ -3350,15 +3350,15 @@ wheels = [ [[package]] name = "httpcore2" -version = "2.5.0" +version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "h11" }, { name = "truststore" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/47/06/5c12df521b5322fb1114a83d46911b2fbcb8855ddb3a635f11c01a214af5/httpcore2-2.5.0.tar.gz", hash = "sha256:88aa170137c17328d5ac44234f9fd10706466d5fb347f3edac4d39b91137b09d", size = 64808, upload-time = "2026-06-25T14:16:56.472Z" } +sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/a1/7564199d1a8728fe737b0a72e5b3f8d92dfe085a74ddf7cdd83bce5f206d/httpcore2-2.5.0-py3-none-any.whl", hash = "sha256:5ce35188de461d31e8d000bfb8ef8bf22c6c16587a211e5571deaa5e9bdf842a", size = 80330, upload-time = "2026-06-25T14:16:53.634Z" }, + { url = "https://files.pythonhosted.org/packages/d2/74/d370e55600d9bcfa0d9794b0166126d49291a3d2b20c268fc98c453a4948/httpcore2-2.12.0-py3-none-any.whl", hash = "sha256:7e04258ce01013d7d615e5b910a3b27fac937d7a95038227e79652b4ba3b4ceb", size = 83074, upload-time = "2026-08-18T13:22:05.854Z" }, ] [[package]] @@ -3422,18 +3422,28 @@ wheels = [ [[package]] name = "httpx2" -version = "2.5.0" +version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, - { name = "httpcore2" }, + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" }, { name = "idna" }, - { name = "truststore" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d0/e2/b5dedc0cf35aa65de5f541ccd30d2bc1fd7f1d43c9ab09f8ed9a7342317b/httpx2-2.5.0.tar.gz", hash = "sha256:e2df9cb4611021527ff8a675b1c320b610a2ec397acc8d6fe6e91df2d9b33c29", size = 83121, upload-time = "2026-06-25T14:16:57.491Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7f/f8/579a8b51e42e38ee32647df9f08aa25643ae788e275cc625b199829c4671/httpx2-2.12.0.tar.gz", hash = "sha256:7631fe9887a8a2275f4a2540e053aa670fcc50742864a9ae7c66e609fdcf12cf", size = 100040, upload-time = "2026-08-18T13:22:09.086Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/31/22/859d8252dad9bc9adee34b52e62cde621ece07b042ccb2ab4da1be46695f/httpx2-2.5.0-py3-none-any.whl", hash = "sha256:3d2d4d9cf4b61f1a1f46a95947cfdb47e80cb56a2f91c6256ac8f58e4891df41", size = 76652, upload-time = "2026-06-25T14:16:55.23Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/411ba65569158e862368917aaf56597f3e5fa3b91b0502919638465a08f3/httpx2-2.12.0-py3-none-any.whl", hash = "sha256:cc8b6eecb8661c146b8f89a60e97456ee086e91a784ed31ac450c3a9e613dd36", size = 95427, upload-time = "2026-08-18T13:22:06.834Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, ] [[package]] From 8c5dd51446ef97c16227c93ad15bbdd662abd52a Mon Sep 17 00:00:00 2001 From: Coding On Star <447357187@qq.com> Date: Wed, 9 Sep 2026 09:15:40 +0000 Subject: [PATCH 10/28] fix(web): open embedded recommend banner templates in the detail dialog (#42063) Co-authored-by: CodingOnStar --- .../__tests__/hydration-server.spec.tsx | 2 +- .../marketplace/__tests__/utils.spec.ts | 32 ++-- .../home/__tests__/home-trending.spec.tsx | 100 ++++++++++++- .../marketplace/home/home-trending-slides.tsx | 137 ++++++++++++++++-- .../components/plugins/marketplace/utils.ts | 9 +- .../marketplace-template-discovery.spec.ts | 2 +- web/service/marketplace-template-discovery.ts | 4 +- 7 files changed, 236 insertions(+), 50 deletions(-) diff --git a/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx b/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx index eb010d5e4cb..f3a734eec9c 100644 --- a/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx +++ b/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx @@ -112,7 +112,7 @@ describe('HydrateQueryClient', () => { expect(state.queries[0]?.queryKey).toEqual([ 'marketplace', 'collections', - { input: { query: { limit: 20 } } }, + { input: { query: {} } }, ]) }) diff --git a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts index 0fcb52f7b7c..2cb649046cc 100644 --- a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts +++ b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts @@ -267,13 +267,12 @@ describe('getMarketplacePluginsByCollectionId', () => { ) }) - it('should send the warmed preview limit when query is omitted', async () => { + it('should omit a preview limit when query is omitted', async () => { mockCollectionPlugins.mockResolvedValueOnce({ data: { plugins: [] }, }) - const { COLLECTION_PREVIEW_PLUGIN_LIMIT, getMarketplacePluginsByCollectionId } = - await import('../utils') + const { getMarketplacePluginsByCollectionId } = await import('../utils') await getMarketplacePluginsByCollectionId('test-collection') expect(mockCollectionPlugins).toHaveBeenCalledWith( @@ -281,7 +280,7 @@ describe('getMarketplacePluginsByCollectionId', () => { params: { collectionId: 'test-collection', }, - body: { limit: COLLECTION_PREVIEW_PLUGIN_LIMIT }, + body: {}, }, expect.objectContaining({ signal: undefined, @@ -319,8 +318,7 @@ describe('getMarketplaceCollectionsAndPlugins', () => { mockCollections.mockResolvedValueOnce({ data: { collections: mockCollectionData } }) mockCollectionPlugins.mockResolvedValue({ data: { plugins: mockPluginData } }) - const { COLLECTION_PREVIEW_PLUGIN_LIMIT, getMarketplaceCollectionsAndPlugins } = - await import('../utils') + const { getMarketplaceCollectionsAndPlugins } = await import('../utils') const result = await getMarketplaceCollectionsAndPlugins({ condition: 'category=tool', type: 'plugin', @@ -334,14 +332,13 @@ describe('getMarketplaceCollectionsAndPlugins', () => { body: { condition: 'category=tool', type: 'plugin', - limit: COLLECTION_PREVIEW_PLUGIN_LIMIT, }, }), expect.any(Object), ) }) - it('posts the warmed preview limit when the catalog has no extra filters', async () => { + it('posts without a preview limit when the catalog has no extra filters', async () => { mockCollections.mockResolvedValueOnce({ data: { collections: [ @@ -358,14 +355,13 @@ describe('getMarketplaceCollectionsAndPlugins', () => { }) mockCollectionPlugins.mockResolvedValue({ data: { plugins: [] } }) - const { COLLECTION_PREVIEW_PLUGIN_LIMIT, getMarketplaceCollectionsAndPlugins } = - await import('../utils') + const { getMarketplaceCollectionsAndPlugins } = await import('../utils') await getMarketplaceCollectionsAndPlugins() expect(mockCollectionPlugins).toHaveBeenCalledWith( expect.objectContaining({ params: { collectionId: 'featured' }, - body: { limit: COLLECTION_PREVIEW_PLUGIN_LIMIT }, + body: {}, }), expect.any(Object), ) @@ -446,22 +442,18 @@ describe('getMarketplaceCollectionsAndPlugins', () => { }) describe('getCollectionsParams', () => { - it('should return the warmed preview limit for all category', async () => { - const { COLLECTION_PREVIEW_PLUGIN_LIMIT, getCollectionsParams } = await import('../utils') - expect(getCollectionsParams(PLUGIN_TYPE_SEARCH_MAP.all)).toEqual({ - limit: COLLECTION_PREVIEW_PLUGIN_LIMIT, - }) - expect(COLLECTION_PREVIEW_PLUGIN_LIMIT).toBe(20) + it('should return an empty query for all category', async () => { + const { getCollectionsParams } = await import('../utils') + expect(getCollectionsParams(PLUGIN_TYPE_SEARCH_MAP.all)).toEqual({}) }) - it('should return category, condition, type, and preview limit for tool category', async () => { - const { COLLECTION_PREVIEW_PLUGIN_LIMIT, getCollectionsParams } = await import('../utils') + it('should return category, condition, and type for tool category', async () => { + const { getCollectionsParams } = await import('../utils') const result = getCollectionsParams(PLUGIN_TYPE_SEARCH_MAP.tool) expect(result).toEqual({ category: PluginCategoryEnum.tool, condition: 'category=tool', type: 'plugin', - limit: COLLECTION_PREVIEW_PLUGIN_LIMIT, }) }) }) diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx index 93c20a2dee5..ac1d6294811 100644 --- a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx +++ b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx @@ -37,6 +37,10 @@ vi.mock('@/config', async (importOriginal) => ({ MARKETPLACE_URL_PREFIX: 'https://marketplace.example.com', })) +vi.mock('@/next/navigation', () => ({ + useRouter: () => ({ push: vi.fn() }), +})) + vi.mock('@/app/components/plugins/install-plugin/hooks/use-check-installed', () => ({ default: () => ({ installedInfo: {} }), })) @@ -62,6 +66,21 @@ vi.mock('../../detail-dialog', () => ({ ) : null, })) +vi.mock('../../templates/template-detail-dialog', () => ({ + default: ({ + open, + template, + }: { + open: boolean + template: { id: string; template_name: string } + }) => + open ? ( +
+ {template.template_name} +
+ ) : null, +})) + const banners: PluginBanner[] = [ { id: 'recommend', @@ -761,10 +780,7 @@ describe('HomeTrending', () => { expect(screen.queryByRole('link', { name: 'Dropbox' })).not.toBeInTheDocument() expect(screen.queryByRole('link', { name: 'Notion' })).not.toBeInTheDocument() - expect(screen.getByRole('link', { name: 'Support Bot' })).toHaveAttribute( - 'href', - '/templates?tid=tpl-1', - ) + expect(screen.queryByRole('link', { name: 'Support Bot' })).not.toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Dropbox' })) @@ -780,6 +796,82 @@ describe('HomeTrending', () => { ) }) + it('opens embedded recommend template cards in the template dialog', async () => { + const user = userEvent.setup() + const bannerWithTemplates: PluginBanner = { + id: 'recommend-templates-embedded', + style_type: 'recommend', + title: 'Trending', + sort: 0, + language: 'en', + content: { + theme_type: 'newest', + cards: [ + { + item_type: 'template', + item_id: 'tpl-1', + display_name: 'Support Bot', + creator: 'aisa-team', + link: 'https://external.example.com/support-bot', + card_position: 0, + }, + ], + }, + } + + render( + , + ) + + expect(screen.queryByRole('link', { name: 'Support Bot' })).not.toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Support Bot' })) + + expect(screen.getByRole('dialog', { name: 'template-detail' })).toHaveTextContent('Support Bot') + expect(mockTrackMarketplaceSiteEvent).toHaveBeenCalledWith( + 'marketplace_banner_click', + expect.objectContaining({ + click_target: 'recommendation', + item_id: 'tpl-1', + item_type: 'template', + item_name: 'Support Bot', + }), + ) + }) + + it('opens embedded recommend plugin cards from /plugins links when item_id is not org/name', async () => { + const user = userEvent.setup() + const banner: PluginBanner = { + id: 'recommend-plugin-href', + style_type: 'recommend', + title: 'Trending', + sort: 0, + language: 'en', + content: { + theme_type: 'hottest', + cards: [ + { + item_type: 'plugin', + item_id: 'baserow', + display_name: 'Baserow', + link: '/plugins/langgenius/baserow', + card_position: 0, + }, + ], + }, + } + + render() + + expect(screen.queryByRole('link', { name: 'Baserow' })).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Baserow' })) + expect(screen.getByRole('dialog', { name: 'plugin-detail' })).toHaveTextContent('baserow') + }) + it('shows the served author on recommend template cards the same way as plugins', () => { const banner: PluginBanner = { id: 'recommend-templates', diff --git a/web/app/components/plugins/marketplace/home/home-trending-slides.tsx b/web/app/components/plugins/marketplace/home/home-trending-slides.tsx index 5a3b1c25284..aa898514064 100644 --- a/web/app/components/plugins/marketplace/home/home-trending-slides.tsx +++ b/web/app/components/plugins/marketplace/home/home-trending-slides.tsx @@ -6,6 +6,7 @@ import type { BannerEvent, BannerRecommend, BannerRecommendCard, + MarketplaceTemplate, PluginBanner, } from '@dify/contracts/marketplace' import type { MarketplaceBannerPage } from './banners' @@ -20,13 +21,15 @@ import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use import { PluginCategoryEnum } from '@/app/components/plugins/types' import { MARKETPLACE_API_PREFIX } from '@/config' import Link from '@/next/link' +import { useRouter } from '@/next/navigation' import { fetchPluginInfoFromMarketPlace } from '@/service/plugins' import { rememberMarketplaceSiteReferrer, trackMarketplaceSiteEvent, } from '@/utils/marketplace-site-track' import MarketplaceDetailDialog from '../detail-dialog' -import { getPluginLinkInMarketplace } from '../utils' +import TemplateDetailDialog from '../templates/template-detail-dialog' +import { getPluginLinkInMarketplace, getTemplateLinkInMarketplace } from '../utils' import background from './assets/background.webp' import difyUpdatesArt from './assets/dify-updates-art.png' import { @@ -53,21 +56,49 @@ const getMarketplaceAssetURL = (path?: string) => { } const getPluginIdentity = (itemId: string) => { - const [org, name] = itemId.split('/') + const [org, name, ...rest] = itemId.split('/') + if (!org || !name || rest.length > 0) return null + return { org, name } +} + +const pathFromHref = (href: string) => { + if (href.startsWith('/') && !href.startsWith('//')) return href + try { + return new URL(href).pathname + } catch { + return href + } +} + +const pluginIdentityFromHref = (href: string) => { + const parts = pathFromHref(href).split('/').filter(Boolean) + const index = parts.findIndex((part) => part === 'plugin' || part === 'plugins') + if (index < 0 || index + 2 >= parts.length) return null + const org = decodeURIComponent(parts[index + 1] ?? '') + const name = decodeURIComponent(parts[index + 2] ?? '') if (!org || !name) return null return { org, name } } +const templateIdFromHref = (href: string) => { + const path = pathFromHref(href) + const tid = new URL(path, 'https://marketplace.local').searchParams.get('tid') + if (tid) return tid + const parts = path.split('/').filter(Boolean) + if (parts[0] === 'templates' && parts[1]) return decodeURIComponent(parts[1]) + return null +} + const pluginFromRecommendCard = (card: BannerRecommendCard): Plugin | null => { if (card.item_type !== 'plugin') return null - const identity = getPluginIdentity(card.item_id) + const identity = getPluginIdentity(card.item_id) ?? pluginIdentityFromHref(card.link) if (!identity) return null return { type: 'plugin', org: identity.org, name: identity.name, - plugin_id: card.item_id, + plugin_id: `${identity.org}/${identity.name}`, version: '', latest_version: '', latest_package_identifier: '', @@ -90,6 +121,25 @@ const pluginFromRecommendCard = (card: BannerRecommendCard): Plugin | null => { } } +const templateFromRecommendCard = (card: BannerRecommendCard): MarketplaceTemplate | null => { + if (card.item_type !== 'template') return null + const id = card.item_id || templateIdFromHref(card.link) + if (!id) return null + + return { + id, + template_name: card.display_name, + overview: '', + icon: card.icon ?? '', + icon_background: card.icon_background ?? '', + icon_file_key: '', + publisher_unique_handle: card.creator, + usage_count: 0, + categories: [], + badges: card.badges, + } +} + const getLocalCardHref = (card: BannerRecommendCard) => { if (card.item_type === 'plugin') { const identity = getPluginIdentity(card.item_id) @@ -332,6 +382,47 @@ function EmbeddedRecommendPluginCard({ ) } +function EmbeddedRecommendTemplateCard({ + banner, + card, + template, + page, +}: { + banner: BannerRecommend + card: BannerRecommendCard + template: MarketplaceTemplate + page: MarketplaceBannerPage +}) { + const [open, setOpen] = useState(false) + const router = useRouter() + const href = getTemplateLinkInMarketplace(template) + + return ( + <> + + { + setOpen(false) + router.push(`/apps?template-id=${encodeURIComponent(template.id)}`) + }} + onOpenChange={setOpen} + /> + + ) +} + function TrendingCard({ banner, card, @@ -343,16 +434,34 @@ function TrendingCard({ isMarketplacePlatform: boolean page: MarketplaceBannerPage }) { - const embeddedPlugin = isMarketplacePlatform ? null : pluginFromRecommendCard(card) - if (embeddedPlugin) { - return ( - - ) + if (!isMarketplacePlatform) { + if (card.item_type === 'plugin') { + const embeddedPlugin = pluginFromRecommendCard(card) + if (embeddedPlugin) { + return ( + + ) + } + } + + if (card.item_type === 'template') { + const embeddedTemplate = templateFromRecommendCard(card) + if (embeddedTemplate) { + return ( + + ) + } + } } const href = getCardHref(card, isMarketplacePlatform) diff --git a/web/app/components/plugins/marketplace/utils.ts b/web/app/components/plugins/marketplace/utils.ts index a55bbc59baf..7e00ff3d7ac 100644 --- a/web/app/components/plugins/marketplace/utils.ts +++ b/web/app/components/plugins/marketplace/utils.ts @@ -16,10 +16,6 @@ type MarketplaceFetchOptions = { signal?: AbortSignal } -// Matches backend warmup homepageCollectionPluginsRequests Limit: 20 so the -// public POST hits the Redis bucket the scheduler already writes. -export const COLLECTION_PREVIEW_PLUGIN_LIMIT = 20 - type MarketplacePluginListExtras = { agent_strategy?: unknown data_sources?: unknown @@ -160,7 +156,7 @@ export const getMarketplacePluginsByCollectionId = async ( params: { collectionId, }, - body: { limit: COLLECTION_PREVIEW_PLUGIN_LIMIT, ...query }, + body: query ?? {}, }, { signal: options?.signal, @@ -301,12 +297,11 @@ export function getCollectionsParams( category: ActivePluginType, ): CollectionsAndPluginsSearchParams { if (category === PLUGIN_TYPE_SEARCH_MAP.all) { - return { limit: COLLECTION_PREVIEW_PLUGIN_LIMIT } + return {} } return { category, condition: getMarketplaceListCondition(category), type: getMarketplaceListFilterType(category), - limit: COLLECTION_PREVIEW_PLUGIN_LIMIT, } } diff --git a/web/service/marketplace-template-discovery.spec.ts b/web/service/marketplace-template-discovery.spec.ts index ef5cc2e939d..4422c20e034 100644 --- a/web/service/marketplace-template-discovery.spec.ts +++ b/web/service/marketplace-template-discovery.spec.ts @@ -52,7 +52,7 @@ describe('marketplace template discovery', () => { 1, { params: { collectionName: 'featured' }, - body: { limit: 20 }, + body: {}, }, expect.objectContaining({ signal: expect.any(AbortSignal) }), ) diff --git a/web/service/marketplace-template-discovery.ts b/web/service/marketplace-template-discovery.ts index 5b20a34f55c..d293c0b1769 100644 --- a/web/service/marketplace-template-discovery.ts +++ b/web/service/marketplace-template-discovery.ts @@ -32,8 +32,6 @@ const FAILED_COLLECTIONS_RESULT: MarketplaceTemplateCollectionsResult = { ok: false, } -const COLLECTION_PREVIEW_TEMPLATE_LIMIT = 20 - type MarketplaceTemplateListExtras = { asset_files?: unknown asset_tree_nodes?: unknown @@ -102,7 +100,7 @@ async function fetchCollectionsAndTemplates(): Promise Date: Wed, 9 Sep 2026 09:16:40 +0000 Subject: [PATCH 11/28] chore(deps): bump httpx2 from 2.5.0 to 2.12.0 in /dify-agent (#42011) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- dify-agent/uv.lock | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/dify-agent/uv.lock b/dify-agent/uv.lock index 2fa42630174..c7f474a625c 100644 --- a/dify-agent/uv.lock +++ b/dify-agent/uv.lock @@ -990,15 +990,15 @@ wheels = [ [[package]] name = "httpcore2" -version = "2.5.0" +version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "h11" }, { name = "truststore" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/47/06/5c12df521b5322fb1114a83d46911b2fbcb8855ddb3a635f11c01a214af5/httpcore2-2.5.0.tar.gz", hash = "sha256:88aa170137c17328d5ac44234f9fd10706466d5fb347f3edac4d39b91137b09d", size = 64808, upload-time = "2026-06-25T14:16:56.472Z" } +sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c9/a1/7564199d1a8728fe737b0a72e5b3f8d92dfe085a74ddf7cdd83bce5f206d/httpcore2-2.5.0-py3-none-any.whl", hash = "sha256:5ce35188de461d31e8d000bfb8ef8bf22c6c16587a211e5571deaa5e9bdf842a", size = 80330, upload-time = "2026-06-25T14:16:53.634Z" }, + { url = "https://files.pythonhosted.org/packages/d2/74/d370e55600d9bcfa0d9794b0166126d49291a3d2b20c268fc98c453a4948/httpcore2-2.12.0-py3-none-any.whl", hash = "sha256:7e04258ce01013d7d615e5b910a3b27fac937d7a95038227e79652b4ba3b4ceb", size = 83074, upload-time = "2026-08-18T13:22:05.854Z" }, ] [[package]] @@ -1047,18 +1047,28 @@ wheels = [ [[package]] name = "httpx2" -version = "2.5.0" +version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, - { name = "httpcore2" }, + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" }, { name = "idna" }, - { name = "truststore" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/d0/e2/b5dedc0cf35aa65de5f541ccd30d2bc1fd7f1d43c9ab09f8ed9a7342317b/httpx2-2.5.0.tar.gz", hash = "sha256:e2df9cb4611021527ff8a675b1c320b610a2ec397acc8d6fe6e91df2d9b33c29", size = 83121, upload-time = "2026-06-25T14:16:57.491Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7f/f8/579a8b51e42e38ee32647df9f08aa25643ae788e275cc625b199829c4671/httpx2-2.12.0.tar.gz", hash = "sha256:7631fe9887a8a2275f4a2540e053aa670fcc50742864a9ae7c66e609fdcf12cf", size = 100040, upload-time = "2026-08-18T13:22:09.086Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/31/22/859d8252dad9bc9adee34b52e62cde621ece07b042ccb2ab4da1be46695f/httpx2-2.5.0-py3-none-any.whl", hash = "sha256:3d2d4d9cf4b61f1a1f46a95947cfdb47e80cb56a2f91c6256ac8f58e4891df41", size = 76652, upload-time = "2026-06-25T14:16:55.23Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/411ba65569158e862368917aaf56597f3e5fa3b91b0502919638465a08f3/httpx2-2.12.0-py3-none-any.whl", hash = "sha256:cc8b6eecb8661c146b8f89a60e97456ee086e91a784ed31ac450c3a9e613dd36", size = 95427, upload-time = "2026-08-18T13:22:06.834Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, ] [[package]] From a1a1a42c42ceb317e88a476936057325d8d80d4e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:18:06 +0000 Subject: [PATCH 12/28] chore(deps): bump the storage group across 1 directory with 4 updates (#41893) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- api/pyproject.toml | 8 ++++---- api/uv.lock | 38 +++++++++++++++++++------------------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/api/pyproject.toml b/api/pyproject.toml index 2ca877a8bd5..2106fe83d1e 100644 --- a/api/pyproject.toml +++ b/api/pyproject.toml @@ -6,7 +6,7 @@ requires-python = "~=3.12.0" dependencies = [ # Legacy: mature and widely deployed "bleach>=6.4.0,<7.0.0", - "boto3>=1.43.76,<2.0.0", + "boto3>=1.43.88,<2.0.0", "celery>=5.6.3,<6.0.0", "croniter>=6.2.2,<7.0.0", "dify-agent", @@ -198,7 +198,7 @@ dev = [ # Required for key management / credential encryption key providers ############################################################ kms = [ - "azure-keyvault-keys>=4.10.0,<5.0.0", + "azure-keyvault-keys>=4.11.2,<5.0.0", ] ############################################################ @@ -206,8 +206,8 @@ kms = [ # Required for storage clients ############################################################ storage = [ - "azure-storage-blob>=12.30.0,<13.0.0", - "bce-python-sdk==0.9.76", + "azure-storage-blob>=12.30.1,<13.0.0", + "bce-python-sdk==0.9.79", "cos-python-sdk-v5>=1.9.44,<2.0.0", "esdk-obs-python>=3.26.6,<4.0.0", "google-cloud-storage>=3.13.1,<4.0.0", diff --git a/api/uv.lock b/api/uv.lock index e35807e8b90..7774a0d8d7d 100644 --- a/api/uv.lock +++ b/api/uv.lock @@ -471,7 +471,7 @@ wheels = [ [[package]] name = "azure-keyvault-keys" -version = "4.11.1" +version = "4.11.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "azure-core" }, @@ -479,14 +479,14 @@ dependencies = [ { name = "isodate" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f4/03/5ce6db28b545427d4ab572f6a4ef2a727b6b4e7bf6941cedddf98822535b/azure_keyvault_keys-4.11.1.tar.gz", hash = "sha256:90caa3a7b2c8f6b53c247ec115cf1c1dad7f107cc3aa9f35aff4838bbce7e562", size = 260915, upload-time = "2026-05-19T20:01:08.041Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3d/97/2881414bdb1c9885c2e2195364b726d0ea3a2ef8a01c99e71238fc72b3b8/azure_keyvault_keys-4.11.2.tar.gz", hash = "sha256:8459c86542d103f8b67acb845fae5168029b6f7eb0fd7678ed8628c7b928addf", size = 261148, upload-time = "2026-08-26T16:05:33.779Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/3d/7bed91ae9268cf48124cf6990d8cd2c3daff7a2bb1e91a439d26ee90d705/azure_keyvault_keys-4.11.1-py3-none-any.whl", hash = "sha256:f46cdf6ee7a9baf27f70e6838327032886c8a087041dd56397773b1639da8fe2", size = 200651, upload-time = "2026-05-19T20:01:09.809Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c5/7dd5c7ee55b608fb54143253214391e58c7fe404b115b557226f69495c52/azure_keyvault_keys-4.11.2-py3-none-any.whl", hash = "sha256:aa5eecd5a5f868d619542c5528bc8edbc9bc71d7ce46721c366a9d3c7cac6759", size = 200715, upload-time = "2026-08-26T16:05:35.588Z" }, ] [[package]] name = "azure-storage-blob" -version = "12.30.0" +version = "12.30.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "azure-core" }, @@ -494,9 +494,9 @@ dependencies = [ { name = "isodate" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/48/84a820d898267f662b5c06f7cd76fdb8a9e272b44aa9376cef3ec0f6a294/azure_storage_blob-12.30.0.tar.gz", hash = "sha256:2cd74d4d5731e5eb6b8d5c5056ee115a5e88f8fdf22517b739836fda685018be", size = 618229, upload-time = "2026-06-08T11:45:35.575Z" } +sdist = { url = "https://files.pythonhosted.org/packages/39/7e/834d7bfcf999ab89d1bd3a5d235ece6824686da2f3d315e2162c613fe43d/azure_storage_blob-12.30.1.tar.gz", hash = "sha256:7a24f978c51d56a0375beebffcbe8453e59ae390d2695705848edc75083e4184", size = 624787, upload-time = "2026-08-27T19:12:54.967Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5e/0b/e106f0fd7fa785867d9ffcc47dc9e6237c0e58f51058473b777487a98edc/azure_storage_blob-12.30.0-py3-none-any.whl", hash = "sha256:d415ac50b67a8da6b3ae7e9f1014b1b55cd7aafa0b8d4ca9b380568dc7360423", size = 435610, upload-time = "2026-06-08T11:45:37.213Z" }, + { url = "https://files.pythonhosted.org/packages/ff/90/f06915ccf78a6d965901aae093bd7e88e486c52e0773202656fb29c2304a/azure_storage_blob-12.30.1-py3-none-any.whl", hash = "sha256:7dc09c37f4f58508e20532b4b4c178f4763f41b01e0b9063835b994fd9d2a7b3", size = 438131, upload-time = "2026-08-27T19:12:56.796Z" }, ] [[package]] @@ -535,7 +535,7 @@ wheels = [ [[package]] name = "bce-python-sdk" -version = "0.9.76" +version = "0.9.79" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "crc32c" }, @@ -543,9 +543,9 @@ dependencies = [ { name = "pycryptodome" }, { name = "six" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0a/ed/b41906366c0e1e3a1a883e0f1bcfc927403d9697d74b1eb7e89502870218/bce_python_sdk-0.9.76.tar.gz", hash = "sha256:01c630ce8dcbf8be0563d65f18b5201eaac6bd954b3dc776040aec268f81b6ff", size = 317399, upload-time = "2026-07-24T05:12:57.005Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9d/64/d31e61620ddaecb7039dc7b8f62eb75b95d2281f2d2016b6d6b22396e16f/bce_python_sdk-0.9.79.tar.gz", hash = "sha256:cd77476b43347ed28d0211d5ad557e524e1ec648bd093d57c6a6d3de075a7508", size = 322059, upload-time = "2026-09-01T05:48:52.013Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b9/06/4d4a26c3dfcdb29599f563329b87eefe55b02b3c2b9d8f8c3aeaa38a33a6/bce_python_sdk-0.9.76-py3-none-any.whl", hash = "sha256:e629181d060f4ed8f29749f47139bf08f1f9b0d8b15daedc956900785587e8d8", size = 435179, upload-time = "2026-07-24T05:12:55.064Z" }, + { url = "https://files.pythonhosted.org/packages/ef/de/52b763b183e23f4dd73811a2dd2664824ae7fc6ceb1aa8dcd3f1102b1094/bce_python_sdk-0.9.79-py3-none-any.whl", hash = "sha256:71799ac8740505e0759d30873f6f1a478fa8f83aedf425d511f1419a5f30082e", size = 440268, upload-time = "2026-09-01T05:48:50.459Z" }, ] [[package]] @@ -658,16 +658,16 @@ wheels = [ [[package]] name = "boto3" -version = "1.43.76" +version = "1.43.88" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "botocore" }, { name = "jmespath" }, { name = "s3transfer" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/4f/6c/0cc8c0fe7b6564a3dd3b8066a2a262ee9874272defb517f461677a8c76c8/boto3-1.43.76.tar.gz", hash = "sha256:fa4dc85f735bb67d8f82e42ac50af7e1d2c039aeacf40c878067c9046464b6ad", size = 112656, upload-time = "2026-08-20T19:25:46.007Z" } +sdist = { url = "https://files.pythonhosted.org/packages/71/a4/d7b6ca0c2c21722c12b6ecc942ff3e2304c40f00724182500236616c4236/boto3-1.43.88.tar.gz", hash = "sha256:b3d03fba8ace049de27e3a6ed69b25a55d752f49d563394985e805ed5f0a0a74", size = 112730, upload-time = "2026-09-03T19:24:05.814Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/db/81/5179853e14d7068e02d2f535ca620d98d1a95249ccfc2933f414ed51ded4/boto3-1.43.76-py3-none-any.whl", hash = "sha256:249f55274aef9fa3b9de6afb6f5b2effbbb15c5263d97c13e7b691f479a62c04", size = 140025, upload-time = "2026-08-20T19:25:44.427Z" }, + { url = "https://files.pythonhosted.org/packages/fc/04/b024d6c8ba2ae18ebaf6597981069a6f51d97ab64d769d466936f1454954/boto3-1.43.88-py3-none-any.whl", hash = "sha256:62efee681fefc9b14244d66ab66ead11dd4a32fec0a54ac9f23106003ef210ca", size = 140024, upload-time = "2026-09-03T19:24:04.27Z" }, ] [[package]] @@ -690,16 +690,16 @@ bedrock-runtime = [ [[package]] name = "botocore" -version = "1.43.78" +version = "1.43.89" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jmespath" }, { name = "python-dateutil" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/67/71/490aaa384855bf3b69405ded52ae77a0e5f4eeb2165044fa65466c4d3a73/botocore-1.43.78.tar.gz", hash = "sha256:e8238d22c1e1342025d75d2e33d154a375e7caad0fc67f77d77faa2d82668b94", size = 15982895, upload-time = "2026-08-21T19:37:32.402Z" } +sdist = { url = "https://files.pythonhosted.org/packages/53/06/f63fb1befdf77af18539fb24ea01f2da0f13965ed5de091061708ac96416/botocore-1.43.89.tar.gz", hash = "sha256:f0574942970742657b0e0716cf08c2dfe6bef8e6de5fbb7081c3424e262b4cca", size = 16074206, upload-time = "2026-09-04T19:24:52.464Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c5/5b/b7c5c22767c0e8eb4bb2bd0a972d77bd0be3dd9908e15d4487094a31fa4b/botocore-1.43.78-py3-none-any.whl", hash = "sha256:ddd020493235e264b3bd12606f239a3d3b2dd7cfb1d25a0691061183c290c228", size = 15677214, upload-time = "2026-08-21T19:37:28.894Z" }, + { url = "https://files.pythonhosted.org/packages/9e/9d/96f9dee6d12eedf1c2b4264eefd59c7ac8cac10daadb9a7bfccc9ee881c6/botocore-1.43.89-py3-none-any.whl", hash = "sha256:d7211220c815427fe71225acc6909e4ab5dfab3b03770e72fd16cf9eb86b3d1a", size = 15768272, upload-time = "2026-09-04T19:24:49.769Z" }, ] [[package]] @@ -1687,7 +1687,7 @@ requires-dist = [ { name = "aliyun-log-python-sdk", specifier = "==0.9.44" }, { name = "azure-identity", specifier = ">=1.25.3,<2.0.0" }, { name = "bleach", specifier = ">=6.4.0,<7.0.0" }, - { name = "boto3", specifier = ">=1.43.76,<2.0.0" }, + { name = "boto3", specifier = ">=1.43.88,<2.0.0" }, { name = "celery", specifier = ">=5.6.3,<6.0.0" }, { name = "croniter", specifier = ">=6.2.2,<7.0.0" }, { name = "dify-agent", editable = "../dify-agent" }, @@ -1794,10 +1794,10 @@ dev = [ { name = "types-ujson", specifier = ">=5.10.0" }, { name = "xinference-client", specifier = ">=2.7.0" }, ] -kms = [{ name = "azure-keyvault-keys", specifier = ">=4.10.0,<5.0.0" }] +kms = [{ name = "azure-keyvault-keys", specifier = ">=4.11.2,<5.0.0" }] storage = [ - { name = "azure-storage-blob", specifier = ">=12.30.0,<13.0.0" }, - { name = "bce-python-sdk", specifier = "==0.9.76" }, + { name = "azure-storage-blob", specifier = ">=12.30.1,<13.0.0" }, + { name = "bce-python-sdk", specifier = "==0.9.79" }, { name = "cos-python-sdk-v5", specifier = ">=1.9.44,<2.0.0" }, { name = "esdk-obs-python", specifier = ">=3.26.6,<4.0.0" }, { name = "google-cloud-storage", specifier = ">=3.13.1,<4.0.0" }, From 647fec55d9e741e32f806e6c48fc6dcb69054bd6 Mon Sep 17 00:00:00 2001 From: Duda Nogueira Date: Wed, 9 Sep 2026 09:19:54 +0000 Subject: [PATCH 13/28] chore(release): Upgrade self-hosted Weaviate to 1.39 (#38214) Co-authored-by: Claude Opus 5 (1M context) --- api/.env.example | 1 + .../src/dify_vdb_weaviate/weaviate_vector.py | 46 ++++++++ .../test_weaviate_integration_header.py | 103 ++++++++++++++++++ api/tests/integration_tests/.env.example | 1 + docker/docker-compose-template.yaml | 2 +- docker/docker-compose.middleware.yaml | 2 +- docker/docker-compose.yaml | 2 +- docker/envs/middleware.env.example | 1 + 8 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 api/providers/vdb/vdb-weaviate/tests/unit_tests/test_weaviate_integration_header.py diff --git a/api/.env.example b/api/.env.example index 15829262e8b..0bf7b9493ac 100644 --- a/api/.env.example +++ b/api/.env.example @@ -234,6 +234,7 @@ VECTOR_INDEX_NAME_PREFIX=Vector_index # Weaviate configuration WEAVIATE_ENDPOINT=http://localhost:8080 +WEAVIATE_GRPC_ENDPOINT=grpc://localhost:50051 WEAVIATE_API_KEY=WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih WEAVIATE_BATCH_SIZE=100 WEAVIATE_TOKENIZATION=word diff --git a/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py b/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py index ca6081ff89e..5735b6a018a 100644 --- a/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py +++ b/api/providers/vdb/vdb-weaviate/src/dify_vdb_weaviate/weaviate_vector.py @@ -7,6 +7,7 @@ document embeddings used in retrieval-augmented generation workflows. import atexit import datetime +import importlib.metadata import json import logging import threading @@ -37,6 +38,48 @@ logger = logging.getLogger(__name__) _weaviate_client: weaviate.WeaviateClient | None = None _weaviate_client_lock = threading.Lock() +# Identifies Dify to Weaviate's server-side telemetry via the X-Weaviate-Client-Integration +# header, matching the identifier emitted by other official Weaviate integrations. +_INTEGRATION_NAME = "dify" + + +def _integration_version() -> str: + """Best-effort Dify version reported in the integration telemetry header.""" + version = (dify_config.project.version or "").strip() + if version: + return version + try: + return importlib.metadata.version("dify-api") + except Exception: + return "unknown" + + +def _register_integration(client: weaviate.WeaviateClient) -> None: + """ + Registers the ``X-Weaviate-Client-Integration`` telemetry header on the client. + + The header value is ``dify/`` and is sent on both HTTP and gRPC requests, letting + Weaviate's server attribute traffic to Dify in its telemetry (alongside the built-in + ``X-Weaviate-Client`` header). Registration is best-effort: any failure — including older + weaviate-client releases that lack the ``integrations`` API — is swallowed so telemetry never + breaks client initialization. + """ + try: + from pydantic import Field + from weaviate.connect.integrations import _IntegrationConfig + + value = f"{_INTEGRATION_NAME}/{_integration_version()}" + + class _DifyIntegration(_IntegrationConfig): + integration: str = Field( + default=value, + serialization_alias="X-Weaviate-Client-Integration", + ) + + client.integrations.configure(_DifyIntegration()) + except Exception: + logger.debug("Could not register Dify Weaviate integration header", exc_info=True) + def _shutdown_weaviate_client() -> None: """ @@ -159,6 +202,9 @@ class WeaviateVector(BaseVector): skip_init_checks=True, # Skip PyPI version check to avoid unnecessary HTTP requests ) + # Tag outgoing requests so Weaviate can attribute traffic to Dify in its telemetry. + _register_integration(client) + if not client.is_ready(): raise ConnectionError("Vector database is not ready") diff --git a/api/providers/vdb/vdb-weaviate/tests/unit_tests/test_weaviate_integration_header.py b/api/providers/vdb/vdb-weaviate/tests/unit_tests/test_weaviate_integration_header.py new file mode 100644 index 00000000000..927ed344100 --- /dev/null +++ b/api/providers/vdb/vdb-weaviate/tests/unit_tests/test_weaviate_integration_header.py @@ -0,0 +1,103 @@ +"""Unit tests for the Weaviate client integration telemetry header. + +Verifies that Dify registers the ``X-Weaviate-Client-Integration`` header on the Weaviate +client so server-side telemetry can attribute traffic to Dify, mirroring the behavior of other +official Weaviate integrations. +""" + +import unittest +from typing import override +from unittest.mock import MagicMock, patch + +from dify_vdb_weaviate import weaviate_vector as weaviate_vector_module +from dify_vdb_weaviate.weaviate_vector import ( + _INTEGRATION_NAME, + WeaviateConfig, + WeaviateVector, + _integration_version, + _register_integration, +) + + +class TestIntegrationVersion(unittest.TestCase): + """Tests for resolving the version reported in the integration header.""" + + def test_uses_dify_project_version_when_present(self): + with patch.object(weaviate_vector_module.dify_config.project, "version", "1.15.0"): + assert _integration_version() == "1.15.0" + + def test_strips_whitespace_from_version(self): + with patch.object(weaviate_vector_module.dify_config.project, "version", " 1.15.0 "): + assert _integration_version() == "1.15.0" + + def test_falls_back_to_package_metadata_when_version_empty(self): + with ( + patch.object(weaviate_vector_module.dify_config.project, "version", ""), + patch("dify_vdb_weaviate.weaviate_vector.importlib.metadata.version", return_value="9.9.9"), + ): + assert _integration_version() == "9.9.9" + + def test_falls_back_to_unknown_when_everything_fails(self): + with ( + patch.object(weaviate_vector_module.dify_config.project, "version", ""), + patch( + "dify_vdb_weaviate.weaviate_vector.importlib.metadata.version", + side_effect=Exception("no metadata"), + ), + ): + assert _integration_version() == "unknown" + + +class TestRegisterIntegration(unittest.TestCase): + """Tests for registering the integration header on the client.""" + + def test_configures_header_with_dify_name_and_version(self): + client = MagicMock() + with patch.object(weaviate_vector_module.dify_config.project, "version", "1.15.0"): + _register_integration(client) + + client.integrations.configure.assert_called_once() + config = client.integrations.configure.call_args.args[0] + header = config._to_header() + assert header == {"X-Weaviate-Client-Integration": "dify/1.15.0"} + assert _INTEGRATION_NAME == "dify" + + def test_swallows_errors_so_init_never_breaks(self): + client = MagicMock() + client.integrations.configure.side_effect = Exception("old client without integrations API") + + # Must not raise. + with patch.object(weaviate_vector_module.dify_config.project, "version", "1.15.0"): + _register_integration(client) + + +class TestInitClientRegistersIntegration(unittest.TestCase): + """Ensures the integration header is registered during client initialization.""" + + @override + def setUp(self): + weaviate_vector_module._weaviate_client = None + self.config = WeaviateConfig(endpoint="http://localhost:8080", api_key="test-key") + + @override + def tearDown(self): + weaviate_vector_module._weaviate_client = None + + @patch("dify_vdb_weaviate.weaviate_vector.weaviate") + def test_init_client_registers_integration(self, mock_weaviate_module): + mock_client = MagicMock() + mock_client.is_ready.return_value = True + mock_weaviate_module.connect_to_custom.return_value = mock_client + + with patch("dify_vdb_weaviate.weaviate_vector._register_integration") as mock_register: + WeaviateVector( + collection_name="Test_Collection_Node", + config=self.config, + attributes=["doc_id"], + ) + + mock_register.assert_called_once_with(mock_client) + + +if __name__ == "__main__": + unittest.main() diff --git a/api/tests/integration_tests/.env.example b/api/tests/integration_tests/.env.example index 76ad277101d..53e655dcd92 100644 --- a/api/tests/integration_tests/.env.example +++ b/api/tests/integration_tests/.env.example @@ -62,6 +62,7 @@ WEBSOCKET_MAX_HTTP_BUFFER_SIZE=10485760 VECTOR_STORE=weaviate # Weaviate configuration WEAVIATE_ENDPOINT=http://localhost:8080 +WEAVIATE_GRPC_ENDPOINT=grpc://localhost:50051 WEAVIATE_API_KEY=WVF5YThaHlkYwhGUSmCRgsX3tD5ngdN8pkih WEAVIATE_BATCH_SIZE=100 WEAVIATE_TOKENIZATION=word diff --git a/docker/docker-compose-template.yaml b/docker/docker-compose-template.yaml index 3ce3358c569..e8e7a0b148a 100644 --- a/docker/docker-compose-template.yaml +++ b/docker/docker-compose-template.yaml @@ -809,7 +809,7 @@ services: # The Weaviate vector store. weaviate: - image: semitechnologies/weaviate:1.27.0 + image: cr.weaviate.io/semitechnologies/weaviate:1.39.2 profiles: - weaviate restart: always diff --git a/docker/docker-compose.middleware.yaml b/docker/docker-compose.middleware.yaml index 0f32cb0a6bf..5b30bfdda1f 100644 --- a/docker/docker-compose.middleware.yaml +++ b/docker/docker-compose.middleware.yaml @@ -250,7 +250,7 @@ services: # The Weaviate vector store. weaviate: - image: semitechnologies/weaviate:1.27.0 + image: cr.weaviate.io/semitechnologies/weaviate:1.39.2 profiles: - "" - weaviate diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml index fd59abaa3f9..cf3468e3224 100644 --- a/docker/docker-compose.yaml +++ b/docker/docker-compose.yaml @@ -815,7 +815,7 @@ services: # The Weaviate vector store. weaviate: - image: semitechnologies/weaviate:1.27.0 + image: cr.weaviate.io/semitechnologies/weaviate:1.39.2 profiles: - weaviate restart: always diff --git a/docker/envs/middleware.env.example b/docker/envs/middleware.env.example index faf8307ff43..fcd58cef5a9 100644 --- a/docker/envs/middleware.env.example +++ b/docker/envs/middleware.env.example @@ -154,6 +154,7 @@ EXPOSE_SANDBOX_PORT=8194 EXPOSE_LOCAL_SANDBOX_PORT=5004 EXPOSE_SSRF_PROXY_PORT=3128 EXPOSE_WEAVIATE_PORT=8080 +EXPOSE_WEAVIATE_GRPC_PORT=50051 # ------------------------------ # Plugin Daemon Configuration From 06f58809f23bc1058d224fb4a8d432e26c6bdae2 Mon Sep 17 00:00:00 2001 From: Joel Date: Wed, 9 Sep 2026 09:27:56 +0000 Subject: [PATCH 14/28] fix(web): restore focus after closing overlays (#42068) --- oxlint-suppressions.json | 6 - .../app/log/__tests__/list.spec.tsx | 29 ++ web/app/components/app/log/list.tsx | 285 ++++++------ .../app/workflow-log/__tests__/list.spec.tsx | 38 ++ web/app/components/app/workflow-log/list.tsx | 231 +++++----- .../__tests__/feedback-focus.browser.spec.tsx | 153 +++++++ .../base/chat/chat/answer/operation.tsx | 424 +++++++++--------- .../__tests__/focus.browser.spec.tsx | 79 ++++ .../template-card/__tests__/index.spec.tsx | 7 +- .../list/template-card/actions.tsx | 20 +- .../list/template-card/index.tsx | 46 +- .../note-editor/__tests__/store.spec.tsx | 24 + .../__tests__/hooks.spec.tsx | 5 + .../plugins/format-detector-plugin/hooks.ts | 7 +- .../__tests__/component.spec.tsx | 1 + .../__tests__/focus.browser.spec.tsx | 185 ++++++++ .../plugins/link-editor-plugin/component.tsx | 67 +-- .../plugins/link-editor-plugin/hooks.ts | 16 +- .../workflow/note-node/note-editor/store.ts | 32 +- 19 files changed, 1117 insertions(+), 538 deletions(-) create mode 100644 web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx create mode 100644 web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/focus.browser.spec.tsx create mode 100644 web/app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/__tests__/focus.browser.spec.tsx diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 32b771f1555..36bcf9d4477 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -4621,15 +4621,9 @@ "eslint-react/set-state-in-effect": { "count": 1 }, - "jsx-a11y/click-events-have-key-events": { - "count": 2 - }, "jsx-a11y/no-autofocus": { "count": 1 }, - "jsx-a11y/no-static-element-interactions": { - "count": 2 - }, "no-restricted-imports": { "count": 1 } diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsx index 4e04298a86d..8ec242fce30 100644 --- a/web/app/components/app/log/__tests__/list.spec.tsx +++ b/web/app/components/app/log/__tests__/list.spec.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from 'react' import { act, fireEvent, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' import { createAccountProfileQueryClient } from '@/test/console/account-profile' import { QueryClientTestProvider } from '@/test/console/query-provider' import { renderWithNuqs } from '@/test/nuqs-testing' @@ -306,6 +307,34 @@ describe('ConversationList', () => { expect(update.options.history).toBe('push') }) + it.each(['keyboard', 'row'])( + 'restores focus to the conversation entry after %s opening', + async (opening) => { + const user = userEvent.setup() + const { onUrlUpdate } = renderConversationList() + const trigger = screen.getByRole('button', { name: 'formatted-1710000000' }) + if (opening === 'keyboard') { + trigger.focus() + await user.keyboard('{Enter}') + } else { + await user.click(screen.getByText('hello world')) + } + await screen.findByRole('dialog') + await waitFor(() => { + expect(onUrlUpdate.mock.calls.at(-1)![0].searchParams.get('conversation_id')).toBe( + 'conversation-1', + ) + }) + await user.keyboard('{Escape}') + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect(trigger).toHaveFocus() + }) + expect(mockOnRefresh).toHaveBeenCalledTimes(1) + expect(onUrlUpdate.mock.calls.at(-1)![0].searchParams.has('conversation_id')).toBe(false) + }, + ) + it('should close the drawer, refresh, and clear modal flags', async () => { mockChatConversationDetail = { id: 'conversation-1', diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsx index d159fd409da..5a6eb91d4ce 100644 --- a/web/app/components/app/log/list.tsx +++ b/web/app/components/app/log/list.tsx @@ -24,6 +24,7 @@ import { DrawerContent, DrawerPopup, DrawerPortal, + DrawerTrigger, DrawerViewport, } from '@langgenius/dify-ui/drawer' import { IconButton } from '@langgenius/dify-ui/icon-button' @@ -912,141 +913,6 @@ const ConversationList: FC = ({ logs, appDetail, onRefresh }) return (
- - - - - - - {isChatflow && ( - - )} - - - - - - - - - {logs.data.map((log: any) => { - const { endUser, isLeftEmpty, isRightEmpty, leftValue, rightValue } = - getConversationRowValues({ - isChatMode, - log, - noChatLabel: t(($) => $['table.empty.noChat'], { ns: 'appLog' }), - noOutputLabel: t(($) => $['table.empty.noOutput'], { ns: 'appLog' }), - }) - return ( - handleRowClick(log)} - > - - - - {isChatflow && ( - - )} - - - - - - - ) - })} - -
- {isChatMode - ? t(($) => $['table.header.summary'], { ns: 'appLog' }) - : t(($) => $['table.header.input'], { ns: 'appLog' })} - - {t(($) => $['table.header.endUser'], { ns: 'appLog' })} - - {t(($) => $['table.header.status'], { ns: 'appLog' })} - - {isChatMode - ? t(($) => $['table.header.messageCount'], { ns: 'appLog' }) - : t(($) => $['table.header.output'], { ns: 'appLog' })} - - {t(($) => $['table.header.userRate'], { ns: 'appLog' })} - - {t(($) => $['table.header.adminRate'], { ns: 'appLog' })} - - {t(($) => $['table.header.updatedTime'], { ns: 'appLog' })} - - {t(($) => $['table.header.time'], { ns: 'appLog' })} -
- {!log.read_at && ( -
- -
- )} -
- {renderTdValue(leftValue, isLeftEmpty, isChatMode && log.annotated)} - {renderTdValue(endUser || defaultValue, !endUser)} - {statusTdRender(log.status_count)} - - {renderTdValue( - rightValue, - isRightEmpty, - !isChatMode && !!log.annotation?.content, - log.annotation, - )} - - {!log.user_feedback_stats.like && !log.user_feedback_stats.dislike ? ( - renderTdValue(defaultValue, true) - ) : ( - <> - {!!log.user_feedback_stats.like && ( - - )} - {!!log.user_feedback_stats.dislike && ( - - )} - - )} - - {!log.admin_feedback_stats.like && !log.admin_feedback_stats.dislike ? ( - renderTdValue(defaultValue, true) - ) : ( - <> - {!!log.admin_feedback_stats.like && ( - - )} - {!!log.admin_feedback_stats.dislike && ( - - )} - - )} - - {formatTime( - log.updated_at, - t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, - )} - - {formatTime( - log.created_at, - t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, - )} -
= ({ logs, appDetail, onRefresh }) if (!open) onCloseDrawer() }} > + + + + + + + {isChatflow && ( + + )} + + + + + + + + + {logs.data.map((log: any) => { + const { endUser, isLeftEmpty, isRightEmpty, leftValue, rightValue } = + getConversationRowValues({ + isChatMode, + log, + noChatLabel: t(($) => $['table.empty.noChat'], { ns: 'appLog' }), + noOutputLabel: t(($) => $['table.empty.noOutput'], { ns: 'appLog' }), + }) + return ( + { + if ((event.target as HTMLElement).closest('button, a')) return + event.currentTarget + .querySelector('button[data-log-detail-trigger]') + ?.click() + }} + > + + + + {isChatflow && ( + + )} + + + + + + + ) + })} + +
+ {isChatMode + ? t(($) => $['table.header.summary'], { ns: 'appLog' }) + : t(($) => $['table.header.input'], { ns: 'appLog' })} + + {t(($) => $['table.header.endUser'], { ns: 'appLog' })} + + {t(($) => $['table.header.status'], { ns: 'appLog' })} + + {isChatMode + ? t(($) => $['table.header.messageCount'], { ns: 'appLog' }) + : t(($) => $['table.header.output'], { ns: 'appLog' })} + + {t(($) => $['table.header.userRate'], { ns: 'appLog' })} + + {t(($) => $['table.header.adminRate'], { ns: 'appLog' })} + + {t(($) => $['table.header.updatedTime'], { ns: 'appLog' })} + + {t(($) => $['table.header.time'], { ns: 'appLog' })} +
+ {!log.read_at && ( +
+ +
+ )} +
+ {renderTdValue(leftValue, isLeftEmpty, isChatMode && log.annotated)} + {renderTdValue(endUser || defaultValue, !endUser)} + {statusTdRender(log.status_count)} + + {renderTdValue( + rightValue, + isRightEmpty, + !isChatMode && !!log.annotation?.content, + log.annotation, + )} + + {!log.user_feedback_stats.like && !log.user_feedback_stats.dislike ? ( + renderTdValue(defaultValue, true) + ) : ( + <> + {!!log.user_feedback_stats.like && ( + + )} + {!!log.user_feedback_stats.dislike && ( + + )} + + )} + + {!log.admin_feedback_stats.like && !log.admin_feedback_stats.dislike ? ( + renderTdValue(defaultValue, true) + ) : ( + <> + {!!log.admin_feedback_stats.like && ( + + )} + {!!log.admin_feedback_stats.dislike && ( + + )} + + )} + + {formatTime( + log.updated_at, + t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, + )} + + { + event.stopPropagation() + handleRowClick(log) + }} + > + {formatTime( + log.created_at, + t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, + )} + +
diff --git a/web/app/components/app/workflow-log/__tests__/list.spec.tsx b/web/app/components/app/workflow-log/__tests__/list.spec.tsx index 3f5bc414ea0..ff5170a7efd 100644 --- a/web/app/components/app/workflow-log/__tests__/list.spec.tsx +++ b/web/app/components/app/workflow-log/__tests__/list.spec.tsx @@ -457,6 +457,44 @@ describe('WorkflowAppLogList', () => { expect(screen.getByText('appLog.runDetail.workflowTitle'))!.toBeInTheDocument() }) + it.each(['keyboard', 'row'])( + 'restores focus to the selected log after %s opening and refresh', + async (opening) => { + const user = userEvent.setup() + const appDetail = createMockApp() + const onRefresh = vi.fn() + useAppStore.setState({ appDetail }) + const logs = createMockLogsResponse([ + createMockWorkflowLog({ id: 'log-1', created_at: 100 }), + createMockWorkflowLog({ id: 'log-2', created_at: 200 }), + ]) + const { rerender } = render( + , + ) + const trigger = screen.getByRole('button', { name: 'formatted-100' }) + if (opening === 'keyboard') { + trigger.focus() + await user.keyboard('{Enter}') + } else { + await user.click(screen.getAllByRole('row')[2]!) + } + await screen.findByRole('dialog') + rerender( + ({ ...log, read_at: 300 })))} + appDetail={appDetail} + onRefresh={onRefresh} + />, + ) + await user.keyboard('{Escape}') + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + expect(trigger).toHaveFocus() + }) + expect(onRefresh).toHaveBeenCalledTimes(1) + }, + ) + it('should close drawer and call onRefresh when closing', async () => { const user = userEvent.setup() const onRefresh = vi.fn() diff --git a/web/app/components/app/workflow-log/list.tsx b/web/app/components/app/workflow-log/list.tsx index 0a3d77e3619..df3ce6d7ba4 100644 --- a/web/app/components/app/workflow-log/list.tsx +++ b/web/app/components/app/workflow-log/list.tsx @@ -14,6 +14,7 @@ import { DrawerContent, DrawerPopup, DrawerPortal, + DrawerTrigger, DrawerViewport, } from '@langgenius/dify-ui/drawer' import { StatusDot } from '@langgenius/dify-ui/status-dot' @@ -128,115 +129,6 @@ const WorkflowAppLogList: FC = ({ logs, appDetail, onRefresh }) => { return (
- - - - - - - - - - {isWorkflow && ( - - )} - - - - {localLogs.map((log: WorkflowAppLogDetail) => { - const endUser = log.created_by_end_user - ? log.created_by_end_user.session_id - : log.created_by_account - ? log.created_by_account.name - : defaultValue - return ( - { - setCurrentLog(log) - setShowDrawer(true) - }} - > - - - - - - - {isWorkflow && ( - - )} - - ) - })} - -
- - - {t(($) => $['table.header.status'], { ns: 'appLog' })} - - {t(($) => $['table.header.runtime'], { ns: 'appLog' })} - - {t(($) => $['table.header.tokens'], { ns: 'appLog' })} - - {t(($) => $['table.header.user'], { ns: 'appLog' })} - - {t(($) => $['table.header.triggered_from'], { ns: 'appLog' })} -
- {!log.read_at && ( -
- -
- )} -
- {formatTime( - log.created_at, - t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, - )} - {statusTdRender(log.workflow_run.status)} -
- {`${log.workflow_run.elapsed_time.toFixed(3)}s`} -
-
{log.workflow_run.total_tokens} -
- {endUser} -
-
- -
= ({ logs, appDetail, onRefresh }) => { if (!open) onCloseDrawer() }} > + + + + + + + + + + {isWorkflow && ( + + )} + + + + {localLogs.map((log: WorkflowAppLogDetail) => { + const endUser = log.created_by_end_user + ? log.created_by_end_user.session_id + : log.created_by_account + ? log.created_by_account.name + : defaultValue + return ( + { + if ((event.target as HTMLElement).closest('button, a')) return + event.currentTarget + .querySelector('button[data-log-detail-trigger]') + ?.click() + }} + > + + + + + + + {isWorkflow && ( + + )} + + ) + })} + +
+ + + {t(($) => $['table.header.status'], { ns: 'appLog' })} + + {t(($) => $['table.header.runtime'], { ns: 'appLog' })} + + {t(($) => $['table.header.tokens'], { ns: 'appLog' })} + + {t(($) => $['table.header.user'], { ns: 'appLog' })} + + {t(($) => $['table.header.triggered_from'], { ns: 'appLog' })} +
+ {!log.read_at && ( +
+ +
+ )} +
+ { + event.stopPropagation() + setCurrentLog(log) + setShowDrawer(true) + }} + > + {formatTime( + log.created_at, + t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string, + )} + + {statusTdRender(log.workflow_run.status)} +
+ {`${log.workflow_run.elapsed_time.toFixed(3)}s`} +
+
{log.workflow_run.total_tokens} +
+ {endUser} +
+
+ +
diff --git a/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx new file mode 100644 index 00000000000..de2b015d8db --- /dev/null +++ b/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx @@ -0,0 +1,153 @@ +import type { ChatItem } from '../../../types' +import { userEvent } from 'vite-plus/test/browser' +import { render } from 'vitest-browser-react' +import Operation from '../operation' + +const feedback = vi.hoisted(() => ({ admin: false, onFeedback: vi.fn() })) + +vi.mock('../../context', () => ({ + useChatContext: () => ({ + config: { supportFeedback: true, supportAnnotation: feedback.admin }, + onFeedback: feedback.onFeedback, + }), +})) + +// These independently owned features do not participate in feedback focus restoration. +vi.mock('@/app/components/app/annotation/edit-annotation-modal', () => ({ default: () => null })) +vi.mock( + '@/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button', + () => ({ default: () => null }), +) +vi.mock('@/app/components/base/new-audio-button', () => ({ default: () => null })) +vi.mock('@/app/components/base/chat/chat/log', () => ({ default: () => null })) + +const item: ChatItem = { id: 'answer', content: 'An answer', isAnswer: true } + +// The exit transition is rendered by Chromium; the default test setup disables it. +it.each(['cancel', 'submit'])( + 'preserves the feedback draft during the %s exit animation', + async (close) => { + const settings = globalThis as typeof globalThis & { BASE_UI_ANIMATIONS_DISABLED: boolean } + const animationsDisabled = settings.BASE_UI_ANIMATIONS_DISABLED + settings.BASE_UI_ANIMATIONS_DISABLED = false + feedback.admin = false + feedback.onFeedback.mockReset().mockResolvedValue(undefined) + try { + const screen = await render( +
+

{item.content}

+ +
, + ) + await screen.getByRole('article', { name: 'Answer' }).hover() + const trigger = screen.getByRole('button', { + name: 'appLog.table.header.userRate: appLog.detail.operation.dislike', + }) + await trigger.click() + const dialog = screen.getByRole('dialog') + const popup = dialog.element() + const textbox = dialog.getByRole('textbox') + await textbox.fill('Please explain the answer') + await expect.poll(() => getComputedStyle(popup).opacity).toBe('1') + const input = textbox.element() as HTMLTextAreaElement + const exitFrame = new Promise<{ draft: string; opacity: number }>((resolve) => { + const onTransition = (event: Event) => { + if (event.target !== popup || (event as TransitionEvent).propertyName !== 'opacity') + return + popup.removeEventListener('transitionrun', onTransition) + resolve({ draft: input.value, opacity: Number(getComputedStyle(popup).opacity) }) + } + popup.addEventListener('transitionrun', onTransition) + }) + + await dialog.getByRole('button', { name: `common.operation.${close}` }).click() + + const closing = await exitFrame + expect(closing.opacity).toBeGreaterThan(0) + expect(closing.draft).toBe('Please explain the answer') + await expect.element(dialog).not.toBeInTheDocument() + await expect.element(trigger).toHaveFocus() + if (close === 'cancel') { + await trigger.click() + await expect.element(screen.getByRole('dialog').getByRole('textbox')).toHaveValue('') + await userEvent.keyboard('{Escape}') + await expect.element(dialog).not.toBeInTheDocument() + } + } finally { + settings.BASE_UI_ANIMATIONS_DISABLED = animationsDisabled + } + }, +) + +describe('Feedback dialog focus', () => { + beforeEach(() => { + feedback.onFeedback.mockReset().mockResolvedValue(undefined) + }) + + // Browser-owned contract: CSS hover visibility must not make the return target unfocusable. + it.each([ + { admin: false, close: 'Escape' }, + { admin: true, close: 'cancel' }, + { admin: false, close: 'submit' }, + { admin: true, close: 'submit' }, + ])( + 'returns to the visible feedback button after $close (admin: $admin)', + async ({ admin, close }) => { + feedback.admin = admin + const screen = await render( + <> + +
+

{item.content}

+ +
+ , + ) + const trigger = screen.getByRole('button', { + name: `${admin ? 'appLog.table.header.adminRate' : 'appLog.table.header.userRate'}: appLog.detail.operation.dislike`, + }) + if (close === 'Escape') { + await screen.getByRole('button', { name: 'Before answer' }).click() + await userEvent.keyboard('{Tab}{Tab}') + await expect.element(trigger).toHaveFocus() + await userEvent.keyboard('{Enter}') + } else { + await screen.getByRole('article', { name: 'Answer' }).hover() + await trigger.click() + } + const dialog = screen.getByRole('dialog') + await expect.element(dialog).toBeVisible() + await dialog.getByRole('textbox').hover() + if (close === 'Escape') await userEvent.keyboard('{Escape}') + else if (close === 'submit') + await dialog.getByRole('button', { name: 'common.operation.submit' }).click() + else await dialog.getByRole('button', { name: 'common.operation.cancel' }).click() + + await expect.element(dialog).not.toBeInTheDocument() + await expect.element(trigger).toBeVisible() + await expect.element(trigger).toHaveFocus() + expect(trigger.element().checkVisibility({ checkOpacity: true })).toBe(true) + if (close === 'submit') { + await expect.element(trigger).toHaveAttribute('aria-pressed', 'true') + expect(feedback.onFeedback).toHaveBeenCalledWith('answer', { + rating: 'dislike', + content: '', + }) + } + }, + ) +}) diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsx index 5efbe278609..cecf5d452b2 100644 --- a/web/app/components/base/chat/chat/answer/operation.tsx +++ b/web/app/components/base/chat/chat/answer/operation.tsx @@ -8,6 +8,7 @@ import { DialogContent, DialogDescription, DialogTitle, + DialogTrigger, } from '@langgenius/dify-ui/dialog' import { IconButton } from '@langgenius/dify-ui/icon-button' import { Textarea } from '@langgenius/dify-ui/textarea' @@ -15,7 +16,7 @@ import { toast } from '@langgenius/dify-ui/toast' import { Toggle } from '@langgenius/dify-ui/toggle' import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip' import copy from 'copy-to-clipboard' -import { memo, useId, useMemo, useState } from 'react' +import { memo, useId, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import EditReplyModal from '@/app/components/app/annotation/edit-annotation-modal' import Log from '@/app/components/base/chat/chat/log' @@ -45,6 +46,8 @@ type FeedbackTooltipProps = { const feedbackTooltipClassName = 'max-w-[260px]' const answerActiveFlexClassName = 'group-hover:flex group-has-[[data-popup-open]]:flex' const answerActiveBlockClassName = 'group-hover:block group-has-[[data-popup-open]]:block' +const feedbackActionsClassName = + 'flex pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100 has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100' const accentPressedClassName = 'data-pressed:bg-state-accent-active data-pressed:text-text-accent data-pressed:hover:bg-state-accent-active-alt' const destructivePressedClassName = @@ -99,6 +102,9 @@ function Operation({ readonly, } = useChatContext() const [isShowReplyModal, setIsShowReplyModal] = useState(false) + // Submitting replaces the dialog trigger with the current rating button. + const userFeedbackRef = useRef(null) + const adminFeedbackRef = useRef(null) const [isShowFeedbackModal, setIsShowFeedbackModal] = useState(false) const [feedbackContent, setFeedbackContent] = useState('') const { id, isOpeningStatement, annotation, feedback, adminFeedback, humanInputFormDataList } = @@ -177,21 +183,14 @@ function Operation({ void handleFeedback('like', undefined, target) } - const handleDislikeClick = (target: 'user' | 'admin') => { - setFeedbackTarget(target) - setIsShowFeedbackModal(true) - } - const handleFeedbackSubmit = async () => { const succeeded = await handleFeedback('dislike', feedbackContent, feedbackTarget) if (!succeeded) return - setFeedbackContent('') setIsShowFeedbackModal(false) } const handleFeedbackCancel = () => { - setFeedbackContent('') setIsShowFeedbackModal(false) } @@ -235,164 +234,228 @@ function Operation({ style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}} data-testid="operation-bar" > - {shouldShowUserFeedbackBar && !humanInputFormDataList?.length && ( -
- {hasUserFeedback ? ( - - - !pressed && void handleFeedback(null, undefined, 'user') - } - render={ - - {displayUserFeedback?.rating === 'like' ? ( - - } - /> - - ) : ( - <> - pressed && handleLikeClick('user')} - render={ - - - } - /> - pressed && handleDislikeClick('user')} - render={ - - - } - /> - - )} -
- )} - {shouldShowAdminFeedbackBar && !humanInputFormDataList?.length && ( -
- {displayUserFeedback?.rating && ( - - - - - )} - - {displayUserFeedback?.rating && ( -
- )} - {hasAdminFeedback ? ( - - - !pressed && void handleFeedback(null, undefined, 'admin') - } - render={ - - {displayAdminFeedback?.rating === 'like' ? ( - - } - /> - - ) : ( - <> + { + if (!open) setFeedbackContent('') + }} + > + {shouldShowUserFeedbackBar && !humanInputFormDataList?.length && ( +
+ {hasUserFeedback ? ( + + !pressed && void handleFeedback(null, undefined, 'user') + } + render={ + + {displayUserFeedback?.rating === 'like' ? ( + + } + /> + + ) : ( + <> pressed && handleLikeClick('admin')} + onPressedChange={(pressed) => pressed && handleLikeClick('user')} render={ - + } /> - - - pressed && handleDislikeClick('admin')} + setFeedbackTarget('user')} render={ - + } /> + + )} +
+ )} + {shouldShowAdminFeedbackBar && !humanInputFormDataList?.length && ( +
+ {displayUserFeedback?.rating && ( + + + - - )} -
- )} + )} + + {displayUserFeedback?.rating && ( +
+ )} + {hasAdminFeedback ? ( + + + !pressed && void handleFeedback(null, undefined, 'admin') + } + render={ + + {displayAdminFeedback?.rating === 'like' ? ( + + } + /> + + ) : ( + <> + + pressed && handleLikeClick('admin')} + render={ + + + } + /> + + + setFeedbackTarget('admin')} + render={ + + + } + /> + + + )} +
+ )} + +
+
+ + {t(($) => $['feedback.title'], { ns: 'common' }) || 'Provide Feedback'} + + + {t(($) => $['feedback.subtitle'], { ns: 'common' }) || + 'Please tell us what went wrong with this response'} + + $['operation.close'], { ns: 'common' })} + size="lg" + className="absolute top-5 right-5" + > + + + } + /> +
+
+ +