Skip to content

test(web): serve browser spec service calls from a contract-validated fake API - #46695

Merged
hyoban merged 50 commits into
mainfrom
test/fake-console-server
Nov 23, 2026
Merged

hyoban merged 50 commits into
mainfrom
test/fake-console-server

Conversation

@hyoban

@hyoban hyoban commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces vi.mock('@/service/...') in Web browser specs with a contract-validated fake API, so service calls run through the real clients, transports and TanStack Query, and requests and responses are checked against the generated contracts at runtime.

Result: all 162 service-mocking browser specs are migrated, and no browser spec mocks @/service/* anymore. The migration exposed two product bugs, both filed: one is covered by a test that asserts the known bug, and the other was fixed on main (see below).

Problem

The service mocks (withConsoleResponses, whole-module replacements, legacy @/service/base stubs) bypassed request serialization, error handling and the HTTP round trip, and let fixtures drift from the backend contract without any test failing.

The fake API (web/test/fake-api.ts)

const fake = setupFakeApi({
  console: { knowledgeFs: { spaces: { get: () => spaceList } } },
  routes: [route('POST', 'console', '/files/upload', ({ body }) => ({ id: 'file-1' }))],
})

it('…', async () => {
  const save = hold(fake.console.knowledgeFs.spaces.post) // keep the next request pending
  // …
  expect(await save.arrived).toEqual({ body: { name: 'Docs' } }) // exact request parts
  save.reject(apiError({ status: 409, message: 'Name taken' })) // or resolve(value) / release()
})
  • console / marketplace: handlers mirror the generated contract trees and are typed from them. Each is wrapped with oRPC implement() and served by OpenAPIHandler. Console segments load through the app's own loadConsoleContractForSegment, now exported, so the enterprise segment works too.
  • Spies: every handler is a vi.fn reachable at its contract path (fake.console..., fake.marketplace...), typed from the contract signature. Tests can assert on the decoded request input, or return a deferred with mockReturnValueOnce, without hand-made spies.
  • setupFakeApi(api | () => api): installs a fresh fake before each test in the file and tears it down afterwards; the handle always points at the current test's fake. installFakeApi + onTestFinished remains for fakes built from per-test arguments.
  • Exact request inputs: spies record only the parts the client sent ({ body }, { params }, { query }), so assertions don't need expect.objectContaining. Procedures without an input schema drop transport headers and empty parts.
  • pendingResponse(): a response that never arrives, for loading states; teardown treats it as deliberately held.
  • hold(spy): keeps the spy's next request pending and returns { arrived, resolve, reject, release }. release() answers with the handler's regular implementation (tracked by the fake, since Vitest's getMockImplementation() returns the next queued once-implementation), and teardown waits for it. Settling before the request arrives is safe, so a rejected hold never becomes an unhandled rejection.
  • fake.use(...): overrides or adds handlers mid-test and returns typed spies for the ones it adds.
  • routes: route(method, 'console' | 'public' | 'marketplace' | 'origin', '/path/:id', handler) serves endpoints without a contract: legacy @/service/base calls, share and public APIs, and same-origin device-flow URLs. Route handlers and spies receive the request body decoded by Content-Type: JSON (application/json or application/*+json, as Flask reads it), FormData, or text; a JSON or form body that fails to parse fails the test. fake.route(method, base, path) returns a route's spy.
  • Prefixes: absolute and same-origin relative API prefixes (/console/api, /api) are resolved against the page, like the app's clients do.
  • Transports: fetch is stubbed, and so is XMLHttpRequest, which legacy uploads use. Both follow native behavior where clients depend on it: an aborted fetch rejects with the signal's AbortError (before or while the response is pending) and errors a body still being read, an aborted XHR cancels its tracked request, and an XHR with responseType = 'json' and a non-JSON body completes with response = null. sseResponse([...]) streams SSE. data: and blob: URLs pass through natively.
  • Errors: apiError({ status, message, code?, details? }) answers in the Python API's { code, message, status, ...details } shape. networkError() fails a request like an offline fetch. Any other exception from a handler is reported as a broken fixture.
  • Teardown: async; it keeps the fake transports in place while it first waits for requests still being answered or whose body the client is reading (except ones held with hold() or pendingResponse(), or aborted by the client), then fails the test on input or output contract violations, request bodies that cannot be decoded (a handler's own apiError({ status: 400 }) is still allowed), form bodies sent to JSON endpoints (only bodies with a file field accept forms; answered with 415), bodies Flask would not read as JSON (no Content-Type, or a type other than application/json or application/*+json; also answered with 415), paths with a trailing slash the Flask routes do not declare, requests still pending 2 s after the test, requests within an API prefix that no handler answers, and any other network request. Each problem is also logged when it happens.
  • Python API differences the helper bridges: schema-based coercion of query, path and header values (SmartCoercionPlugin; JSON bodies keep the types the client sent, since the Python API validates them strictly), repeated-key arrays (using the client's own rules, now exported from openapi-url.ts), and header-name casing such as Idempotency-Key. Custom-method paths that put a parameter and a literal in one segment (/workflows/{workflow_id}:precheck), which oRPC's router cannot match, are split into separate segments on both sides; a request that arrives in that internal ~method form is reported, so the client must still send the contract's :method path.

Asserting through these spies replaced about 250 delegating spies ((input) => api.x(input)) across the migrated specs. The snippet fixtures are now typed as the contract response types.

Across the specs: 70 files moved to setupFakeApi, 26 hand-made deferreds became hold(), the 8 getMockImplementation() workarounds became hold(...).release(), and 33 objectContaining wrappers on spy assertions were removed where the input is exact. Shared fixtures now use UUIDs for IDs that appear in request paths: workspace, IP policy, app, agent, dataset, snippet, access policy and roles (web/test/console/ids.ts). Specs no longer copy their own UUIDs to get past the old defaults; for example, the same dataset UUID had been pasted into 6 specs.

Guardrails

  • check-browser-spec-policy.ts now rejects vi.mock('@/service/...') in browser specs (even with a boundary comment, and in the vi.mock(import('…')) form, and when the path is relative, such as ../../service/console) and direct fetch/XMLHttpRequest stubs (vi.stubGlobal, vi.spyOn(globalThis, …), assignment). Before this, service mocks were outside the policy's owned-path rule, which is how new ones kept arriving from main.
  • That surfaced 3 more service mocks and 13 raw fetch stubs (MCP server and update dialogs, tag editor, app deploy, audio player, image preview actions, members invite flows, workflow node specs, create-app emoji data); all now use the fake API, or guardUnexpectedFetch where no request is expected. The voice-input spec's mock of the feature-owned transcription wrapper (which calls consoleClient) was moved to the fake API too.
  • It also rejects it.fails (including chained and tagged-template forms such as it.fails.each, and the { fails: true } option) in specs that use the fake API, whichever path imports it: Vitest inverts the fake's teardown failures too, so a contract violation would be recorded as the expected failure. Known product bugs are covered instead by a normal test that inverts only the assertion showing the bug, with a TODO linking the issue (Agent credential selection drops keyboard focus while credential info refetches #46384, AudioPlayer hidden unavailable overlay blocks pointer input #45655). The New RAG overview keeps polling metrics after indexing tasks finish #46699 journey is skipped instead, because inverting it would make continued polling a passing condition.
  • The fake reports indexed query keys (tag_ids[0]=…) for the repeated-key arrays the Python API reads with getlist(), since the backend would ignore them.
  • web/docs/test.md has a new "API Data in Browser Specs" section on how to use the fake.

What the migration found

  • Fixture drift. Many fixtures returned data the contracts reject: non-UUID path ids, missing required fields, wrong response shapes such as {} for void responses, and invalid enum values. Spec-local data was fixed in place; the shared fixtures' ID defaults are now fixed at the source (see above).
  • Unguarded real requests. At least one spec was sending a real network request (a stale profile refetch) that no mock caught.
  • Assertions changed:
    • Assertions on client call options such as { context: { silent: true } } are dropped, because they aren't observable over HTTP.
    • Rejections with plain Errors became apiError(...), or networkError() where the scenario is offline.
    • Some synchronous assertions now poll, because the response makes a real round trip.
    • Two "empty error message" cases were dropped: over HTTP the client always derives a message from the status, so the generic fallback can't be reached.

Product bugs found

Other CI fixes

Dependencies

Adds test-only devDependencies pinned to the existing oRPC version (1.16.2): @orpc/server, @orpc/openapi, @orpc/json-schema, @orpc/zod.

Prior art

Supabase Studio requires network-level mocks typed from its OpenAPI paths and forbids mocking the data layer. Grafana and Backstage mock at the network level with MSW. oRPC's official @orpc/msw follows the same idea but is only published for oRPC 2.0 beta; the handler shape here would carry over.

Verification

  • All 164 specs using the fake API: vp test run --project browser --maxWorkers=2 <files>, giving 806 tests passed, 3 expected fails and 1 skipped. Specs touched by the main merge were rerun afterwards, and timing-sensitive specs were also run individually two to five times.
  • Helper unit tests: vp test run --project unit test/__tests__/fake-api.spec.ts, 23 tests; policy script tests, 27 tests.
  • After the ergonomics and fixture changes: the full unit project (1,899 files, 15,563 tests) and the full browser project (424 files, 1,704 passed, 8 expected fails, 2 skipped). The one failure in that browser run was a pre-existing race in crawl-selection-form (navigation asserted before the request), now fixed and passing 3 of 3 runs.
  • vp check on every changed file, check-browser-spec-policy.ts, and pnpm knip.

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
  • I've updated the documentation accordingly.
  • I ran make lint && make type-check (backend) and vp staged (frontend) to appease the lint gods

Serve console API requests in tests from oRPC handlers built on the generated
contract, so the real client, transport and TanStack Query run while requests
and responses are validated against the contract. Pilot it on three specs that
previously mocked the service module or transport.
@github-actions github-actions Bot added size:L This PR changes 100-499 lines, ignoring generated files. web This relates to changes on the web. labels Nov 18, 2026
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.29%. Comparing base (7ae3af4) to head (2dc08ce).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #46695      +/-   ##
==========================================
- Coverage   90.34%   90.29%   -0.05%     
==========================================
  Files        6515     6460      -55     
  Lines      408603   406636    -1967     
  Branches    81980    81385     -595     
==========================================
- Hits       369147   367174    -1973     
- Misses      33051    33060       +9     
+ Partials     6405     6402       -3     
Flag Coverage Δ
cli 94.56% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

# Conflicts:
#	web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx
…HR uploads

Rename the helper to installFakeApi and serve every transport the Web client uses:
console and marketplace contracts, legacy REST endpoints, server-sent events,
and XMLHttpRequest uploads. Migrate the upload pilot.
Replace vi.mock('@/service/...') in 159 browser specs with installFakeApi, so
requests run through the real clients and transports and are validated against
the generated contracts. Extend the helper for enterprise contract segments,
same-origin endpoints, backend-shaped error details, offline network failures,
and local data:/blob: URLs.

Fix fixtures the contracts reject (UUID ids, missing required fields, wrong
response shapes), and drop assertions that are not observable over HTTP, such as
client call options. Two specs keep their service mock because migrating them
exposed product behavior that needs a decision: page-indexing (stale polling
intervals) and authorize-account (focus lost while Approve is disabled).
@github-actions github-actions Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Nov 18, 2026
@hyoban hyoban changed the title test(web): pilot a contract-validated fake console for browser specs test(web): serve browser spec service calls from a contract-validated fake API Nov 18, 2026
- Migrate page-indexing and authorize-account to the fake API and mark the
  failures they expose as known product bugs (#46699, #46700).
- Wait for the document title in the device page spec instead of reading it
  once after the heading renders.
- Skip the pricing infotip hover test, which flakes with fake timers, with the
  observed failure and re-enable condition.
- Stop exporting fake API types nothing imports (knip).
…Error options

installFakeApi now wraps every handler in a vi.fn spy reachable at its contract
path (fake.console..., fake.marketplace..., fake.route(...)), adds fake.use() to
override or add handlers mid-test, logs problems as they happen, and apiError
takes an options object. Convert existing apiError calls.
Type handler spies from the contract signature, give route handlers a pre-read
request body, and return typed spies from fake.use(). Convert browser specs to
inline handlers asserted through fake.console/fake.marketplace/fake.route,
replacing about 250 delegating spies, and align the snippet fixtures with the
contract response types.
# Conflicts:
#	web/app/(auth)/device/components/__tests__/authorize-sso.browser.spec.tsx
…rives

The ported focus-retry tests rejected the pending approval before the fake API
route had picked it up under CI load, which surfaced as an unhandled rejection.
…nggenius/dify into test/fake-console-server

# Conflicts:
#	web/app/components/billing/pricing/__tests__/feature-infotip.browser.spec.tsx
…ole-server

# Conflicts:
#	web/app/components/header/account-setting/__tests__/settings-loading.browser.spec.tsx
#	web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
…ole-server

# Conflicts:
#	web/app/components/header/account-setting/__tests__/settings-loading.browser.spec.tsx
#	web/app/components/header/account-setting/ip-policies-page/__tests__/index.browser.spec.tsx
…ole-server

# Conflicts:
#	web/app/components/header/account-setting/__tests__/settings-loading.browser.spec.tsx
#	web/app/components/header/account-setting/permissions-page/__tests__/role-editing.browser.spec.tsx
- Coerce only URL and header values; validate JSON bodies with the types the client sent.
- Report request bodies oRPC cannot decode, while keeping handler-thrown 400s.
- Report custom-method paths sent in the internal ~method form.
- Catch chained it.fails forms such as it.fails.each in the browser spec policy.
…es by type

- Make teardown async and wait for requests still being answered, so a response that breaks
  the contract after the last assertion fails the test. Requests held with hold() or
  pendingResponse(), and requests the client aborted, are exempt; any other request still
  pending after 2s is reported.
- Add pendingResponse() for loading states and use it for never-settling handlers.
- Decode REST route bodies by Content-Type: report JSON or form bodies that fail to parse,
  and pass other bodies through as text.
…rough teardown

- Track each fake spy's regular implementation, since getMockImplementation() returns the next
  queued once-implementation; release() now calls it directly and marks the request settled at
  once, so teardown waits for it.
- Re-stub fetch and XMLHttpRequest at the start of teardown and restore them only after the
  in-flight wait and checks, so requests made meanwhile are still served and checked.
- Report handler exceptions other than apiError() and networkError() as broken fixtures.
…R aborts

- Re-stream response bodies so a request stays tracked until its body ends or is cancelled,
  aborting after the headers errors a body being read, and teardown waits for bodies the client
  is reading before restoring the real transports.
- Pass the XHR abort signal to the tracked request, so teardown treats it as cancelled.
- Resolve same-origin relative API prefixes against the page origin.
- Catch tagged-template it.fails.each in the browser spec policy.
- Serve the emoji catalog that the icon picker refetches after the test body.
…ake-timer boundary

Vitest Browser locator retries advance fake timers, so a check at exactly 2499 ms depended on
how many retries the preceding assertions needed.
…in the fake API

- Report form or multipart bodies sent to endpoints whose contract body has no file field,
  before schema validation, and answer them with 415.
- Report API paths with a trailing slash, which the Flask routes do not declare.
- Hold the stale preview job and wait for it to arrive before closing the edit dialog.
- Resolve relative vi.mock paths before checking for service mocks in the browser spec policy.
@hyoban
hyoban marked this pull request as ready for review November 23, 2026 07:02
@hyoban
hyoban added this pull request to the merge queue Nov 23, 2026
Merged via the queue into main with commit 8549310 Nov 23, 2026
63 checks passed
@hyoban
hyoban deleted the test/fake-console-server branch November 23, 2026 07:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files. web This relates to changes on the web.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants