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

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

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

No files matched your search

@@ -0,0 +1,81 @@
# E2E test environment template — copy to ../.env.e2e or cli/.env.e2e
# depending on the test command working directory, then fill in values.
#
# .env.e2e is git-ignored; this file is safe to commit.
#
# ── Run mode ────────────────────────────────────────────────────────────────
# Leave unset for real staging E2E. Set to "local" only for local-mode suites.
# DIFY_E2E_MODE=local
# ── Edition selector ────────────────────────────────────────────────────────
# ce = Community Edition (default)
# ee = Enterprise Edition; requires workspaces named exactly auto_test0/auto_test1.
DIFY_E2E_EDITION=ee
# ── Required for real staging E2E ───────────────────────────────────────────
# DIFY_E2E_HOST is the OpenAPI / console base URL unless DIFY_E2E_CONSOLE_URL is set.
DIFY_E2E_HOST=
DIFY_E2E_EMAIL=
DIFY_E2E_PASSWORD=
# ── Enterprise workspace contract ───────────────────────────────────────────
# For DIFY_E2E_EDITION=ee, the logged-in account must already have:
# auto_test0 → primary workspace; global-setup checks 8 fixture apps here.
# auto_test1 → secondary workspace; global-setup checks 1 fixture app here.
#
# If either workspace is missing, global-setup does not import DSL fixtures.
# If a fixture app is missing, global-setup imports it from test/e2e/fixtures/apps.
# If it already exists by exact app name, import is skipped.
#
# auto_test0 fixture apps:
# echo-chat.yml → echo-bot
# echo-workflow.yml → basic_auto_test
# file-upload.yml → file_auto_test
# hitl-main.yml → hitl_auto_test
# hitl-external.yml → DIFY_E2E_HITL_EXTERNAL
# hitl-single-action.yml → DIFY_E2E_HITL_SINGLE_ACTION
# hitl-multi-node.yml → DIFY_E2E_HITL_MULTI_NODE
# file-chat.yml → DIFY_E2E_FILE_CHAT
#
# auto_test1 fixture app:
# ws2-workflow.yml → auto_test_workspace2
# ── Optional host override ──────────────────────────────────────────────────
# Use only when console login/provisioning URL differs from DIFY_E2E_HOST.
# DIFY_E2E_CONSOLE_URL=
# ── Optional tokens ─────────────────────────────────────────────────────────
# Primary internal bearer token (dfoa_). When unset, global-setup mints/caches one.
# DIFY_E2E_TOKEN=
#
# External SSO bearer token (dfoe_). Required only for SSO-specific cases.
# DIFY_E2E_SSO_TOKEN=
# ── Optional manual fallbacks ────────────────────────────────────────────────
# Normally leave these blank: global-setup discovers workspaces and fixture app IDs.
# They are fallback values for debugging or when provisioning is intentionally skipped.
# DIFY_E2E_WORKSPACE_ID=
# DIFY_E2E_WORKSPACE_NAME=auto_test0
# DIFY_E2E_WS2_ID=
#
# DIFY_E2E_CHAT_APP_ID=
# DIFY_E2E_WORKFLOW_APP_ID=
# DIFY_E2E_FILE_APP_ID=
# DIFY_E2E_FILE_CHAT_APP_ID=
# DIFY_E2E_HITL_APP_ID=
# DIFY_E2E_HITL_EXTERNAL_APP_ID=
# DIFY_E2E_HITL_SINGLE_ACTION_APP_ID=
# DIFY_E2E_HITL_MULTI_NODE_APP_ID=
# DIFY_E2E_WS2_APP_ID=
# ── Separated-mode reasoning suite (opt-in) ─────────────────────────────────
# run-app-reasoning.e2e.ts is skipped unless DIFY_E2E_REASONING_APP_ID resolves.
# It needs a chatflow whose LLM node uses reasoning_format=separated AND a
# workspace with a default chat model configured.
#
# Either point at an existing app:
# DIFY_E2E_REASONING_APP_ID=
#
# …or auto-provision reasoning-chat.yml (→ app name "reasoning-bot"). Off by
# default so the shared bootstrap stays free of any model dependency.
# DIFY_E2E_REASONING_PROVISION=1
+209
View File
@@ -0,0 +1,209 @@
# Dify CLI — E2E Test Suite
End-to-end tests that exercise the **real `difyctl` binary** against a live
Dify server. Every test uses an isolated temporary config directory so no
state leaks between test files.
## Directory layout
```
test/e2e/
├── setup/
│ ├── env.ts — Load & validate DIFY_E2E_* env vars (CE + EE)
│ ├── global-setup.ts — CE/EE-aware bootstrap: account creation, token
│ │ minting, workspace provisioning, DSL import
│ └── global-teardown.ts — Delete conversations created during the run
│
├── helpers/
│ ├── cli.ts — run(), withAuthFixture(), mintFreshToken(),
│ │ injectAuth(), spawn_background()
│ ├── assert.ts — assertExitCode, assertJson, assertErrorEnvelope,
│ │ assertNoAnsi, assertPipeFriendlyJson, ...
│ ├── cleanup-registry.ts — registerConversation() / cleanupRegisteredConversations()
│ ├── retry.ts — withRetry(fn, { attempts, delayMs })
│ └── skip.ts — optionalIt(), optionalDescribe(),
│ enterpriseOnlyIt(), enterpriseOnlyDescribe(), isEE()
│
└── suites/
├── auth/
│ ├── status.e2e.ts — auth status (text + JSON + SSO)
│ ├── use.e2e.ts — workspace switching ([EE] cases require 2 workspaces)
│ ├── whoami.e2e.ts — whoami + external SSO session checks
│ ├── devices.e2e.ts — devices list + revoke (runs near-last)
│ └── logout.e2e.ts — logout + local credential cleanup (runs last)
├── config/
│ └── config.e2e.ts — config path/get/set/unset/view, env override
├── discovery/
│ ├── get-app-list.e2e.ts — basic get app list
│ ├── get-app-single.e2e.ts — get single app by ID
│ ├── describe-app.e2e.ts — describe app
│ └── get-app-all-workspaces.e2e.ts — get app -A ([EE] multi-workspace cases)
└── run/
├── run-app-basic.e2e.ts — basic run, -o json, --inputs, streaming,
│ conversation, CI mode
├── run-app-streaming.e2e.ts — Ctrl+C / error-event / chunk timing
├── run-app-file.e2e.ts — --file upload (local + remote URL)
├── run-app-reasoning.e2e.ts — separated-mode reasoning (--think); opt-in
└── run-app-hitl.e2e.ts — HITL pause + resume
```
## Edition support
`difyctl` supports two Dify editions. The test suite adapts automatically:
| Edition | `DIFY_E2E_EDITION` | Workspaces | EE-only cases |
| ----------------------- | ------------------ | ---------------- | ------------- |
| Community Edition (CE) | `ce` (default) | 1 | Skipped |
| Enterprise Edition (EE) | `ee` | 2 (auto-created) | Active |
### EE-only test cases
Tests that require Enterprise Edition features (workspace switching between
independent workspaces, cross-workspace app query, etc.) are tagged `[EE]`
in their names and wrapped with `enterpriseOnlyIt()` / `enterpriseOnlyDescribe()`
from `helpers/skip.ts`. In CE mode these tests are automatically skipped.
```ts
// helpers/skip.ts usage
const eeIt = enterpriseOnlyIt(caps)
eeIt('[EE][P0] cross-workspace query returns apps from all workspaces', async () => {
// test body
})
```
## Setup
Copy the credential template and fill in your values:
```bash
cp cli/test/e2e/.env.e2e.example cli/.env.e2e
# edit cli/.env.e2e with real credentials
```
### Community Edition (CE) — minimum 3 vars
| Variable | Description |
| ------------------- | ----------------------------------------------------- |
| `DIFY_E2E_HOST` | Server base URL (`http://localhost`) |
| `DIFY_E2E_EMAIL` | Account email — created automatically by global-setup |
| `DIFY_E2E_PASSWORD` | Account password |
global-setup will:
1. Register the account (idempotent — safe to rerun)
1. Login and mint a bearer token via the device flow
1. Import all DSL fixtures into the single workspace
1. Publish apps and set access_mode → public
### Enterprise Edition (EE) — 5 required vars
| Variable | Description |
| ------------------------------------ | ------------------------------------------------------- |
| `DIFY_E2E_EDITION` | Must be `ee` |
| `DIFY_E2E_HOST` | Console/API base URL |
| `DIFY_E2E_EMAIL` | Member account email — created via enterprise API |
| `DIFY_E2E_PASSWORD` | Member account password |
| `DIFY_E2E_ENTERPRISE_API_URL` | Enterprise admin API base URL (`https://.../inner/api`) |
| `DIFY_E2E_ENTERPRISE_API_SECRET_KEY` | Enterprise admin API secret key |
Optional:
| Variable | Description |
| ---------------------- | --------------------------------------------- |
| `DIFY_E2E_CONSOLE_URL` | Console URL if different from `DIFY_E2E_HOST` |
global-setup will:
1. Create the member account via the enterprise admin API (idempotent)
1. Login and obtain a session cookie
1. Create two workspaces (`e2e-primary-auto`, `e2e-secondary-auto`) via the enterprise API
1. Import DSL fixtures into both workspaces
1. Publish apps and set access_mode → public via the enterprise API
### Optional overrides (both editions)
| Variable | Description |
| ------------------------------------ | ------------------------------------------------ |
| `DIFY_E2E_TOKEN` | Pre-minted bearer token — skips device-flow mint |
| `DIFY_E2E_SSO_TOKEN` | External SSO bearer token (`dfoe_...`) |
| `DIFY_E2E_WORKSPACE_ID` | Override primary workspace ID |
| `DIFY_E2E_WORKSPACE_NAME` | Override primary workspace name |
| `DIFY_E2E_WS2_ID` | Override secondary workspace ID (EE) |
| `DIFY_E2E_CHAT_APP_ID` | Override echo-chat app ID |
| `DIFY_E2E_WORKFLOW_APP_ID` | Override echo-workflow app ID |
| `DIFY_E2E_FILE_APP_ID` | Override file-upload app ID |
| `DIFY_E2E_FILE_CHAT_APP_ID` | Override file-chat app ID |
| `DIFY_E2E_HITL_APP_ID` | Override HITL main app ID |
| `DIFY_E2E_HITL_EXTERNAL_APP_ID` | |
| `DIFY_E2E_HITL_SINGLE_ACTION_APP_ID` | |
| `DIFY_E2E_HITL_MULTI_NODE_APP_ID` | |
| `DIFY_E2E_WS2_APP_ID` | Override secondary workspace app ID (EE) |
| `DIFY_E2E_REASONING_APP_ID` | separated-reasoning chatflow app ID (opt-in) |
| `DIFY_E2E_REASONING_PROVISION` | `1` → auto-provision `reasoning-chat.yml` |
### Separated-mode reasoning suite (opt-in)
`run-app-reasoning.e2e.ts` verifies the out-of-band `reasoning_chunk` channel
(PR #37460): `--think` surfaces the chain-of-thought to stderr framed as
`<think>…</think>`, the answer stays clean, and `-o json` persists it under
`metadata.reasoning`. It is **skipped** unless `DIFY_E2E_REASONING_APP_ID`
resolves, because it runs a real LLM node and needs:
1. a chatflow whose LLM node uses `reasoning_format: separated`, and
1. a workspace with a default chat model configured.
Point `DIFY_E2E_REASONING_APP_ID` at such an app, or set
`DIFY_E2E_REASONING_PROVISION=1` to import the `reasoning-chat.yml` fixture
(its system prompt forces a `<think>` block, so any chat model triggers the
separated path — no dedicated reasoning model required).
## Running tests
```bash
cd cli
# Community Edition (default)
bun run test:e2e
# Enterprise Edition
DIFY_E2E_EDITION=ee bun run test:e2e
# Run only [P0] smoke cases
bun run test:e2e:smoke
# Run only EE-tagged cases (P0 smoke)
DIFY_E2E_EDITION=ee bun run test:e2e:smoke --testNamePattern "\[EE\]"
# Run offline-safe config tests only (no network required)
bun run test:e2e:local
# Run a single file
vp test --config vitest.e2e.config.ts test/e2e/suites/auth/status.e2e.ts
```
## Test execution order
Files run sequentially (`fileParallelism: false`) in this order:
```
login → status → use → whoami → help → config → output → error-handling
→ framework → discovery → run (basic / streaming / file / HITL)
→ devices → logout
```
`devices` and `logout` run last because they revoke real server sessions.
## Design decisions
| Decision | Rationale |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| **CE/EE edition flag** | `DIFY_E2E_EDITION=ce/ee` controls global-setup bootstrap path and activates/skips `[EE]`-tagged tests. |
| **`[EE]` tag convention** | Test names include `[EE]` to make skipped cases visible in the report and to allow `--testNamePattern "\[EE\]"` filtering. |
| **`enterpriseOnlyIt(caps)`** | Returns `it` in EE mode, `it.skip` in CE mode — no runtime assertions needed, skip is declarative. |
| **No mocking** | All HTTP traffic goes to the real server — this catches real integration regressions. |
| **Isolated config dirs** | Each test creates a fresh `withTempConfig()` dir; session state never leaks between tests. |
| **`withAuthFixture()`** | Combines `withTempConfig` + `injectAuth` into a single fixture; reduces beforeEach boilerplate. |
| **`injectAuth()` bypasses Device Flow** | Non-auth tests skip the browser step; only `auth/` suites exercise the real flow. |
| **`mintFreshToken()`** | `logout` and `devices-revoke` tests mint a disposable `dfoa_` token via the device flow API. |
| **Global `retry: 0`** | Flaky network calls use `withRetry()` locally; global retry masks non-idempotent failures. |
| **Conversation cleanup** | `registerConversation()` + global-teardown delete staging conversations after the run. |
@@ -0,0 +1,124 @@
app:
description: e2e-test
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: advanced-chat
name: echo-bot
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
sourceType: start
targetType: answer
id: 1779690795511-answer
source: '1779690795511'
sourceHandle: source
target: answer
targetHandle: target
type: custom
nodes:
- data:
selected: false
title: User Input
type: start
variables:
- default: ''
hint: ''
label: input
max_length: 256
options: []
placeholder: ''
required: false
type: text-input
variable: input
height: 109
id: '1779690795511'
position:
x: 79
y: 282
positionAbsolute:
x: 79
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
answer: 'echo:{{#sys.query#}}'
selected: false
title: Reply
type: answer
variables: []
height: 103
id: answer
position:
x: 380
y: 282
positionAbsolute:
x: 380
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 151
y: 125
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,157 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: basic_auto_test
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: end
id: 1779097154262-source-1779171097399-target
source: '1779097154262'
sourceHandle: source
target: '1779171097399'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: true
title: User Input
type: start
variables:
- default: ''
hint: ''
label: x
options: []
placeholder: ''
required: true
type: text-input
variable: x
- default: ''
hint: ''
label: num
options: []
placeholder: ''
required: true
type: number
variable: num
- hint: ''
label: enum_var
options:
- A
- B
- C
placeholder: ''
required: true
type: select
variable: enum_var
- default: ''
hint: ''
label: paragraph
max_length: 100
options: []
placeholder: ''
required: true
type: text-input
variable: paragraph
height: 187
id: '1779097154262'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
selected: true
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1779097154262'
- x
value_type: string
variable: x
selected: false
title: Output
type: end
height: 88
id: '1779171097399'
position:
x: 752
y: 259
positionAbsolute:
x: 752
y: 259
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 68
y: 131
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,130 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: advanced-chat
name: DIFY_E2E_FILE_CHAT
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
sourceType: start
targetType: answer
id: 1780453002656-answer
source: '1780453002656'
sourceHandle: source
target: answer
targetHandle: target
type: custom
nodes:
- data:
selected: false
title: User Input
type: start
variables:
- allowed_file_extensions: []
allowed_file_types:
- document
allowed_file_upload_methods:
- local_file
- remote_url
default: ''
hide: false
hint: ''
label: file_input
options: []
placeholder: ''
required: true
type: file
variable: file_input
height: 109
id: '1780453002656'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
answer: ok
selected: false
title: Reply
type: answer
variables: []
height: 103
id: answer
position:
x: 380
y: 282
positionAbsolute:
x: 380
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 0
y: 0
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,147 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: file_auto_test
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: end
id: 1779693724732-source-1779693765299-target
source: '1779693724732'
sourceHandle: source
target: '1779693765299'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: true
title: User Input
type: start
variables:
- allowed_file_extensions: []
allowed_file_types:
- document
allowed_file_upload_methods:
- local_file
- remote_url
default: ''
hide: false
hint: ''
label: doc
options: []
placeholder: ''
required: true
type: file
variable: doc
- allowed_file_extensions: []
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
default: ''
hide: false
hint: ''
label: picture
options: []
placeholder: ''
required: true
type: file
variable: picture
height: 135
id: '1779693724732'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
selected: true
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs: []
selected: false
title: Output
type: end
height: 88
id: '1779693765299'
position:
x: 684
y: 282
positionAbsolute:
x: 684
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 49
y: 23
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,204 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: DIFY_E2E_HITL_EXTERNAL
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: human-input
id: 1780458810652-source-1780467012278-target
source: '1780458810652'
sourceHandle: source
target: '1780467012278'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: end
id: 1780467012278-__timeout-1780467075179-target
source: '1780467012278'
sourceHandle: __timeout
target: '1780467075179'
targetHandle: target
type: custom
zIndex: 0
- data:
isInLoop: false
sourceType: human-input
targetType: end
id: 1780467012278-action_1-1780467098495-target
source: '1780467012278'
sourceHandle: action_1
target: '1780467098495'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: true
title: 用户输入
type: start
variables: []
height: 73
id: '1780458810652'
position:
x: 79
y: 282
positionAbsolute:
x: 79
y: 282
selected: true
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
delivery_methods:
- config:
body: '{{#url#}}'
debug_mode: false
recipients:
items: []
whole_workspace: true
subject: TEST
enabled: true
id: 74e23f16-04ad-45cd-9984-55d491b47ae7
type: email
form_content: TEST
inputs: []
selected: false
timeout: 1
timeout_unit: hour
title: 人工介入
type: human-input
user_actions:
- button_style: default
id: action_1
title: Button Text 1
height: 164
id: '1780467012278'
position:
x: 382
y: 282
positionAbsolute:
x: 382
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1780467012278'
- __action_id
value_type: string
variable: X
selected: false
title: 输出
type: end
height: 88
id: '1780467075179'
position:
x: 684
y: 282
positionAbsolute:
x: 684
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- sys
- user_id
value_type: string
variable: X
selected: false
title: 输出 2
type: end
height: 89
id: '1780467098495'
position:
x: 684
y: 409
positionAbsolute:
x: 684
y: 409
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: -153
y: -2
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,239 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: hitl_auto_test
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: human-input
id: 1779694031897-source-1779786788846-target
source: '1779694031897'
sourceHandle: source
target: '1779786788846'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: end
id: 1779786788846-__timeout-1779786805561-target
source: '1779786788846'
sourceHandle: __timeout
target: '1779786805561'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: end
id: 1779786788846-action_2-1780468501391-target
source: '1779786788846'
sourceHandle: action_2
target: '1780468501391'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: end
id: 1779786788846-action_3-1780468504241-target
source: '1779786788846'
sourceHandle: action_3
target: '1780468504241'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: false
title: 用户输入
type: start
variables: []
height: 73
id: '1779694031897'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
delivery_methods:
- enabled: true
id: d3e67c3d-1779-478a-af2e-17d6da044175
type: webapp
form_content: ''
inputs: []
selected: false
timeout: 3
timeout_unit: day
title: 人工介入
type: human-input
user_actions:
- button_style: default
id: action_1
title: Button Text 1
- button_style: default
id: action_2
title: Button Text 2
- button_style: default
id: action_3
title: Button Text 3
height: 216
id: '1779786788846'
position:
x: 382
y: 282
positionAbsolute:
x: 382
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1779786788846'
- __action_id
value_type: string
variable: x
selected: false
title: 输出
type: end
height: 88
id: '1779786805561'
position:
x: 685
y: 282
positionAbsolute:
x: 685
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1779786788846'
- __action_id
value_type: string
variable: x
selected: false
title: 输出 2
type: end
height: 88
id: '1780468501391'
position:
x: 685
y: 409
positionAbsolute:
x: 685
y: 409
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1779786788846'
- __action_id
value_type: string
variable: x
selected: true
title: 输出 3
type: end
height: 88
id: '1780468504241'
position:
x: 685
y: 500
positionAbsolute:
x: 685
y: 500
selected: true
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 149
y: 87
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,203 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: DIFY_E2E_HITL_MULTI_NODE
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: human-input
id: 1780469920434-source-1780469926552-target
source: '1780469920434'
sourceHandle: source
target: '1780469926552'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: human-input
id: 1780469926552-action_1-1780469934902-target
source: '1780469926552'
sourceHandle: action_1
target: '1780469934902'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: end
id: 1780469934902-action_1-1780469952268-target
source: '1780469934902'
sourceHandle: action_1
target: '1780469952268'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: false
title: 用户输入
type: start
variables: []
height: 73
id: '1780469920434'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
delivery_methods:
- enabled: true
id: bc4c7145-a3df-4d15-835f-4e2ebd7a8c16
type: webapp
form_content: ''
inputs: []
selected: false
timeout: 3
timeout_unit: day
title: 人工介入
type: human-input
user_actions:
- button_style: default
id: action_1
title: Button Text 1
height: 164
id: '1780469926552'
position:
x: 382
y: 282
positionAbsolute:
x: 382
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
delivery_methods:
- enabled: true
id: d6e91d88-30bb-4397-a5a2-21c7c76382ea
type: webapp
form_content: ''
inputs: []
selected: false
timeout: 3
timeout_unit: day
title: 人工介入 2
type: human-input
user_actions:
- button_style: default
id: action_1
title: Button Text 1
height: 164
id: '1780469934902'
position:
x: 684
y: 282
positionAbsolute:
x: 684
y: 282
selected: true
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1780469934902'
- __action_id
value_type: string
variable: x
selected: true
title: 输出
type: end
height: 88
id: '1780469952268'
position:
x: 986
y: 282
positionAbsolute:
x: 986
y: 282
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 0
y: 0
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,163 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: DIFY_E2E_HITL_SINGLE_ACTION
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: human-input
id: 1780469476206-source-1780469487574-target
source: '1780469476206'
sourceHandle: source
target: '1780469487574'
targetHandle: target
type: custom
zIndex: 0
- data:
isInIteration: false
isInLoop: false
sourceType: human-input
targetType: end
id: 1780469487574-action_1-1780469495040-target
source: '1780469487574'
sourceHandle: action_1
target: '1780469495040'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: false
title: 用户输入
type: start
variables: []
height: 73
id: '1780469476206'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
delivery_methods:
- enabled: true
id: 2375bc8b-8a9e-4ce6-a87c-9354e05735b7
type: webapp
form_content: ''
inputs: []
selected: true
timeout: 3
timeout_unit: day
title: 人工介入
type: human-input
user_actions:
- button_style: default
id: action_1
title: Button Text 1
height: 164
id: '1780469487574'
position:
x: 382
y: 282
positionAbsolute:
x: 382
y: 282
selected: true
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs:
- value_selector:
- '1780469487574'
- __action_id
value_type: string
variable: x
selected: false
title: 输出
type: end
height: 88
id: '1780469495040'
position:
x: 684
y: 282
positionAbsolute:
x: 684
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: 0
y: 0
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,120 @@
# Chatflow that exercises separated-mode reasoning (PR #37460): the LLM node sets
# reasoning_format=separated, so the server strips <think>...</think> from the
# answer and streams the chain-of-thought on the out-of-band `reasoning_chunk`
# channel instead. The system prompt forces a <think> block, so the separated
# path triggers with any chat model — no dedicated reasoning model required.
#
# NOTE: the LLM node leaves model.provider/name empty and relies on the target
# workspace's configured default chat model. The run-app-reasoning E2E suite is
# gated on DIFY_E2E_REASONING_APP_ID, so it is skipped unless a server with a
# working model is wired up.
app:
description: e2e-test reasoning (separated mode)
icon: 🧠
icon_background: '#FFEAD5'
icon_type: emoji
mode: advanced-chat
name: reasoning-bot
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload: {}
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- id: start-llm
source: '1755189262236'
sourceHandle: source
target: llm
targetHandle: target
- id: llm-answer
source: llm
sourceHandle: source
target: answer
targetHandle: target
nodes:
- data:
desc: ''
title: Start
type: start
variables: []
id: '1755189262236'
position:
x: 80
y: 282
sourcePosition: right
targetPosition: left
type: custom
- data:
context:
enabled: false
variable_selector: []
desc: ''
memory:
query_prompt_template: '{{#sys.query#}}'
window:
enabled: false
size: 10
model:
completion_params:
temperature: 0.7
mode: chat
name: ''
provider: ''
prompt_template:
- role: system
text: >-
You are a helpful assistant. Always reason step by step INSIDE a
single <think>...</think> block first, then write the final
answer AFTER the closing </think> tag. The final answer must not
contain any <think> tags.
reasoning_format: separated
selected: false
title: LLM
type: llm
variables: []
vision:
enabled: false
id: llm
position:
x: 380
y: 282
sourcePosition: right
targetPosition: left
type: custom
- data:
answer: '{{#llm.text#}}'
desc: ''
title: Answer
type: answer
variables: []
id: answer
position:
x: 680
y: 282
sourcePosition: right
targetPosition: left
type: custom
viewport:
x: 0
y: 0
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,116 @@
app:
description: ''
icon: 🤖
icon_background: '#FFEAD5'
icon_type: emoji
mode: workflow
name: auto_test_workspace2
use_icon_as_answer_icon: false
dependencies: []
kind: app
version: 0.6.0
workflow:
conversation_variables: []
environment_variables: []
features:
file_upload:
allowed_file_extensions:
- .JPG
- .JPEG
- .PNG
- .GIF
- .WEBP
- .SVG
allowed_file_types:
- image
allowed_file_upload_methods:
- local_file
- remote_url
enabled: false
fileUploadConfig:
attachment_image_file_size_limit: 2
audio_file_size_limit: 50
batch_count_limit: 5
file_size_limit: 15
file_upload_limit: 20
image_file_batch_limit: 10
image_file_size_limit: 10
single_chunk_attachment_limit: 10
video_file_size_limit: 100
workflow_file_upload_limit: 10
image:
enabled: false
number_limits: 3
transfer_methods:
- local_file
- remote_url
number_limits: 3
opening_statement: ''
retriever_resource:
enabled: true
sensitive_word_avoidance:
enabled: false
speech_to_text:
enabled: false
suggested_questions: []
suggested_questions_after_answer:
enabled: false
text_to_speech:
enabled: false
language: ''
voice: ''
graph:
edges:
- data:
isInIteration: false
isInLoop: false
sourceType: start
targetType: end
id: 1780305524693-source-1780305600095-target
source: '1780305524693'
sourceHandle: source
target: '1780305600095'
targetHandle: target
type: custom
zIndex: 0
nodes:
- data:
selected: false
title: User Input
type: start
variables: []
height: 73
id: '1780305524693'
position:
x: 80
y: 282
positionAbsolute:
x: 80
y: 282
sourcePosition: right
targetPosition: left
type: custom
width: 242
- data:
outputs: []
selected: false
title: Output
type: end
height: 88
id: '1780305600095'
position:
x: 684
y: 282
positionAbsolute:
x: 684
y: 282
selected: false
sourcePosition: right
targetPosition: left
type: custom
width: 242
viewport:
x: -153
y: 125
zoom: 1
rag_pipeline_variables: []
@@ -0,0 +1,152 @@
/**
* E2E assertion helpers.
*
* These wrap vitest's `expect` with richer failure messages that include the
* full stdout / stderr of the failing process — essential for debugging CI.
*/
import type { RunResult } from './cli.js'
import { expect } from 'vite-plus/test'
import './vitest-context.js'
// ── ANSI ──────────────────────────────────────────────────────────────────
const ANSI_RE = /\x1B\[[0-9;]*[mGKHFA-DJsuhl]/g
function redact(text: string): string {
return text
.replace(/\bBearer\s+[\w.-]+\b/g, 'Bearer [REDACTED]')
.replace(/\bdfo[ae]_[\w-]+\b/g, 'dfo*_REDACTED')
}
// ── Exit code ─────────────────────────────────────────────────────────────
/**
* Assert the exit code matches `expected`.
* On failure, prints the full stdout and stderr so the cause is visible in CI.
*/
export function assertExitCode(result: RunResult, expected: number): void {
if (result.exitCode !== expected) {
process.stderr.write(
`\n[E2E assertExitCode] expected ${expected}, got ${result.exitCode}\n` +
`stdout:\n${redact(result.stdout) || '(empty)'}\n` +
`stderr:\n${redact(result.stderr) || '(empty)'}\n`,
)
}
expect(result.exitCode, `exit code should be ${expected}`).toBe(expected)
}
/**
* Assert the exit code is NOT 0 (i.e. some error occurred).
*/
export function assertNonZeroExit(result: RunResult): void {
expect(result.exitCode, 'exit code should be non-zero').not.toBe(0)
}
// ── Stdout / stderr content ───────────────────────────────────────────────
/**
* Assert stdout is valid JSON and return the parsed value.
*/
export function assertJson<T = unknown>(result: RunResult): T {
let parsed: T
try {
parsed = JSON.parse(result.stdout) as T
} catch {
throw new Error(
`stdout is not valid JSON.\nstdout:\n${redact(result.stdout)}\nstderr:\n${redact(result.stderr)}`,
)
}
return parsed
}
/**
* Assert stderr contains a valid JSON error envelope of the shape:
* { error: { code: string, message: string, hint?: string } }
*
* @param result - The run result to inspect.
* @param expectedCode - When provided, also asserts that error.code equals this value.
* Use the stable error codes from the CLI contract, e.g.:
* 'not_logged_in', 'app_not_found', 'insufficient_scope', 'auth_expired'
*
* @example
* assertErrorEnvelope(result, 'not_logged_in')
* assertErrorEnvelope(result, 'app_not_found')
*/
export function assertErrorEnvelope(
result: RunResult,
expectedCode?: string,
): { error: { code: string; message: string; hint?: string } } {
const raw = result.stderr.trim()
let parsed: { error: { code: string; message: string; hint?: string } }
try {
parsed = JSON.parse(raw) as typeof parsed
} catch {
throw new Error(
`stderr is not valid JSON.\nstdout:\n${redact(result.stdout)}\nstderr:\n${redact(result.stderr)}`,
)
}
expect(parsed, 'stderr envelope missing "error" key').toHaveProperty('error')
expect(parsed.error, 'error.code must be a non-empty string').toHaveProperty('code')
expect(parsed.error, 'error.message must be a non-empty string').toHaveProperty('message')
expect(typeof parsed.error.code, 'error.code must be a string').toBe('string')
expect(parsed.error.code.length, 'error.code must be non-empty').toBeGreaterThan(0)
if (expectedCode !== undefined) {
expect(
parsed.error.code,
`error.code should be "${expectedCode}", got "${parsed.error.code}"\nstderr:\n${redact(result.stderr)}`,
).toBe(expectedCode)
}
return parsed
}
// ── ANSI / formatting ────────────────────────────────────────────────────
/**
* Assert the given text contains no ANSI escape sequences.
* Pass `label` to identify which stream failed (e.g. 'stdout', 'stderr').
*/
export function assertNoAnsi(text: string, label = 'output'): void {
const clean = text.replace(ANSI_RE, '')
expect(text, `${label} must not contain ANSI control codes`).toBe(clean)
}
/**
* Assert stdout starts with `{` and ends with `\n` — the canonical format
* for pipe-friendly JSON output.
*/
export function assertPipeFriendlyJson(result: RunResult): void {
assertNoAnsi(result.stdout, 'stdout')
expect(
result.stdout.trimStart().startsWith('{') || result.stdout.trimStart().startsWith('['),
'stdout should start with { or [ for pipe-friendly JSON',
).toBe(true)
expect(result.stdout.endsWith('\n'), 'stdout should end with newline').toBe(true)
}
// ── stdout / stderr contains ──────────────────────────────────────────────
/**
* Assert stdout contains the given substring, printing full output on failure.
*/
export function assertStdoutContains(result: RunResult, expected: string): void {
if (!result.stdout.includes(expected)) {
process.stderr.write(
`\n[E2E assertStdoutContains] "${expected}" not found in stdout.\n` +
`stdout:\n${redact(result.stdout)}\nstderr:\n${redact(result.stderr)}\n`,
)
}
expect(result.stdout).toContain(expected)
}
/**
* Assert stderr contains the given substring, printing full output on failure.
*/
export function assertStderrContains(result: RunResult, expected: string): void {
if (!result.stderr.includes(expected)) {
process.stderr.write(
`\n[E2E assertStderrContains] "${expected}" not found in stderr.\n` +
`stdout:\n${redact(result.stdout)}\nstderr:\n${redact(result.stderr)}\n`,
)
}
expect(result.stderr).toContain(expected)
}
@@ -0,0 +1,90 @@
/**
* E2E cleanup registry.
*
* Test suites call `registerConversation(host, token, appId, conversationId)`
* whenever a real conversation is created on staging. The global teardown
* iterates the registry and deletes all collected conversations so staging
* data stays clean between CI runs.
*
* Design notes:
* - Uses a module-level array (shared within the same worker process).
* - vitest runs E2E suites in a single fork (fileParallelism: false), so one
* process owns the full registry.
* - Deletion is best-effort: individual failures are logged but do not throw.
*/
export type ConversationEntry = {
host: string
token: string
appId: string
conversationId: string
}
const _conversations: ConversationEntry[] = []
/**
* Register a conversation for cleanup in teardown.
* Call this whenever `run app` returns a `conversation_id`.
*/
export function registerConversation(
host: string,
token: string,
appId: string,
conversationId: string,
): void {
if (!conversationId || !appId) return
_conversations.push({ host, token, appId, conversationId })
}
/**
* Return all registered conversations (for use in teardown).
*/
export function getRegisteredConversations(): readonly ConversationEntry[] {
return _conversations
}
/**
* Delete all registered conversations from the staging server.
* Called once from global-teardown.ts.
*/
export async function cleanupRegisteredConversations(): Promise<void> {
if (_conversations.length === 0) return
console.warn(`[E2E teardown] Cleaning up ${_conversations.length} staged conversation(s)…`)
const results = await Promise.allSettled(
_conversations.map(({ host, token, appId, conversationId }) =>
deleteConversation(host, token, appId, conversationId),
),
)
const failed = results.filter((r) => r.status === 'rejected')
if (failed.length > 0) {
console.warn(
`[E2E teardown] ${failed.length} conversation deletion(s) failed (non-blocking):`,
failed.map((r) => (r as PromiseRejectedResult).reason).join(', '),
)
} else {
console.warn(`[E2E teardown] All conversations cleaned up.`)
}
_conversations.length = 0
}
async function deleteConversation(
host: string,
token: string,
appId: string,
conversationId: string,
): Promise<void> {
const url = `${host.replace(/\/$/, '')}/openapi/v1/apps/${appId}/conversations/${conversationId}`
const res = await fetch(url, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(8_000),
})
// 404 is acceptable — conversation may have already been cleaned up
if (!res.ok && res.status !== 404) {
throw new Error(`DELETE ${url} → HTTP ${res.status}`)
}
}
+511
View File
@@ -0,0 +1,511 @@
/**
* E2E CLI runner helpers.
*
* Core primitive: run(argv, opts) → { stdout, stderr, exitCode }
*
* The binary is invoked via `bun bin/dev.js` so tests work without a prior
* `pnpm build`. Each test should use its own isolated configDir (created via
* withTempConfig) to prevent session state leaking between tests.
*/
import { Buffer } from 'node:buffer'
import { execSync, spawn } from 'node:child_process'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { dump } from 'js-yaml'
/** Path to the dev entry point — no build required. */
export const BIN = resolve(__dirname, '../../../bin/dev.js')
/**
* Resolve the `bun` executable path.
* Priority: PATH → ~/.bun/bin/bun → /usr/local/bin/bun
*/
function resolveBun(): string {
const candidates = [
// Respect PATH first
'bun',
// Common install locations
`${process.env.HOME}/.bun/bin/bun`,
'/usr/local/bin/bun',
'/opt/homebrew/bin/bun',
]
for (const candidate of candidates) {
try {
execSync(`${candidate} --version`, { stdio: 'ignore', timeout: 3000 })
return candidate
} catch {
/* try next */
}
}
throw new Error('bun not found. Install it with: curl -fsSL https://bun.sh/install | bash')
}
export const BUN = resolveBun()
// ── Types ─────────────────────────────────────────────────────────────────
export type RunOptions = {
/**
* Override or extend the process environment.
* Values are merged on top of `process.env`.
*/
env?: Record<string, string>
/**
* Path to an isolated config directory.
* The CLI reads hosts.yml from this directory.
* Passed as DIFY_CONFIG_DIR env var.
*/
configDir?: string
/** Maximum time to wait for the process, in ms. Default: 30 000 */
timeout?: number
/** String to write to stdin, then close the pipe. */
stdin?: string
}
export type RunResult = {
stdout: string
stderr: string
exitCode: number
}
// ── Core runner ────────────────────────────────────────────────────────────
/**
* Execute `difyctl <argv>` and return the captured stdout, stderr and exit code.
*
* Environment notes:
* - CI=1 suppresses interactive prompts and spinners.
* - NO_COLOR=1 strips ANSI escape codes from output.
* - DIFY_CONFIG_DIR is set to opts.configDir when provided.
*/
export function run(argv: string[], opts: RunOptions = {}): Promise<RunResult> {
return new Promise((resolve, reject) => {
const env: Record<string, string> = {
...(process.env as Record<string, string>),
// Suppress interactive prompts in all E2E tests.
CI: '1',
NO_COLOR: '1',
// Point the CLI at the isolated config directory.
...(opts.configDir !== undefined ? { DIFY_CONFIG_DIR: opts.configDir } : {}),
...opts.env,
}
const proc = spawn(BUN, [BIN, ...argv], { env })
const timeoutMs = opts.timeout ?? 60_000
let timedOut = false
const timeoutId = setTimeout(() => {
timedOut = true
proc.kill('SIGINT')
setTimeout(() => proc.kill('SIGKILL'), 2000).unref?.()
}, timeoutMs)
timeoutId.unref?.()
let stdout = ''
let stderr = ''
proc.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString('utf8')
})
proc.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString('utf8')
})
if (opts.stdin !== undefined) {
proc.stdin.write(opts.stdin)
proc.stdin.end()
}
proc.on('close', (code: number | null) => {
clearTimeout(timeoutId)
resolve({ stdout, stderr, exitCode: code ?? (timedOut ? 124 : 1) })
})
proc.on('error', (err: Error) => {
clearTimeout(timeoutId)
reject(new Error(`Failed to spawn CLI process: ${err.message}`))
})
})
}
// ── Config directory helpers ───────────────────────────────────────────────
export type TempConfig = {
/** Path to the isolated config directory. */
configDir: string
/** Remove the directory and all its contents. */
cleanup: () => Promise<void>
}
/**
* Create a fresh temporary config directory for a single test.
* Always call cleanup() in afterEach to avoid leaking temp directories.
*/
export async function withTempConfig(): Promise<TempConfig> {
const configDir = await mkdtemp(join(tmpdir(), 'difyctl-e2e-'))
return {
configDir,
cleanup: () => rm(configDir, { recursive: true, force: true }),
}
}
// ── Auth injection ─────────────────────────────────────────────────────────
export type AuthInjectionOptions = {
/** Staging server base URL (no trailing slash). */
host: string
/** Bearer token — dfoa_ for internal, dfoe_ for SSO. */
bearer: string
/** Account email — written into hosts.yml and used as the token store key. */
email?: string
/** Account display name. Defaults to the email local part. */
accountName?: string
/** Account ID written into hosts.yml when a test needs it. */
accountId?: string
/** Primary workspace to write into the bundle. */
workspaceId: string
workspaceName: string
workspaceRole?: string
/** Full available get workspace. Defaults to the primary workspace only. */
availableWorkspaces?: Array<{ id: string; name: string; role: string }>
/**
* Server-side session UUID (OAuthAccessToken.id).
* When provided, written as `token_id` in hosts.yml so that
* `devices revoke` can correctly detect selfHit and clear local credentials.
*/
tokenId?: string
}
export type SsoAuthInjectionOptions = {
host: string
bearer: string
email?: string
issuer?: string
}
function splitHost(host: string): { bare: string; scheme: string } {
const bare = (() => {
try {
return new URL(host).host || host
} catch {
return host
}
})()
const scheme = (() => {
try {
return new URL(host).protocol.replace(':', '')
} catch {
return 'https'
}
})()
return { bare, scheme }
}
type TokenDoc = {
version: number
tokens: Record<string, Record<string, string>>
}
async function writeFileToken(
configDir: string,
host: string,
email: string,
bearer: string,
): Promise<void> {
const doc: TokenDoc = {
version: 1,
tokens: { [host]: { [email]: bearer } },
}
await writeFile(join(configDir, 'tokens.yml'), dump(doc, { lineWidth: -1, noRefs: true }), {
mode: 0o600,
})
}
/**
* Write a pre-baked hosts.yml into configDir so tests can skip the real
* Device-Flow login. Auth-specific E2E tests (login/logout/status) use the
* real flow and should NOT call this function.
*/
export async function injectAuth(configDir: string, opts: AuthInjectionOptions): Promise<void> {
await mkdir(configDir, { recursive: true, mode: 0o700 })
const role = opts.workspaceRole ?? 'owner'
// ── Derive bare host and scheme ───────────────────────────────────────────
// difyctl stores the bare hostname (no scheme) as the registry key.
// The scheme is stored separately in the host entry so hostWithScheme()
// can reconstruct the full URL. Without scheme, difyctl defaults to https.
const { bare, scheme } = splitHost(opts.host)
const email = opts.email ?? 'e2e@example.com'
const accountName = opts.accountName ?? email.split('@')[0] ?? ''
const availableWorkspaces = opts.availableWorkspaces ?? [
{
id: opts.workspaceId,
name: opts.workspaceName,
role,
},
]
// ── hosts.yml ────────────────────────────────────────────────────────────
// difyctl 0.1.0-rc.1 uses a nested registry format:
// token_storage / current_host / hosts.<bareHost>.accounts.<email>.(workspace|...)
// On macOS (keychain available) difyctl always uses the OS keychain for tokens.
// We probe keychain availability the same way difyctl does: try a round-trip.
// Always use file-based storage in E2E tests to avoid macOS keychain
// UI prompts that block CLI child processes spawned by vitest workers.
const canUseKeychain = false
const storageMode = 'file' as const
const hostsYml = `${[
`token_storage: ${storageMode}`,
`current_host: ${bare}`,
`hosts:`,
` ${bare}:`,
...(scheme !== 'https' ? [` scheme: ${scheme}`] : []),
` current_account: ${email}`,
` accounts:`,
` ${email}:`,
` account:`,
...(opts.accountId !== undefined ? [` id: ${opts.accountId}`] : []),
` email: ${email}`,
` name: ${accountName}`,
...(opts.tokenId !== undefined ? [` token_id: ${opts.tokenId}`] : []),
` workspace:`,
` id: ${opts.workspaceId}`,
` name: "${opts.workspaceName}"`,
` role: ${role}`,
` available_workspaces:`,
...availableWorkspaces.flatMap((workspace) => [
` - id: ${workspace.id}`,
` name: "${workspace.name}"`,
` role: ${workspace.role}`,
]),
].join('\n')}\n`
await writeFile(join(configDir, 'hosts.yml'), hostsYml, { mode: 0o600 })
// ── Store bearer token ────────────────────────────────────────────────────
// Token storage key: tokens.<bareHost>.<email> (dot-path for YamlStore.doGet)
if (canUseKeychain) {
// Write to OS keychain using the same service+account that difyctl uses:
// service = "difyctl", account = tokenKey = "tokens.<bareHost>.<email>"
// KeyringBasedStore.set JSON-encodes the value before storing.
const { Entry } = await import('@napi-rs/keyring')
const account = `tokens.${bare}.${email}`
new Entry('difyctl', account).setPassword(JSON.stringify(opts.bearer))
} else {
// Fall back to tokens.yml, which FileTokenStore reads as tokens[host][email].
await writeFileToken(configDir, bare, email, opts.bearer)
}
}
export async function injectSsoAuth(
configDir: string,
opts: SsoAuthInjectionOptions,
): Promise<void> {
await mkdir(configDir, { recursive: true, mode: 0o700 })
const { bare, scheme } = splitHost(opts.host)
const email = opts.email ?? 'sso@example.com'
const issuer = opts.issuer ?? 'https://issuer.example.com'
const hostsYml = `${[
`token_storage: file`,
`current_host: ${bare}`,
`hosts:`,
` ${bare}:`,
...(scheme !== 'https' ? [` scheme: ${scheme}`] : []),
` current_account: ${email}`,
` accounts:`,
` ${email}:`,
` account:`,
` email: ""`,
` name: ""`,
` external_subject:`,
` email: ${email}`,
` issuer: ${issuer}`,
].join('\n')}\n`
await writeFile(join(configDir, 'hosts.yml'), hostsYml, { mode: 0o600 })
await writeFileToken(configDir, bare, email, opts.bearer)
}
// ── Process signal helpers ─────────────────────────────────────────────────
export type SpawnedProcess = {
/** Send SIGINT (Ctrl+C) to the process. */
interrupt: () => void
/** Wait for the process to exit and return the result. */
wait: () => Promise<RunResult>
}
/**
* Start `difyctl <argv>` in the background without waiting for it to finish.
* Useful for testing interrupt / timeout behaviour.
*/
export function spawn_background(argv: string[], opts: RunOptions = {}): SpawnedProcess {
const env: Record<string, string> = {
...(process.env as Record<string, string>),
CI: '1',
NO_COLOR: '1',
...(opts.configDir !== undefined ? { DIFY_CONFIG_DIR: opts.configDir } : {}),
...opts.env,
}
const proc = spawn(BUN, [BIN, ...argv], { env })
const timeoutMs = opts.timeout ?? 60_000
let timedOut = false
const timeoutId = setTimeout(() => {
timedOut = true
proc.kill('SIGINT')
setTimeout(() => proc.kill('SIGKILL'), 2000).unref?.()
}, timeoutMs)
timeoutId.unref?.()
let stdout = ''
let stderr = ''
proc.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString('utf8')
})
proc.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString('utf8')
})
return {
interrupt: () => {
proc.kill('SIGINT')
},
wait: () =>
new Promise((res) => {
proc.on('close', (code: number | null) => {
clearTimeout(timeoutId)
res({ stdout, stderr, exitCode: code ?? (timedOut ? 124 : 1) })
})
}),
}
}
// ── Auth fixture ───────────────────────────────────────────────────────────
export type AuthFixture = {
/** Path to the isolated config directory, pre-loaded with a valid session. */
configDir: string
/**
* Run `difyctl <argv>` using the fixture's config dir.
* Shorthand for `run(argv, { configDir, env })`.
*/
r: (argv: string[], extraEnv?: Record<string, string>) => Promise<RunResult>
/** Remove the temp config directory. Call in afterEach. */
cleanup: () => Promise<void>
}
/**
* Create an isolated config directory pre-loaded with a valid internal-user
* session. Designed for use with vitest's beforeEach / afterEach:
*
* @example
* let fx: AuthFixture
* beforeEach(async () => { fx = await withAuthFixture(E) })
* afterEach(async () => { await fx.cleanup() })
*
* it('...', async () => {
* const result = await fx.r(['get', 'app'])
* assertExitCode(result, 0)
* })
*/
export async function withAuthFixture(E: {
host: string
token: string
workspaceId: string
workspaceName: string
email?: string
}): Promise<AuthFixture> {
const { configDir, cleanup } = await withTempConfig()
await injectAuth(configDir, {
host: E.host,
bearer: E.token,
email: E.email,
workspaceId: E.workspaceId,
workspaceName: E.workspaceName,
})
return {
configDir,
r: (argv, extraEnv) => run(argv, { configDir, env: extraEnv }),
cleanup,
}
}
// ── On-demand disposable token ─────────────────────────────────────────────
/**
* Mint a fresh dfoa_ OAuth token on demand via the 3-step device flow API.
* Use this inside tests that need to revoke a real session without consuming
* the shared DIFY_E2E_TOKEN or the global-setup disposableToken.
*
* Requires DIFY_E2E_EMAIL and DIFY_E2E_PASSWORD to be set.
* Returns empty string if credentials are missing.
*
* Steps:
* 1. POST /console/api/login (Base64 password) → session cookie
* 2. POST /openapi/v1/oauth/device/code → device_code + user_code
* 3. POST /openapi/v1/oauth/device/approve → approved
* 4. POST /openapi/v1/oauth/device/token → dfoa_ token
*/
export async function mintFreshToken(
host: string,
email: string,
password: string,
): Promise<string> {
if (!email || !password) return ''
const base = host.replace(/\/$/, '')
const sig = AbortSignal.timeout(15_000)
// Step 1 — console login
const passwordB64 = Buffer.from(password, 'utf8').toString('base64')
const loginRes = await fetch(`${base}/console/api/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password: passwordB64, remember_me: false }),
signal: AbortSignal.timeout(20_000),
})
if (!loginRes.ok) return ''
const setCookieHeaders = loginRes.headers.getSetCookie?.() ?? []
const cookieString = setCookieHeaders.map((c) => c.split(';')[0]).join('; ')
const csrfMatch = cookieString.match(/csrf_token=([^;]+)/)
const csrfToken = csrfMatch ? csrfMatch[1] : ''
// Step 2 — device code
const codeRes = await fetch(`${base}/openapi/v1/oauth/device/code`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: 'difyctl', device_label: 'e2e-fresh' }),
signal: sig,
})
if (!codeRes.ok) return ''
const { device_code, user_code } = (await codeRes.json()) as {
device_code: string
user_code: string
}
// Step 3 — approve
const approveRes = await fetch(`${base}/openapi/v1/oauth/device/approve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Cookie: cookieString, 'X-CSRFToken': csrfToken },
body: JSON.stringify({ user_code }),
signal: AbortSignal.timeout(20_000),
})
if (!approveRes.ok) return ''
// Step 4 — poll token
const tokenRes = await fetch(`${base}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code, client_id: 'difyctl' }),
signal: AbortSignal.timeout(20_000),
})
if (!tokenRes.ok) return ''
const body = (await tokenRes.json()) as { token?: string }
return body.token ?? ''
}
@@ -0,0 +1,51 @@
/**
* Retry helper for E2E tests running against a staging server.
*
* Staging environments can be flaky — occasional 5xx errors or slow cold
* starts are expected. Use `withRetry` to wrap assertions that may fail
* transiently without masking real failures.
*/
const DEFAULT_ATTEMPTS = 3
const DEFAULT_DELAY_MS = 1000
export type RetryOptions = {
/** Total number of attempts (first try + retries). Default: 3 */
attempts?: number
/** Delay between retries in ms. Default: 1000 */
delayMs?: number
/** Optional predicate — only retry when this returns true for the error. */
shouldRetry?: (err: unknown) => boolean
}
/**
* Execute `fn()` and retry on failure.
*
* @example
* const result = await withRetry(() => run(['get', 'app', '-o', 'json']))
*/
export async function withRetry<T>(fn: () => Promise<T>, opts: RetryOptions = {}): Promise<T> {
const total = opts.attempts ?? DEFAULT_ATTEMPTS
const delay = opts.delayMs ?? DEFAULT_DELAY_MS
const shouldRetry = opts.shouldRetry ?? (() => true)
let lastErr: unknown
for (let attempt = 1; attempt <= total; attempt++) {
try {
return await fn()
} catch (err) {
lastErr = err
if (attempt === total || !shouldRetry(err)) break
console.warn(`[E2E retry] attempt ${attempt}/${total} failed — retrying in ${delay}ms`)
await sleep(delay)
}
}
throw lastErr instanceof Error
? lastErr
: new Error('Retry failed with a non-Error value.', { cause: lastErr })
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
@@ -0,0 +1,54 @@
import type { SuiteAPI, TestAPI } from 'vite-plus/test'
import type { DifyEdition, E2ECapabilities } from '../setup/env.js'
import { describe, it } from 'vite-plus/test'
// Explicit casts bridge the ChainableFunction vs SuiteAPI/TestAPI
// incompatibility introduced in vite-plus-test@0.1.22 (TS2322 / TS4058).
// Using 'unknown' as an intermediate to satisfy strict no-explicit-any rules.
export function optionalDescribe(condition: boolean): SuiteAPI {
return (condition ? describe : describe.skip) as unknown as SuiteAPI
}
export function optionalIt(condition: boolean): TestAPI {
return (condition ? it : it.skip) as unknown as TestAPI
}
/**
* Return an `it` variant that only runs in Enterprise Edition (EE) mode.
*
* Usage:
* const eeIt = enterpriseOnlyIt(caps)
* eeIt('[EE][P0] workspace switching works across two workspaces', async () => { … })
*
* In CE mode the test is automatically skipped with a clear label.
* The [EE] tag in the test name is purely informational and documents the
* requirement in the test report.
*/
export function enterpriseOnlyIt(caps: E2ECapabilities): TestAPI {
return optionalIt(caps.edition === 'ee')
}
/**
* Return a `describe` variant that only runs in Enterprise Edition (EE) mode.
*
* Usage:
* const eeDescribe = enterpriseOnlyDescribe(caps)
* eeDescribe('[EE] cross-workspace suite', () => { … })
*/
export function enterpriseOnlyDescribe(caps: E2ECapabilities): SuiteAPI {
return optionalDescribe(caps.edition === 'ee')
}
/**
* Convenience: return true when capabilities indicate Enterprise Edition.
* Use for inline guards inside regular `it` blocks.
*
* @example
* it('cross-workspace query [EE]', async () => {
* if (!isEE(caps)) return // skip silently in CE
* …
* })
*/
export function isEE(caps: { edition: DifyEdition }): boolean {
return caps.edition === 'ee'
}
@@ -0,0 +1,13 @@
// ProvidedContext augmentation intentionally omitted.
//
// Both 'vitest' and '@voidzero-dev/vite-plus-test' module augmentation paths
// cause errors under the tsgo type-checker used by the Main CI pipeline:
// - Augmenting 'vitest' → TS2300 duplicate identifier (re-exported in @0.1.22)
// - Augmenting '@voidzero-dev/vite-plus-test' → TS2664 module not found
// (tsgo runs in cli/ and cannot resolve pnpm virtual-store symlinks)
//
// The three call sites (global-setup, devices, logout) use @ts-ignore to
// suppress the TS2345 / TS2339 errors locally. Runtime behaviour is correct
// because project.provide() / inject() work via string keys at runtime
// regardless of the compile-time type constraint.
export {}
+225
View File
@@ -0,0 +1,225 @@
/**
* E2E environment configuration.
*
* ── Edition modes ─────────────────────────────────────────────────────────
*
* Community Edition (CE) — default, set DIFY_E2E_EDITION=ce or leave unset.
* Required: DIFY_E2E_HOST, DIFY_E2E_EMAIL, DIFY_E2E_PASSWORD
* global-setup registers the account (idempotent), mints tokens, imports
* all DSL fixtures into the single workspace, and publishes apps.
*
* Enterprise Edition (EE) — set DIFY_E2E_EDITION=ee.
* Required: DIFY_E2E_HOST, DIFY_E2E_EMAIL, DIFY_E2E_PASSWORD
* The operator must pre-create two workspaces for the test account:
* primary → named "auto_test0"
* secondary → named "auto_test1"
* global-setup logs in, discovers the two workspaces by name, imports DSL
* fixtures into both, publishes apps, and sets access_mode → public.
*
* ── EE-only test cases ────────────────────────────────────────────────────
* Tests that require multiple workspaces or EE-specific features are tagged
* [EE] and wrapped with enterpriseOnlyIt() / enterpriseOnlyDescribe() from
* helpers/skip.ts. They are automatically skipped in CE mode.
*
* ── Optional env-var overrides (both editions) ────────────────────────────
* DIFY_E2E_TOKEN Pre-minted bearer token — skips device-flow mint
* DIFY_E2E_SSO_TOKEN External SSO bearer token (dfoe_ prefix)
* DIFY_E2E_CONSOLE_URL Console URL when different from DIFY_E2E_HOST
* DIFY_E2E_WORKSPACE_ID Override primary workspace ID
* DIFY_E2E_WORKSPACE_NAME Override primary workspace name
* DIFY_E2E_WS2_ID Override secondary workspace ID (EE)
* DIFY_E2E_WS2_APP_ID Override secondary workspace app ID (EE)
* DIFY_E2E_CHAT_APP_ID Override echo-chat app ID
* DIFY_E2E_WORKFLOW_APP_ID Override echo-workflow app ID
* DIFY_E2E_FILE_APP_ID Override file-upload app ID
* DIFY_E2E_FILE_CHAT_APP_ID Override file-chat app ID
* DIFY_E2E_HITL_APP_ID Override HITL main app ID
* DIFY_E2E_HITL_EXTERNAL_APP_ID
* DIFY_E2E_HITL_SINGLE_ACTION_APP_ID
* DIFY_E2E_HITL_MULTI_NODE_APP_ID
* DIFY_E2E_REASONING_APP_ID Override separated-reasoning chatflow app ID
* DIFY_E2E_REASONING_PROVISION=1 Opt in to auto-provisioning reasoning-chat.yml
* (needs a workspace default chat model)
*/
/** Supported edition values. */
export type DifyEdition = 'ce' | 'ee'
export type E2EEnv = {
/** Staging server base URL (API endpoint) */
host: string
/**
* Edition: "ce" (Community Edition, default) or "ee" (Enterprise Edition).
* Controls which global-setup path runs and which test cases are active.
*/
edition: DifyEdition
/** Internal user bearer token (dfoa_…) */
token: string
/** External SSO bearer token (dfoe_…) — may be empty */
ssoToken: string
/** Primary workspace ID */
workspaceId: string
/** Workspace name (informational) */
workspaceName: string
/** Chat app that echoes the query */
chatAppId: string
/** Workflow app that echoes input x */
workflowAppId: string
/** Workflow app with HITL node (display_in_ui=true) — empty when not configured */
hitlAppId: string
/** Workflow app with HITL node (display_in_ui=false) — empty when not configured */
hitlExternalAppId: string
/** Workflow app with HITL node (display_in_ui=true, exactly 1 action) */
hitlSingleActionAppId: string
/** Workflow app with 2 serial Human-Input nodes */
hitlMultiNodeAppId: string
/** Workflow app with file input (doc variable) */
fileAppId: string
/** Chat app (advanced-chat) with a file input variable */
fileChatAppId: string
/**
* Chatflow whose LLM node uses reasoning_format=separated. Empty unless
* DIFY_E2E_REASONING_APP_ID is set or the fixture is auto-provisioned; the
* run-app-reasoning suite is skipped when empty.
*/
reasoningAppId: string
/**
* Secondary workspace ID — EE only ("auto_test1").
* Empty in CE mode (CE has a single workspace).
*/
ws2Id: string
/** App ID inside the secondary workspace — EE only. Empty in CE mode. */
ws2AppId: string
/** Console account email */
email: string
/** Console account password (plain-text; Base64-encoded before sending) */
password: string
/**
* Console URL — defaults to `host` when not set separately.
* Useful when the API host and the console host differ.
*/
consoleUrl: string
}
export type E2ECapabilities = {
tokenValid: boolean
tokenId?: string
/**
* Edition resolved by global-setup — "ce" or "ee".
* Injected into every test file so helpers/skip.ts can gate EE-only cases.
*/
edition: DifyEdition
/** Primary bearer token minted by global-setup via the device flow. */
token: string
/**
* Per-suite dedicated tokens — each destructive suite (logout, devices)
* gets its own fresh dfoa_ token so revoking it never kills the main token.
*/
logoutToken: string
devicesToken: string
/** Primary workspace info. */
workspaceId: string
workspaceName: string
/** Secondary workspace ID (EE only). Empty string in CE mode. */
ws2Id: string
/** App IDs resolved by provisionApps. Empty = fall back to env var. */
chatAppId: string
workflowAppId: string
fileAppId: string
fileChatAppId: string
reasoningAppId: string
hitlAppId: string
hitlExternalAppId: string
hitlSingleActionAppId: string
hitlMultiNodeAppId: string
ws2AppId: string
}
let _cached: E2EEnv | undefined
/** Return true when running in Enterprise Edition mode. */
export function isEnterpriseEdition(): boolean {
return (process.env.DIFY_E2E_EDITION ?? 'ce').toLowerCase() === 'ee'
}
/** Load and validate E2E environment variables. Throws if required vars are missing. */
export function loadE2EEnv(): E2EEnv {
if (_cached !== undefined) return _cached
const edition: DifyEdition = isEnterpriseEdition() ? 'ee' : 'ce'
// Same 3 required vars for both CE and EE.
const required: Array<[keyof NodeJS.ProcessEnv, string]> = [
['DIFY_E2E_HOST', 'Staging server URL'],
['DIFY_E2E_EMAIL', 'Console account email'],
['DIFY_E2E_PASSWORD', 'Console account password'],
]
const missing = required.filter(([k]) => !process.env[k])
if (missing.length > 0) {
const list = missing.map(([k, desc]) => ` ${k} (${desc})`).join('\n')
throw new Error(
`E2E tests require the following environment variables to be set:\n${list}\n\n` +
`Edition: ${edition.toUpperCase()}\n` +
'See test/e2e/setup/env.ts for documentation.',
)
}
_cached = {
host: process.env.DIFY_E2E_HOST!,
edition,
token: process.env.DIFY_E2E_TOKEN ?? '',
ssoToken: process.env.DIFY_E2E_SSO_TOKEN ?? '',
workspaceId: process.env.DIFY_E2E_WORKSPACE_ID ?? '',
workspaceName: process.env.DIFY_E2E_WORKSPACE_NAME ?? '',
chatAppId: process.env.DIFY_E2E_CHAT_APP_ID ?? '',
workflowAppId: process.env.DIFY_E2E_WORKFLOW_APP_ID ?? '',
hitlAppId: process.env.DIFY_E2E_HITL_APP_ID ?? '',
hitlExternalAppId: process.env.DIFY_E2E_HITL_EXTERNAL_APP_ID ?? '',
hitlSingleActionAppId: process.env.DIFY_E2E_HITL_SINGLE_ACTION_APP_ID ?? '',
hitlMultiNodeAppId: process.env.DIFY_E2E_HITL_MULTI_NODE_APP_ID ?? '',
fileAppId: process.env.DIFY_E2E_FILE_APP_ID ?? '',
fileChatAppId: process.env.DIFY_E2E_FILE_CHAT_APP_ID ?? '',
reasoningAppId: process.env.DIFY_E2E_REASONING_APP_ID ?? '',
ws2Id: process.env.DIFY_E2E_WS2_ID ?? '',
ws2AppId: process.env.DIFY_E2E_WS2_APP_ID ?? '',
email: process.env.DIFY_E2E_EMAIL!,
password: process.env.DIFY_E2E_PASSWORD!,
consoleUrl: process.env.DIFY_E2E_CONSOLE_URL ?? process.env.DIFY_E2E_HOST!,
}
return _cached
}
export function isE2ELocalMode(): boolean {
return process.env.DIFY_E2E_MODE === 'local'
}
/**
* Resolve the E2E environment, merging capabilities (from global-setup) on top
* of the optional env-var overrides. Capabilities always take priority.
*
* `caps` may be undefined in local mode (DIFY_E2E_MODE=local), where
* global-setup returns early without calling project.provide().
*/
export function resolveEnv(caps: E2ECapabilities | undefined): E2EEnv {
if (!caps) return loadE2EEnv()
const env = loadE2EEnv()
return {
...env,
edition: caps.edition || env.edition,
token: caps.token || env.token,
workspaceId: caps.workspaceId || env.workspaceId,
workspaceName: caps.workspaceName || env.workspaceName,
ws2Id: caps.ws2Id || env.ws2Id,
chatAppId: caps.chatAppId || env.chatAppId,
workflowAppId: caps.workflowAppId || env.workflowAppId,
fileAppId: caps.fileAppId || env.fileAppId,
fileChatAppId: caps.fileChatAppId || env.fileChatAppId,
reasoningAppId: caps.reasoningAppId || env.reasoningAppId,
hitlAppId: caps.hitlAppId || env.hitlAppId,
hitlExternalAppId: caps.hitlExternalAppId || env.hitlExternalAppId,
hitlSingleActionAppId: caps.hitlSingleActionAppId || env.hitlSingleActionAppId,
hitlMultiNodeAppId: caps.hitlMultiNodeAppId || env.hitlMultiNodeAppId,
ws2AppId: caps.ws2AppId || env.ws2AppId,
}
}
@@ -0,0 +1,718 @@
/**
* Vitest global setup — runs once before all E2E suites.
*
* ── CE path (DIFY_E2E_EDITION=ce or unset) ───────────────────────────────
* 1. Register a new account with EMAIL/PASSWORD (idempotent).
* 2. Login to obtain a session cookie.
* 3. Mint the primary bearer token via the device flow.
* 4. Validate the token.
* 5. Discover the single workspace (falls back to first available).
* 6. Mint per-suite dedicated tokens (logout / devices suites).
* 7. Import all DSL fixtures into the workspace, publish & set public.
*
* ── EE path (DIFY_E2E_EDITION=ee) ────────────────────────────────────────
* Workspaces are pre-created by the operator and must be named:
* primary → "auto_test0"
* secondary → "auto_test1"
*
* 1. Login with EMAIL/PASSWORD to obtain a session cookie.
* 2. Mint the primary bearer token via the device flow.
* 3. Validate the token.
* 4. Discover "auto_test0" (primary) and "auto_test1" (secondary) workspaces.
* 5. Mint per-suite dedicated tokens.
* 6. Import DSL fixtures into primary workspace; import ws2-workflow.yml
* into the secondary workspace. Publish & set access_mode → public.
*/
import type { TestProject } from 'vite-plus/test/node'
import type { E2ECapabilities } from './env.js'
import { Buffer } from 'node:buffer'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { injectAuth, run } from '../helpers/cli.js'
import { loadE2EEnv } from './env.js'
const TOKEN_MINT_APPROVE_ATTEMPTS = 5
const TOKEN_MINT_RETRY_BASE_MS = 2_000
export async function setup(project: TestProject): Promise<void> {
if (process.env.DIFY_E2E_MODE === 'local') return
const E = loadE2EEnv()
const consoleBase = E.consoleUrl.replace(/\/$/, '')
const apiBase = E.host.replace(/\/$/, '')
console.warn(`[E2E global-setup] Edition: ${E.edition.toUpperCase()}`)
// ── Account bootstrap ────────────────────────────────────────────────────
if (E.edition === 'ce') {
await ceRegisterAccount(consoleBase, E.email, E.password)
}
// EE: account & workspaces are pre-provisioned by the operator — just login.
// ── Login ────────────────────────────────────────────────────────────────
const { cookieString, csrfToken } = await consoleLogin(consoleBase, E.email, E.password)
// ── Mint primary token (with local cache to avoid rate-limit) ──────────
// Priority: DIFY_E2E_TOKEN env → .token-cache.json → fresh mint
// The cache file lives next to .env.e2e and is git-ignored.
// logoutToken/devicesToken are intentionally NOT cached — those suites
// revoke their token, so they always need a fresh one.
const TOKEN_CACHE = join(process.cwd(), '.token-cache.json')
async function loadCachedToken(): Promise<string> {
try {
const raw = await readFile(TOKEN_CACHE, 'utf8')
const { token, host } = JSON.parse(raw) as { token?: string; host?: string }
// Invalidate if host changed (different staging env)
if (!token || host !== E.host) return ''
return token
} catch {
return ''
}
}
async function saveCachedToken(token: string): Promise<void> {
try {
await writeFile(TOKEN_CACHE, JSON.stringify({ token, host: E.host }, null, 2), 'utf8')
} catch (err) {
console.warn(`[E2E] Could not save token cache: ${err}`)
}
}
async function validateToken(token: string): Promise<boolean> {
try {
const r = await fetch(`${apiBase}/openapi/v1/account/sessions?page=1&limit=100`, {
headers: { Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(8_000),
})
return r.ok
} catch {
return false
}
}
let primaryToken = E.token
if (primaryToken) {
console.warn(`[E2E] primaryToken from env: ${primaryToken.slice(0, 20)}…`)
} else {
// Try cache first
const cached = await loadCachedToken()
if (cached && (await validateToken(cached))) {
primaryToken = cached
console.warn(`[E2E] primaryToken from cache: ${primaryToken.slice(0, 20)}…`)
} else {
if (cached) console.warn('[E2E] Cached token invalid or expired — re-minting…')
try {
primaryToken = await mintTokenWithSession(
consoleBase,
cookieString,
csrfToken,
'e2e-primary',
)
await saveCachedToken(primaryToken)
console.warn(`[E2E] primaryToken minted and cached: ${primaryToken.slice(0, 20)}…`)
} catch (err) {
throw new Error(
`[E2E global-setup] Failed to mint primary token: ${err}\n` +
'Ensure DIFY_E2E_EMAIL and DIFY_E2E_PASSWORD are correct.',
)
}
}
}
// ── Validate primary token ───────────────────────────────────────────────
const sessionsUrl = `${apiBase}/openapi/v1/account/sessions?page=1&limit=100`
let res: Response
try {
res = await fetch(sessionsUrl, {
headers: { Authorization: `Bearer ${primaryToken}` },
signal: AbortSignal.timeout(10_000),
})
} catch (err) {
throw new Error(
`[E2E global-setup] Cannot reach staging server at ${sessionsUrl}.\n` +
`Check DIFY_E2E_HOST and network connectivity.\n${String(err)}`,
)
}
if (!res.ok) {
throw new Error(
`[E2E global-setup] Primary token is invalid or expired (HTTP ${res.status}).\n` +
`URL: ${sessionsUrl}`,
)
}
console.warn(`[E2E] Server healthy, primary token valid at ${E.host}`)
// ── Resolve token_id ─────────────────────────────────────────────────────
const body = (await res.json()) as { data: Array<{ id: string; prefix: string }> }
const match = body.data.find((s) => s.prefix !== '' && primaryToken.startsWith(s.prefix))
if (!match) {
console.warn(
'[E2E global-setup] Could not resolve token_id — devicesToken selfHit detection may not work',
)
} else {
console.warn(`[E2E] Resolved token_id: ${match.id}`)
}
// ── Discover workspaces ──────────────────────────────────────────────────
const workspaces = await discoverWorkspaces(consoleBase, cookieString, csrfToken, E.edition)
if (!workspaces) {
// @ts-expect-error — ProvidedContext augmentation cannot be expressed without
// triggering TS2300 or TS2664 under tsgo; safe at runtime.
project.provide('e2eCapabilities', {
tokenValid: true,
tokenId: match?.id,
edition: E.edition,
token: primaryToken,
logoutToken: '',
devicesToken: '',
workspaceId: '',
workspaceName: '',
ws2Id: '',
chatAppId: '',
workflowAppId: '',
fileAppId: '',
fileChatAppId: '',
reasoningAppId: '',
hitlAppId: '',
hitlExternalAppId: '',
hitlSingleActionAppId: '',
hitlMultiNodeAppId: '',
ws2AppId: '',
} satisfies E2ECapabilities)
return
}
const { primaryWsId, primaryWsName, secondaryWsId } = workspaces
// ── Mint per-suite dedicated tokens ──────────────────────────────────────
let logoutToken = ''
let devicesToken = ''
const mint = (label: string) => mintTokenWithSession(consoleBase, cookieString, csrfToken, label)
const [lt, dt] = await Promise.allSettled([mint('e2e-logout-suite'), mint('e2e-devices-suite')])
if (lt.status === 'fulfilled') {
logoutToken = lt.value
console.warn(`[E2E] logoutToken minted: ${logoutToken.slice(0, 20)}…`)
} else {
console.warn(`[E2E global-setup] Failed to mint logoutToken: ${lt.reason}`)
}
if (dt.status === 'fulfilled') {
devicesToken = dt.value
console.warn(`[E2E] devicesToken minted: ${devicesToken.slice(0, 20)}…`)
} else {
console.warn(`[E2E global-setup] Failed to mint devicesToken: ${dt.reason}`)
}
// ── Provision fixture apps ───────────────────────────────────────────────
// Skip provisionApps when app IDs are already injected via DIFY_E2E_*_APP_ID
// environment variables (e.g. from the CI provision job). Running provisionApps
// in every parallel suite job causes race conditions: multiple jobs query
// findAppByName simultaneously, all get "not found", then each imports the DSL
// independently — creating duplicate apps per workspace.
let provisionedIds: Record<string, string> = {}
const preProvisioned = [
'DIFY_E2E_CHAT_APP_ID',
'DIFY_E2E_WORKFLOW_APP_ID',
'DIFY_E2E_FILE_APP_ID',
'DIFY_E2E_FILE_CHAT_APP_ID',
'DIFY_E2E_HITL_APP_ID',
'DIFY_E2E_HITL_EXTERNAL_APP_ID',
'DIFY_E2E_HITL_SINGLE_ACTION_APP_ID',
'DIFY_E2E_HITL_MULTI_NODE_APP_ID',
'DIFY_E2E_WS2_APP_ID',
]
const envAppIds: Record<string, string> = {}
for (const key of preProvisioned) {
const val = process.env[key]
if (val && val !== '') envAppIds[key] = val
}
const allPreset = preProvisioned.every((k) => envAppIds[k] !== undefined)
if (allPreset) {
// All app IDs already available via env — skip provisioning to avoid
// race conditions in parallel CI jobs.
provisionedIds = envAppIds
console.warn(
`[E2E global-setup] App IDs pre-set via env — skipping provisionApps (${Object.keys(provisionedIds).length} apps)`,
)
} else {
try {
const fixturesDir = join(fileURLToPath(import.meta.url), '..', '..', 'fixtures', 'apps')
provisionedIds = await provisionApps(
consoleBase,
cookieString,
csrfToken,
primaryWsId,
secondaryWsId,
fixturesDir,
E.edition,
primaryToken,
apiBase,
E.email,
primaryWsName,
)
console.warn(
`[E2E global-setup] Provisioned ${Object.keys(provisionedIds).length} fixture apps`,
)
} catch (err) {
console.warn(`[E2E global-setup] provisionApps failed (non-fatal): ${err}`)
}
}
// ── Provide capabilities ─────────────────────────────────────────────────
const capabilities: E2ECapabilities = {
tokenValid: true,
tokenId: match?.id,
edition: E.edition,
token: primaryToken,
logoutToken,
devicesToken,
workspaceId: primaryWsId,
workspaceName: primaryWsName,
ws2Id: secondaryWsId,
chatAppId: provisionedIds.DIFY_E2E_CHAT_APP_ID || E.chatAppId,
workflowAppId: provisionedIds.DIFY_E2E_WORKFLOW_APP_ID || E.workflowAppId,
fileAppId: provisionedIds.DIFY_E2E_FILE_APP_ID || E.fileAppId,
fileChatAppId: provisionedIds.DIFY_E2E_FILE_CHAT_APP_ID || E.fileChatAppId,
reasoningAppId: provisionedIds.DIFY_E2E_REASONING_APP_ID || E.reasoningAppId,
hitlAppId: provisionedIds.DIFY_E2E_HITL_APP_ID || E.hitlAppId,
hitlExternalAppId: provisionedIds.DIFY_E2E_HITL_EXTERNAL_APP_ID || E.hitlExternalAppId,
hitlSingleActionAppId:
provisionedIds.DIFY_E2E_HITL_SINGLE_ACTION_APP_ID || E.hitlSingleActionAppId,
hitlMultiNodeAppId: provisionedIds.DIFY_E2E_HITL_MULTI_NODE_APP_ID || E.hitlMultiNodeAppId,
ws2AppId: provisionedIds.DIFY_E2E_WS2_APP_ID || E.ws2AppId,
}
// @ts-expect-error — ProvidedContext augmentation cannot be expressed without
// triggering TS2300 or TS2664 under tsgo; safe at runtime.
project.provide('e2eCapabilities', capabilities)
}
export { teardown } from './global-teardown.js'
// ══════════════════════════════════════════════════════════════════════════════
// CE — account registration
// ══════════════════════════════════════════════════════════════════════════════
/**
* Register a CE account idempotently.
* Tries /init (fresh server) first, then falls back to /register.
* A 409 "already exists" response is treated as success.
*/
async function ceRegisterAccount(
consoleBase: string,
email: string,
password: string,
): Promise<void> {
const passwordB64 = Buffer.from(password, 'utf8').toString('base64')
const name = email.split('@')[0] ?? 'e2e-user'
const initRes = await fetch(`${consoleBase}/console/api/init`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, name, password: passwordB64 }),
signal: AbortSignal.timeout(15_000),
})
if (initRes.ok || initRes.status === 409) {
console.warn(`[E2E CE] Account ready via /init (status ${initRes.status})`)
return
}
const registerRes = await fetch(`${consoleBase}/console/api/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, name, password: passwordB64 }),
signal: AbortSignal.timeout(15_000),
})
if (!registerRes.ok && registerRes.status !== 409) {
console.warn(
`[E2E CE] /register returned HTTP ${registerRes.status} — account may already exist; continuing`,
)
} else {
console.warn(`[E2E CE] Account ready via /register (status ${registerRes.status})`)
}
}
// ══════════════════════════════════════════════════════════════════════════════
// Shared helpers
// ══════════════════════════════════════════════════════════════════════════════
// ── Console login ─────────────────────────────────────────────────────────
async function consoleLogin(
consoleBase: string,
email: string,
password: string,
): Promise<{ cookieString: string; csrfToken: string }> {
const passwordB64 = Buffer.from(password, 'utf8').toString('base64')
const loginRes = await fetch(`${consoleBase}/console/api/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password: passwordB64, remember_me: false }),
signal: AbortSignal.timeout(15_000),
})
if (!loginRes.ok) throw new Error(`console/api/login failed: HTTP ${loginRes.status}`)
const setCookies = loginRes.headers.getSetCookie?.() ?? []
const cookieString = setCookies.map((c) => c.split(';')[0]).join('; ')
const csrfToken = (cookieString.match(/csrf_token=([^;]+)/) ?? [])[1] ?? ''
return { cookieString, csrfToken }
}
// ── Workspace discovery ───────────────────────────────────────────────────
/**
* Discover primary and secondary workspaces.
*
* CE: looks for any workspace with "auto" in its name; falls back to the
* first available workspace. secondaryWsId === primaryWsId when only
* one workspace exists.
*
* EE: looks for workspaces named exactly "auto_test0" (primary) and
* "auto_test1" (secondary). These must be pre-created by the operator.
* Throws if "auto_test0" is not found.
*/
async function discoverWorkspaces(
consoleBase: string,
cookieString: string,
csrfToken: string,
edition: 'ce' | 'ee',
): Promise<{ primaryWsId: string; primaryWsName: string; secondaryWsId: string } | null> {
const wsRes = await fetch(`${consoleBase}/console/api/workspaces`, {
headers: { Cookie: cookieString, 'X-CSRF-Token': csrfToken },
signal: AbortSignal.timeout(10_000),
})
if (!wsRes.ok) throw new Error(`list workspaces failed: HTTP ${wsRes.status}`)
const wsBody = (await wsRes.json()) as {
workspaces?: Array<{ id: string; name: string }>
}
const all = wsBody.workspaces ?? []
if (edition === 'ee') {
// EE: must find the two pre-created workspaces by exact name
const ws0 = all.find((w) => w.name === 'auto_test0')
const ws1 = all.find((w) => w.name === 'auto_test1')
if (!ws0 || !ws1) {
const existing = all.map((w) => w.name).join(', ') || '(none)'
console.warn(
`[E2E EE] Required workspaces not found; expected auto_test0 and auto_test1, got: ${existing}. ` +
'Skip fixture app provisioning.',
)
return null
}
const primaryWsId = ws0.id
const primaryWsName = ws0.name
const secondaryWsId = ws1.id
console.warn(`[E2E EE] primary workspace: ${primaryWsName} (${primaryWsId})`)
console.warn(`[E2E EE] secondary workspace: ${ws1.name} (${secondaryWsId})`)
return { primaryWsId, primaryWsName, secondaryWsId }
}
// CE: look for workspaces with "auto" in the name, sorted alphabetically
const autoWorkspaces = all
.filter((w) => w.name.toLowerCase().includes('auto'))
.sort((a, b) => a.name.localeCompare(b.name))
if (autoWorkspaces.length > 0) {
const primaryWsId = autoWorkspaces[0]!.id
const primaryWsName = autoWorkspaces[0]!.name
const secondaryWsId = autoWorkspaces[1]?.id ?? primaryWsId
console.warn(`[E2E CE] primary workspace: ${primaryWsName} (${primaryWsId})`)
if (autoWorkspaces[1])
console.warn(`[E2E CE] secondary workspace: ${autoWorkspaces[1].name} (${secondaryWsId})`)
else console.warn('[E2E CE] only one "auto" workspace found — ws2 reuses primary')
return { primaryWsId, primaryWsName, secondaryWsId }
}
// CE fallback: use the first available workspace
if (all.length === 0) throw new Error('[E2E CE] No workspaces found for this account')
const primaryWsId = all[0]!.id
const primaryWsName = all[0]!.name
console.warn(`[E2E CE] primary workspace (fallback): ${primaryWsName} (${primaryWsId})`)
return { primaryWsId, primaryWsName, secondaryWsId: primaryWsId }
}
// ── App provisioning ──────────────────────────────────────────────────────
/**
* Idempotently provision all E2E fixture apps.
*
* CE: imports all primary-workspace fixtures; skips ws2-workflow.yml
* (no real secondary workspace).
*
* EE: imports primary-workspace fixtures into auto_test0, and
* ws2-workflow.yml into auto_test1.
*
* Per app:
* 1. Switch to the target workspace
* 2. Search by app name — reuse existing app when found
* 3. If not found → import from DSL file
* 4. Enable Service API
* 5. Publish (workflow / advanced-chat / agent-chat only)
* 6. Set access_mode → public
*/
async function provisionApps(
consoleBase: string,
cookieString: string,
csrfToken: string,
primaryWsId: string,
secondaryWsId: string,
fixturesDir: string,
edition: 'ce' | 'ee',
token: string,
host: string,
email: string,
primaryWsName: string,
): Promise<Record<string, string>> {
const NEEDS_PUBLISH = new Set(['workflow', 'advanced-chat', 'agent-chat'])
const mkHeaders = (extra: Record<string, string> = {}): Record<string, string> => ({
Cookie: cookieString,
'X-CSRF-Token': csrfToken,
...extra,
})
// ws2-workflow.yml is only provisioned in EE mode (real secondary workspace)
const APP_SPECS: Array<[string, string, string]> = [
['echo-chat.yml', 'DIFY_E2E_CHAT_APP_ID', primaryWsId],
['echo-workflow.yml', 'DIFY_E2E_WORKFLOW_APP_ID', primaryWsId],
['file-upload.yml', 'DIFY_E2E_FILE_APP_ID', primaryWsId],
['hitl-main.yml', 'DIFY_E2E_HITL_APP_ID', primaryWsId],
['hitl-external.yml', 'DIFY_E2E_HITL_EXTERNAL_APP_ID', primaryWsId],
['hitl-single-action.yml', 'DIFY_E2E_HITL_SINGLE_ACTION_APP_ID', primaryWsId],
['hitl-multi-node.yml', 'DIFY_E2E_HITL_MULTI_NODE_APP_ID', primaryWsId],
['file-chat.yml', 'DIFY_E2E_FILE_CHAT_APP_ID', primaryWsId],
// reasoning-chat.yml runs a real LLM node, so it is opt-in: provisioning it
// requires the workspace to have a default chat model configured. Off by
// default to keep the shared bootstrap free of any model dependency.
...(process.env.DIFY_E2E_REASONING_PROVISION === '1'
? [
['reasoning-chat.yml', 'DIFY_E2E_REASONING_APP_ID', primaryWsId] as [
string,
string,
string,
],
]
: []),
...(edition === 'ee'
? [['ws2-workflow.yml', 'DIFY_E2E_WS2_APP_ID', secondaryWsId] as [string, string, string]]
: []),
]
const configDir = await mkdtemp(join(tmpdir(), 'difyctl-e2e-provision-'))
await injectAuth(configDir, {
host,
bearer: token,
email,
workspaceId: primaryWsId,
workspaceName: primaryWsName,
})
async function importAppCli(filePath: string, wsId: string): Promise<string> {
const result = await run(
['import', 'studio-app', '--from-file', filePath, '--workspace', wsId],
{ configDir, timeout: 60_000 },
)
if (result.exitCode !== 0)
throw new Error(`import studio-app failed (exit ${result.exitCode}): ${result.stderr}`)
const match = result.stderr.match(/app ([0-9a-f-]{36})/)
if (!match?.[1]) throw new Error(`import studio-app: could not parse app_id: ${result.stderr}`)
return match[1]
}
async function switchWorkspace(wsId: string): Promise<void> {
const r = await fetch(`${consoleBase}/console/api/workspaces/switch`, {
method: 'POST',
headers: mkHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ tenant_id: wsId }),
signal: AbortSignal.timeout(10_000),
})
if (!r.ok) throw new Error(`switch workspace to ${wsId} failed: HTTP ${r.status}`)
}
async function findAppByName(name: string): Promise<string | null> {
const url = `${consoleBase}/console/api/apps?name=${encodeURIComponent(name)}&limit=50&page=1`
const r = await fetch(url, { headers: mkHeaders(), signal: AbortSignal.timeout(10_000) })
if (!r.ok) throw new Error(`list apps by name "${name}" failed: HTTP ${r.status}`)
const d = (await r.json()) as { data?: Array<{ id: string; name: string }> }
return d.data?.find((a) => a.name === name)?.id ?? null
}
async function enableApi(appId: string): Promise<void> {
await fetch(`${consoleBase}/console/api/apps/${appId}/api-enable`, {
method: 'POST',
headers: mkHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ enable_api: true }),
signal: AbortSignal.timeout(10_000),
})
}
async function publishWorkflow(appId: string): Promise<void> {
await fetch(`${consoleBase}/console/api/apps/${appId}/workflows/publish`, {
method: 'POST',
headers: mkHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ marked_name: 'e2e-provision', marked_comment: '' }),
signal: AbortSignal.timeout(20_000),
})
}
async function setAppPublic(appId: string): Promise<void> {
try {
const r = await fetch(`${consoleBase}/console/api/enterprise/webapp/app/access-mode`, {
method: 'POST',
headers: mkHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ appId, accessMode: 'public' }),
signal: AbortSignal.timeout(10_000),
})
if (r.ok) {
console.warn(`[E2E provision] setAppPublic(${appId}): access_mode → public`)
} else {
// CE servers return 404 here — non-fatal
const text = await r.text().catch(() => '')
console.warn(
`[E2E provision] setAppPublic(${appId}) skipped: HTTP ${r.status} ${text.slice(0, 100)}`,
)
}
} catch (err) {
console.warn(`[E2E provision] setAppPublic(${appId}) error (non-fatal): ${err}`)
}
}
const results: Record<string, string> = {}
let currentWs = ''
for (const [dslFile, envVar, wsId] of APP_SPECS) {
try {
if (wsId !== currentWs) {
await switchWorkspace(wsId)
currentWs = wsId
}
const dsl = await readFile(join(fixturesDir, dslFile), 'utf8')
const appName =
(dsl.match(/^[ \t]+name:[ \t]*(\S[^\n]*)$/m) ?? [])[1]
?.trim()
.replace(/^['"]|['"]$/g, '') ?? dslFile
const appMode = (dsl.match(/^\s+mode:\s*(\S+)/m) ?? [])[1] ?? ''
let appId = await findAppByName(appName)
if (appId) {
console.warn(`[E2E provision] ${dslFile}: exists in workspace id=${appId}; skip import`)
} else {
appId = await importAppCli(join(fixturesDir, dslFile), wsId)
console.warn(`[E2E provision] ${dslFile}: imported id=${appId}`)
}
await enableApi(appId)
await setAppPublic(appId)
if (NEEDS_PUBLISH.has(appMode)) await publishWorkflow(appId)
results[envVar] = appId
} catch (err) {
console.warn(`[E2E provision] ${dslFile} skipped: ${err}`)
}
}
await rm(configDir, { recursive: true, force: true }).catch((err: unknown) =>
console.warn(`[E2E provision] failed to clean up configDir: ${err}`),
)
return results
}
// ── Token minting via device flow ─────────────────────────────────────────
async function mintTokenWithSession(
consoleBase: string,
cookieString: string,
csrfToken: string,
label: string,
): Promise<string> {
// Step 1 — request device code
const codeRes = await fetch(`${consoleBase}/openapi/v1/oauth/device/code`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: 'difyctl', device_label: label }),
signal: AbortSignal.timeout(15_000),
})
if (!codeRes.ok) throw new Error(`device/code failed: HTTP ${codeRes.status}`)
const { device_code, user_code } = (await codeRes.json()) as {
device_code: string
user_code: string
}
// Step 2 — approve
const approveRes = await approveDeviceCodeWithRetry({
consoleBase,
cookieString,
csrfToken,
userCode: user_code,
})
if (!approveRes.ok) throw new Error(`device/approve failed: HTTP ${approveRes.status}`)
// Step 3 — exchange for bearer token
const tokenRes = await fetch(`${consoleBase}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code, client_id: 'difyctl' }),
signal: AbortSignal.timeout(10_000),
})
if (!tokenRes.ok) throw new Error(`device/token failed: HTTP ${tokenRes.status}`)
const tokenBody = (await tokenRes.json()) as { token?: string; error?: string }
if (!tokenBody.token)
throw new Error(`device/token response missing token: ${JSON.stringify(tokenBody)}`)
return tokenBody.token
}
async function approveDeviceCodeWithRetry(opts: {
readonly consoleBase: string
readonly cookieString: string
readonly csrfToken: string
readonly userCode: string
}): Promise<Response> {
let lastResponse: Response | undefined
for (let attempt = 1; attempt <= TOKEN_MINT_APPROVE_ATTEMPTS; attempt++) {
const response = await fetch(`${opts.consoleBase}/openapi/v1/oauth/device/approve`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: opts.cookieString,
'X-CSRFToken': opts.csrfToken,
},
body: JSON.stringify({ user_code: opts.userCode }),
signal: AbortSignal.timeout(10_000),
})
if (response.ok || !isRetryableApproveStatus(response.status)) return response
lastResponse = response
const delayMs = TOKEN_MINT_RETRY_BASE_MS * attempt
console.warn(
`[E2E] device approve HTTP ${response.status}; retrying in ${delayMs}ms (${attempt}/${TOKEN_MINT_APPROVE_ATTEMPTS})`,
)
await sleep(delayMs)
}
return lastResponse ?? new Response(null, { status: 429 })
}
function isRetryableApproveStatus(status: number): boolean {
return status === 429 || status >= 500
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
@@ -0,0 +1,15 @@
/**
* Vitest global teardown — runs once after all E2E suites complete.
*
* Responsibilities:
* 1. Delete all conversations created on the staging server during the run
* (collected via registerConversation() in test suites).
*
* Deletion is best-effort — failures are logged but do not fail the run.
*/
import { cleanupRegisteredConversations } from '../helpers/cleanup-registry.js'
export async function teardown(): Promise<void> {
await cleanupRegisteredConversations()
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach } from 'vite-plus/test'
import { ENV_CONFIG_DIR } from '../../src/store/dir.js'
// Points ENV_CONFIG_DIR at a fresh temp dir per test and restores it after.
// Call inside a describe block; returns a getter because the dir changes per test.
export function useTempConfigDir(prefix: string): () => string {
let dir = ''
let prev: string | undefined
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), prefix))
prev = process.env[ENV_CONFIG_DIR]
process.env[ENV_CONFIG_DIR] = dir
})
afterEach(async () => {
if (prev === undefined) delete process.env[ENV_CONFIG_DIR]
else process.env[ENV_CONFIG_DIR] = prev
await rm(dir, { recursive: true, force: true })
})
return () => dir
}
+197
View File
@@ -0,0 +1,197 @@
export type Scenario =
| 'happy'
| 'resource-token'
| 'sso'
| 'no-email'
| 'denied'
| 'expired'
| 'auth-expired'
| 'forbidden'
| 'rate-limited'
| 'server-5xx'
| 'slow-down'
| 'stream-error'
| 'slow-stream'
| 'broken-stream'
| 'hitl-pause'
| 'hitl-resume'
| 'catalog-changed'
| 'no-catalog'
| 'workspaces-malformed'
| 'always-stale'
| 'import-pending'
| 'import-failed'
| 'no-device-flow'
| 'bad-verification-uri'
export type AccountFixture = {
id: string
email: string
name: string
is_external: boolean
current_workspace_id: string | null
}
export type WorkspaceFixture = {
id: string
name: string
role: string
status: string
}
export type AppFixture = {
id: string
workspace_id: string
workspace_name: string
name: string
mode: string
description: string
tags: { name: string }[]
created_at: string
updated_at: string
created_by_name: string
author?: string
service_api_enabled?: boolean
is_agent?: boolean
parameters?: Record<string, unknown>
input_schema?: Record<string, unknown>
}
export type SessionFixture = {
id: string
prefix: string
client_id: string
device_label: string
created_at: string
last_used_at: string
expires_at: string
}
export const ACCOUNT: AccountFixture = {
id: 'acct-1',
email: 'tester@dify.ai',
name: 'Test Tester',
is_external: false,
current_workspace_id: 'ws-1',
}
export const WORKSPACES: WorkspaceFixture[] = [
{
id: 'ws-1',
name: 'Default',
role: 'owner',
status: 'normal',
},
{
id: 'ws-2',
name: 'Other',
role: 'normal',
status: 'normal',
},
]
export const APPS: AppFixture[] = [
{
id: 'app-1',
workspace_id: 'ws-1',
workspace_name: 'Default',
name: 'Greeter',
mode: 'chat',
description: 'A simple greeting bot',
tags: [{ name: 'demo' }],
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-02T00:00:00Z',
created_by_name: 'tester',
author: 'tester',
service_api_enabled: true,
is_agent: false,
parameters: {
opening_statement: 'Hi, I am Greeter.',
suggested_questions: ['What is your name?'],
user_input_form: [
{ type: 'text-input', variable: 'name', label: 'Your name', required: true },
],
system_parameters: { image_file_size_limit: 10 },
},
},
{
id: 'app-4',
workspace_id: 'ws-2',
workspace_name: 'Other',
name: 'Researcher',
mode: 'agent-chat',
description: 'An agent that researches',
tags: [],
created_at: '2026-02-01T00:00:00Z',
updated_at: '2026-02-02T00:00:00Z',
created_by_name: 'tester',
author: 'tester',
service_api_enabled: false,
is_agent: true,
},
{
id: 'app-2',
workspace_id: 'ws-1',
workspace_name: 'Default',
name: 'Workflow',
mode: 'workflow',
description: '',
tags: [],
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-02T00:00:00Z',
created_by_name: 'tester',
author: 'tester',
service_api_enabled: false,
},
{
id: 'app-3',
workspace_id: 'ws-2',
workspace_name: 'Other',
name: 'OtherWS Bot',
mode: 'chat',
description: '',
tags: [{ name: 'wip' }],
created_at: '2026-01-03T00:00:00Z',
updated_at: '2026-01-04T00:00:00Z',
created_by_name: 'admin',
author: 'admin',
service_api_enabled: false,
},
]
export const DSL_YAML = `app:
description: A simple greeting bot
mode: chat
name: Greeter
version: '0.1.4'
`
export const SESSIONS: SessionFixture[] = [
{
id: 'tok-1',
prefix: 'dfoa',
client_id: 'difyctl',
device_label: 'difyctl on laptop',
created_at: '2026-05-01T00:00:00Z',
last_used_at: '2026-05-08T00:00:00Z',
expires_at: '2026-08-01T00:00:00Z',
},
{
id: 'tok-2',
prefix: 'dfoa',
client_id: 'difyctl',
device_label: 'difyctl on desktop',
created_at: '2026-04-15T00:00:00Z',
last_used_at: '2026-05-07T00:00:00Z',
expires_at: '2026-07-15T00:00:00Z',
},
{
id: 'tok-3',
prefix: 'dfoa',
client_id: 'cloud-console',
device_label: 'web ui',
created_at: '2026-05-05T00:00:00Z',
last_used_at: '2026-05-08T00:00:00Z',
expires_at: '2026-08-05T00:00:00Z',
},
]
@@ -0,0 +1,423 @@
import type { DifyMock } from './server.js'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vite-plus/test'
import { CATALOG_HEADER, CATALOG_PATH } from '@/plugins/catalog'
import { startMock } from './server.js'
const CATALOG_FIXTURE = readFileSync(join(__dirname, '../catalog.json'))
const CATALOG_V2_FIXTURE = readFileSync(join(__dirname, '../catalog-v2.json'))
const CATALOG_FINGERPRINT = createHash('sha256').update(CATALOG_FIXTURE).digest('hex')
const CATALOG_V2_FINGERPRINT = createHash('sha256').update(CATALOG_V2_FIXTURE).digest('hex')
const AUTH_HEADERS = { Authorization: 'Bearer dfoa_test', [CATALOG_HEADER]: CATALOG_FINGERPRINT }
describe('dify-mock fixture server', () => {
let mock: DifyMock
beforeEach(async () => {
mock = await startMock()
})
afterEach(async () => {
await mock.stop()
})
it('listens on an ephemeral port', () => {
expect(mock.port).toBeGreaterThan(0)
expect(mock.url).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)
})
it('GET /healthz returns 200 without auth', async () => {
const r = await fetch(`${mock.url}/healthz`)
expect(r.status).toBe(200)
expect(await r.json()).toEqual({ ok: true })
})
it('rejects /openapi/v1/* without Authorization header', async () => {
const r = await fetch(`${mock.url}/openapi/v1/workspaces`)
expect(r.status).toBe(401)
})
it('rejects malformed Bearer tokens', async () => {
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, {
headers: { Authorization: 'Bearer wrongprefix_abc' },
})
expect(r.status).toBe(401)
})
it('accepts dfoa_ tokens (community/account)', async () => {
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, { headers: AUTH_HEADERS })
expect(r.status).toBe(200)
})
it('accepts dfoe_ tokens (enterprise/external-subject)', async () => {
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, {
headers: { ...AUTH_HEADERS, Authorization: 'Bearer dfoe_test' },
})
expect(r.status).toBe(200)
})
it('GET /openapi/v1/workspaces returns the seeded list with status + current', async () => {
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, { headers: AUTH_HEADERS })
expect(r.status).toBe(200)
const body = (await r.json()) as {
data: Array<{
id: string
name: string
role: string
status: string
current: boolean
}>
hints: unknown[]
}
expect(body.data).toHaveLength(2)
expect(body.data[0]?.id).toBe('ws-1')
expect(body.data[0]?.status).toBe('normal')
expect(body.hints).toEqual([])
})
it('GET /openapi/v1/workspaces returns empty list under sso scenario', async () => {
mock.setScenario('sso')
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, { headers: AUTH_HEADERS })
expect(r.status).toBe(200)
const body = (await r.json()) as { data: unknown[] }
expect(body.data).toHaveLength(0)
})
it('GET /openapi/v1/account returns the seeded account envelope', async () => {
const r = await fetch(`${mock.url}/openapi/v1/account`, { headers: AUTH_HEADERS })
expect(r.status).toBe(200)
const body = (await r.json()) as {
subject_type: string
account: { email: string } | null
workspaces: Array<{ id: string }>
default_workspace_id: string
}
expect(body.subject_type).toBe('account')
expect(body.account?.email).toBe('tester@dify.ai')
expect(body.workspaces).toHaveLength(2)
expect(body.default_workspace_id).toBe('ws-1')
})
it('GET /openapi/v1/apps respects ?mode filter', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps?workspace_id=ws-1&mode=workflow`, {
headers: AUTH_HEADERS,
})
const body = (await r.json()) as { data: Array<{ mode: string }>; total: number }
expect(body.data).toHaveLength(1)
expect(body.data[0]?.mode).toBe('workflow')
expect(body.total).toBe(1)
})
it('GET /openapi/v1/apps scopes by workspace_id', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps?workspace_id=ws-2`, {
headers: AUTH_HEADERS,
})
const body = (await r.json()) as { data: Array<{ id: string }> }
expect(body.data).toHaveLength(2)
expect(body.data.map((r) => r.id).sort()).toEqual(['app-3', 'app-4'])
})
it('GET /openapi/v1/apps paginates with a "Next page" hint when has_more', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps?workspace_id=ws-1&limit=1`, {
headers: AUTH_HEADERS,
})
const body = (await r.json()) as { has_more: boolean; hints: Array<Record<string, unknown>> }
expect(body.has_more).toBe(true)
expect(body.hints).toEqual([
{
summary: 'Next page',
op: 'get.console_app',
input: { workspace_id: 'ws-1', page: 2, limit: 1 },
},
])
})
it('GET /openapi/v1/apps/:id returns 404 for unknown id', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/nope?workspace_id=ws-1`, {
headers: AUTH_HEADERS,
})
expect(r.status).toBe(404)
const body = (await r.json()) as { code: string; message: string; status: number }
expect(body).toEqual({ code: 'not_found', message: 'app not found', status: 404 })
})
it('GET /openapi/v1/apps/:id returns the app for known id', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-1?workspace_id=ws-1`, {
headers: AUTH_HEADERS,
})
expect(r.status).toBe(200)
const body = (await r.json()) as { info: { id: string } }
expect(body.info.id).toBe('app-1')
})
it('POST /openapi/v1/apps/:id:legacy_run returns SSE stream for chat app', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-1:legacy_run`, {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ query: 'hi', inputs: {} }),
})
expect(r.status).toBe(200)
expect(r.headers.get('content-type')).toContain('text/event-stream')
const text = await r.text()
expect(text).toContain('"answer":"echo: "')
expect(text).toContain('"op":"run.console_app.chat"')
})
it('POST /openapi/v1/apps/:id:legacy_run returns SSE stream for workflow app', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-2:legacy_run`, {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ inputs: { x: 1 } }),
})
expect(r.status).toBe(200)
expect(r.headers.get('content-type')).toContain('text/event-stream')
const text = await r.text()
expect(text).toContain('"workflow_finished"')
})
it('POST /openapi/v1/apps/:id/workflow:run runs the workflow app by mode-specific route', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-2/workflow:run`, {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ inputs: { x: 1 } }),
})
expect(r.status).toBe(200)
const text = await r.text()
expect(text).toContain('"workflow_finished"')
expect(mock.lastRunBody).toEqual({ inputs: { x: 1 } })
})
it('POST /openapi/v1/apps/:id/chat:run runs the chat app by mode-specific route', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-1/chat:run`, {
method: 'POST',
headers: { ...AUTH_HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({ query: 'hi', inputs: {} }),
})
expect(r.status).toBe(200)
const text = await r.text()
expect(text).toContain('"answer":"echo: "')
})
it('POST /openapi/v1/apps/:id/chat:run accepts multipart bodies and records the parts', async () => {
const form = new FormData()
form.set('query', JSON.stringify('hi'))
form.set('inputs', JSON.stringify({}))
form.set('files[avatar]', new File(['x'], 'avatar.png', { type: 'image/png' }))
form.append('attachments[]', new File(['a'], 'a.txt'))
form.append('attachments[]', new File(['b'], 'b.txt'))
const r = await fetch(`${mock.url}/openapi/v1/apps/app-1/chat:run`, {
method: 'POST',
headers: AUTH_HEADERS,
body: form,
})
expect(r.status).toBe(200)
expect(mock.lastRunBody).toEqual({ query: 'hi', inputs: {} })
const parts = mock.lastRunParts
expect(parts?.query).toBe('"hi"')
const avatar = parts?.['files[avatar]']
expect(Array.isArray(avatar) && avatar[0]?.name).toBe('avatar.png')
const attachments = parts?.['attachments[]']
expect(Array.isArray(attachments) && attachments.length).toBe(2)
})
it('GET /openapi/v1/apps/:id?fields=info returns slim payload', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-1?workspace_id=ws-1&fields=info`, {
headers: AUTH_HEADERS,
})
expect(r.status).toBe(200)
const body = (await r.json()) as {
info: { id: string }
parameters: unknown
input_schema: unknown
}
expect(body.info.id).toBe('app-1')
expect(body.parameters).toBeNull()
expect(body.input_schema).toBeNull()
})
it('GET /openapi/v1/apps/:id full returns parameters when present', async () => {
const r = await fetch(`${mock.url}/openapi/v1/apps/app-1?workspace_id=ws-1`, {
headers: AUTH_HEADERS,
})
expect(r.status).toBe(200)
const body = (await r.json()) as { parameters: { opening_statement: string } | null }
expect(body.parameters?.opening_statement).toBe('Hi, I am Greeter.')
})
it('POST /openapi/v1/oauth/device/code returns RFC 8628 fields', async () => {
const r = await fetch(`${mock.url}/openapi/v1/oauth/device/code`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: 'difyctl', device_label: 'difyctl on host' }),
})
expect(r.status).toBe(200)
const body = (await r.json()) as Record<string, unknown>
expect(body.device_code).toBeDefined()
expect(body.user_code).toBeDefined()
expect(body.interval).toBeDefined()
})
it('POST /openapi/v1/oauth/device/token returns Dify token envelope', async () => {
const r = await fetch(`${mock.url}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: 'difyctl', device_code: 'devcode-1' }),
})
expect(r.status).toBe(200)
const body = (await r.json()) as {
token: string
subject_type: string
account?: { email: string }
}
expect(body.token).toMatch(/^dfoa_/)
expect(body.subject_type).toBe('account')
expect(body.account?.email).toBe('tester@dify.ai')
})
it('scenario:sso returns external_sso envelope with dfoe_ token', async () => {
mock.setScenario('sso')
const r = await fetch(`${mock.url}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code: 'devcode-1' }),
})
expect(r.status).toBe(200)
const body = (await r.json()) as { token: string; subject_type: string; subject_email: string }
expect(body.token).toMatch(/^dfoe_/)
expect(body.subject_type).toBe('external_sso')
expect(body.subject_email).toBe('sso@dify.ai')
})
it('scenario:denied returns access_denied on token poll', async () => {
mock.setScenario('denied')
const r = await fetch(`${mock.url}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code: 'devcode-1' }),
})
expect(r.status).toBe(400)
const body = (await r.json()) as { error: string }
expect(body.error).toBe('access_denied')
})
it('scenario:expired returns expired_token on token poll', async () => {
mock.setScenario('expired')
const r = await fetch(`${mock.url}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code: 'devcode-1' }),
})
expect(r.status).toBe(400)
const body = (await r.json()) as { error: string }
expect(body.error).toBe('expired_token')
})
it('scenario:slow-down returns slow_down on token poll', async () => {
mock.setScenario('slow-down')
const r = await fetch(`${mock.url}/openapi/v1/oauth/device/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ device_code: 'devcode-1' }),
})
expect(r.status).toBe(400)
const body = (await r.json()) as { error: string }
expect(body.error).toBe('slow_down')
})
it('scenario:auth-expired returns 401 on bearer-protected endpoint', async () => {
mock.setScenario('auth-expired')
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, { headers: AUTH_HEADERS })
expect(r.status).toBe(401)
const body = (await r.json()) as { code: string }
expect(body.code).toBe('unauthorized')
})
it('scenario:rate-limited returns 429 with retry-after', async () => {
mock.setScenario('rate-limited')
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, { headers: AUTH_HEADERS })
expect(r.status).toBe(429)
expect(r.headers.get('retry-after')).toBe('1')
const body = (await r.json()) as { code: string; status: number }
expect(body).toMatchObject({ code: 'rate_limited', status: 429 })
})
it('scenario:server-5xx returns 503', async () => {
mock.setScenario('server-5xx')
const r = await fetch(`${mock.url}/openapi/v1/workspaces`, { headers: AUTH_HEADERS })
expect(r.status).toBe(503)
const body = (await r.json()) as { code: string; status: number }
expect(body).toMatchObject({ code: 'server_5xx', status: 503 })
})
it('GET _catalog serves the catalog bytes and its own fingerprint header, no auth required', async () => {
const r = await fetch(`${mock.url}${CATALOG_PATH}`)
expect(r.status).toBe(200)
expect(new Uint8Array(await r.arrayBuffer())).toEqual(new Uint8Array(CATALOG_FIXTURE))
expect(r.headers.get(CATALOG_HEADER.toLowerCase())).toBe(CATALOG_FINGERPRINT)
})
it('scenario:catalog-changed serves catalog-v2 bytes and fingerprint', async () => {
mock.setScenario('catalog-changed')
const r = await fetch(`${mock.url}${CATALOG_PATH}`)
expect(r.status).toBe(200)
expect(new Uint8Array(await r.arrayBuffer())).toEqual(new Uint8Array(CATALOG_V2_FIXTURE))
expect(r.headers.get(CATALOG_HEADER.toLowerCase())).toBe(CATALOG_V2_FINGERPRINT)
})
it('scenario:no-catalog returns 404 for _catalog', async () => {
mock.setScenario('no-catalog')
const r = await fetch(`${mock.url}${CATALOG_PATH}`)
expect(r.status).toBe(404)
})
it('every response carries the current catalog fingerprint header', async () => {
const r = await fetch(`${mock.url}/openapi/v1/account`, { headers: AUTH_HEADERS })
expect(r.headers.get(CATALOG_HEADER.toLowerCase())).toBe(CATALOG_FINGERPRINT)
})
it('rejects a stale X-Dify-Catalog header with 412', async () => {
const r = await fetch(`${mock.url}/openapi/v1/account`, {
headers: { Authorization: 'Bearer dfoa_test', [CATALOG_HEADER]: 'deadbeef' },
})
expect(r.status).toBe(412)
const body = (await r.json()) as { code: string; message: string; status: number; hint: string }
expect(body).toEqual({
code: 'catalog_stale',
message: "The request was built from a catalog that is not this server's current catalog.",
status: 412,
hint: 'GET /openapi/v1/_catalog, rebuild the request from it, and send its sha256 in X-Dify-Catalog.',
})
})
it('scenario:always-stale rejects even a fresh header', async () => {
mock.setScenario('always-stale')
const r = await fetch(`${mock.url}/openapi/v1/account`, { headers: AUTH_HEADERS })
expect(r.status).toBe(412)
})
it('_version and oauth/* are exempt from the catalog gate', async () => {
const version = await fetch(`${mock.url}/openapi/v1/_version`)
expect(version.status).toBe(200)
const device = await fetch(`${mock.url}/openapi/v1/oauth/device/code`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
expect(device.status).toBe(200)
})
it('tracks lastRequest (with query string) and requestCount across requests', async () => {
expect(mock.requestCount).toBe(0)
await fetch(`${mock.url}${CATALOG_PATH}`)
await fetch(`${mock.url}/openapi/v1/apps?limit=1&workspace_id=ws-1`, { headers: AUTH_HEADERS })
expect(mock.requestCount).toBe(2)
expect(mock.lastRequest).toMatchObject({
method: 'GET',
path: '/openapi/v1/apps?limit=1&workspace_id=ws-1',
})
expect(mock.lastRequest?.headers.authorization).toBe('Bearer dfoa_test')
})
})
+910
View File
@@ -0,0 +1,910 @@
import type { Context as HonoContext } from 'hono'
import type { ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { AppFixture, Scenario } from './scenarios.js'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { serve } from '@hono/node-server'
import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response'
import { Hono } from 'hono'
import { matchedRoutes } from 'hono/route'
import { METHOD_NAME_ALL } from 'hono/router'
import { CATALOG_HEADER, CATALOG_PATH } from '@/plugins/catalog'
import { ACCOUNT, APPS, DSL_YAML, SESSIONS, WORKSPACES } from './scenarios.js'
export type DifyMockOptions = {
scenario?: Scenario
port?: number
}
export type LastRequest = Readonly<{
method: string
path: string
headers: Record<string, string>
contentType: string | null
}>
export type DifyMock = {
url: string
port: number
scenario: Scenario
setScenario: (s: Scenario) => void
stop: () => Promise<void>
/** Body of the most recent POST to a run route */
lastRunBody: Record<string, unknown> | null
/** Multipart parts of the most recent POST to a run route, keyed by part name as received */
lastRunParts: Record<string, string | File[]> | null
/** Number of times POST /apps/:id/files was called */
uploadCallCount: number
/** Body of the most recent POST to /workspaces/:id/apps/imports */
lastImportBody: Record<string, unknown> | null
/** Method, path (with query string), headers and content-type of the most recent request */
lastRequest: LastRequest | null
/** Number of requests received, including GET _catalog */
requestCount: number
/** Runs before each device-token poll is answered: lets a test act while a resume waits. */
onDeviceTokenPoll: (hook: () => void) => void
}
const TOKEN_RE = /^Bearer\s+dfo[ae]_[\w-]+$/
const VERSION_PATH = '/openapi/v1/_version'
const HANG_PATH = '/hang'
const EMPTY_ERROR_PATH = '/empty-error'
const BAD_VERIFICATION_URI = 'ftp://elsewhere.example/device'
const HANG_MS = 30_000
const OAUTH_PREFIX = '/openapi/v1/oauth/'
export const FORBIDDEN_HINT = 'ask a workspace owner for the editor role'
const ServerErrorCode = {
Unauthorized: 'unauthorized',
Forbidden: 'forbidden',
RateLimited: 'rate_limited',
Server5xx: 'server_5xx',
NotFound: 'not_found',
CatalogStale: 'catalog_stale',
ValidationError: 'validation_error',
} as const
const OpId = {
AppList: 'get.console_app',
WorkspaceList: 'get.workspace',
AccountSessionsList: 'get.account.session',
ChatRun: 'run.console_app.chat',
AdvancedChatRun: 'run.console_app.advanced_chat',
FormSubmit: 'submit.run.form',
RunEvents: 'get.run.event',
} as const
const CATALOG_STALE_MESSAGE =
"The request was built from a catalog that is not this server's current catalog."
const CATALOG_STALE_HINT =
'GET /openapi/v1/_catalog, rebuild the request from it, and send its sha256 in X-Dify-Catalog.'
type MockErrorBody = { code: string; message: string; status: number; hint?: string }
function errorBody(code: string, message: string, status: number, hint?: string): MockErrorBody {
return hint === undefined ? { code, message, status } : { code, message, status, hint }
}
function errorResponse(code: string, message: string, status: number, hint?: string) {
return Response.json(errorBody(code, message, status, hint), { status })
}
function unauthorized() {
return errorResponse(ServerErrorCode.Unauthorized, 'invalid or expired token', 401)
}
const FIXTURE_DIR = dirname(fileURLToPath(import.meta.url))
const CATALOG_BYTES = readFileSync(join(FIXTURE_DIR, '..', 'catalog.json'))
const CATALOG_V2_BYTES = readFileSync(join(FIXTURE_DIR, '..', 'catalog-v2.json'))
const CATALOG_FINGERPRINT = createHash('sha256').update(CATALOG_BYTES).digest('hex')
const CATALOG_V2_FINGERPRINT = createHash('sha256').update(CATALOG_V2_BYTES).digest('hex')
function catalogBytesFor(scenario: Scenario): Uint8Array | undefined {
if (scenario === 'no-catalog') return undefined
if (scenario === 'catalog-changed') return CATALOG_V2_BYTES
return CATALOG_BYTES
}
function catalogFingerprintFor(scenario: Scenario): string {
return scenario === 'catalog-changed' ? CATALOG_V2_FINGERPRINT : CATALOG_FINGERPRINT
}
function sseChunks(events: { event: string; data: Record<string, unknown> }[]): string {
return events.map((e) => `data: ${JSON.stringify({ ...e.data, event: e.event })}\n\n`).join('')
}
function chatReplyHints(mode: string, appId: string): Record<string, unknown>[] {
const op =
mode === 'chat' ? OpId.ChatRun : mode === 'advanced-chat' ? OpId.AdvancedChatRun : undefined
if (op === undefined) return []
return [
{
summary: 'Reply in this conversation',
op,
input: { app_id: appId, conversation_id: 'conv-1', query: null, inputs: {} },
},
]
}
function nextPageHints(
op: string,
query: Record<string, string>,
page: number,
limit: number,
hasMore: boolean,
): Record<string, unknown>[] {
if (!hasMore) return []
return [{ summary: 'Next page', op, input: { ...query, page: page + 1, limit } }]
}
function streamingRunResponse(
mode: string,
query: string,
isAgent: boolean,
appId: string,
): string {
if (mode === 'workflow') {
return sseChunks([
{ event: 'workflow_started', data: { id: 'wf-run-1', workflow_id: 'wf-1' } },
{ event: 'node_started', data: { id: 'n1', title: 'first' } },
{ event: 'node_finished', data: { id: 'n1', status: 'succeeded' } },
{
event: 'workflow_finished',
data: {
id: 'wf-run-1',
workflow_id: 'wf-1',
data: { id: 'wf-run-1', status: 'succeeded', outputs: { result: `echo: ${query}` } },
},
},
])
}
if (mode === 'completion') {
return sseChunks([
{ event: 'message', data: { message_id: 'msg-1', mode, answer: 'echo: ' } },
{ event: 'message', data: { answer: query } },
{
event: 'message_end',
data: {
message_id: 'msg-1',
task_id: 'task-1',
metadata: {},
hints: chatReplyHints(mode, appId),
},
},
])
}
const evt = isAgent ? 'agent_message' : 'message'
const events: { event: string; data: Record<string, unknown> }[] = [
{
event: evt,
data: { message_id: 'msg-1', conversation_id: 'conv-1', mode, answer: 'echo: ' },
},
{ event: evt, data: { answer: query } },
]
if (isAgent) events.push({ event: 'agent_thought', data: { thought: 'thinking…' } })
events.push({
event: 'message_end',
data: {
message_id: 'msg-1',
conversation_id: 'conv-1',
metadata: {},
hints: chatReplyHints(mode, appId),
},
})
return sseChunks(events)
}
function hitlPauseResponse(appId: string): string {
return sseChunks([
{
event: 'workflow_started',
data: {
workflow_run_id: 'wf-run-hitl-1',
data: { id: 'wf-run-hitl-1', workflow_id: 'wf-1' },
},
},
{ event: 'node_started', data: { id: 'n1', title: 'First Node' } },
{
event: 'human_input_required',
data: {
task_id: 'task-hitl-1',
workflow_run_id: 'wf-run-hitl-1',
data: {
form_id: 'form-hitl-1',
node_id: 'n1',
node_title: 'First Node',
form_content: 'Please provide input',
inputs: [{ output_variable_name: 'name' }],
actions: [{ id: 'submit', title: 'Submit' }],
display_in_ui: false,
form_token: 'ft-hitl-1',
resolved_default_values: { name: 'Alice' },
expiration_time: 9999999999,
},
hints: [
{
summary: 'Submit',
op: OpId.FormSubmit,
input: {
app_id: appId,
form_token: 'ft-hitl-1',
action: 'submit',
inputs: { name: null },
},
form: [{ output_variable_name: 'name' }],
},
],
},
},
{ event: 'workflow_paused', data: { reasons: [] } },
])
}
function hitlResumedResponse(): string {
return sseChunks([
{ event: 'node_started', data: { id: 'n2', title: 'After Resume' } },
{ event: 'node_finished', data: { id: 'n2', status: 'succeeded' } },
{
event: 'workflow_finished',
data: {
id: 'wf-run-hitl-1',
workflow_id: 'wf-1',
data: { id: 'wf-run-hitl-1', status: 'succeeded', outputs: { result: 'echo: resumed' } },
},
},
])
}
export type MockState = {
lastRunBody: Record<string, unknown> | null
lastRunParts: Record<string, string | File[]> | null
uploadCallCount: number
lastImportBody: Record<string, unknown> | null
lastRequest: LastRequest | null
requestCount: number
beforeDeviceToken?: () => void
}
async function readMultipartRunBody(
c: HonoContext,
): Promise<{ json: Record<string, unknown>; parts: Record<string, string | File[]> }> {
const parsed = await c.req.parseBody({ all: true })
const json: Record<string, unknown> = {}
const parts: Record<string, string | File[]> = {}
for (const [key, value] of Object.entries(parsed)) {
const values = Array.isArray(value) ? value : [value]
const files = values.filter((v): v is File => v instanceof File)
if (files.length > 0) {
parts[key] = files
continue
}
const text = values[0] as string
parts[key] = text
json[key] = JSON.parse(text)
}
return { json, parts }
}
const SLOW_STREAM_GAP_MS = 200
function sseResponse(body: string | ReadableStream<Uint8Array>): Response {
return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } })
}
// Headers land at once, the first event right after, and the rest only after a gap —
// the shape that a whole-request timeout would cut short but a headers deadline must not.
function slowStreamBody(query: string): ReadableStream<Uint8Array> {
const enc = new TextEncoder()
return new ReadableStream({
async start(controller) {
controller.enqueue(
enc.encode(
sseChunks([{ event: 'message', data: { message_id: 'msg-1', answer: 'echo: ' } }]),
),
)
await new Promise((r) => setTimeout(r, SLOW_STREAM_GAP_MS))
controller.enqueue(
enc.encode(
sseChunks([
{ event: 'message', data: { answer: query } },
{ event: 'message_end', data: { message_id: 'msg-1', metadata: {} } },
]),
),
)
controller.close()
},
})
}
// One good event, then the socket dies under the client: the body read rejects
// mid-stream, which an errored ReadableStream alone does not reproduce.
function destroyMidStream(c: HonoContext): Response {
const { outgoing } = c.env as { outgoing: ServerResponse }
outgoing.writeHead(200, { 'content-type': 'text/event-stream' })
outgoing.write(
sseChunks([{ event: 'message', data: { message_id: 'msg-1', answer: 'partial' } }]),
() => outgoing.socket?.destroy(),
)
return RESPONSE_ALREADY_SENT
}
function runResponse(
c: HonoContext,
app: AppFixture,
body: Record<string, unknown>,
scenario: Scenario,
): Response {
if (scenario === 'broken-stream') return destroyMidStream(c)
const isAgent = app.is_agent === true || app.mode === 'agent-chat'
const query = (body.query as string | undefined) ?? ''
if (scenario === 'stream-error')
return sseResponse(sseChunks([{ event: 'error', data: { message: 'boom', status: 503 } }]))
if (scenario === 'slow-stream') return sseResponse(slowStreamBody(query))
if (scenario === 'hitl-pause') return sseResponse(hitlPauseResponse(app.id))
return sseResponse(streamingRunResponse(app.mode, query, isAgent, app.id))
}
async function handleRun(
c: HonoContext,
id: string,
state: MockState | undefined,
getScenario: () => Scenario,
): Promise<Response> {
const contentType = c.req.header('content-type') ?? ''
let body: Record<string, unknown>
if (contentType.includes('multipart/form-data')) {
const { json, parts } = await readMultipartRunBody(c)
body = json
if (state !== undefined) state.lastRunParts = parts
} else {
body = (await c.req.json()) as Record<string, unknown>
if (state !== undefined) state.lastRunParts = null
}
if (state !== undefined) state.lastRunBody = body
const app = APPS.find((a) => a.id === id)
if (app === undefined) return errorResponse(ServerErrorCode.NotFound, 'app not found', 404)
return runResponse(c, app, body, getScenario())
}
function recoverLegacyRunId(c: HonoContext): string {
// Hono drops the param adjacent to the `:legacy_run` literal; recover the app id from the path.
return c.req.path.replace(/^.*\/apps\//, '').replace(/:legacy_run$/, '')
}
export function buildApp(getScenario: () => Scenario, state?: MockState): Hono {
const app = new Hono()
app.use('*', async (c, next) => {
if (state !== undefined) {
state.requestCount++
const url = new URL(c.req.url)
state.lastRequest = {
method: c.req.method,
path: url.pathname + url.search,
headers: Object.fromEntries(c.req.raw.headers.entries()),
contentType: c.req.header('content-type') ?? null,
}
}
await next()
})
app.use('*', async (c, next) => {
await next()
c.res.headers.set(CATALOG_HEADER, catalogFingerprintFor(getScenario()))
})
app.notFound(() =>
errorResponse(ServerErrorCode.NotFound, 'The requested URL was not found on the server.', 404),
)
app.get('/healthz', (c) => c.json({ ok: true }))
// A rejection with no body at all: nothing for the client to name it by but the status.
app.get(EMPTY_ERROR_PATH, () => new Response(null, { status: 503 }))
// Accepts the connection and never answers: the headers deadline has to fire.
// The timer is unref'd so it never holds the test process open.
app.get(HANG_PATH, async () => {
await new Promise<void>((resolve) => {
setTimeout(resolve, HANG_MS).unref()
})
return new Response('too late', { status: 200 })
})
app.get(CATALOG_PATH, (_c) => {
const bytes = catalogBytesFor(getScenario())
if (bytes === undefined)
return errorResponse(ServerErrorCode.NotFound, 'catalog not found', 404)
return new Response(bytes, { status: 200, headers: { 'content-type': 'application/json' } })
})
app.use('*', async (c, next) => {
if (c.req.path === '/healthz') {
await next()
return
}
if (c.req.path.startsWith(OAUTH_PREFIX)) {
await next()
return
}
if (c.req.path === VERSION_PATH) {
await next()
return
}
const auth = c.req.header('Authorization') ?? ''
const resourceToken = getScenario() === 'resource-token' && auth === 'Bearer sk-test-resource'
if (!TOKEN_RE.test(auth) && !resourceToken) return unauthorized()
if (
resourceToken &&
c.req.path !== '/openapi/v1/workspaces' &&
c.req.path !== '/openapi/v1/apps' &&
!c.req.path.startsWith(`/openapi/v1/apps/${APPS[0]!.id}`)
)
return c.json({ code: 'forbidden', message: 'resource_not_authorized', status: 403 }, 403)
const scenario = getScenario()
if (scenario === 'auth-expired') return unauthorized()
if (scenario === 'forbidden')
return errorResponse(ServerErrorCode.Forbidden, 'you may not do this', 403, FORBIDDEN_HINT)
await next()
})
app.get(VERSION_PATH, (c) => c.json({ version: '1.6.4', edition: 'CLOUD' }))
app.use('*', async (c, next) => {
const path = c.req.path
if (!path.startsWith('/openapi/v1/')) {
await next()
return
}
if (path === CATALOG_PATH || path === VERSION_PATH || path.startsWith(OAUTH_PREFIX)) {
await next()
return
}
// Flask answers an unknown path 404 before any per-route guard runs.
if (!matchedRoutes(c).some((route) => route.method !== METHOD_NAME_ALL)) {
await next()
return
}
const scenario = getScenario()
const clientFingerprint = c.req.header(CATALOG_HEADER) ?? ''
const serverFingerprint = catalogFingerprintFor(scenario)
if (scenario === 'always-stale' || clientFingerprint !== serverFingerprint) {
return errorResponse(
ServerErrorCode.CatalogStale,
CATALOG_STALE_MESSAGE,
412,
CATALOG_STALE_HINT,
)
}
await next()
})
app.use('*', async (c, next) => {
const scenario = getScenario()
if (scenario === 'rate-limited') {
// Per-token throttle (retryable); Retry-After advises the wait.
return Response.json(
errorBody(ServerErrorCode.RateLimited, 'Too many requests for this API token.', 429),
{ status: 429, headers: { 'retry-after': '1' } },
)
}
if (scenario === 'server-5xx') {
return errorResponse(ServerErrorCode.Server5xx, 'upstream broken', 503)
}
await next()
})
app.get('/openapi/v1/account', (c) => {
const scenario = getScenario()
if (scenario === 'sso') {
return c.json({
subject_type: 'external_sso',
subject_email: 'sso@dify.ai',
subject_issuer: 'https://issuer.example',
account: null,
workspaces: [],
default_workspace_id: null,
})
}
return c.json({
subject_type: 'account',
subject_email: ACCOUNT.email,
account: { id: ACCOUNT.id, email: ACCOUNT.email, name: ACCOUNT.name },
workspaces: WORKSPACES.map((w) => ({ id: w.id, name: w.name, role: w.role })),
default_workspace_id: ACCOUNT.current_workspace_id,
})
})
app.get('/openapi/v1/account/sessions', (c) => {
const page = Number(c.req.query('page') ?? '1')
const limit = Number(c.req.query('limit') ?? '100')
const total = SESSIONS.length
const start = (page - 1) * limit
const slice = SESSIONS.slice(start, start + limit)
const hasMore = page * limit < total
return c.json({
page,
limit,
total,
has_more: hasMore,
data: slice,
hints: nextPageHints(OpId.AccountSessionsList, c.req.query(), page, limit, hasMore),
})
})
app.delete('/openapi/v1/account/sessions/self', () =>
Response.json({ status: 'revoked' }, { status: 200 }),
)
app.delete('/openapi/v1/account/sessions/:id', (c) => {
const id = c.req.param('id')
if (!SESSIONS.some((s) => s.id === id))
return errorResponse(ServerErrorCode.NotFound, 'session not found', 404)
return Response.json({ status: 'revoked' }, { status: 200 })
})
app.get('/openapi/v1/workspaces', (c) => {
// A server that answers the list op with something other than a list envelope.
if (getScenario() === 'workspaces-malformed') return c.json({ data: { id: 'ws-1' } })
const page = Number(c.req.query('page') ?? '1')
const limit = Number(c.req.query('limit') ?? '20')
const rows =
getScenario() === 'sso'
? []
: WORKSPACES.filter(
(w) => getScenario() !== 'resource-token' || w.id === APPS[0]!.workspace_id,
).map((w) => ({
id: w.id,
name: w.name,
role: getScenario() === 'resource-token' ? '' : w.role,
status: w.status,
}))
const total = rows.length
const hasMore = page * limit < total
return c.json({
page,
limit,
total,
has_more: hasMore,
data: rows.slice((page - 1) * limit, page * limit),
hints: nextPageHints(OpId.WorkspaceList, c.req.query(), page, limit, hasMore),
})
})
app.get('/openapi/v1/workspaces/:wsId', (c) => {
const ws = WORKSPACES.find((w) => w.id === c.req.param('wsId'))
if (ws === undefined) return errorResponse(ServerErrorCode.NotFound, 'workspace not found', 404)
return c.json({ id: ws.id, name: ws.name, role: ws.role, status: ws.status, created_at: null })
})
// Reachable only under the `catalog-changed` scenario: the op that catalog v2 adds.
app.get('/openapi/v1/workspaces/:wsId/ping', (c) => c.json({ ok: true }))
app.get('/openapi/v1/apps', (c) => {
const page = Number(c.req.query('page') ?? '1')
const limit = Number(c.req.query('limit') ?? '20')
const mode = c.req.query('mode')
const tag = c.req.query('tag')
const name = c.req.query('name')
const workspaceId = c.req.query('workspace_id') ?? ACCOUNT.current_workspace_id
let filtered = APPS.filter((a) => a.workspace_id === workspaceId)
if (getScenario() === 'resource-token') filtered = filtered.filter((a) => a.id === APPS[0]!.id)
if (mode !== undefined && mode !== '') filtered = filtered.filter((a) => a.mode === mode)
if (tag !== undefined && tag !== '')
filtered = filtered.filter((a) => a.tags.some((t) => t.name === tag))
if (name !== undefined && name !== '') filtered = filtered.filter((a) => a.name.includes(name))
const total = filtered.length
const start = (page - 1) * limit
const slice = filtered.slice(start, start + limit)
const hasMore = page * limit < total
return c.json({
page,
limit,
total,
has_more: hasMore,
data: slice,
hints: nextPageHints(OpId.AppList, c.req.query(), page, limit, hasMore),
})
})
app.get('/openapi/v1/apps/:id', (c) => {
const id = c.req.param('id')
const wsId = c.req.query('workspace_id')
const fieldsRaw = c.req.query('fields') ?? ''
const fields =
fieldsRaw === ''
? []
: fieldsRaw
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '')
const app = APPS.find(
(a) => a.id === id && (wsId === undefined || wsId === '' || a.workspace_id === wsId),
)
if (app === undefined) return errorResponse(ServerErrorCode.NotFound, 'app not found', 404)
const wantInfo = fields.length === 0 || fields.includes('info')
const wantParams = fields.length === 0 || fields.includes('parameters')
const wantInputSchema = fields.length === 0 || fields.includes('input_schema')
return c.json({
info: wantInfo
? {
id: app.id,
name: app.name,
description: app.description,
mode: app.mode,
updated_at: app.updated_at,
service_api_enabled: app.service_api_enabled ?? false,
is_agent: app.is_agent ?? false,
}
: null,
parameters: wantParams ? (app.parameters ?? null) : null,
input_schema: wantInputSchema ? (app.input_schema ?? null) : null,
})
})
app.get('/openapi/v1/permitted-external-apps/:id', (c) => {
const id = c.req.param('id')
const fieldsRaw = c.req.query('fields') ?? ''
const fields =
fieldsRaw === ''
? []
: fieldsRaw
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '')
// External subjects have no workspace scope; the app is reachable across workspaces.
const app = APPS.find((a) => a.id === id)
if (app === undefined) return errorResponse(ServerErrorCode.NotFound, 'app not found', 404)
const wantInfo = fields.length === 0 || fields.includes('info')
const wantParams = fields.length === 0 || fields.includes('parameters')
const wantInputSchema = fields.length === 0 || fields.includes('input_schema')
return c.json({
info: wantInfo
? {
id: app.id,
name: app.name,
description: app.description,
mode: app.mode,
updated_at: app.updated_at,
service_api_enabled: app.service_api_enabled ?? false,
is_agent: app.is_agent ?? false,
}
: null,
parameters: wantParams ? (app.parameters ?? null) : null,
input_schema: wantInputSchema ? (app.input_schema ?? null) : null,
})
})
app.get('/openapi/v1/apps/:id/dsl', (c) => {
const id = c.req.param('id')
const found = APPS.find((a) => a.id === id)
if (found === undefined) return errorResponse(ServerErrorCode.NotFound, 'app not found', 404)
return c.json({ data: DSL_YAML })
})
app.get('/openapi/v1/apps/:id/dependencies:check', (c) => {
const id = c.req.param('id')
const found = APPS.find((a) => a.id === id)
if (found === undefined) return errorResponse(ServerErrorCode.NotFound, 'app not found', 404)
return c.json({ leaked_dependencies: [] })
})
app.post('/openapi/v1/workspaces/:wsId/apps/imports', async (c) => {
const body = (await c.req.json()) as Record<string, unknown>
if (state !== undefined) state.lastImportBody = body
const scenario = getScenario()
if (scenario === 'import-failed')
return c.json(
{ id: 'imp-1', status: 'failed', error: 'unsupported DSL version' },
{ status: 400 },
)
if (scenario === 'import-pending')
return c.json(
{
id: 'imp-1',
status: 'pending',
current_dsl_version: '0.1.4',
imported_dsl_version: '0.0.9',
},
{ status: 202 },
)
return c.json(
{ id: 'imp-1', status: 'completed', app_id: 'app-1', app_mode: 'chat' },
{ status: 200 },
)
})
app.post('/openapi/v1/workspaces/:wsId/apps/imports/:importId:confirm', (c) => {
return c.json(
{ id: 'imp-1', status: 'completed', app_id: 'app-1', app_mode: 'chat' },
{ status: 200 },
)
})
// A deprecated op the fixture catalogs keep so the deprecation notice stays tested.
app.post('/openapi/v1/apps/:id:legacy_run', (c) =>
handleRun(c, recoverLegacyRunId(c), state, getScenario),
)
app.post('/openapi/v1/apps/:id/workflow:run', (c) =>
handleRun(c, c.req.param('id'), state, getScenario),
)
app.post('/openapi/v1/apps/:id/chat:run', (c) =>
handleRun(c, c.req.param('id'), state, getScenario),
)
app.post('/openapi/v1/apps/:id/completion:run', (c) =>
handleRun(c, c.req.param('id'), state, getScenario),
)
app.post('/openapi/v1/apps/:id/advanced-chat:run', (c) =>
handleRun(c, c.req.param('id'), state, getScenario),
)
app.post('/openapi/v1/apps/:id/files', async (c) => {
if (state !== undefined) state.uploadCallCount++
const form = await c.req.formData()
const file = form.get('file')
if (!(file instanceof File))
return errorResponse(ServerErrorCode.ValidationError, 'No file uploaded', 400)
const ext = file.name.split('.').pop() ?? null
return Response.json(
{
id: 'upload-file-1',
name: file.name,
size: file.size,
extension: ext,
mime_type: file.type || null,
created_by: 'acct-1',
},
{ status: 201 },
)
})
app.post('/openapi/v1/apps/:id/runs/:runId:stop', (c) => {
return c.json({ result: 'success' })
})
// Like the server: the submit names the run to follow, stopping at the next pause.
app.post('/openapi/v1/apps/:id/human-input-forms/:formToken:submit', (c) =>
c.json({
hints: [
{
summary: 'Follow the run',
op: OpId.RunEvents,
input: { app_id: c.req.param('id'), run_id: 'wf-run-hitl-1', continue_on_pause: false },
},
],
}),
)
app.get('/openapi/v1/apps/:id/runs/:run_id/events', (_c) => sseResponse(hitlResumedResponse()))
app.post('/openapi/v1/oauth/device/code', (c) => {
const scenario = getScenario()
if (scenario === 'no-device-flow')
return errorResponse(ServerErrorCode.NotFound, 'not found', 404)
if (scenario === 'bad-verification-uri')
return c.json({
device_code: 'devcode-1',
user_code: 'ABCD-1234',
verification_uri: BAD_VERIFICATION_URI,
verification_uri_complete: BAD_VERIFICATION_URI,
expires_in: 600,
interval: 1,
})
return c.json({
device_code: 'devcode-1',
user_code: 'ABCD-1234',
verification_uri: `${new URL(c.req.url).origin}/device`,
verification_uri_complete: `${new URL(c.req.url).origin}/device?user_code=ABCD-1234`,
expires_in: 600,
interval: 1,
})
})
app.post('/openapi/v1/oauth/device/token', async (c) => {
state?.beforeDeviceToken?.()
const scenario = getScenario()
if (scenario === 'denied')
return c.json({ error: 'access_denied', error_description: 'user rejected' }, { status: 400 })
if (scenario === 'expired')
return c.json(
{ error: 'expired_token', error_description: 'device_code expired' },
{ status: 400 },
)
if (scenario === 'slow-down')
return c.json({ error: 'slow_down', error_description: 'increase interval' }, { status: 400 })
if (scenario === 'sso') {
return c.json({
token: 'dfoe_test',
subject_type: 'external_sso',
subject_email: 'sso@dify.ai',
subject_issuer: 'https://issuer.example',
account: null,
workspaces: [],
default_workspace_id: null,
token_id: 'tok-sso-1',
})
}
if (scenario === 'no-email') {
return c.json({
token: 'dfoa_test',
subject_type: 'account',
account: { id: ACCOUNT.id, email: '', name: '' },
workspaces: WORKSPACES.map((w) => ({ id: w.id, name: w.name, role: w.role })),
default_workspace_id: ACCOUNT.current_workspace_id,
token_id: 'tok-1',
})
}
return c.json({
token: 'dfoa_test',
subject_type: 'account',
account: ACCOUNT,
workspaces: WORKSPACES.map((w) => ({ id: w.id, name: w.name, role: w.role })),
default_workspace_id: ACCOUNT.current_workspace_id,
token_id: 'tok-1',
})
})
return app
}
export function startMock(opts: DifyMockOptions = {}): Promise<DifyMock> {
let scenario: Scenario = opts.scenario ?? 'happy'
const state: MockState = {
lastRunBody: null,
lastRunParts: null,
uploadCallCount: 0,
lastImportBody: null,
lastRequest: null,
requestCount: 0,
}
const app = buildApp(() => scenario, state)
return new Promise((resolve, reject) => {
const server = serve({
fetch: app.fetch,
port: opts.port ?? 0,
hostname: '127.0.0.1',
overrideGlobalObjects: false,
})
server.on('listening', () => {
const addr = server.address() as AddressInfo
resolve({
url: `http://127.0.0.1:${addr.port}`,
port: addr.port,
scenario,
setScenario(s) {
scenario = s
},
stop() {
return new Promise<void>((res, rej) => {
server.close((err) => (err ? rej(err) : res()))
})
},
get lastRunBody() {
return state.lastRunBody
},
get lastRunParts() {
return state.lastRunParts
},
get uploadCallCount() {
return state.uploadCallCount
},
get lastImportBody() {
return state.lastImportBody
},
get lastRequest() {
return state.lastRequest
},
get requestCount() {
return state.requestCount
},
onDeviceTokenPoll(hook) {
state.beforeDeviceToken = hook
},
})
})
server.on('error', reject)
})
}
+110
View File
@@ -0,0 +1,110 @@
import type { DifyMock } from '@test/fixtures/dify-mock/server'
import type { Override } from '@/kernel/context'
import type { Login } from '@/plugins/session'
import type { BufferStreams } from '@/sys/io/streams'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { startMock } from '@test/fixtures/dify-mock/server'
import { Context } from '@/kernel/context'
import { argv } from '@/plugins/argv'
import { ENV } from '@/plugins/env'
import { io, ioService } from '@/plugins/io'
import { resolveOutput } from '@/plugins/output'
import { session } from '@/plugins/session'
import { token } from '@/plugins/token'
import { bufferStreams } from '@/sys/io/streams'
export type TestWorld = {
ctx: Context
io: BufferStreams
mock: DifyMock
dir: string
overrides: Override[]
stop: () => Promise<void>
}
export type TestWorldOptions = {
readonly login: boolean
readonly argv?: readonly string[]
readonly env?: boolean
readonly stdin?: string
readonly tty?: boolean
/** Share another world's temp dir and mock instead of making new ones. */
readonly reuseDirOf?: TestWorld
}
const TEMP_PREFIX = 'difyctl-world-'
const FILE_EMAIL = 'me@x'
const FILE_WORKSPACE_ID = 'ws-1'
const FILE_LOGIN_TOKEN = 'dfoa_file'
const ENV_LOGIN_TOKEN = 'dfoa_env'
type EnvPatch = Readonly<Record<string, string | undefined>>
function applyEnv(patch: EnvPatch): () => void {
const saved = new Map<string, string | undefined>()
for (const [key, value] of Object.entries(patch)) {
saved.set(key, process.env[key])
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
return () => {
for (const [key, value] of saved) {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
}
}
async function writeFileLogin(server: string): Promise<void> {
const boot = new Context()
const sessionService = await boot.get(session)
const tokenService = await boot.get(token)
const login: Login = {
server,
email: FILE_EMAIL,
account: null,
workspaceId: FILE_WORKSPACE_ID,
tokenStorage: 'file',
insecure: false,
}
await sessionService.save(login)
await tokenService.write(login, FILE_LOGIN_TOKEN)
}
export async function testContext(opts: TestWorldOptions): Promise<TestWorld> {
const shared = opts.reuseDirOf
const mock = shared === undefined ? await startMock() : shared.mock
const dir = shared === undefined ? await mkdtemp(join(tmpdir(), TEMP_PREFIX)) : shared.dir
const restoreEnv = applyEnv({
[ENV.ConfigDir]: dir,
[ENV.Server]: opts.env === true ? mock.url : undefined,
[ENV.Token]: opts.env === true ? ENV_LOGIN_TOKEN : undefined,
[ENV.WorkspaceId]: undefined,
})
if (opts.login) await writeFileLogin(mock.url)
const streams = bufferStreams(opts.stdin ?? '')
streams.isOutTTY = streams.isErrTTY = opts.tty === true
const overrides: Override[] = [
[io, ioService(streams, resolveOutput({ argv: opts.argv ?? [], env: {}, streams }))],
[argv, opts.argv ?? []],
]
return {
ctx: new Context(overrides),
io: streams,
mock,
dir,
overrides,
stop: async () => {
restoreEnv()
if (shared !== undefined) return
await mock.stop()
await rm(dir, { recursive: true, force: true })
},
}
}
+55
View File
@@ -0,0 +1,55 @@
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
// Mirrors PKG_PATH_ENV in scripts/release-naming.mjs, which cannot be imported
// here: its shebang breaks the Windows test runner. Divergence is self-
// reporting, not silent — the script would fall back to the real
// cli/package.json and every fixture-window assertion would fail.
const PKG_PATH_ENV = 'DIFYCTL_PKG_PATH'
// release-naming.mjs and release-r2-edge.mjs read their data from
// cli/package.json. Tests spawn them against this fixture instead, so
// assertions can name an exact version/channel without tracking the live release.
export const FIXTURE_VERSION = '7.7.7'
export const FIXTURE_CHANNEL = 'stable'
export const FIXTURE_TAG_PREFIX = 'difyctl-v'
export const FIXTURE_TARGET_IDS = [
'linux-x64',
'linux-arm64',
'darwin-x64',
'darwin-arm64',
'windows-x64',
] as const
const FIXTURE_RELEASE = {
tagPrefix: FIXTURE_TAG_PREFIX,
binName: 'difyctl',
checksumsSuffix: '-checksums.txt',
targets: FIXTURE_TARGET_IDS.map((id) => ({
id,
bunTarget: `bun-${id}`,
exe: id.startsWith('windows'),
})),
}
export type PkgManifestOverrides = {
version?: string
channel?: string
}
// Returns the env additions that point a spawned script at the fixture.
export function pkgManifestEnv(overrides: PkgManifestOverrides = {}): Record<string, string> {
const manifest = {
version: overrides.version ?? FIXTURE_VERSION,
difyctl: {
channel: overrides.channel ?? FIXTURE_CHANNEL,
release: FIXTURE_RELEASE,
},
}
const path = join(mkdtempSync(join(tmpdir(), 'difyctl-pkg-')), 'package.json')
writeFileSync(path, JSON.stringify(manifest))
return { [PKG_PATH_ENV]: path }
}
@@ -0,0 +1,155 @@
import { execFileSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
import { BUILD_CHANNELS, resolveBuildInfo } from '../../scripts/lib/resolve-buildinfo.js'
const CLI_ROOT = new URL('../../', import.meta.url)
const RELEASE_NAMING = fileURLToPath(new URL('scripts/release-naming.mjs', CLI_ROOT))
const FIXED_DATE = new Date('2026-05-09T12:00:00.000Z')
const fixedNow = () => FIXED_DATE
const noGit = () => null
// Stub the package.json reader so tests exercise the "no sources" path
// without coupling to the live cli/package.json#difyctl.channel value.
const noPkg = () => ({})
describe('resolveBuildInfo', () => {
it('uses env values when fully populated', () => {
const info = resolveBuildInfo({
env: {
DIFYCTL_VERSION: '1.2.3',
DIFYCTL_COMMIT: 'abcdef0123456789',
DIFYCTL_BUILD_DATE: '2026-01-01T00:00:00.000Z',
DIFYCTL_CHANNEL: 'stable',
},
git: () => 'should-not-be-called',
now: fixedNow,
pkg: noPkg,
})
expect(info).toStrictEqual({
version: '1.2.3',
commit: 'abcdef0123456789',
buildDate: '2026-01-01T00:00:00.000Z',
channel: 'stable',
})
})
it('falls back to git probes when env unset', () => {
const calls: string[] = []
const git = (cmd: string) => {
calls.push(cmd)
if (cmd.startsWith('git describe')) return 'v1.0.0-5-gabc1234-dirty'
if (cmd.startsWith('git rev-parse')) return '1234567890abcdef'
return null
}
const info = resolveBuildInfo({ env: {}, git, now: fixedNow, pkg: noPkg })
expect(info).toStrictEqual({
version: 'v1.0.0-5-gabc1234-dirty',
commit: '1234567890abcdef',
buildDate: '2026-05-09T12:00:00.000Z',
channel: 'dev',
})
expect(calls).toStrictEqual(['git describe --tags --dirty --always', 'git rev-parse HEAD'])
})
it('uses string defaults when env unset, git unavailable, and package.json empty', () => {
const info = resolveBuildInfo({ env: {}, git: noGit, now: fixedNow, pkg: noPkg })
expect(info).toStrictEqual({
version: '0.0.0-dev',
commit: 'none',
buildDate: '2026-05-09T12:00:00.000Z',
channel: 'dev',
})
})
it('throws on invalid channel', () => {
expect(() =>
resolveBuildInfo({ env: { DIFYCTL_CHANNEL: 'beta' }, git: noGit, now: fixedNow, pkg: noPkg }),
).toThrow(/invalid DIFYCTL_CHANNEL: beta/)
})
it('throws on removed nightly channel', () => {
expect(() =>
resolveBuildInfo({
env: { DIFYCTL_CHANNEL: 'nightly' },
git: noGit,
now: fixedNow,
pkg: noPkg,
}),
).toThrow(/invalid DIFYCTL_CHANNEL: nightly/)
})
it('accepts alpha channel', () => {
const info = resolveBuildInfo({
env: { DIFYCTL_CHANNEL: 'alpha' },
git: noGit,
now: fixedNow,
pkg: noPkg,
})
expect(info.channel).toBe('alpha')
})
it('accepts rc channel', () => {
const info = resolveBuildInfo({
env: {
DIFYCTL_VERSION: '0.1.0-rc.1',
DIFYCTL_CHANNEL: 'rc',
DIFYCTL_COMMIT: 'abc',
DIFYCTL_BUILD_DATE: '2026-01-01T00:00:00.000Z',
},
git: noGit,
now: fixedNow,
pkg: noPkg,
})
expect(info.channel).toBe('rc')
})
it('mixes env and git fallbacks per field', () => {
const git = (cmd: string) => (cmd.startsWith('git describe') ? 'v9.9.9' : null)
const info = resolveBuildInfo({
env: { DIFYCTL_COMMIT: 'pinned-sha' },
git,
now: fixedNow,
pkg: noPkg,
})
expect(info.version).toBe('v9.9.9')
expect(info.commit).toBe('pinned-sha')
expect(info.channel).toBe('dev')
})
it('falls back to package.json#difyctl.channel when env unset', () => {
const pkg = () => ({ difyctl: { channel: 'rc' } })
const info = resolveBuildInfo({ env: {}, git: noGit, now: fixedNow, pkg })
expect(info.channel).toBe('rc')
})
it('env wins over package.json for channel', () => {
const pkg = () => ({ difyctl: { channel: 'rc' } })
const info = resolveBuildInfo({
env: { DIFYCTL_CHANNEL: 'stable' },
git: noGit,
now: fixedNow,
pkg,
})
expect(info.channel).toBe('stable')
})
})
function releaseNamingChannels(): string[] {
return execFileSync('node', [RELEASE_NAMING, 'channels'], { encoding: 'utf8' })
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0)
}
const sorted = (names: readonly string[]) => [...names].sort()
describe('channel list parity', () => {
const LOCAL_ONLY_CHANNEL = 'dev'
it('released channels are the build channels minus the local-only one', () => {
expect(sorted(releaseNamingChannels())).toStrictEqual(
sorted(BUILD_CHANNELS.filter((name) => name !== LOCAL_ONLY_CHANNEL)),
)
})
})
+6
View File
@@ -0,0 +1,6 @@
;(globalThis as unknown as Record<string, string>).__DIFYCTL_VERSION__ = '0.0.0-test'
;(globalThis as unknown as Record<string, string>).__DIFYCTL_COMMIT__ = '0000000'
;(globalThis as unknown as Record<string, string>).__DIFYCTL_BUILD_DATE__ =
'1970-01-01T00:00:00.000Z'
;(globalThis as unknown as Record<string, string>).__DIFYCTL_CHANNEL__ = 'dev'
;(globalThis as unknown as Record<string, boolean>).__DIFYCTL_COMPILED__ = false
+202
View File
@@ -0,0 +1,202 @@
import type { CommandConstructor } from '@/plugins/commands/command'
import type { CommandTree } from '@/plugins/commands/registry'
import { readdir, readFile } from 'node:fs/promises'
import { dirname, join, normalize, relative, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vite-plus/test'
import { commandTree } from '@/commands/tree.generated'
import { parseCatalog } from '@/plugins/catalog'
import { HELP_WORD } from '@/plugins/commands/command'
import { mergeTrees, nodeAt } from '@/plugins/commands/registry'
import { GLOBAL_INPUT } from '@/plugins/global-flags'
import { opsTree } from '@/plugins/ops/tree'
import { propertiesOf } from '@/protocol/shape'
import { propertyFor } from '@/util/flag-name'
const SKILL_DIR = fileURLToPath(new URL('../../../skills/difyctl/', import.meta.url))
const CATALOG = fileURLToPath(new URL('../fixtures/catalog.json', import.meta.url))
const ROOT_DOC = 'SKILL.md'
const MAX_HOPS = 2
const LEAF_DEPTH = MAX_HOPS
const MAP_MAX_LINES = 60
const TOC_AFTER_LINES = 100
const TOC_HEADING = '## Contents'
const H2 = /^## .*$/m
const LINK = /\]\(([^)#\s]+\.md)\)/g
const COMMAND = /`difyctl ([^`]+)`/g
const FENCE = /^(`{3,})/
const CONTINUATION = /\\\s*\n\s*/g
const CODE_COMMAND = /^difyctl (.+)$/
const PIPE = ' | '
const FLAG = /(?:^|\s)--([a-z][a-z0-9-]*)/g
const PLACEHOLDER = /^<[^>]+>$/
const WORD = /^[a-z_]+(?:-[a-z_]+)*$/
const DOTTED_ID = /^[a-z_]+(?:\.[a-z_]+)+$/
const SPAN = /`([^`]+)`/g
const NON_WORD_START = /^[-<]/
const GLOBAL_FLAGS = [...Object.keys(GLOBAL_INPUT.shape), HELP_WORD]
async function docs(): Promise<string[]> {
const out: string[] = []
for (const entry of await readdir(SKILL_DIR, { recursive: true, withFileTypes: true })) {
if (entry.isFile() && entry.name.endsWith('.md'))
out.push(relative(SKILL_DIR, join(entry.parentPath, entry.name)).split(sep).join('/'))
}
return out
}
function links(doc: string, text: string): string[] {
return [...text.matchAll(LINK)].map((m) =>
normalize(join(dirname(doc), m[1] as string))
.split(sep)
.join('/'),
)
}
function depths(text: ReadonlyMap<string, string>): Map<string, number> {
const depth = new Map([[ROOT_DOC, 0]])
const queue = [ROOT_DOC]
while (queue.length > 0) {
const doc = queue.shift() as string
for (const next of links(doc, text.get(doc) ?? '')) {
if (depth.has(next)) continue
depth.set(next, (depth.get(doc) as number) + 1)
queue.push(next)
}
}
return depth
}
/** `difyctl` command lines inside fenced code blocks, with `\` continuations joined. */
function fencedCommands(body: string): string[] {
const code: string[] = []
let fence: string | undefined
for (const line of body.split('\n')) {
const open = FENCE.exec(line.trim())?.[1]
if (fence === undefined) {
if (open !== undefined) fence = open
} else if (open !== undefined && open.length >= fence.length && line.trim() === open) {
fence = undefined
} else {
code.push(line)
}
}
return code
.join('\n')
.replace(CONTINUATION, ' ')
.split('\n')
.map((line) => CODE_COMMAND.exec(line.trim())?.[1])
.filter((span): span is string => span !== undefined)
}
function leadingWords(span: string): string[] {
const words: string[] = []
for (const word of span.split(' ')) {
if (!WORD.test(word)) break
words.push(word)
}
return words
}
/**
* The commands a line names: the exact command, or — when a `<placeholder>` follows a
* group — every command one word below it.
*/
function commandsNamed(tree: CommandTree, span: string, words: readonly string[]) {
const node = nodeAt(tree, words)
if (node === undefined) return []
if (node.command !== undefined) return [node.command]
if (!PLACEHOLDER.test(span.split(' ')[words.length] ?? '')) return []
return Object.values(node.subcommands)
.map((child) => child.command)
.filter((command): command is CommandConstructor => command !== undefined)
}
function flagsOf(command: CommandConstructor): string[] {
return [...Object.keys(propertiesOf(command.flags())), ...GLOBAL_FLAGS]
}
function typedFlags(span: string): string[] {
return [...(span.split(PIPE)[0] as string).matchAll(FLAG)].map((m) => propertyFor(m[1] as string))
}
describe('skills/difyctl tree', async () => {
const all = await docs()
const text = new Map(
await Promise.all(
all.map(async (d) => [d, await readFile(join(SKILL_DIR, d), 'utf8')] as const),
),
)
const catalog = parseCatalog(await readFile(CATALOG)).ops
const ops = Object.keys(catalog)
const { tree } = mergeTrees(commandTree, opsTree(catalog))
const depth = depths(text)
const commands = [...text].flatMap(([doc, body]) => [
...[...body.matchAll(COMMAND)].map((m) => ({ doc, span: m[1] as string })),
...fencedCommands(body).map((span) => ({ doc, span })),
])
it('every relative link resolves', () => {
for (const [doc, body] of text)
for (const target of links(doc, body)) expect(all, `${doc} → ${target}`).toContain(target)
})
it('every doc is reachable within two hops of SKILL.md', () => {
for (const doc of all) {
expect(depth.has(doc), `${doc} unreachable`).toBe(true)
expect(depth.get(doc) as number, doc).toBeLessThanOrEqual(MAX_HOPS)
}
})
it('maps stay short and leaves link only to siblings', () => {
for (const [doc, body] of text) {
if ((depth.get(doc) as number) < LEAF_DEPTH) {
expect(body.split('\n').length, doc).toBeLessThan(MAP_MAX_LINES)
continue
}
for (const target of links(doc, body))
expect(dirname(target), `${doc} → ${target}`).toBe(dirname(doc))
}
})
it('long leaves open with contents', () => {
for (const [doc, body] of text) {
if ((depth.get(doc) as number) < LEAF_DEPTH) continue
if (body.split('\n').length <= TOC_AFTER_LINES) continue
expect(H2.exec(body)?.[0], doc).toBe(TOC_HEADING)
}
})
it('every difyctl command exists locally or in the catalog', () => {
for (const { doc, span } of commands) {
const words = leadingWords(span)
if (words.length === 0) {
expect(span, `${doc}: difyctl ${span} names no command`).toMatch(NON_WORD_START)
continue
}
const found = words[0] === HELP_WORD || nodeAt(tree, words) !== undefined
expect(found, `${doc}: difyctl ${span}`).toBe(true)
}
})
it('every flag on a command is one that command parses', () => {
for (const { doc, span } of commands) {
const named = commandsNamed(tree, span, leadingWords(span))
if (named.length === 0) continue
const allowed = new Set(named.flatMap(flagsOf))
for (const flag of typedFlags(span))
expect(allowed.has(flag), `${doc}: difyctl ${span}: ${flag}`).toBe(true)
}
})
it('every dotted op id exists in the catalog', () => {
const verbs = new Set(ops.map((op) => op.split('.')[0]))
for (const [doc, body] of text) {
for (const m of body.matchAll(SPAN)) {
const span = m[1] as string
if (!DOTTED_ID.test(span) || !verbs.has(span.split('.')[0])) continue
expect(ops, `${doc}: ${span}`).toContain(span)
}
}
})
})