Compare commits

...
Author SHA1 Message Date
james.maes d81b7ed5ae chore(#1002): integrate current main for date-default verification 2026-10-06 07:25:30 -05:00
james.maes 22c9e02f20 test: consolidate browser capture and security review follow-ups (#42)
* test(#1003): await complete chart label geometry

Keep the original strict overlap check on the same completed measurement sample. Refs QRun-IO/qqq#1003; historical rendering cause remains unproved.

(cherry picked from commit 4aa95cc363)

* test(acceptance): capture selected navigation request ownership

(cherry picked from commit bd7716fe8d)

* test(acceptance): integrate session capture with selective navigation

(cherry picked from commit 6c5d6d92e14536ed472b2c8357a00c652718198b)

* docs(#696): reconcile merged security qualifications

(cherry picked from commit b6106062bb09381407e92bdb55352175062941d2)
2026-10-04 18:48:11 -05:00
james.maes 138c3c6db5 fix: derive standalone CSP from application metadata (QRun-IO/qqq#1017) (#40)
* fix: derive standalone CSP from application metadata (#1017)

Consume optional bounded CSP source metadata through the existing auth cache. Remove fixture-derived policy masking and qualify the actual analytics hook.

* docs(qqq#696): reconcile current security integration evidence

* test(qqq#1022): close owned analytics fixture connections
2026-10-04 17:07:09 -05:00
james.maes 70f26e9c9a Merge pull request #38 from QRun-IO/feature/GH-1009-standalone-branding
fix: complete standalone security and branding acceptance
2026-10-04 14:19:35 -05:00
james.maes 2bc75d779e Merge qualified Auth0 fixture correction into branding acceptance 2026-10-04 12:55:09 -05:00
james.maes 17e22edaee Merge reviewed NAV-018 readiness correction into branding acceptance 2026-10-04 12:54:47 -05:00
james.maes 66d02c7b6a test: align owned Auth0 issuer with trusted provider contract (#1016) 2026-10-04 12:53:20 -05:00
james.maes 20fe7b7b9b test(GH-1014): await process response completion before navigation 2026-10-04 11:55:45 -05:00
james.maes 4190ee01ba test: restrict acceptance javac to owned fixture sources (QQQ #1013) 2026-10-04 10:35:06 -05:00
james.maes 62d1e77847 fix: route declared standalone branding images through fixed backend roles 2026-10-04 10:21:43 -05:00
james.maes a23fd997db test: qualify standalone security variants against real Node origins 2026-10-04 10:06:27 -05:00
james.maes f367756b8c Merge pull request #36 from QRun-IO/feature/GH-1006-next-query-cleanup
fix(qqq#1006): clear private query state between users
2026-10-04 09:06:18 -05:00
james.maes 4a055463bd fix(GH-1006): clear private query state between users
Refs QRun-IO/qqq#1006 and QRun-IO/qqq#696.
2026-10-02 09:41:42 -05:00
james.maes 0222f0dcad test(widgets): await resized chart label geometry (#31) 2026-10-02 06:58:12 -05:00
james.maes 4fea636f24 Merge reviewed main before widget acceptance qualification (#31) 2026-10-02 06:56:43 -05:00
james.maes 5ca3e0b17a Merge pull request #30 from QRun-IO/feature/GH-995-cell-focus-investigation
fix(qqq#995): preserve grid body-cell focus and state
2026-10-02 05:40:58 -05:00
james.maes a32ef74a9d chore(GH-995): integrate reviewed main for cell focus 2026-10-02 04:21:31 -05:00
james.maes d292c76530 Merge pull request #28: preserve report-copy keyboard focus
Fixes QRun-IO/qqq#994. Source-specific required checks verified.
2026-10-02 04:18:17 -05:00
james.maes e3fc4b2f52 chore(qqq#994): integrate current main for verification 2026-10-02 03:00:53 -05:00
james.maes b5f8be7645 Merge pull request #27 from QRun-IO/feature/GH-716-menu-viewport
fix(query): keep column menus reachable after scrolling
2026-10-02 02:57:12 -05:00
james.maes 8f552e2e29 Merge current acceptance evidence baseline for date fix (#31) 2026-10-02 02:21:54 -05:00
james.maes 1f18575abe test(widgets): await default selection request (#31) 2026-10-02 02:15:08 -05:00
james.maes 6a5c1bb237 fix(widgets): preserve date request normalization (#31) 2026-10-02 02:09:21 -05:00
james.maes 58a896345f Merge pull request #29 from QRun-IO/feature/GH-904-document-capture
test(qqq#904): capture document and XHR boundaries
2026-10-02 02:00:41 -05:00
james.maes bd904fe4ac fix(widgets): apply untouched date defaults (#31) 2026-10-02 01:41:59 -05:00
james.maes 09c271384c test(qqq#996): wait for report setup before pivot input 2026-10-02 01:39:17 -05:00
james.maes 05763450ff fix(qqq#995): preserve grid body-cell focus and state
Invoke locally owned pure cell renderers as content so selection and refresh retain focused children and current callbacks.
2026-10-02 00:32:46 -05:00
james.maes aa0129f024 test(qqq#904): capture document and XHR boundaries
Add opt-in bounded evidence for QRun-IO/qqq#904 and #960. Preserve native outcomes and mark ambiguous request reuse incomplete.
2026-10-02 00:31:09 -05:00
james.maes 2bdc048440 fix(query): preserve report column copy focus (#994)
Keep current header callbacks and child identity across preview updates.
2026-10-02 00:02:07 -05:00
james.maes 7bd157dd81 fix(query): reveal column anchor before opening menu (#716)
Restore keyboard menu reachability after scrolling a focused header away.
2026-10-01 23:24:21 -05:00
james.maes 2535e98c7e Merge pull request #25 from QRun-IO/feature/GH-904-transport-capture
test(browser): retain transport and query retry evidence
2026-10-01 22:44:07 -05:00
james.maes 2853b9b148 Merge pull request #26 from QRun-IO/feature/GH-712-next-rc11
chore(#712): prepare Next UI 1.0.0-RC.11
2026-10-01 22:19:50 -05:00
james.maes 29cb5584fc chore(#712): prepare Next UI 1.0.0-RC.11 2026-10-01 22:14:30 -05:00
james.maes f36d8709c9 test(GH-900): cover production query retry lifecycle 2026-10-01 22:05:22 -05:00
james.maes f7b2aa52a8 test(GH-904): capture acceptance response write boundaries 2026-10-01 22:05:08 -05:00
james.maes a1d3e48419 Merge pull request #24 from QRun-IO/feature/GH-970-browser-input-races
fix(browser): stabilize selector and script completion input races
2026-10-01 21:56:06 -05:00
james.maes ea73118fca docs(GH-985): record browser input race corrections
Refs QRun-IO/qqq#970 and QRun-IO/qqq#954.
2026-10-01 21:09:34 -05:00
james.maes c629eb0b6c fix(GH-954): preserve suggestions after deferred scroll events
Dismiss completions only when the textarea moves from the position used to place them. Cover deferred reset and both real scroll axes.

Refs QRun-IO/qqq#954
2026-10-01 21:09:31 -05:00
james.maes 571ee7bc88 fix(GH-970): invalidate stale possible values when search changes
Close the debounce interval in which an old option can disappear during a pointer selection. Cover loaded and in-flight prior searches with deterministic regressions.

Refs QRun-IO/qqq#970
2026-10-01 20:59:51 -05:00
james.maes 12cf7745f6 Merge pull request #23 from QRun-IO/feature/GH-990-esb-touch-coverage
test(GH-990): include all ESB touch acceptance scenarios
2026-10-01 20:52:56 -05:00
james.maes 0f6581b6d7 chore(GH-990): reconcile touch coverage with RC10 preparation 2026-10-01 20:43:46 -05:00
james.maes 46a1d5d7ec Merge pull request #22 from QRun-IO/feature/GH-712-next-rc10
chore(release): prepare Next UI 1.0.0-RC.10
2026-10-01 20:36:14 -05:00
james.maes 226efa841f Merge pull request #21 from QRun-IO/feature/QQQ-989-pr15-reconciliation
fix(records): preserve immediate URL state (QQQ#989)
2026-10-01 20:35:01 -05:00
james.maes dd130238be test(GH-990): include ESB in touch acceptance
Closes QRun-IO/qqq#990. Preserve real-backend assertions and record the original coverage failure.
2026-10-01 20:18:27 -05:00
james.maes d8c803ef5f chore(release): prepare Next UI 1.0.0-RC.10
Record verified candidate scope and disclosed coverage limits. Refs QRun-IO/qqq#712.
2026-10-01 20:15:37 -05:00
james.maes 5e3738b73f fix(records): preserve immediate record view URL state
Closes QRun-IO/qqq#989
2026-10-01 20:00:16 -05:00
james.maes 289eca19d4 Merge pull request #18 from QRun-IO/feature/browser-stability
fix(browser): stabilize Firefox and WebKit interactions and acceptance
2026-10-01 19:44:38 -05:00
james.maes 7ff90f1a63 chore(GH-985): integrate ESB acceptance with browser fixes 2026-10-01 18:46:40 -05:00
james.maes 50a935a4a5 Merge pull request #19 from QRun-IO/feature/GH-10-esb-acceptance
fix(esb): finish management and real-broker acceptance (#10)
2026-10-01 18:30:11 -05:00
james.maes 40e987d4d0 Merge pull request #20 from QRun-IO/feature/GH-985-next-tracking
docs(tracking): manage Next UI through the QQQ project
2026-10-01 18:09:28 -05:00
james.maes 71f5a39b09 docs(tracking): centralize Next UI delivery and unreleased fixes 2026-10-01 18:04:34 -05:00
james.maes 45f99f27ce fix(auth): finish logout before allowing another sign-in
Keep authentication loading through cookie expiry and provider departure (QRun-IO/qqq#984).
2026-10-01 17:40:38 -05:00
james.maes d17e880e79 test(widgets): recognize proven missing script responses 2026-10-01 17:25:44 -05:00
james.maes f8fdb8e997 fix(esb): finish management and real-broker acceptance (#10) 2026-10-01 17:23:24 -05:00
james.maes ad154b5b56 test(acceptance): observe browser framing refusal (#981) 2026-10-01 17:22:43 -05:00
james.maes c6a58933a6 test(#979): account for Linux WebKit download filenames
Verify original application filenames and preserve downloaded data checks while matching the pinned libsoup space sanitization.
2026-10-01 17:16:51 -05:00
james.maes 26e3a0d004 test(acceptance): await initial document fonts before redirect
Complete the rendered initial document before NAV016 tears it down (QRun-IO/qqq#951).
2026-10-01 17:08:48 -05:00
james.maes c9d7fcd393 fix(forms): preserve option pointer targets in WebKit 2026-10-01 17:06:35 -05:00
james.maes b3e1ddda8b test(browser): adopt fixed WebKit network library and retain crash diagnostics
Refs QRun-IO/qqq#904, QRun-IO/qqq#960, QRun-IO/qqq#973. Preserve final RC9 tag outcomes separately from current verification.
2026-10-01 17:06:23 -05:00
james.maes 8d4668cdab test(acceptance): await breadcrumb destination iframe
Require the owned chart heading before leaving Greetings App so navigation does not cancel its pending document. Refs QRun-IO/qqq#972.
2026-10-01 16:53:35 -05:00
james.maes 254a0a2050 test(reports): await summary metadata before navigation
Refs QRun-IO/qqq#961.
2026-10-01 16:39:39 -05:00
james.maes 52cc038fa6 test(acceptance): observe transient Firefox feedback reliably
Capture toast visibility before actions and verify navigation-cancelled legacy fonts in the final document. Refs QRun-IO/qqq#951, QRun-IO/qqq#953, QRun-IO/qqq#967.
2026-10-01 16:39:23 -05:00
james.maes 6090f2f9b4 fix(search): preserve focus after early keyboard interaction
Refs QRun-IO/qqq#950.
2026-10-01 16:32:48 -05:00
james.maes 32a9560970 Merge pull request #17 from QRun-IO/feature/rc9-publication-notes
docs: record verified RC9 public delivery
2026-10-01 14:29:27 -05:00
james.maes 96085c72e2 docs(release): record verified RC9 public delivery
Refs QRun-IO/qqq#712. Preserve immutable source and distinguish active tag acceptance from completed checks.
2026-10-01 14:28:27 -05:00
james.maes c029ad2a70 Merge pull request #14 from QRun-IO/feature/next-1.0
Next UI 1.0 RC9 integration: compatibility, verification and issue tracking
2026-10-01 14:12:28 -05:00
james.maes 32a3b281ff chore(release): prepare Next UI 1.0.0-RC.9
Refs QRun-IO/qqq#712 and QRun-IO/qqq#713. Preserve known issue disclosures and the final release hold.
2026-10-01 14:11:48 -05:00
james.maes a0a18cfa76 Merge pull request #16 from QRun-IO/feature/next-issue-tracking
docs: make GitHub the Next UI source of truth
2026-10-01 14:06:09 -05:00
122 changed files with 6011 additions and 460 deletions

No files matched your search

+5
View File
@@ -72,6 +72,11 @@ jobs:
- name: Acceptance (${{ matrix.browser }})
env:
QQQ_ACCEPTANCE_BROWSERS: ${{ matrix.browser }}
QQQ_ACCEPTANCE_TRANSPORT_TRACE: '1'
# Fixed NAV023/NAV056 ownership capture only; original assertions and diagnostics remain strict.
QQQ_ACCEPTANCE_BROWSER_TRACE: ${{ (matrix.browser == 'webkit' || matrix.browser == 'mobile,tablet') && 'navigation' || '0' }}
# Retain native browser crashes alongside traces (QQQ#904, QQQ#960).
DEBUG: pw:browser
run: node scripts/acceptance.mjs --skip-build
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
+3 -3
View File
@@ -2,7 +2,7 @@
A metadata-driven admin UI for the QQQ low-code application framework, rewritten from React + Material UI to Next.js 16 + Tailwind CSS + shadcn/ui. The UI renders entirely from backend metadata — no table names, field lists, or navigation items are hardcoded in the frontend.
[Next UI 1.0.0-RC.8 is published](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.8) for application testing. Installation requirements, verified artifacts and known gaps are in the [RC8 notes](docs/releases/1.0.0-RC.8.md). Final 1.0 remains held for owner application testing and explicit approval.
**This checkout targets Next UI 1.0.0-RC.11**, with searchable-selector and script-completion input-race corrections. Confirm availability in the [RC11 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.11) before installing; see the [RC11 notes](docs/releases/1.0.0-RC.11.md) for the preparation checkpoint and verification scope. [RC10](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10) was the previously verified public candidate at that checkpoint and remains immutable. Final 1.0 remains held for application soak and explicit owner approval.
**Current roadmap and known issues:** [Next UI 1.0 tracker](https://github.com/QRun-IO/qqq/issues/713). GitHub issues are the source of truth for status and remaining work; see [issue tracking](docs/ISSUE-TRACKING.md).
@@ -14,11 +14,11 @@ The dashboard is the default admin UI for QQQ 4.1+. Add the jar (managed by `qqq
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-frontend-next</artifactId>
<version>1.0.0-RC.8</version>
<version>1.0.0-RC.11</version>
</dependency>
```
The explicit version overrides an older BOM-managed frontend. RC8 requires the QQQ 4.1.0-SNAPSHOT development backend including PRs #913 and #908; see the release notes for the verified backend commit. Select Next explicitly with `-Dqqq.javalin.frontend=next`. This does not release QQQ 4.1.
The explicit version overrides an older BOM-managed frontend. RC11 requires the QQQ 4.1.0-SNAPSHOT development backend including PRs #913 and #908; see the release notes for the verified backend commit. Select Next explicitly with `-Dqqq.javalin.frontend=next`. This does not release QQQ 4.1.
The jar holds the static export (`pnpm build:export`) under `next-dashboard/`. Deep links such as `/app/person/1` are served from placeholder pages and read their route from the browser path, so no Node.js server is involved. The Material Dashboard remains available: select it with `withServeFrontendMaterialDashboard(true)` or `-Dqqq.javalin.frontend=material`. Material routes are `/<app>/<table>/<id>`; Next routes are `/app/<table>/<id>`.
+1 -1
View File
@@ -18,7 +18,7 @@ COPY --from=frontend --chown=node:node /app/.next/static ./.next/static
COPY --from=frontend --chown=node:node /app/public ./public
# server.js wrapped with the dashboard security headers (QRun-IO/qqq#734); add origins the
# dashboard must reach (QuickSight, custom component bundles) with QQQ_DASHBOARD_CSP_SOURCES
COPY --from=frontend --chown=node:node /app/standalone/qqq-server.mjs /app/standalone/security-headers.mjs /app/standalone/backend-prefixes.json ./
COPY --from=frontend --chown=node:node /app/standalone/qqq-server.mjs /app/standalone/security-headers.mjs /app/standalone/branding-assets.mjs /app/standalone/backend-prefixes.json ./
COPY LICENSE ./LICENSE
USER node
EXPOSE 3000
+31 -3
View File
@@ -10,12 +10,36 @@ GitHub issues are the source of truth for scope, current status, remaining work
| Feature acceptance and default adoption | [qqq#649](https://github.com/QRun-IO/qqq/issues/649) |
| Behavior and metadata compatibility | [qqq#714](https://github.com/QRun-IO/qqq/issues/714) |
| Original Next visual review and owner approval | [qqq#711](https://github.com/QRun-IO/qqq/issues/711) |
| Browser failures and incomplete run evidence | [frontend#12](https://github.com/QRun-IO/qqq-frontend-next/issues/12) |
| Browser failures and incomplete run evidence | [qqq#985](https://github.com/QRun-IO/qqq/issues/985) |
| Real application soak and final release hold | [qqq#712](https://github.com/QRun-IO/qqq/issues/712) |
| Cross-application launch/restart acceptance | [qqq#650](https://github.com/QRun-IO/qqq/issues/650) |
| ESB integration and acceptance | [qqq#986](https://github.com/QRun-IO/qqq/issues/986) |
| Paired runtime provenance and CI handoff | [qqq#905](https://github.com/QRun-IO/qqq/issues/905) |
Use existing issues for the same requirement or failure. Create focused Next release issues in QRun-IO/qqq and link them to #713 and their feature parent. Keep existing frontend-repository issues linked; do not duplicate their scope.
Create **all Next UI tickets in [QRun-IO/qqq](https://github.com/QRun-IO/qqq/issues)** and add them to the [QQQ Roadmap, Project 12](https://github.com/orgs/QRun-IO/projects/12). Use existing issues for the same requirement or failure, and link each focused ticket to #713 and its feature or investigation parent. Frontend issues #12 and #10 were transferred to central issues #985 and #986; use the central identifiers and preserve their report history.
## Required ticket fields
Every new ticket needs these fields on the issue and its Project 12 item; complete them before work advances to **Ready**:
| Field | Required value |
|---|---|
| Issue Type | Native issue: Bug, Feature, Task or Epic. Mirror it in the Project field, using Planning Epic for Epic; Improvement is a Project-only category. |
| Assignees | The person accountable for completing or coordinating the ticket |
| Milestone | The agreed delivery milestone; keep it consistent with the target version |
| Priority | Critical, High, Medium or Low, with an impact-based rationale in the issue |
| Component | The owning implementation component: `qqq-frontend-next` for Next source, or the actual backend/sample component for a dependency. |
| Target Version | The agreed version of the owning component or an explicit pending release decision. A backend dependency in the Next UI 1.0 milestone does not imply a backend 1.0 release. Never imply delivery in an already published RC. |
| Status | The current workflow state below |
Record unresolved ownership or release decisions explicitly while a ticket remains in **Backlog**. Do not invent dates, estimates or a new release version to fill a field. A browser assertion failure alone does not establish high product severity.
## Workflow and evidence
- **Backlog / Ready:** capture the expected behavior, scope, acceptance criteria, required fields and dependencies; Ready means actionable work with an owner.
- **In progress:** link the active branch or work and record reproduction, confirmed cause, implementation progress and remaining blockers.
- **In review:** link the reviewable PR, source commit and verification evidence; keep unmet acceptance criteria visible. A local fix or passing subset does not imply merge or release.
- **Done:** close only after the accepted fix is integrated and every acceptance criterion is verified, or an explicit approved disposition is recorded. Link the merged PR/commit and evidence. Identify whether the change is unreleased or delivered, with the version and release link when published.
## Updating an issue
@@ -30,4 +54,8 @@ Use existing issues for the same requirement or failure. Create focused Next rel
Preserve the original Next design at `e42ad2b2bcdc76311e13002a22dd70e3ec437192`. Material Dashboard is the behavior and metadata compatibility reference. Prioritize primary-browser functional depth and disclose secondary-browser failures.
RC8 is a prerelease for application testing. Final 1.0 remains held for the owner's requested soak and explicit final approval. This project does not authorize releasing QQQ 4.1.
[RC9](releases/1.0.0-RC.9.md) is the published prerelease for application testing. Its immutable-tag acceptance run has known Firefox/tablet failures; consult the release notes and #985 for the exact evidence. The browser fixes in [PR #18](https://github.com/QRun-IO/qqq-frontend-next/pull/18) are [unreleased](releases/unreleased.md).
Every release and changelog entry must link its central QQQ issues and distinguish product changes, test/infrastructure corrections, verification and unresolved work. A published RC's tag and artifacts remain immutable; subsequent fixes require a separately authorized version and release. Update tickets and Project 12 with the actual delivery version and release link after publication.
Final 1.0 remains held for the owner's requested application soak and renewed, explicit final approval ([#712](https://github.com/QRun-IO/qqq/issues/712)). Passing CI, an issue marked Done or elapsed time does not release that hold. This project does not authorize releasing QQQ 4.1.
+4 -4
View File
@@ -71,11 +71,11 @@ QQQ_ACCEPTANCE_BROWSERS=chromium,firefox,webkit,mobile,tablet \
QQQ_ACCEPTANCE_BROWSERS=mobile,tablet node scripts/acceptance.mjs --skip-build
```
| Project | Playwright device | Engine (Playwright 1.58.2) | Runs |
| Project | Playwright device | Engine (Playwright 1.64.0-alpha-2026-10-01) | Runs |
|----------|-------------------|----------------------------|------|
| chromium | Desktop Chrome | Chrome for Testing 145 | every spec |
| firefox | Desktop Firefox | Firefox 146 | every spec |
| webkit | Desktop Safari | WebKit 26.0 | every spec |
| chromium | Desktop Chrome | Chrome for Testing 155 | every spec |
| firefox | Desktop Firefox | Firefox 156 | every spec |
| webkit | Desktop Safari | WebKit 26.6 | every spec |
| mobile | Pixel 7 (412 × 839, touch) | Chromium | tests tagged `@mobile` |
| tablet | iPad (gen 7) (810 × 1080, touch) | WebKit | tests tagged `@mobile` or `@tablet` |
+5
View File
@@ -0,0 +1,5 @@
# ESB integration acceptance
The ten required [ESB matrix scenarios](../../tests/acceptance/matrix/esb.json) pass in Chromium, Firefox and WebKit: 30 cases with no failures, skips or retries. They exercise the stock sample’s embedded Artemis broker, table-event delivery into `syncPerson`, service/table/process views, permission denial, subscription browsing, trigger pause/resume/restart and confirmed dead-letter replay. A further 38 Chromium navigation, permission and table Developer-view cases, plus 12 security-variant and search cases, pass without skips or retries. The main and security fixtures use separate broker ports. These are focused ESB results; general Next browser/parity and final release acceptance remain tracked separately.
The backend integration fixes are [QQQ PR #980](https://github.com/QRun-IO/qqq/pull/980), based on `5bf02d54`: normal sample ESB registration, API documentation route isolation and nullable subscription/dead-letter pause state. Frontend verification passes 105 focused ESB tests, all 1,951 unit tests with coverage thresholds, type checking, the production static export and bundle budgets. The [acceptance README](../../tests/acceptance/README.md) gives the commands and fixture boundaries; [Next #10](https://github.com/QRun-IO/qqq-frontend-next/issues/10) and [QQQ #739](https://github.com/QRun-IO/qqq/issues/739) track delivery. RabbitMQ and broker management behavior are covered by the backend conformance suite; these browser tests use Artemis without an HTTP management endpoint, so unavailable broker actions remain hidden.
+2
View File
@@ -12,6 +12,8 @@ Recorded runs: `/Users/james.maes/Git.Local/QRunIO/qqq-frontend-next/test-result
Corrected RC8 source cd3d473: 602 local and 602 hosted Chromium cases passed, with zero failed/skipped/flaky cases or report errors. Hosted run 36798799502. Three approved external-service exclusions remain. Earlier failed runs are retained and described in docs/releases/1.0.0-RC.8.md; this matrix records the corrected primary runs only. Other browser profiles and whole-product compatibility/visual approval remain separate.
The additional ESB integration scenarios and their focused three-browser results are recorded in [ESB acceptance](esb.md). The historical full-suite counts above predate those ten new matrix rows.
## Navigation, application structure, branding and icons
| ID | Feature | Scenarios | Negative | Fixture | Result | Issues |
+4 -2
View File
@@ -1,8 +1,10 @@
# Next UI agent guide
> **This checkout targets RC11.** Confirm availability in the [RC11 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.11) before installing. [RC11 notes](../releases/1.0.0-RC.11.md) record the preparation checkpoint and verification scope; RC10 was the previously verified public candidate at that checkpoint. Earlier versioned receipts remain historical evidence; final 1.0 remains held.
> **Live roadmap and known issues:** [QRun-IO/qqq#713](https://github.com/QRun-IO/qqq/issues/713). GitHub issues own current status and remaining work. Follow the [issue-tracking policy](../ISSUE-TRACKING.md) when reporting or resolving findings; keep this guide focused on usage and evidence.
This is an implementation playbook for coding agents working on the QQQ Next UI. Read the [developer guide](./next-ui-developer-guide.md) for user and integrator behavior, the repository [AGENTS.md](../../AGENTS.md) and [CLAUDE.md](../../CLAUDE.md) for scoped conventions, and the [real-server feature matrix](../acceptance/feature-matrix.md) plus [Material parity ledger](../acceptance/material-parity.md) before claiming compatibility. This guide reflects the `feature/next-1.0` release worktree as of 2026-10-01; the latest published prerelease is [1.0.0-RC.8](../releases/1.0.0-RC.8.md) at `cd3d473`, and final `1.0.0` remains on hold. Later branch changes must not be attributed to that immutable release. Some ledger entries predate integrated changes, so reconcile them with source and real-server evidence. A green subset of tests is evidence for that subset, not proof of complete Material parity or a published 1.0 release.
This is an implementation playbook for coding agents working on the QQQ Next UI. Read the [developer guide](./next-ui-developer-guide.md) for user and integrator behavior, the repository [AGENTS.md](../../AGENTS.md) and [CLAUDE.md](../../CLAUDE.md) for scoped conventions, and the [real-server feature matrix](../acceptance/feature-matrix.md) plus [Material parity ledger](../acceptance/material-parity.md) before claiming compatibility. This guide reflects the `feature/next-1.0` release worktree as of 2026-10-01; the previously verified public candidate at the RC11 preparation checkpoint was [1.0.0-RC.10](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10) at `12cf774`, and final `1.0.0` remains on hold. Later branch changes must not be attributed to that immutable release. Some ledger entries predate integrated changes, so reconcile them with source and real-server evidence. A green subset of tests is evidence for that subset, not proof of complete Material parity or a published 1.0 release.
## Operating rule: metadata is the product boundary
@@ -223,7 +225,7 @@ Google Drive picker changes span the frontend component/SDK loader and Javalin's
and v1 public-environment allow-list (#704; backend PR #908 merged to develop as `bac663044`). The frontend needs those backend changes to receive its public configuration and load under the configured CSP. PRC-065 tests controlled SDK responses with
real process execution and SQL; PRC-039 is the approved real-account exclusion. Preserve
the shared-drive view, folder-only validation, cancellation and token expiry handling.
Never log or persist the access token, and never publish OAuth client secrets in metadata. Javalin conditional CSP covers its static export only; standalone Node/container deployments also require runtime `QQQ_DASHBOARD_CSP_SOURCES` using the [documented Google directives](./next-ui-developer-guide.md#google-drive-process-configuration). Check the actual dashboard HTML response from the selected host. RC1 remains immutable and retains its historical placeholder; these changes belong to the ongoing final 1.0 work.
Never log or persist the access token, and never publish OAuth client secrets in metadata. Javalin applies conditional CSP to its static export; standalone Node/container deployments derive the same sources from backend `dashboardCspSources` authentication metadata. Older backends that omit that optional field require runtime `QQQ_DASHBOARD_CSP_SOURCES` using the [documented Google directives](./next-ui-developer-guide.md#google-drive-process-configuration). Check the actual dashboard HTML response from the selected host. RC1 remains immutable and retains its historical placeholder; these changes belong to the ongoing final 1.0 work.
### Script editor suggestions
+10 -5
View File
@@ -1,8 +1,12 @@
# Next UI developer guide
> **This checkout targets RC11.** Confirm availability in the [RC11 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.11) before installing. [RC11 notes](../releases/1.0.0-RC.11.md) record the preparation checkpoint and verification scope; RC10 was the previously verified public candidate at that checkpoint. Earlier versioned receipts remain historical evidence; final 1.0 remains held.
> **RC9:** application code is unchanged from RC8. See [RC9 notes](../releases/1.0.0-RC.9.md) and [published releases](https://github.com/QRun-IO/qqq-frontend-next/releases) for versioned verification and public delivery status. Earlier RC8 receipts below remain historical evidence.
> **Live roadmap and known issues:** [QRun-IO/qqq#713](https://github.com/QRun-IO/qqq/issues/713). GitHub issues own current status and remaining work. Follow the [issue-tracking policy](../ISSUE-TRACKING.md) when reporting or resolving findings; keep this guide focused on usage and evidence.
This guide describes the `feature/next-1.0` release worktree as of 2026-10-01. It explains the current frontend and backend metadata contract. The latest published prerelease is [1.0.0-RC.8](../releases/1.0.0-RC.8.md) (commit `cd3d473`); final `1.0.0` remains on hold. Later branch changes are not retroactive changes to that immutable release. For behavior proven against a real server use the [feature matrix](../acceptance/feature-matrix.md); for the full Material inventory use the [parity ledger](../acceptance/material-parity.md). Some ledger rows predate recent work, so verify an individual status against current source and acceptance results before making a release claim.
This guide describes the `feature/next-1.0` release worktree as of 2026-10-01. It explains the current frontend and backend metadata contract. The previously verified public candidate at the RC11 preparation checkpoint was [1.0.0-RC.10](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10) (commit `12cf774`); final `1.0.0` remains on hold. Later branch changes are not retroactive changes to that immutable release. For behavior proven against a real server use the [feature matrix](../acceptance/feature-matrix.md); for the full Material inventory use the [parity ledger](../acceptance/material-parity.md). Some ledger rows predate recent work, so verify an individual status against current source and acceptance results before making a release claim.
The visual baseline is the September 25 Next UI design (`e42ad2b2`). Material remains the reference for backend contracts and functional behavior. The layout defaults below describe current source; they do not certify a completed visual review.
@@ -31,7 +35,7 @@ The preferred QQQ-hosted distribution is the `com.kingsrook.qqq:qqq-frontend-nex
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-frontend-next</artifactId>
<version>1.0.0-RC.5</version>
<version>1.0.0-RC.11</version>
</dependency>
```
@@ -44,7 +48,7 @@ pnpm build:export
pnpm build:jar
```
The mock setting is for isolated development. Set `NEXT_PUBLIC_MOCK_API=false` and connect a real QQQ backend for integration. `build:export` writes `out/`; `build:jar` packages it with Maven. The Maven POM enforces the presence of static placeholder pages. The default `pnpm build` instead creates a standalone Node server, whose `QQQ_BACKEND_URL` build setting adds same-origin rewrites. For the container path see [`docker/quickstart/Dockerfile`](../../docker/quickstart/Dockerfile). Use version `1.0.0-RC.8` for the published prerelease, overriding an older BOM-managed frontend. It requires the QQQ 4.1.0-SNAPSHOT development backend including PRs #913 and #908; see the release notes for its verified backend commit. Use a matching local backend/frontend build to test later branch changes.
The mock setting is for isolated development. Set `NEXT_PUBLIC_MOCK_API=false` and connect a real QQQ backend for integration. `build:export` writes `out/`; `build:jar` packages it with Maven. The Maven POM enforces the presence of static placeholder pages. The default `pnpm build` instead creates a standalone Node server, whose `QQQ_BACKEND_URL` build setting adds same-origin rewrites. For the container path see [`docker/quickstart/Dockerfile`](../../docker/quickstart/Dockerfile). This checkout targets `1.0.0-RC.11`, overriding an older BOM-managed frontend; confirm its availability in the [RC11 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.11) before installing. It requires the QQQ 4.1.0-SNAPSHOT development backend including PRs #913 and #908; see the release notes for its verified backend commit. Use a matching local backend/frontend build to test later branch changes.
| Setting | Behavior in this checkout |
|---|---|
@@ -455,8 +459,9 @@ Client secrets are not browser configuration and are not published in v1 metadat
The Next UI middleware must include the #704 changes (backend PR #908, merged to develop as `bac663044`) that publish these two settings
and permit Google's SDK and picker origins in CSP only when both are configured.
Those conditional headers apply to the Javalin-hosted static export. The standalone
Node/container host must receive `QQQ_DASHBOARD_CSP_SOURCES` at runtime; it does not derive
Google allowances from instance metadata. Merge these sources with any other deployment
Node/container host also derives them when the backend publishes `dashboardCspSources`
in authentication metadata. With an older backend that omits that optional field, supply
`QQQ_DASHBOARD_CSP_SOURCES` at runtime. Merge these sources with any other deployment
additions and start through [`standalone/qqq-server.mjs`](../../standalone/qqq-server.mjs):
```bash
+4 -11
View File
@@ -10,23 +10,16 @@ RC1 remains immutable: [v1.0.0-RC.1](https://github.com/QRun-IO/qqq-frontend-nex
The owner authorizes publishing new RCs at verified stability or daily milestones. Each RC gets a new immutable version and notes describing its fixes, backend prerequisites, verification, and known gaps. RC publication does not authorize final 1.0.
Latest published candidate: **[1.0.0-RC.7](1.0.0-RC.7.md)**. Its notes record installation, backend requirements, exact artifact verification and known failures. RC1 through RC6 remain available and unchanged.
Previously verified public candidate at the RC11 preparation checkpoint: **[1.0.0-RC.10](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10)**. Its public release entry records exact artifact verification, backend requirements and known limits. RC1 through RC9 remain available and unchanged.
## Fixes during testing
Development and verification continue on `feature/next-1.0`, tracked in [PR #14](https://github.com/QRun-IO/qqq-frontend-next/pull/14). The branch can include changes beyond the latest published RC. Check the version of each preview separately; a local preview may intentionally preserve an earlier design checkpoint. Branch changes are **not retroactive changes to published RC artifacts**.
This checkout targets [RC11](1.0.0-RC.11.md); confirm availability in the [RC11 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.11) before installing. The candidate adds searchable-selector and script-completion input-race corrections from [PR24](https://github.com/QRun-IO/qqq-frontend-next/pull/24). These changes are absent from immutable RC10. Candidate notes distinguish versioned local checks from public delivery and retain the historical browser failures and remaining RC limits. Local previews may intentionally preserve an earlier version.
The branch includes subsequent report editor fixes, script completions, and corrections found in the original Next UI visual review. The latest visual corrections restore Copy form alignment and selected-section defaults, and expose the full table checkbox target on touch devices. Verification details are in the [visual review](../acceptance/next-ui-visual-review.md). The review remains open for other screen families.
For the complete change history, compare the immutable RC1 tag with the branch:
```sh
git fetch origin tag v1.0.0-RC.1
git log --oneline v1.0.0-RC.1..feature/next-1.0
```
RC9's immutable-tag acceptance run completed with known Firefox and tablet failures; its release notes preserve the exact results. Follow [qqq#985](https://github.com/QRun-IO/qqq/issues/985) for browser investigations and [qqq#713](https://github.com/QRun-IO/qqq/issues/713) for the complete backlog. The [original Next visual review](../acceptance/next-ui-visual-review.md) and owner approval remain separate requirements.
## Reporting application issues
Include the exact UI artifact/version or branch commit, QQQ backend version, page/workflow, expected and actual results, reproduction steps, and relevant screenshots or sanitized errors. This distinguishes an RC1 issue already fixed on the branch from a new regression. Never include credentials or sensitive application records.
Create or update the central QQQ ticket and Project 12 item using the [tracking policy](../ISSUE-TRACKING.md). Include the exact UI artifact/version or branch commit, QQQ backend version, page/workflow, expected and actual results, reproduction steps, and relevant screenshots or sanitized errors. This distinguishes an issue in a published RC from a later branch regression. Never include credentials or sensitive application records.
The compatibility ledger and remaining acceptance work still govern final readiness. The testing hold does not waive those requirements or authorize a QQQ 4.1 release.
+30
View File
@@ -0,0 +1,30 @@
# Next UI 1.0.0-RC.10 — preparation
RC10 is being prepared for application testing and **is not yet published**. [RC9](1.0.0-RC.9.md) remains the latest verified public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.10` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.10`. Public checksums, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
## Changes from RC9
- Fix section-hash loss and stale immediate URLs when changing record tabs or views (#989), preserving URL context, return links, focus and history. The baseline eventually restored the tab; this is not a claim of proven tab loss.
- Preserve search-dialog keyboard focus (#950), WebKit possible-value selections (#978), and authentication loading through logout/provider departure (#984).
- Add ESB developer views and overview/management controls, with real-backend acceptance. See the [ESB contract](../acceptance/esb.md).
- Improve browser readiness and diagnostic checks while preserving assertions. The pinned Playwright runner contains the corrected Linux WebKit library; stable-runner migration remains #973. See [change details](unreleased.md).
## Verification
Verification uses source `5e3738b73f14d7ed25580560f3c97b91aed58fce` ([PR21](https://github.com/QRun-IO/qqq-frontend-next/pull/21)) with RC10 metadata and QQQ backend `55b33e6bd7f8cc2aef3b41546ef8409ad307ff05`.
- **1,979 unit tests / 184 files**, typecheck, lint/license (zero errors, five existing warnings), static export, Maven packaging and bundle budgets pass.
- The actual RC10 JAR passes **85/85** auth/focus/selection/ESB real-backend cases: Chromium, Firefox and WebKit 21 each; mobile and tablet 11 each.
- Four navigation regressions pass **8/8 in Firefox/WebKit**, using the same JAR's assets with mocked APIs. These are separate from real-backend API coverage.
Both browser reports have zero failures, skips, flaky outcomes or report errors, with retries disabled. All 192 dashboard files are packaged without a mock service worker; Maven and compiled frontend versions are RC10. Served JavaScript and font bytes match the JAR. The primary fixture serves the JAR directly; authentication variants use verified assets extracted from it. These are local candidate checks, not public delivery receipts. PR23 changes test selection and documentation only; production code and test assertions are unchanged from this verified candidate.
## Browser coverage and remaining RC limits
The historical [PR18 run](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36942612338) failed its touch-coverage gate despite all 2,972 executed cases passing: ESB-001–010 were required but not selected on phone and tablet. The original failed result is retained under [#990](https://github.com/QRun-IO/qqq/issues/990).
[PR23](https://github.com/QRun-IO/qqq-frontend-next/pull/23) corrects selection by adding touch markers to the ten existing ESB tests, preserving production code and every assertion. Its separate focused real-broker run on the PR18 export and QQQ `55b33e6` passed all 20 phone/tablet cases with zero retries, failures, skips, flaky outcomes or report errors. This focused result is not a fresh full hosted matrix pass; full hosted verification remains pending at this preparation checkpoint.
The secondary-browser/tablet RC exception remains documented in [#985](https://github.com/QRun-IO/qqq/issues/985#issuecomment-5943724086) and [#798](https://github.com/QRun-IO/qqq/issues/798#issuecomment-5943457468). No gate, test requirement or exclusion was weakened. This exception does not waive product defects or authorize GA.
Remaining parity, real Auth0/Drive/QuickSight checks, browser investigations, visual review and application soak stay tracked in [#713](https://github.com/QRun-IO/qqq/issues/713), [#985](https://github.com/QRun-IO/qqq/issues/985), [#711](https://github.com/QRun-IO/qqq/issues/711) and [#712](https://github.com/QRun-IO/qqq/issues/712). The container backend origin is fixed at build time to `host.docker.internal:8000`; use the JAR or rebuild for another origin. This candidate does not itself publish QQQ 4.1.
+19
View File
@@ -0,0 +1,19 @@
# Next UI 1.0.0-RC.11 — preparation
At this preparation checkpoint, RC11 is being prepared for application testing and **is not yet published**. [RC10](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10) remains the latest verified public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.11` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.11`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
## Changes from RC10
[PR24](https://github.com/QRun-IO/qqq-frontend-next/pull/24), merged source `a1d3e48419812fcb8d47091cb4af315cad4e76e9` (tree-identical to reviewed head `ea73118fcabdf3c08ea8614c8bd0ad63749fb598`), invalidates stale searchable-selector results immediately when input changes (#970), and keeps script-completion suggestions open when a delayed scroll event reports an unchanged position (#954). Actual position changes still dismiss suggestions. No acceptance assertion or gate is weakened.
## Verification checkpoint
PR24's [hosted primary acceptance](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36954433088) passes on its exact source: 614 cases and 401 required rows. The actual merged source above has the same tree. With RC11 metadata, fresh verification passes **1,984 unit tests / 184 files**, typecheck, lint/license (zero errors, five existing warnings), static export, Maven packaging and bundle budgets. All **192 dashboard files** match the export byte-for-byte, with no mock service worker and matching RC11 frontend/Maven versions.
The actual RC11 JAR passes **125/125 real-backend cases** against QQQ `55b33e6bd7f8cc2aef3b41546ef8409ad307ff05`: 25 each in Chromium, Firefox, WebKit, phone and tablet. These include the 105 auth/focus/selection/ESB cases and 20 selector/completion regression cases. A separate **8/8 record-navigation regressions in Firefox/WebKit** use the same JAR assets with mocked APIs. Both reports have zero failures, skips, flaky outcomes or report errors, with retries disabled. Served versioned JavaScript and font bytes match the JAR. The scoped matrix check passes only the exercised rows; it is not a full hosted matrix result. These local candidate checks are separate from eventual public-artifact verification; no RC10 test count or artifact digest is attributed to RC11.
## Remaining RC limits
Historical observations remain preserved: REC-054 on mobile light expected three completion options but found none; PRC-061 in WebKit left the Casey selection at its placeholder. See [#954](https://github.com/QRun-IO/qqq/issues/954), [#970](https://github.com/QRun-IO/qqq/issues/970) and [RC10 delivery notes](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10). The original [PR18 touch-coverage failure](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36942612338) remains historical evidence. [#990 is complete](https://github.com/QRun-IO/qqq/issues/990#issuecomment-5944836159): PR23’s complete touch report covers all 401 required IDs on each profile, with zero missing, and all ten ESB scenarios pass first attempt on both phone and tablet. That report records **1,149 passes and one unrelated tablet NAV-056 failure**; its full touch gate and whole workflow remain **failed**. [NAV-056 diagnostics remain under investigation](https://github.com/QRun-IO/qqq/issues/985#issuecomment-5944830383), provisionally tracked in [#904](https://github.com/QRun-IO/qqq/issues/904#issuecomment-5944558037), without claiming a shared historical cause. Scoped #990 completion does not imply an all-browser pass or waive that failure.
The documented secondary-browser/tablet RC exception remains under [#985](https://github.com/QRun-IO/qqq/issues/985#issuecomment-5943724086) and [#798](https://github.com/QRun-IO/qqq/issues/798#issuecomment-5943457468); it does not waive new product defects or authorize GA. Material parity, sub-path hosting, real Auth0/Drive/QuickSight verification, visual review and application soak remain tracked in [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711) and [#712](https://github.com/QRun-IO/qqq/issues/712). The image backend origin remains fixed at build time to `host.docker.internal:8000`; use the JAR or rebuild for another origin. This candidate does not publish QQQ 4.1.
+41
View File
@@ -0,0 +1,41 @@
# Next UI 1.0.0-RC.9
Release candidate for application testing, October 1, 2026. The [GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.9) records public artifact availability and final delivery verification; a source tag alone is not delivery confirmation. Final 1.0 remains held for owner application testing and explicit approval.
## Changes from RC8
RC9 integrates the GitHub tracking policy, current roadmap links, and updated developer/agent documentation. Application code and dependencies are unchanged from RC8. This candidate does not claim fixes for the open functional or visual findings.
[QRun-IO/qqq#713](https://github.com/QRun-IO/qqq/issues/713) is the source of truth for current status and remaining work. Original issue reports and historical acceptance evidence remain available. See the [tracking policy](../ISSUE-TRACKING.md).
## Verification baseline and known issues
The documentation source `354ee2709d8ee553de5e3ad823ce9d1190887d4c`, merged through PR #16, passed general CI (typecheck, lint, unit coverage, mocked Chromium E2E, Storybook and bundle budgets) and both container architecture builds. Real-backend [run 36861609503](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36861609503) passed all 602 Chromium cases and all 391 required rows, with three approved real-provider exclusions.
Its secondary reports remain failed: Firefox 599 passed / 3 failed (NAV-014, NAV-016 and REC-056 legacy-font diagnostics, [#951](https://github.com/QRun-IO/qqq/issues/951)), WebKit 601 / 1 (WID-073 metadata access-control diagnostic, [#961](https://github.com/QRun-IO/qqq/issues/961)), and combined touch 1,124 / 2 (tablet NAV-025 and REL-005). Reports contain zero skips/flaky outcomes/report errors. These are pre-RC9-version source results; final tag results and public artifact receipts are recorded separately below. No all-browser pass is claimed.
Current open work includes embedded report/query equivalence, remaining input configurations, subpath hosting, real Auth0/Google Drive/QuickSight checks, browser investigations, original-Next visual approval, real-application soak and final release approval. See [#713](https://github.com/QRun-IO/qqq/issues/713) and [browser evidence](https://github.com/QRun-IO/qqq-frontend-next/issues/12) for individual issues. Material remains the behavior reference; the original Next design remains the visual reference.
## Versioned local verification
RC9 passes all 1,919 unit tests across 181 files, typechecking, lint/license (zero errors, five existing warnings), production export, Maven packaging and unchanged bundle budgets. All 193 packaged dashboard files are present; the Maven version is RC9 and no mock service worker is included. The actual locally packaged RC9 JAR passes 28 affected desktop/mobile browser cases with zero failures/skips/flaky outcomes/report errors. These checks cover API controls/theme/search focus, exact numeric persistence and composite field submission against backend e0d57dd31. They do not replace public artifact verification or certify other profiles.
## Installation
Maven coordinate: `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.9`.
Container: `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.9` (AMD64/ARM64 verified). The container backend origin is fixed at build time; the published image targets `host.docker.internal:8000`. Use the JAR or rebuild for another origin.
As with RC8, verification uses the QQQ 4.1 development backend. The locally verified backend source is `e0d57dd31b979b17215370546ef4e26cd8a38d21`; hosted workflows resolve their configured QQQ ref separately. This release does not publish QQQ 4.1 or certify every real consumer/backend combination.
## Public delivery — October 1, 2026
[RC9](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.9) was published at 19:25:28 UTC as a prerelease, latest=false. PR16 and PR14 are merged. The signed immutable tag points to `c029ad2a70948aac6469d8a71ccefc80c6e00d74`.
- Public JAR: 1,864,121 bytes; SHA256 `969034566c6b30a5034680dcf2d46aec327240db6cdd3fb7b31f1fae7cb9f17d`; SHA1 `3943c8641c14554999206cf52357c32b8f397b7b`.
- Release signature verified against fingerprint `68A49476754103988EA3ED924B88CBB3D6DCB237`; a clean ordinary Maven consumer resolved identical bytes without manual installation.
- Actual public JAR: all 28 targeted desktop/mobile cases passed, zero failures/skips/flaky outcomes/report errors. All 193 dashboard files and RC9 version markers are present, without the mock service worker.
- Public image: `sha256:c2c684733deb98fd8355d4a9e2a53bf4af429bd16d9e7802641f9ef9d44e1017`. Anonymous AMD64/ARM64 pulls and both architecture startup, route, JavaScript, pinned-font and version checks passed.
- Merged-source general CI36912597438 passed. Fresh full dependency audit reports zero advisories across1,038dependencies; GitHub marked all four outstanding alerts fixed, none dismissed. Issues #647/#698 are closed with that evidence.
Full immutable-tag acceptance [36912641399](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36912641399) completed after publication: Chromium 602 passed / 0 failed; desktop WebKit 602 / 0; Firefox 600 / 2; mobile 563 / 0; tablet 560 / 3. All reports contain zero skips, flaky outcomes and report errors. Firefox failed NAV-016 legacy-font diagnostics and REC-048 validation-toast visibility; tablet failed NAV-015 JavaScript loading, NAV-016 root navigation (both WebKit internal errors), and NAV-025 Clear-search focus in dark mode. The overall run failed; later passing cases do not resolve older investigations. Follow [frontend#12](https://github.com/QRun-IO/qqq-frontend-next/issues/12) for individual failure tracking and [#713](https://github.com/QRun-IO/qqq/issues/713) for the live backlog. Final 1.0 remains held.
+53
View File
@@ -0,0 +1,53 @@
# Next UI — unreleased
[RC11 is published and immutable](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.11). It includes the searchable-selector and script-completion corrections from [PR24](https://github.com/QRun-IO/qqq-frontend-next/pull/24); its release details remain in [RC11 notes](1.0.0-RC.11.md). Current main also contains the later menu, copy-focus and grid fixes, which are not in that published artifact. Central tracking: [qqq#713](https://github.com/QRun-IO/qqq/issues/713), [browser investigations #985](https://github.com/QRun-IO/qqq/issues/985), and [QQQ Roadmap Project 12](https://github.com/orgs/QRun-IO/projects/12).
## Product fixes
- Clear remembered query filters and saved-view selections on logout or a detected user identity change. Same-user resumes keep their query state; global appearance, density and legacy column preferences remain intact. This correction awaits its own branch acceptance. [#1006](https://github.com/QRun-IO/qqq/issues/1006)
- In searchable possible-value fields, invalidate old results immediately when the search term changes, so a debounced request cannot remove an option during its selection. [#970](https://github.com/QRun-IO/qqq/issues/970)
- Keep code suggestions open when a delayed textarea scroll event reports the position already used for the popup; dismiss them when the scroll position actually changes. [#954](https://github.com/QRun-IO/qqq/issues/954)
- Preserve focus on the search dialog's Clear control when keyboard interaction occurs before its scheduled initial focus. [#950](https://github.com/QRun-IO/qqq/issues/950)
- Preserve a clicked possible-value option in WebKit when blurring its search input would scroll the form between mousedown and mouseup. The selected value now reaches process submission and generated output. [#978](https://github.com/QRun-IO/qqq/issues/978)
- Keep authentication loading until explicit logout finishes, so a late logout response cannot erase cookies from a subsequent successful sign-in. [#984](https://github.com/QRun-IO/qqq/issues/984)
## Browser testing and infrastructure
- Pin the official Playwright runner containing the fixed Linux WebKit network library, and retain native browser diagnostics for navigation failures. The previous bundle's heap corruption was reproduced; migration to a stable runner remains tracked separately. [#904](https://github.com/QRun-IO/qqq/issues/904), [#973](https://github.com/QRun-IO/qqq/issues/973)
- Correlate interrupted Firefox font diagnostics with real request and decode evidence, wait for initial fonts before the deliberate redirect, and observe transient feedback during the action that produces it. [#951](https://github.com/QRun-IO/qqq/issues/951), [#953](https://github.com/QRun-IO/qqq/issues/953), [#967](https://github.com/QRun-IO/qqq/issues/967)
- Wait for nested report metadata and the destination's owned iframe before advancing acceptance navigation. [#961](https://github.com/QRun-IO/qqq/issues/961), [#972](https://github.com/QRun-IO/qqq/issues/972)
- Verify Linux WebKit's downloaded filename normalization while retaining file-content and cleanup assertions. [#979](https://github.com/QRun-IO/qqq/issues/979)
- Verify actual browser refusal of disallowed framing with a control that renders when the protective headers are removed. [#981](https://github.com/QRun-IO/qqq/issues/981)
- Recognize Firefox's network-error diagnostic for the gallery's intentionally missing extension only after that same script request returns HTTP 404; preserve the raw evidence and reject unrelated failures. [#983](https://github.com/QRun-IO/qqq/issues/983)
- Select all ten ESB scenarios for both phone and tablet acceptance, retaining real broker delivery, lifecycle, replay, SQL and permission checks. Matrix references now use the central QQQ tickets. [#986](https://github.com/QRun-IO/qqq/issues/986), [#990](https://github.com/QRun-IO/qqq/issues/990)
## Verification and remaining work
Current main `5ca3e0b` has a complete [3,010-case first-attempt acceptance pass](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36989591498): 620 per desktop browser and 575 per touch profile. That run qualifies the main tree before the query-state correction above. The earlier checkpoints below are retained separately.
The [combined acceptance run](https://github.com/QRun-IO/qqq-frontend-next/actions/runs/36942612338) on head `7ff90f1` (the same tree as merge `289eca19`) passed all 2,972 executed cases: 614 each in Chromium, Firefox and WebKit, and 565 each on phone and tablet. All desktop gates covered 401 required rows. The workflow still failed its touch coverage gate because ten ESB rows were not selected; that original failure remains retained under [#990](https://github.com/QRun-IO/qqq/issues/990). After adding the selection markers, a separate native Linux run passed all 20 ESB phone/tablet cases, with zero retries, skips, flaky outcomes or report errors. Its frozen frontend export is unchanged; its freshly rebuilt backend is `55b33e6`. Complete touch collection is 575 cases per profile. The subsequent [complete PR23 outcome](https://github.com/QRun-IO/qqq/issues/990#issuecomment-5944836159) covers all 401 required IDs on each profile with zero missing and all 20 ESB touch cases passing, completing #990. Touch totals are 1,149 passes and one unrelated tablet NAV-056 failure; the full gate and workflow remain failed. [NAV-056 investigation](https://github.com/QRun-IO/qqq/issues/985#issuecomment-5944830383) remains separate, with no shared-cause claim or new waiver.
Each linked issue and PR records the source commit, reproduction and scoped verification. Preserve failed full-run snapshots separately from later focused passes. The broader historical navigation inventory [#904](https://github.com/QRun-IO/qqq/issues/904), same-user session stall [#952](https://github.com/QRun-IO/qqq/issues/952), legacy process-navigation stall [#960](https://github.com/QRun-IO/qqq/issues/960), and original toast-paint uncertainty [#967](https://github.com/QRun-IO/qqq/issues/967) remain open. The [RC10 preparation notes](1.0.0-RC.10.md) retain their historical checkpoint; its [public release entry](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.10) records final delivery verification. See [RC11 notes](1.0.0-RC.11.md) for the successor candidate. No final-release approval is claimed by these results.
Final 1.0 remains held for real-application soak and explicit owner approval under [#712](https://github.com/QRun-IO/qqq/issues/712). This work does not authorize a QQQ 4.1 release. See the [testing-period policy](1.0-testing.md) and [issue lifecycle](../ISSUE-TRACKING.md).
## Pending standalone branding compatibility (QQQ #1009)
The standalone Node server can route the exact root-relative `branding.logo` and
`branding.icon` paths published by authentication metadata through fixed backend
image roles. Local Node `public` files keep precedence; external image URLs and
Java dashboard serving are unchanged. This does not expose the whole application
overlay or add a general proxy.
This requires **a QQQ middleware-javalin build containing QQQ #1009's
`/qqq/branding/logo` and `/qqq/branding/icon` endpoints**. They are absent from
published **4.1.0-RC.1**. The minimum numbered release is not yet assigned; a
source build must record the exact backend commit/JAR hashes. Older deployments
must supply branding through their Node `public` files or an existing external
image URL. No automatic compatibility with old relative backend assets is claimed.
The preserved standalone qualification against public RC1 remains **5 passed,
38 failed** out of 43 cases because of missing branding assets. The original
staging failure is also retained. The corrected cross-repository pairing has
not yet received its browser qualification; neither #1009 nor #734 is closed by
focused unit/HTTP results.
+44
View File
@@ -1,5 +1,49 @@
# Next UI security review (QRun-IO/qqq#696)
## Current status — October 4, 2026
This addendum supersedes the historical disposition statements below where noted.
The September 25 review remains intact as evidence of its original source and scope.
Current findings and release decisions are tracked in
[QQQ #696](https://github.com/QRun-IO/qqq/issues/696#issuecomment-5982040326).
This is a scoped security review, not a certification of ASVS Level 2 compliance.
| Finding | Current disposition |
| --- | --- |
| NUI-04: dashboard headers | [#695](https://github.com/QRun-IO/qqq/issues/695) is closed for the Javalin static-export scope, with current-source provider tests and browser evidence. Standalone qualification is separate. |
| NUI-05: readable session cookie | [#733](https://github.com/QRun-IO/qqq/issues/733) is closed. Next resumes through the backend-owned cookie; the legacy endpoint correction is merged. Material's explicit readable-cookie compatibility mode remains supported. |
| NUI-06: previous-user browser state | The additional query-filter and saved-view-pointer retention finding is fixed in [#1006](https://github.com/QRun-IO/qqq/issues/1006), merged in frontend `f367756`. Global visual preferences are preserved. |
| NUI-09: standalone headers | [#734](https://github.com/QRun-IO/qqq/issues/734) and the metadata-derived CSP correction [#1017](https://github.com/QRun-IO/qqq/issues/1017) are closed after scoped qualification and integration. The paired implementation passed 48 standalone first-attempt cases across five profiles. [Frontend PR #40](https://github.com/QRun-IO/qqq-frontend-next/pull/40) merged as `138c3c6d`, tree `328bc322`, exactly matching the qualified combined candidate. Its separate full Javalin acceptance passed 3,015/3,015 first attempts against backend `1d16a70c`. HEAD/304, bounded metadata and Java-customizer limits remain documented in the closeout. |
| NUI-11: custom CSS | Current code treats application `customCss` as trusted developer configuration and inserts it with `textContent`. It is not filtered by the historical deny-list or sanitized by DOMPurify. CSP and application configuration remain separate controls. |
| Auth0 token verification | [#1008](https://github.com/QRun-IO/qqq/issues/1008) confirms issuer/audience validation and cache-boundary findings. [Backend PR #1012](https://github.com/QRun-IO/qqq/pull/1012) contains the correction; 164 focused tests passed on its combined backend tree. The exact-head CI passed and the correction merged into backend develop as `fc67393b`. An unconfigured audience remains supported; no audience enforcement is claimed in that configuration. |
| Signed back-channel logout | [#909](https://github.com/QRun-IO/qqq/issues/909) remains open for stable release delivery. [Backend PR #1021](https://github.com/QRun-IO/qqq/pull/1021) merged the qualified correction into stable main as `9168e434`; its merge tree equals the qualified candidate and the automatic post-merge reactor/sample/static gates passed. Published 4.0.0 remains affected; planned 4.0.1 is not published or artifact-qualified. PR #1018 is closed as superseded, not merged; its original Mongo failure is retained. The corrected 4.1 RC line remains distinct. |
The other scoped finding dispositions remain as reconciled in #696. NUI-10's
runtime-style exception remains deliberate; it does not allow inline scripts.
Negative security tests intentionally produce denied-resource and CSP diagnostics.
A passing test run does not mean those diagnostic arrays are all empty.
### Evidence limits
The reference remains ASVS 4.0.3. Owned identity-provider fixtures do not qualify a
real Auth0 tenant, MFA or step-up policy, provider-grant revocation, or deployment
TLS, HSTS and proxy trust. The approved real-provider exclusion remains explicit.
Configurable TABLE_BASED idle expiration does not prove a 12-hour active / 30-minute
idle policy. Cookie-prefix and shared-host suitability, generic CSRF/Origin
protection, all-session revocation, and application-sensitive storage/cache policy
also remain outside the demonstrated guarantees. These limits are not newly
confirmed High/Critical exploits and must not be presented as universal compliance.
The 48-case standalone result covers its selected security scope and paired
candidate backend. Its analytics case uses an owned plugin through the real
application hook, not a vendor SDK or real account. It does not
replace full-browser acceptance. The separate 3,015-case Javalin gate qualifies
the merged PR40 tree; neither result resolves separately tracked browser failures
or certifies a real provider or deployment. Final 1.0 still requires owner visual
acceptance and real-application soak.
## Historical review — September 25, 2026
Independent review of the QQQ Next admin UI against OWASP ASVS 4.0.3 Level 2, for the
Next UI 1.0 milestone (epic QRun-IO/qqq#713). Reviewed on 2026-09-25 at
`feature/GH-649-next-acceptance` (`2b6569f`, release 0.2.0) with the backend at
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "qqq-frontend-next",
"version": "1.0.0-RC.8",
"version": "1.0.0-RC.11",
"private": true,
"packageManager": "pnpm@9.15.9",
"scripts": {
@@ -60,7 +60,7 @@
"devDependencies": {
"@axe-core/playwright": "^4.11.1",
"@eslint/eslintrc": "^3.3.4",
"@playwright/test": "^1.58.2",
"@playwright/test": "1.64.0-alpha-2026-10-01",
"@storybook/addon-docs": "10.6.0",
"@storybook/nextjs-vite": "10.6.0",
"@storybook/react": "10.6.0",
+28 -38
View File
@@ -72,7 +72,7 @@ importers:
version: 0.485.0(react@19.2.4)
next:
specifier: 16.3.6
version: 16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
version: 16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
rapidoc:
specifier: 9.3.8
version: 9.3.8
@@ -100,19 +100,19 @@ importers:
devDependencies:
'@axe-core/playwright':
specifier: ^4.11.1
version: 4.11.1(playwright-core@1.58.2)
version: 4.11.1(playwright-core@1.64.0-alpha-2026-10-01)
'@eslint/eslintrc':
specifier: ^3.3.4
version: 3.3.4
'@playwright/test':
specifier: ^1.58.2
version: 1.58.2
specifier: 1.64.0-alpha-2026-10-01
version: 1.64.0-alpha-2026-10-01
'@storybook/addon-docs':
specifier: 10.6.0
version: 10.6.0(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))
'@storybook/nextjs-vite':
specifier: 10.6.0
version: 10.6.0(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))
version: 10.6.0(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))
'@storybook/react':
specifier: 10.6.0
version: 10.6.0(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)
@@ -1200,9 +1200,9 @@ packages:
cpu: [x64]
os: [win32]
'@playwright/test@1.58.2':
resolution: {integrity: sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==}
engines: {node: '>=18'}
'@playwright/test@1.64.0-alpha-2026-10-01':
resolution: {integrity: sha512-N/mTE29hNg/pw/ega+N+cEvPmAFwrprMxoacDbaO0fDlpyQ6n/SvCRF9dv6mLa1tjcy9oPStW2o7C1HP2Mh8lQ==}
engines: {node: '>=20'}
hasBin: true
'@polka/url@1.0.0-next.29':
@@ -3250,11 +3250,6 @@ packages:
fraction.js@5.3.4:
resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -4101,14 +4096,14 @@ packages:
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
engines: {node: '>=12'}
playwright-core@1.58.2:
resolution: {integrity: sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==}
engines: {node: '>=18'}
playwright-core@1.64.0-alpha-2026-10-01:
resolution: {integrity: sha512-Dk7ENTj8unFs3o5KNTIhFXO+JN/YGU4FrQvPmxI0Uri9j/5r8Mk0IzmFkNpvx6n83Kcls38qRdkD/fTdAfWvtA==}
engines: {node: '>=20'}
hasBin: true
playwright@1.58.2:
resolution: {integrity: sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==}
engines: {node: '>=18'}
playwright@1.64.0-alpha-2026-10-01:
resolution: {integrity: sha512-Nbe+dTDPKcZjI+lIUe6WLUb3KQ3Wll/SPkf7oCzytUoPZo+wzZY6J2DaD8+7dXMsq+8lUB2dZOMimouiYwpGuw==}
engines: {node: '>=20'}
hasBin: true
possible-typed-array-names@1.1.0:
@@ -5066,10 +5061,10 @@ snapshots:
'@csstools/css-tokenizer': 3.0.4
lru-cache: 10.4.3
'@axe-core/playwright@4.11.1(playwright-core@1.58.2)':
'@axe-core/playwright@4.11.1(playwright-core@1.64.0-alpha-2026-10-01)':
dependencies:
axe-core: 4.11.1
playwright-core: 1.58.2
playwright-core: 1.64.0-alpha-2026-10-01
'@babel/code-frame@7.29.0':
dependencies:
@@ -5884,9 +5879,9 @@ snapshots:
'@oxc-resolver/binding-win32-x64-msvc@11.21.2':
optional: true
'@playwright/test@1.58.2':
'@playwright/test@1.64.0-alpha-2026-10-01':
dependencies:
playwright: 1.58.2
playwright: 1.64.0-alpha-2026-10-01
'@polka/url@1.0.0-next.29': {}
@@ -6386,18 +6381,18 @@ snapshots:
dependencies:
react: 19.2.4
'@storybook/nextjs-vite@10.6.0(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))':
'@storybook/nextjs-vite@10.6.0(@babel/core@7.29.7)(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))':
dependencies:
'@storybook/builder-vite': 10.6.0(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))
'@storybook/react': 10.6.0(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)
'@storybook/react-vite': 10.6.0(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))
next: 16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
next: 16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
react: 19.2.4
react-dom: 19.2.4(react@19.2.4)
storybook: 10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4)
styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.2.4)
vite: 7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)
vite-plugin-storybook-nextjs: 10.6.0(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))
vite-plugin-storybook-nextjs: 10.6.0(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2))
optionalDependencies:
'@types/react': 19.2.14
'@types/react-dom': 19.2.3(@types/react@19.2.14)
@@ -8369,9 +8364,6 @@ snapshots:
fraction.js@5.3.4: {}
fsevents@2.3.2:
optional: true
fsevents@2.3.3:
optional: true
@@ -9053,7 +9045,7 @@ snapshots:
neotraverse@1.0.1: {}
next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4):
next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4):
dependencies:
'@next/env': 16.3.6
'@swc/helpers': 0.5.23
@@ -9072,7 +9064,7 @@ snapshots:
'@next/swc-linux-x64-musl': 16.3.6
'@next/swc-win32-arm64-msvc': 16.3.6
'@next/swc-win32-x64-msvc': 16.3.6
'@playwright/test': 1.58.2
'@playwright/test': 1.64.0-alpha-2026-10-01
sharp: 0.35.4(@types/node@22.19.11)
transitivePeerDependencies:
- '@babel/core'
@@ -9269,13 +9261,11 @@ snapshots:
picomatch@4.0.7: {}
playwright-core@1.58.2: {}
playwright-core@1.64.0-alpha-2026-10-01: {}
playwright@1.58.2:
playwright@1.64.0-alpha-2026-10-01:
dependencies:
playwright-core: 1.58.2
optionalDependencies:
fsevents: 2.3.2
playwright-core: 1.64.0-alpha-2026-10-01
possible-typed-array-names@1.1.0: {}
@@ -10180,13 +10170,13 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
vite-plugin-storybook-nextjs@10.6.0(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)):
vite-plugin-storybook-nextjs@10.6.0(next@16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(rollup@4.63.5)(storybook@10.6.0(@types/react@19.2.14)(prettier@3.8.1)(react@19.2.4))(typescript@5.9.3)(vite@7.3.6(@types/node@22.19.11)(jiti@2.7.0)(lightningcss@1.31.1)(terser@5.51.2)):
dependencies:
'@next/env': 16.3.6
'@rollup/pluginutils': 5.4.0(rollup@4.63.5)
magic-string: 0.30.21
module-alias: 2.3.4
next: 16.3.6(@babel/core@7.29.7)(@playwright/test@1.58.2)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
next: 16.3.6(@babel/core@7.29.7)(@playwright/test@1.64.0-alpha-2026-10-01)(@types/node@22.19.11)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
pathe: 2.0.3
probe-image-size: 7.4.0
semver: 7.8.5
+1 -1
View File
@@ -47,7 +47,7 @@
</developers>
<properties>
<revision>1.0.0-RC.8</revision>
<revision>1.0.0-RC.11</revision>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.outputTimestamp>2026-09-24T00:00:00Z</project.build.outputTimestamp>
</properties>
+2 -1
View File
@@ -18,7 +18,7 @@ rmSync(classes, { recursive: true, force: true })
mkdirSync(classes, { recursive: true })
const fixtureDirectory = path.resolve('tests/acceptance/fixture')
const sources = readdirSync(fixtureDirectory).filter((name) => name.endsWith('.java')).map((name) => path.join(fixtureDirectory, name))
const javac = spawnSync('javac', ['-proc:none', '-encoding', 'UTF-8', '-cp', fixtureClasspath, '-d', classes, ...sources], { stdio: 'inherit' })
const javac = spawnSync('javac', ['-proc:none', '-sourcepath', '', '-encoding', 'UTF-8', '-cp', fixtureClasspath, '-d', classes, ...sources], { stdio: 'inherit' })
if (javac.status !== 0) {
console.error('Acceptance fixture compilation failed.')
process.exit(1)
@@ -29,6 +29,7 @@ const server = spawn('java', [
'-Dqqq.sample.mockAuthentication=true',
'-Dqqq.sample.sharing=true',
`-Dqqq.sample.port=${port}`,
`-Dqqq.sample.esb.port=${process.env.QQQ_ACCEPTANCE_ESB_PORT ?? '61616'}`,
'-Duser.timezone=UTC',
// javalin mode: the fresh export shadows any dashboard bundled in the sample jar
'-cp', [...(ACCEPTANCE_MODE === 'javalin' ? [EXPORT_CLASSPATH] : []), classes, fixtureClasspath].join(path.delimiter),
+8 -6
View File
@@ -11,6 +11,7 @@ import { spawn } from 'node:child_process'
import { cpSync, existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { BUILD_MARKER } from './acceptance-paths.mjs'
import { assertExplicitCspSources } from './acceptance-standalone.mjs'
const backend = `http://127.0.0.1:${process.env.QQQ_ACCEPTANCE_BACKEND_PORT ?? '18765'}`
const standalone = path.resolve('.next/standalone')
@@ -19,16 +20,16 @@ if (!existsSync(path.join(standalone, 'server.js')) || !existsSync(BUILD_MARKER)
console.error(`No production build for ${backend}; run node scripts/acceptance.mjs.`)
process.exit(1)
}
cpSync(path.resolve('.next/static'), path.join(standalone, '.next/static'), { recursive: true })
cpSync(path.resolve('public'), path.join(standalone, 'public'), { recursive: true })
for (const file of ['qqq-server.mjs', 'security-headers.mjs', 'backend-prefixes.json']) {
// Use the JS copy path for owner-readable files on Docker Desktop mounts.
cpSync(path.resolve('.next/static'), path.join(standalone, '.next/static'), { recursive: true, verbatimSymlinks: true, filter: () => true })
cpSync(path.resolve('public'), path.join(standalone, 'public'), { recursive: true, verbatimSymlinks: true, filter: () => true })
for (const file of ['qqq-server.mjs', 'security-headers.mjs', 'branding-assets.mjs', 'backend-prefixes.json']) {
cpSync(path.resolve('standalone', file), path.join(standalone, file))
}
/**
* The application's policy additions (its QuickSight embed, custom component bundles and
* the fixture's loopback service), which the QQQ server derives in javalin mode and a
* container deployment sets in QQQ_DASHBOARD_CSP_SOURCES.
* Only the fixture's explicit owned frame/image/media overrides. Application
* metadata sources must arrive through the production metadata contract.
*
* @returns {Promise<string>} The sources, once the acceptance backend is up.
*/
@@ -47,6 +48,7 @@ async function dashboardCspSources() {
}
const sources = await dashboardCspSources()
assertExplicitCspSources(sources)
const server = spawn('node', ['qqq-server.mjs'], {
cwd: standalone,
stdio: 'inherit',
+8
View File
@@ -40,3 +40,11 @@ export const BUILD_MARKER = path.resolve('.next/acceptance-backend.txt')
export const EXPORT_CLASSPATH = path.resolve('test-results/acceptance/export-classpath')
export const ACCEPTANCE_MODE = process.env.QQQ_ACCEPTANCE_MODE === 'standalone' ? 'standalone' : 'javalin'
/** Separate backend, browser and provider origins for authentication variants. */
export const SECURITY_BACKEND_PORT = Number(process.env.QQQ_ACCEPTANCE_SECURITY_BACKEND_PORT ?? Number(process.env.QQQ_ACCEPTANCE_BACKEND_PORT ?? 18765) + 10)
export const SECURITY_FRONTEND_PORT = Number(process.env.QQQ_ACCEPTANCE_SECURITY_FRONTEND_PORT ?? Number(process.env.QQQ_ACCEPTANCE_FRONTEND_PORT ?? 13765) + 20)
export const SECURITY_IDP_PORT = Number(process.env.QQQ_ACCEPTANCE_SECURITY_IDP_PORT ?? Number(process.env.QQQ_ACCEPTANCE_FRONTEND_PORT ?? 13765) + 10)
export const SECURITY_BACKEND_URL = `http://127.0.0.1:${SECURITY_BACKEND_PORT}`
export const SECURITY_UI_URL = ACCEPTANCE_MODE === 'standalone' ? `http://127.0.0.1:${SECURITY_FRONTEND_PORT}` : SECURITY_BACKEND_URL
export const SECURITY_STANDALONE = path.resolve('test-results/acceptance/security-standalone')
+58
View File
@@ -0,0 +1,58 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
/** @file Stages and validates an immutable standalone build for an authentication backend. */
import { cpSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { createRequire } from 'node:module'
const prefixes = createRequire(path.resolve('package.json'))('./standalone/backend-prefixes.json')
/** Rejects a missing or differently routed build, regardless of any retained Javalin export. */
export function assertStandaloneTarget(directory, backend) {
if (!existsSync(path.join(directory, 'server.js')) || !existsSync(path.join(directory, 'qqq-server.mjs'))
|| readFileSync(path.join(directory, 'acceptance-backend.txt'), 'utf8').trim() !== backend) {
throw new Error(`No standalone security build for ${backend}; run acceptance without --skip-build.`)
}
const { rewrites } = JSON.parse(readFileSync(path.join(directory, '.next/routes-manifest.json'), 'utf8'))
const routes = Array.isArray(rewrites) ? rewrites : [...rewrites.beforeFiles, ...rewrites.afterFiles, ...rewrites.fallback]
for (const prefix of prefixes) {
if (!routes.some(({ source, destination }) => source === `/${prefix}/:path*` && destination === `${backend}/${prefix}/:path*`)) {
throw new Error(`Standalone security build has the wrong backend rewrite for ${prefix}.`)
}
}
}
/** Copies the same standalone payload as the container image, before the next clean build. */
export function stageStandalone(directory, backend, source = process.cwd()) {
rmSync(directory, { recursive: true, force: true })
// The JS copy path preserves readable files on Docker Desktop mounts; relative links
// must remain relative so deleting the original build cannot invalidate this stage.
cpSync(path.join(source, '.next/standalone'), directory, { recursive: true, verbatimSymlinks: true, filter: () => true })
cpSync(path.join(source, '.next/static'), path.join(directory, '.next/static'), { recursive: true, verbatimSymlinks: true, filter: () => true })
cpSync(path.join(source, 'public'), path.join(directory, 'public'), { recursive: true, verbatimSymlinks: true, filter: () => true })
for (const file of ['qqq-server.mjs', 'security-headers.mjs', 'branding-assets.mjs', 'backend-prefixes.json']) {
cpSync(path.join(source, 'standalone', file), path.join(directory, file))
}
writeFileSync(path.join(directory, 'acceptance-backend.txt'), `${backend}\n`)
assertStandaloneTarget(directory, backend)
}
/** Prevents the fixture from supplying the metadata admissions the production wrapper must derive. */
export function assertExplicitCspSources(text) {
for (const part of text.split(';')) {
const [directive, ...sources] = part.trim().split(/\s+/).filter(Boolean)
if (!directive) continue
if (!['frame-src', 'img-src', 'media-src'].includes(directive) || sources.length !== 1) {
throw new Error('Only explicit owned-service CSP overrides are allowed')
}
let origin
try { origin = new URL(sources[0]) } catch { /* rejected below */ }
if (!origin || !['http:', 'https:'].includes(origin.protocol) || origin.origin !== sources[0] || sources[0].includes('*')) {
throw new Error('Only explicit owned-service CSP overrides are allowed')
}
}
}
+9 -2
View File
@@ -10,7 +10,9 @@
import { spawnSync } from 'node:child_process'
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { ACCEPTANCE_MODE, BUILD_MARKER, EXPORT_CLASSPATH, resolveSampleJar } from './acceptance-paths.mjs'
import { ACCEPTANCE_MODE, BUILD_MARKER, EXPORT_CLASSPATH, resolveSampleJar, SECURITY_BACKEND_URL, SECURITY_STANDALONE } from './acceptance-paths.mjs'
import { stageStandalone } from './acceptance-standalone.mjs'
const args = process.argv.slice(2)
const skipBuild = args.includes('--skip-build')
@@ -38,7 +40,12 @@ if (ACCEPTANCE_MODE === 'javalin') {
cpSync('out', path.join(EXPORT_CLASSPATH, 'next-dashboard'), { recursive: true, filter: (source) => !source.endsWith('mockServiceWorker.js') })
}
if (!skipBuild && ACCEPTANCE_MODE === 'standalone') {
const status = run('pnpm', ['build'], { QQQ_BACKEND_URL: backend, NEXT_PUBLIC_MOCK_API: 'false', NEXT_TELEMETRY_DISABLED: '1' })
// A second immutable build is required: Next bakes the rewrite destination at build time.
const securityStatus = run('pnpm', ['build'], { QQQ_NEXT_OUTPUT: 'standalone', QQQ_BACKEND_URL: SECURITY_BACKEND_URL, NEXT_PUBLIC_MOCK_API: 'false', NEXT_TELEMETRY_DISABLED: '1' })
if (securityStatus !== 0) process.exit(securityStatus)
stageStandalone(SECURITY_STANDALONE, SECURITY_BACKEND_URL)
rmSync('.next', { recursive: true, force: true })
const status = run('pnpm', ['build'], { QQQ_NEXT_OUTPUT: 'standalone', QQQ_BACKEND_URL: backend, NEXT_PUBLIC_MOCK_API: 'false', NEXT_TELEMETRY_DISABLED: '1' })
if (status !== 0) process.exit(status)
writeFileSync(BUILD_MARKER, backend + '\n')
}
+6 -1
View File
@@ -17,7 +17,7 @@
import { act, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { http, HttpResponse } from 'msw'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { QContextProvider } from '@/lib/context/q-context'
import { qInstance } from '@/mocks/fixtures/q-instance'
@@ -124,6 +124,11 @@ const greeting = {
}
describe('SlugPage process initialization', () => {
beforeAll(async () => {
// Keep cold screen compilation outside the metadata-readiness assertion deadline.
await import('@/components/process/ProcessRun')
})
beforeEach(() => {
vi.restoreAllMocks()
params.slug = greeting.name
+135 -13
View File
@@ -24,11 +24,16 @@ import { toast } from 'sonner'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { EsbCapabilities, EsbPermissions } from '@/types'
import { processInit } from '@/lib/api/processes'
import { processInit, processStatus } from '@/lib/api/processes'
import { orderEsb } from '@/mocks/fixtures/esb'
import { EsbQueueActions, EsbTriggerActions, destinationQueue, type EsbQueueRef } from './EsbActions'
import {
EsbQueueActions,
EsbTriggerActions,
destinationQueue,
type EsbQueueRef,
} from './EsbActions'
vi.mock('@/lib/api/processes', () => ({ processInit: vi.fn() }))
vi.mock('@/lib/api/processes', () => ({ processInit: vi.fn(), processStatus: vi.fn() }))
vi.mock('sonner', async (importOriginal) => ({
...(await importOriginal<typeof import('sonner')>()),
toast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
@@ -102,28 +107,44 @@ describe('EsbActions', () => {
it('needs esbOperate for pausing a queue and esbDelete for purging and deleting', () => {
const { unmount } = render(
<QueryClientProvider client={new QueryClient()}>
<EsbQueueActions queue={fulfillmentQueue()} permissions={{ canOperate: true, canDelete: false }} />
<EsbQueueActions
queue={fulfillmentQueue()}
permissions={{ canOperate: true, canDelete: false }}
/>
</QueryClientProvider>
)
expect(screen.getByRole('button', { name: 'Pause queue orderFulfillment' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Purge orderFulfillment' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Delete older messages in orderFulfillment' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Delete older messages in orderFulfillment' })
).not.toBeInTheDocument()
unmount()
renderWithClient(
<EsbQueueActions queue={fulfillmentQueue()} permissions={{ canOperate: false, canDelete: true }} />
<EsbQueueActions
queue={fulfillmentQueue()}
permissions={{ canOperate: false, canDelete: true }}
/>
)
expect(screen.queryByRole('button', { name: 'Pause queue orderFulfillment' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Pause queue orderFulfillment' })
).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Purge orderFulfillment' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Delete older messages in orderFulfillment' })).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Delete older messages in orderFulfillment' })
).toBeInTheDocument()
})
it('offers resume instead of pause for a paused queue', () => {
renderWithClient(
<EsbQueueActions queue={{ ...fulfillmentQueue(), paused: true }} permissions={ALL} />
)
expect(screen.getByRole('button', { name: 'Resume queue orderFulfillment' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Pause queue orderFulfillment' })).not.toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Resume queue orderFulfillment' })
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Pause queue orderFulfillment' })
).not.toBeInTheDocument()
})
it('offers pause for a running trigger and resume for a paused one', () => {
@@ -150,10 +171,29 @@ describe('EsbActions', () => {
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Done.'))
})
it('replays all dead letters with esbReplayDeadLetters', async () => {
it.each([1, null])('confirms replay-all with a safe count of %s', async (count) => {
const user = userEvent.setup()
renderWithClient(<EsbTriggerActions trigger={fulfillTrigger} permissions={ALL} />)
renderWithClient(
<EsbTriggerActions
trigger={{
...fulfillTrigger,
deadLetter: { ...fulfillTrigger.deadLetter, messageCount: count },
}}
permissions={ALL}
/>
)
await user.click(screen.getByRole('button', { name: 'Replay dead letters for Fulfill Order' }))
let dialog = await screen.findByRole('alertdialog')
expect(dialog).toHaveTextContent('orderFulfillment.dlq')
expect(dialog).toHaveTextContent(
count === null ? 'all dead letters (count unknown)' : '1 message'
)
expect(processInit).not.toHaveBeenCalled()
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }))
expect(processInit).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Replay dead letters for Fulfill Order' }))
dialog = await screen.findByRole('alertdialog')
await user.click(within(dialog).getByRole('button', { name: 'Replay dead letters' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbReplayDeadLetters', {
values: { triggerName: 'fulfillOrder.orderFulfillment', all: true },
@@ -188,7 +228,9 @@ describe('EsbActions', () => {
const user = userEvent.setup()
renderWithClient(<EsbQueueActions queue={fulfillmentQueue()} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Delete older messages in orderFulfillment' }))
await user.click(
screen.getByRole('button', { name: 'Delete older messages in orderFulfillment' })
)
const dialog = await screen.findByRole('alertdialog')
expect(dialog).toHaveTextContent('orderFulfillment')
expect(dialog).toHaveTextContent('7 messages')
@@ -227,6 +269,86 @@ describe('EsbActions', () => {
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Broker unavailable'))
})
it.each([
['Resume Cancel Order', 'esbResumeTrigger', 'cancelOrder.orderEvents'],
['Restart Fulfill Order', 'esbRestartTrigger', 'fulfillOrder.orderFulfillment'],
])('sends the exact trigger input for %s', async (label, processName, triggerName) => {
const user = userEvent.setup()
renderWithClient(
<EsbTriggerActions
trigger={triggerName === cancelTrigger.name ? cancelTrigger : fulfillTrigger}
permissions={ALL}
/>
)
await user.click(screen.getByRole('button', { name: label }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith(processName, { values: { triggerName } })
)
})
it('sends provider and broker queue when resuming delivery', async () => {
const user = userEvent.setup()
renderWithClient(
<EsbQueueActions queue={{ ...fulfillmentQueue(), paused: true }} permissions={ALL} />
)
await user.click(screen.getByRole('button', { name: 'Resume queue orderFulfillment' }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbResumeQueue', {
values: { providerName: 'artemis', brokerQueueName: 'orderFulfillment' },
})
)
})
it('hides replay for an empty dead-letter queue and pause when queue state is unknown', () => {
renderWithClient(
<>
<EsbTriggerActions
trigger={{
...fulfillTrigger,
deadLetter: { ...fulfillTrigger.deadLetter, messageCount: 0 },
}}
permissions={ALL}
/>
<EsbQueueActions queue={{ ...fulfillmentQueue(), paused: null }} permissions={ALL} />
</>
)
expect(screen.queryByRole('button', { name: /Replay/ })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: /Pause queue|Resume queue/ })
).not.toBeInTheDocument()
})
it.each(['COMPLETE', 'ERROR'] as const)(
'keeps controls pending and reports only the final async %s outcome',
async (type) => {
vi.mocked(processInit).mockResolvedValue({
type: 'JOB_STARTED',
processUUID: 'uuid',
jobUUID: 'job',
})
vi.mocked(processStatus).mockResolvedValue(
type === 'COMPLETE'
? { type, processUUID: 'uuid', values: { message: 'Restarted 2 consumers.', count: 2 } }
: { type, error: 'Restart failed.' }
)
const user = userEvent.setup()
renderWithClient(<EsbTriggerActions trigger={fulfillTrigger} permissions={ALL} />)
await user.click(screen.getByRole('button', { name: 'Restart Fulfill Order' }))
expect(screen.getByRole('button', { name: 'Restart Fulfill Order' })).toBeDisabled()
expect(toast.success).not.toHaveBeenCalled()
expect(toast.error).not.toHaveBeenCalled()
await waitFor(
() =>
expect(type === 'COMPLETE' ? toast.success : toast.error).toHaveBeenCalledWith(
type === 'COMPLETE' ? 'Restarted 2 consumers.' : 'Restart failed.'
),
{ timeout: 2500 }
)
expect(type === 'COMPLETE' ? toast.error : toast.success).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: 'Restart Fulfill Order' })).toBeEnabled()
}
)
it('treats a topic as having no broker queue', () => {
expect(destinationQueue(orderEsb.publications[0].destination)).toBeNull()
})
+42 -6
View File
@@ -78,7 +78,7 @@ export function deadLetterQueue(trigger: EsbTrigger): EsbQueueRef {
brokerQueueName: trigger.deadLetter.brokerName,
capabilities: trigger.destination.capabilities,
messageCount: trigger.deadLetter.messageCount,
paused: null,
paused: trigger.deadLetter.paused ?? null,
}
}
@@ -144,14 +144,19 @@ export function EsbTriggerActions({
* @returns A group of buttons.
*/
function TriggerButtons({ trigger }: { trigger: EsbTrigger }) {
const action = useEsbAction()
const [confirmReplay, setConfirmReplay] = useState(false)
const action = useEsbAction(() => setConfirmReplay(false))
const run = (processName: string, values: EsbActionValues = {}) =>
action.mutate({ processName, values: { triggerName: trigger.name, ...values } })
const paused = trigger.state === 'PAUSED'
const id = trigger.name
return (
<div className="flex flex-wrap gap-1" role="group" aria-label={`Actions for ${trigger.processLabel}`}>
<div
className="flex flex-wrap gap-1"
role="group"
aria-label={`Actions for ${trigger.processLabel}`}
>
{paused ? (
<ActionButton
label="Resume"
@@ -182,9 +187,25 @@ function TriggerButtons({ trigger }: { trigger: EsbTrigger }) {
ariaLabel={`Replay dead letters for ${trigger.processLabel}`}
qqqId={`button-esb-replay-dead-letters-${id}`}
disabled={action.isPending}
onClick={() => run('esbReplayDeadLetters', { all: true })}
onClick={() => setConfirmReplay(true)}
/>
)}
<EsbConfirmDialog
open={confirmReplay}
title="Replay dead letters"
confirmLabel="Replay dead letters"
destructive={false}
pending={action.isPending}
onCancel={() => setConfirmReplay(false)}
onConfirm={() => run('esbReplayDeadLetters', { all: true })}
>
Replay{' '}
{trigger.deadLetter.messageCount === null
? 'all dead letters (count unknown)'
: `all ${messageCountText(trigger.deadLetter.messageCount)}`}{' '}
from queue {trigger.deadLetter.brokerName} through {trigger.processLabel}? Successful
messages will be removed.
</EsbConfirmDialog>
</div>
)
}
@@ -196,14 +217,17 @@ function TriggerButtons({ trigger }: { trigger: EsbTrigger }) {
* @param props - Component props.
* @param props.queue - The broker queue.
* @param props.permissions - The current user's ESB permissions.
* @param props.onDone - Called after success to clear any browsed selection.
* @returns The buttons, or `null` when none is available.
*/
export function EsbQueueActions({
queue,
permissions,
onDone,
}: {
queue: EsbQueueRef
permissions: EsbPermissions
onDone?: () => void
}) {
const canPause = permissions.canOperate && queue.capabilities.pauseQueue && queue.paused !== null
const canPurge = permissions.canDelete && queue.capabilities.purge
@@ -215,6 +239,7 @@ export function EsbQueueActions({
canPause={canPause}
canPurge={canPurge}
canDeleteOlder={canDeleteOlder}
onDone={onDone}
/>
)
}
@@ -227,6 +252,7 @@ export function EsbQueueActions({
* @param props.canPause - Whether to offer pause or resume.
* @param props.canPurge - Whether to offer purge.
* @param props.canDeleteOlder - Whether to offer deleting messages older than a time.
* @param props.onDone - Called after an action succeeds.
* @returns A group of buttons.
*/
function QueueButtons({
@@ -234,11 +260,13 @@ function QueueButtons({
canPause,
canPurge,
canDeleteOlder,
onDone,
}: {
queue: EsbQueueRef
canPause: boolean
canPurge: boolean
canDeleteOlder: boolean
onDone?: () => void
}) {
const [dialog, setDialog] = useState<'purge' | 'deleteOlder' | null>(null)
const [olderThan, setOlderThan] = useState('')
@@ -247,7 +275,10 @@ function QueueButtons({
setDialog(null)
setOlderThan('')
}
const action = useEsbAction(close)
const action = useEsbAction(() => {
close()
onDone?.()
})
const target = { providerName: queue.providerName, brokerQueueName: queue.brokerQueueName }
const name = queue.brokerQueueName
const inQueue =
@@ -613,7 +644,12 @@ export function EsbConfirmDialog({
onCancel: () => void
}) {
return (
<AlertDialogPrimitive.Root open={open} onOpenChange={(isOpen) => { if (!isOpen) onCancel() }}>
<AlertDialogPrimitive.Root
open={open}
onOpenChange={(isOpen) => {
if (!isOpen) onCancel()
}}
>
<AlertDialogPrimitive.Portal>
<AlertDialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/50" />
<AlertDialogPrimitive.Content
+93 -5
View File
@@ -17,7 +17,7 @@
// Tests for browsing ESB messages and acting on selected ones
import React from 'react'
import { render, screen, waitFor, within } from '@testing-library/react'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { http, HttpResponse } from 'msw'
@@ -72,7 +72,7 @@ describe('EsbMessageList', () => {
})
})
it('lists a queue\'s messages with their event type and subject', async () => {
it("lists a queue's messages with their event type and subject", async () => {
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={NONE} />
)
@@ -80,12 +80,24 @@ describe('EsbMessageList', () => {
const rows = within(table).getAllByRole('row').slice(1)
expect(rows).toHaveLength(2)
expect(rows[0]).toHaveTextContent('ID:msg-1')
expect(rows[0]).toHaveTextContent('qqq.table.order.INSERT')
expect(rows[0]).toHaveTextContent('qqq.table.order.inserted')
expect(rows[0]).toHaveTextContent('1001')
expect(rows[1]).toHaveTextContent('ID:msg-2')
})
it('shows a dead letter\'s error and raw body when it is not a CloudEvent', async () => {
it('browses CloudEvents with the backend event type and source in both parsed and raw bodies', async () => {
renderWithClient(
<EsbMessageList source={QUEUE_SOURCE} queue={fulfillmentQueue()} permissions={NONE} />
)
const table = await screen.findByRole('table', { name: 'Messages' })
expect(table).toHaveTextContent('qqq.table.order.inserted')
for (const message of orderFulfillmentMessages.messages) {
expect(message.event?.source).toBe('qqq://demo/table/order')
expect(JSON.parse(message.rawBody)).toEqual(message.event)
}
})
it("shows a dead letter's error and raw body when it is not a CloudEvent", async () => {
renderWithClient(
<EsbMessageList
source={DEAD_LETTER_SOURCE}
@@ -166,7 +178,11 @@ describe('EsbMessageList', () => {
const dialog = await screen.findByRole('alertdialog')
const confirm = within(dialog).getByRole('button', { name: 'Move messages' })
expect(confirm).toBeDisabled()
await user.type(within(dialog).getByLabelText('Target queue'), 'orderFulfillment.hold')
await user.type(within(dialog).getByLabelText('Target queue'), ' ')
expect(confirm).toBeDisabled()
expect(processInit).not.toHaveBeenCalled()
await user.clear(within(dialog).getByLabelText('Target queue'))
await user.type(within(dialog).getByLabelText('Target queue'), ' orderFulfillment.hold ')
await user.click(confirm)
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith('esbMoveMessages', {
@@ -199,6 +215,78 @@ describe('EsbMessageList', () => {
)
})
it.each(['purge', 'deleteOlder'])('clears the selection after %s succeeds', async (operation) => {
const user = userEvent.setup()
renderWithClient(
<EsbMessageList
source={DEAD_LETTER_SOURCE}
queue={deadLetterQueue(fulfillTrigger)}
permissions={ALL}
/>
)
await user.click(await screen.findByRole('checkbox', { name: 'Select ID:dlq-1' }))
await user.click(
screen.getByRole('button', {
name:
operation === 'purge'
? 'Purge orderFulfillment.dlq'
: 'Delete older messages in orderFulfillment.dlq',
})
)
const dialog = await screen.findByRole('alertdialog')
if (operation === 'deleteOlder') {
fireEvent.change(within(dialog).getByLabelText('Older than'), {
target: { value: '2026-09-25T10:00' },
})
}
await user.click(
within(dialog).getByRole('button', {
name: operation === 'purge' ? 'Purge queue' : 'Delete messages',
})
)
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
await waitFor(() =>
expect(screen.getByRole('checkbox', { name: 'Select ID:dlq-1' })).not.toBeChecked()
)
expect(screen.getByRole('button', { name: 'Replay selected' })).toBeDisabled()
})
it('offers no selection when move and delete are unsupported even with permissions', async () => {
renderWithClient(
<EsbMessageList
source={QUEUE_SOURCE}
queue={{
...fulfillmentQueue(),
capabilities: { ...fulfillmentQueue().capabilities, move: false, deleteSelected: false },
}}
permissions={ALL}
/>
)
await screen.findByRole('table', { name: 'Messages' })
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /selected/ })).not.toBeInTheDocument()
})
it('retains selection and confirmation after a failed purge', async () => {
vi.mocked(processInit).mockResolvedValue({ type: 'ERROR', error: 'Purge refused.' })
const user = userEvent.setup()
renderWithClient(
<EsbMessageList
source={DEAD_LETTER_SOURCE}
queue={deadLetterQueue(fulfillTrigger)}
permissions={ALL}
/>
)
const checkbox = await screen.findByRole('checkbox', { name: 'Select ID:dlq-1' })
await user.click(checkbox)
await user.click(screen.getByRole('button', { name: 'Purge orderFulfillment.dlq' }))
const dialog = await screen.findByRole('alertdialog')
await user.click(within(dialog).getByRole('button', { name: 'Purge queue' }))
await waitFor(() => expect(processInit).toHaveBeenCalled())
expect(dialog).toBeInTheDocument()
expect(checkbox).toBeChecked()
})
it('opens the list in a dialog from the browse button', async () => {
const user = userEvent.setup()
renderWithClient(
+19 -6
View File
@@ -41,6 +41,7 @@ import {
/** What to browse: the queue behind a destination, or a trigger's dead letters. */
export type EsbMessageSource =
| { kind: 'destination'; name: string }
| { kind: 'subscription'; name: string; triggerName: string }
| { kind: 'deadLetters'; triggerName: string }
/** Props for {@link EsbMessageList}. */
@@ -70,11 +71,19 @@ export function EsbMessageList({ source, queue, permissions }: EsbMessageListPro
const selectable = available.replay || available.move || available.delete
const { data, isLoading, error } = useQuery({
queryKey: queryKeys.esbMessages(source.kind, name, offset),
queryKey:
source.kind === 'subscription'
? [...queryKeys.esbMessages('destination', source.name, offset), source.triggerName]
: queryKeys.esbMessages(source.kind, name, offset),
queryFn: () =>
source.kind === 'destination'
? getEsbMessages(source.name, offset)
: getEsbDeadLetters(source.triggerName, offset),
source.kind === 'deadLetters'
? getEsbDeadLetters(source.triggerName, offset)
: getEsbMessages(
source.name,
offset,
ESB_PAGE_SIZE,
source.kind === 'subscription' ? source.triggerName : undefined
),
meta: HANDLES_OWN_ERRORS,
})
@@ -84,12 +93,16 @@ export function EsbMessageList({ source, queue, permissions }: EsbMessageListPro
}
const toggle = (messageId: string) =>
setSelected((current) =>
current.includes(messageId) ? current.filter((id) => id !== messageId) : [...current, messageId]
current.includes(messageId)
? current.filter((id) => id !== messageId)
: [...current, messageId]
)
return (
<div className="space-y-3" data-qqq-id={`esb-message-list-${name}`}>
{source.kind === 'deadLetters' && <EsbQueueActions queue={queue} permissions={permissions} />}
{source.kind !== 'destination' && (
<EsbQueueActions queue={queue} permissions={permissions} onDone={() => setSelected([])} />
)}
{selectable && (
<EsbSelectionActions
queue={queue}
+217 -10
View File
@@ -17,12 +17,18 @@
// Tests for the table Developer-view ESB section
import React from 'react'
import { act, render, screen, within } from '@testing-library/react'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
import { server } from '@/mocks/node'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { axe } from 'jest-axe'
import { describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { processInit } from '@/lib/api/processes'
import { fulfillOrderEsb, orderEsb } from '@/mocks/fixtures/esb'
vi.mock('@/lib/api/processes', () => ({ processInit: vi.fn(), processStatus: vi.fn() }))
import { fulfillOrderEsb, orderEsb, orderFulfillmentMessages } from '@/mocks/fixtures/esb'
import { EsbSection } from './EsbSection'
/**
@@ -47,6 +53,201 @@ function bodyRows(name: string): HTMLElement[] {
}
describe('EsbSection', () => {
beforeEach(() => {
vi.mocked(processInit).mockReset()
vi.mocked(processInit).mockResolvedValue({
type: 'COMPLETE',
processUUID: 'queue-run',
values: { message: 'Done.' },
})
})
it.each([
['subscription', false],
['subscription', true],
['subscription', null],
['subscription', undefined],
['deadLetter', false],
['deadLetter', true],
['deadLetter', null],
['deadLetter', undefined],
] as const)('uses %s paused=%s for broker queue controls', async (kind, paused) => {
const user = userEvent.setup()
const original = orderEsb.subscribers[kind === 'subscription' ? 1 : 0]
const brokerName = 'serialized.custom.queue'
const brokerQueue = { brokerName, messageCount: 9, ...(paused === undefined ? {} : { paused }) }
const trigger = { ...original, [kind]: brokerQueue }
render(
<QueryClientProvider
client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
>
<EsbSection
data={{
...orderEsb,
publications: [],
subscribers: [trigger],
permissions: { canOperate: true, canDelete: true },
}}
/>
</QueryClientProvider>
)
if (kind === 'deadLetter') {
await user.click(
screen.getByRole('button', { name: `Browse dead letters for ${trigger.processLabel}` })
)
await screen.findByRole('dialog')
}
if (paused == null) {
expect(
screen.queryByRole('button', { name: `Pause queue ${brokerName}` })
).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: `Resume queue ${brokerName}` })
).not.toBeInTheDocument()
expect(processInit).not.toHaveBeenCalled()
} else {
const action = paused ? 'Resume' : 'Pause'
expect(
screen.queryByRole('button', { name: `${paused ? 'Pause' : 'Resume'} queue ${brokerName}` })
).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: `${action} queue ${brokerName}` }))
await waitFor(() =>
expect(processInit).toHaveBeenCalledWith(paused ? 'esbResumeQueue' : 'esbPauseQueue', {
values: { providerName: 'artemis', brokerQueueName: brokerName },
})
)
}
})
it.each([
['subscription', 'permission'],
['subscription', 'capability'],
['deadLetter', 'permission'],
['deadLetter', 'capability'],
] as const)(
'hides %s pause/resume without %s even when state is known',
async (kind, missing) => {
const user = userEvent.setup()
const original = orderEsb.subscribers[kind === 'subscription' ? 1 : 0]
const brokerName = 'restricted.queue'
const trigger = {
...original,
[kind]: { brokerName, messageCount: 9, paused: false },
destination: {
...original.destination,
capabilities: {
...original.destination.capabilities,
pauseQueue: missing !== 'capability',
},
},
}
render(
<QueryClientProvider client={new QueryClient()}>
<EsbSection
data={{
...orderEsb,
publications: [],
subscribers: [trigger],
permissions: { canOperate: missing !== 'permission', canDelete: true },
}}
/>
</QueryClientProvider>
)
if (kind === 'deadLetter') {
await user.click(
screen.getByRole('button', { name: `Browse dead letters for ${trigger.processLabel}` })
)
await screen.findByRole('dialog')
}
expect(
screen.queryByRole('button', { name: `Pause queue ${brokerName}` })
).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: `Resume queue ${brokerName}` })
).not.toBeInTheDocument()
expect(processInit).not.toHaveBeenCalled()
}
)
it('uses the serialized subscription name for controls and trigger for browsing', async () => {
let requestedTrigger: string | null = null
server.use(
http.get('/qqq/v1/esb/messages/orderEvents', ({ request }) => {
requestedTrigger = new URL(request.url).searchParams.get('trigger')
return HttpResponse.json(orderFulfillmentMessages)
})
)
const user = userEvent.setup()
render(
<QueryClientProvider
client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
>
<EsbSection
data={{
...orderEsb,
subscribers: [
{
...orderEsb.subscribers[1],
subscription: { brokerName: 'custom.subscription.queue', messageCount: 9 },
},
],
permissions: { canOperate: true, canDelete: true },
}}
/>
</QueryClientProvider>
)
expect(screen.getByText('custom.subscription.queue')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Purge custom.subscription.queue' })
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'Pause queue custom.subscription.queue' })
).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Browse subscription for Cancel Order' }))
const dialog = await screen.findByRole('dialog', {
name: 'Messages in custom.subscription.queue',
})
await within(dialog).findByRole('table', { name: 'Messages' })
await waitFor(() => expect(requestedTrigger).toBe('cancelOrder.orderEvents'))
expect(
within(dialog).queryByRole('button', { name: 'Replay selected' })
).not.toBeInTheDocument()
})
it('hides browsing and broker controls when the trigger destination has no capabilities', () => {
const trigger = orderEsb.subscribers[1]
render(
<QueryClientProvider client={new QueryClient()}>
<EsbSection
data={{
...orderEsb,
publications: [],
subscribers: [
{
...trigger,
destination: {
...trigger.destination,
capabilities: {
browse: false,
pauseQueue: false,
purge: false,
deleteSelected: false,
deleteOlderThan: false,
move: false,
},
},
},
],
permissions: { canOperate: true, canDelete: true },
}}
/>
</QueryClientProvider>
)
expect(screen.queryByRole('button', { name: /Browse/ })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Purge/ })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Resume Cancel Order' })).toBeInTheDocument()
})
it('renders nothing when the table has no ESB section', () => {
const { container } = render(<EsbSection data={null} />)
expect(container).toBeEmptyDOMElement()
@@ -88,7 +289,7 @@ describe('EsbSection', () => {
const fulfillCells = within(fulfill).getAllByRole('cell')
expect(within(fulfillCells[0]).getByRole('link', { name: 'Fulfill Order' })).toHaveAttribute(
'href',
'/app/fulfillOrder'
'/app/fulfillOrder/dev'
)
expect(fulfillCells[0]).toHaveTextContent('Single, concurrency 2, 3 attempts')
expect(fulfillCells[1]).toHaveTextContent('orderFulfillment')
@@ -107,7 +308,7 @@ describe('EsbSection', () => {
const cancelCells = within(cancel).getAllByRole('cell')
expect(within(cancelCells[0]).getByRole('link', { name: 'Cancel Order' })).toHaveAttribute(
'href',
'/app/cancelOrder'
'/app/cancelOrder/dev'
)
expect(cancelCells[1]).toHaveTextContent('orderEvents')
expect(cancelCells[2]).toHaveTextContent('Paused')
@@ -124,11 +325,13 @@ describe('EsbSection', () => {
).toBeInTheDocument()
})
it('offers browsing a queue and a trigger\'s dead letters to anyone who sees them', () => {
it("offers browsing a queue and a trigger's dead letters to anyone who sees them", () => {
render(<EsbSection data={orderEsb} />)
const [topic, queue] = bodyRows('Publications')
expect(within(topic).queryByRole('button')).not.toBeInTheDocument()
expect(within(queue).getByRole('button', { name: 'Browse orderFulfillment' })).toBeInTheDocument()
expect(
within(queue).getByRole('button', { name: 'Browse orderFulfillment' })
).toBeInTheDocument()
expect(within(queue).queryByRole('button', { name: /^Purge/ })).not.toBeInTheDocument()
const [fulfill] = bodyRows('Subscribers')
expect(
@@ -145,7 +348,9 @@ describe('EsbSection', () => {
)
const [topic, queue] = bodyRows('Publications')
expect(within(topic).queryByRole('button')).not.toBeInTheDocument()
expect(within(queue).getByRole('button', { name: 'Purge orderFulfillment' })).toBeInTheDocument()
expect(
within(queue).getByRole('button', { name: 'Purge orderFulfillment' })
).toBeInTheDocument()
expect(
within(queue).getByRole('button', { name: 'Pause queue orderFulfillment' })
).toBeInTheDocument()
@@ -154,7 +359,7 @@ describe('EsbSection', () => {
expect(within(cancel).getByRole('button', { name: 'Resume Cancel Order' })).toBeInTheDocument()
})
it('renders a process\'s publications and the triggers that start it', () => {
it("renders a process's publications and the triggers that start it", () => {
render(<EsbSection data={fulfillOrderEsb} />)
expect(bodyRows('Publications')).toHaveLength(1)
expect(bodyRows('Triggers')).toHaveLength(1)
@@ -163,7 +368,9 @@ describe('EsbSection', () => {
it('says so when a process has no publications or triggers', () => {
render(<EsbSection data={{ ...fulfillOrderEsb, publications: [], triggers: [] }} />)
expect(screen.getByText('This process does not publish to any destination.')).toBeInTheDocument()
expect(
screen.getByText('This process does not publish to any destination.')
).toBeInTheDocument()
expect(screen.getByText('No destinations trigger this process.')).toBeInTheDocument()
})
+45 -11
View File
@@ -25,7 +25,7 @@ import Link from 'next/link'
import type { EsbPermissions, EsbTrigger, EsbTriggerMode, EsbTriggerState } from '@/types'
import { CHIP_COLOR_CLASSES, type ChipColor } from '@/lib/utils/adornment-utils'
import { cn } from '@/lib/utils/cn'
import { EsbTriggerActions, deadLetterQueue } from './EsbActions'
import { EsbTriggerActions, EsbQueueActions, deadLetterQueue, type EsbQueueRef } from './EsbActions'
import { EsbCounters } from './EsbCounters'
import { EsbBrowseButton } from './EsbMessageList'
@@ -59,6 +59,15 @@ export function EsbTriggerRow({
trigger: EsbTrigger
permissions: EsbPermissions
}) {
const subscription: EsbQueueRef | null = trigger.subscription
? {
providerName: trigger.destination.provider,
brokerQueueName: trigger.subscription.brokerName,
capabilities: trigger.destination.capabilities,
messageCount: trigger.subscription.messageCount,
paused: trigger.subscription.paused ?? null,
}
: null
const state = STATES[trigger.state] ?? { label: trigger.state, color: 'default' }
const attempts = `${trigger.maxAttempts} ${trigger.maxAttempts === 1 ? 'attempt' : 'attempts'}`
@@ -69,7 +78,7 @@ export function EsbTriggerRow({
>
<td className="px-2 py-2">
<Link
href={`/app/${encodeURIComponent(trigger.processName)}`}
href={`/app/${encodeURIComponent(trigger.processName)}/dev`}
className="font-medium text-primary underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-ring"
>
{trigger.processLabel}
@@ -78,7 +87,11 @@ export function EsbTriggerRow({
{MODES[trigger.mode] ?? trigger.mode}, concurrency {trigger.concurrency}, {attempts}
</p>
</td>
<td className="px-2 py-2 font-mono text-xs text-foreground">{trigger.destination.name}</td>
<td className="px-2 py-2 font-mono text-xs text-foreground">
{trigger.destination.name}
{subscription && <p className="text-muted-foreground">{subscription.brokerQueueName}</p>}
{subscription && <p>Subscription depth: {subscription.messageCount ?? '—'}</p>}
</td>
<td className="px-2 py-2">
<span
className={cn(
@@ -97,14 +110,35 @@ export function EsbTriggerRow({
</td>
<td className="space-y-1 px-2 py-2">
<EsbTriggerActions trigger={trigger} permissions={permissions} />
<EsbBrowseButton
label="Browse dead letters"
ariaLabel={`Browse dead letters for ${trigger.processLabel}`}
title={`Dead letters for ${trigger.processLabel}`}
source={{ kind: 'deadLetters', triggerName: trigger.name }}
queue={deadLetterQueue(trigger)}
permissions={permissions}
/>
{subscription && (
<>
{subscription.capabilities.browse && (
<EsbBrowseButton
label="Browse subscription"
ariaLabel={`Browse subscription for ${trigger.processLabel}`}
title={`Messages in ${subscription.brokerQueueName}`}
source={{
kind: 'subscription',
name: trigger.destination.name,
triggerName: trigger.name,
}}
queue={subscription}
permissions={permissions}
/>
)}
<EsbQueueActions queue={subscription} permissions={permissions} />
</>
)}
{trigger.destination.capabilities.browse && (
<EsbBrowseButton
label="Browse dead letters"
ariaLabel={`Browse dead letters for ${trigger.processLabel}`}
title={`Dead letters for ${trigger.processLabel}`}
source={{ kind: 'deadLetters', triggerName: trigger.name }}
queue={deadLetterQueue(trigger)}
permissions={permissions}
/>
)}
</td>
</tr>
)
+22 -1
View File
@@ -16,7 +16,7 @@
import React, { useState } from 'react'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { act, render, screen, waitFor } from '@testing-library/react'
import { userEvent } from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -111,6 +111,27 @@ describe('SearchDialog keyboard access', () => {
}
})
it('does not steal focus after the user reaches another dialog control before autofocus', async () => {
let autofocus: FrameRequestCallback | undefined
const request = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
autofocus = callback
return 42
})
try {
const user = userEvent.setup()
render(<Harness />)
await user.click(screen.getByRole('button', { name: 'Open search' }))
await user.type(screen.getByRole('combobox'), 'no matches')
await user.tab()
const clear = screen.getByRole('button', { name: 'Clear search' })
expect(clear).toHaveFocus()
act(() => autofocus?.(0))
expect(clear).toHaveFocus()
} finally {
request.mockRestore()
}
})
it('returns focus after Escape from the input and can reopen', async () => {
const user = userEvent.setup()
render(<Harness />)
+3 -1
View File
@@ -81,7 +81,9 @@ export function SearchDialog({ open, onClose, navTargets, searchTables = NO_SEAR
setRecentRecords(getRecentRecords().slice(0, 10))
setSearchTerm('')
setSelectedIndex(-1)
const frame = requestAnimationFrame(() => inputRef.current?.focus())
const frame = requestAnimationFrame(() => {
if (!dialogRef.current?.contains(document.activeElement)) inputRef.current?.focus()
})
return () => {
cancelAnimationFrame(frame)
if (returnTo instanceof HTMLElement && returnTo.isConnected) returnTo.focus()
@@ -18,7 +18,7 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { act, render, screen, waitFor } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { userEvent } from '@testing-library/user-event'
import { useForm } from 'react-hook-form'
@@ -88,6 +88,25 @@ beforeEach(() => {
mockFetchStandalone.mockResolvedValue(OPTIONS)
})
describe('PossibleValueSelect — pointer selection', () => {
it('keeps search focus while pressing an option until its click selects the value', async () => {
const user = userEvent.setup()
render(<Wrapper />)
await user.click(screen.getByRole('combobox', { name: 'Person' }))
const search = screen.getByRole('textbox', { name: 'Search Person options' })
await waitFor(() => expect(search).toHaveFocus())
const option = await screen.findByRole('option', { name: 'Bob' })
await user.pointer({ target: option, keys: '[MouseLeft>]' })
expect(search).toHaveFocus()
await user.pointer({ target: option, keys: '[/MouseLeft]' })
expect(screen.getByRole('combobox', { name: 'Person' })).toHaveTextContent('Bob')
expect(screen.getByRole('combobox', { name: 'Person' })).toHaveFocus()
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
})
})
describe('PossibleValueSelect — initial value label', () => {
it('looks up and shows the label of a value it did not select (e.g. after process Back)', async () => {
mockFetchProcess.mockResolvedValue([{ id: 2, label: 'Bob' }])
@@ -397,6 +416,38 @@ describe('PossibleValueSelect — option selection', () => {
})
describe('PossibleValueSelect — search', () => {
it.each(['loaded', 'in flight'])('offers only the current search results when the prior request is %s', async (prior) => {
const user = userEvent.setup()
let finishPrior!: (values: QPossibleValue[]) => void
let finishSearch!: (values: QPossibleValue[]) => void
mockFetchTable.mockReset()
.mockImplementationOnce(() => new Promise((resolve) => { finishPrior = resolve }))
.mockImplementationOnce(() => new Promise((resolve) => { finishSearch = resolve }))
render(<Wrapper />)
await user.click(screen.getByRole('combobox', { name: 'Person' }))
const search = screen.getByRole('textbox', { name: 'Search Person options' })
if (prior === 'loaded') await act(async () => finishPrior(OPTIONS))
vi.useFakeTimers()
try {
fireEvent.change(search, { target: { value: 'Bo' } })
if (prior === 'in flight') await act(async () => finishPrior(OPTIONS))
// Old options must not be clickable while a new search is debouncing:
// starting its request would remove the option between pointer down/up.
expect(screen.queryAllByRole('option')).toEqual([])
fireEvent.keyDown(search, { key: 'Enter' })
expect(screen.getByRole('combobox', { name: 'Person' })).toHaveTextContent('-- Select Person --')
await act(async () => vi.advanceTimersByTimeAsync(300))
expect(mockFetchTable).toHaveBeenLastCalledWith('person', 'person', { searchTerm: 'Bo', formValues: { testField: null } })
await act(async () => finishSearch([OPTIONS[1]]))
fireEvent.click(screen.getByRole('option', { name: 'Bob' }))
expect(screen.getByRole('combobox', { name: 'Person' })).toHaveTextContent('Bob')
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
} finally {
vi.useRealTimers()
}
})
it('renders a search input when the dropdown is open', async () => {
const user = userEvent.setup()
render(<Wrapper />)
@@ -204,6 +204,10 @@ export function PossibleValueSelect({
const debouncedFetch = useCallback(
(term: string) => {
if (debounceRef.current) clearTimeout(debounceRef.current)
// Old results must not remain selectable until the debounce removes them mid-click.
requestSequence.current += 1
setOptions([])
setIsLoading(true)
debounceRef.current = setTimeout(() => fetchOptions(term), 300)
},
[fetchOptions]
@@ -480,6 +484,9 @@ export function PossibleValueSelect({
id={`${id}-option-${index}`}
role="option"
aria-selected={isSelected}
// Keep search focus until click: WebKit can scroll on blur
// between mousedown and mouseup, moving the option away.
onMouseDown={(event) => event.preventDefault()}
onClick={() => handleSelect(option)}
className={cn(
'flex cursor-pointer items-center justify-between px-3 py-2 text-sm',
+8 -1
View File
@@ -72,12 +72,19 @@ const itemClass = cn(
* @returns The menu.
*/
export function ColumnHeaderMenu({ column, sort, pinned, hasRows, onSort, onFilter, onHide, onPin, onCopyPageValues, onCopyFullQueryValues, onColumnStats }: ColumnHeaderMenuProps) {
const [open, setOpen] = React.useState(false)
const triggerRef = React.useRef<HTMLButtonElement>(null)
const noRows = hasRows ? undefined : 'There are no rows to copy from'
const id = (action: string) => `column-menu-${action}`
return (
<DropdownMenuPrimitive.Root modal={false}>
<DropdownMenuPrimitive.Root modal={false} open={open} onOpenChange={(nextOpen) => {
// Focus survives scrolling; restore the reference before Radix measures its menu.
if (nextOpen) triggerRef.current?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
setOpen(nextOpen)
}}>
<DropdownMenuPrimitive.Trigger asChild>
<button
ref={triggerRef}
type="button"
onClick={(e) => e.stopPropagation()}
className="shrink-0 rounded p-0.5 text-muted-foreground opacity-60 hover:text-foreground hover:opacity-100 focus:opacity-100 focus:outline-none focus:ring-1 focus:ring-ring group-hover:opacity-100 data-[state=open]:opacity-100 pointer-coarse:opacity-100"
+93 -6
View File
@@ -16,18 +16,19 @@
import React from 'react'
import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type { QRecord, QTableMetaData } from '@/types'
import { DataGrid } from './DataGrid'
const cellRenders = vi.fn()
vi.mock('./DataCell', () => ({
DataCell: ({ value }: { value: unknown }) => {
vi.mock('./DataCell', async (importOriginal) => {
const actual = await importOriginal<typeof import('./DataCell')>()
return { DataCell: (props: React.ComponentProps<typeof actual.DataCell>) => {
cellRenders()
return <span>{String(value ?? '')}</span>
},
}))
return <actual.DataCell {...props} />
} }
})
const router = { push: vi.fn() }
vi.mock('next/navigation', () => ({ useRouter: () => router }))
@@ -137,3 +138,89 @@ describe('DataGrid compact headers (QRun-IO/qqq#728)', () => {
expect(screen.getByRole('button', { name: 'Column statistics for Name' })).toBeInTheDocument()
})
})
describe('DataGrid stable headers (QRun-IO/qqq#994)', () => {
const scrollIntoView = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollIntoView')
beforeAll(() => Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }))
afterAll(() => {
if (scrollIntoView) Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', scrollIntoView)
else Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView')
})
const menu = () => ({ onHide: vi.fn(), onPin: vi.fn(), onCopyPageValues: vi.fn(), onCopyFullQueryValues: vi.fn() })
it('retains a focused menu trigger across nonstructural preview updates', () => {
const { rerender } = render(grid({ columnMenu: menu() }))
const trigger = screen.getByRole('button', { name: 'Name column menu' })
trigger.focus()
rerender(grid({ columnMenu: menu(), isFetching: true }))
expect(screen.getByRole('button', { name: 'Name column menu' })).toBe(trigger)
expect(trigger).toHaveFocus()
})
it('keeps the same header while updating metadata, sort and menu callbacks', () => {
const initialMenu = menu()
const updatedMenu = menu()
const onSortChange = vi.fn()
const { rerender } = render(grid({ columnMenu: initialMenu }))
const trigger = screen.getByRole('button', { name: 'Name column menu' })
const tableMetaData = { ...TABLE, fields: { ...TABLE.fields, name: { ...TABLE.fields.name, label: 'Current name' } } }
rerender(grid({ tableMetaData, columnMenu: updatedMenu, sortOrder: [{ fieldName: 'name', isAscending: true }], onSortChange }))
expect(screen.getByRole('button', { name: 'Current name column menu' })).toBe(trigger)
fireEvent.click(screen.getByRole('button', { name: 'Sort by Current name' }))
expect(onSortChange).toHaveBeenCalledWith([{ fieldName: 'name', isAscending: false }])
fireEvent.keyDown(trigger, { key: 'Enter' })
fireEvent.click(screen.getByRole('menuitem', { name: 'Copy page values' }))
expect(updatedMenu.onCopyPageValues).toHaveBeenCalledWith('name')
expect(initialMenu.onCopyPageValues).not.toHaveBeenCalled()
})
it('retains the selection header and updates its current selection handler', () => {
const onRowSelectionChange = vi.fn()
const { rerender } = render(grid())
const checkbox = screen.getByRole('checkbox', { name: 'Select all rows on this page' })
checkbox.focus()
rerender(grid({ rowSelection: { 1: true, 2: true, 3: true }, onRowSelectionChange }))
expect(screen.getByRole('checkbox', { name: 'Select all rows on this page' })).toBe(checkbox)
expect(checkbox).toHaveFocus()
expect(checkbox).toBeChecked()
fireEvent.click(checkbox)
expect(onRowSelectionChange).toHaveBeenCalledWith({})
})
})
describe('DataGrid stable cells (QRun-IO/qqq#995)', () => {
const menu = () => ({ onHide: vi.fn(), onPin: vi.fn(), onCopyPageValues: vi.fn(), onCopyFullQueryValues: vi.fn() })
it('retains the focused selection checkbox and uses current selection callbacks', () => {
const initialHandler = vi.fn()
const currentHandler = vi.fn()
const { rerender } = render(grid({ columnMenu: menu(), onRowSelectionChange: initialHandler }))
const checkbox = screen.getAllByRole('checkbox', { name: 'Select record' })[0]
checkbox.focus()
rerender(grid({ columnMenu: menu(), rowSelection: { 1: true }, onRowSelectionChange: currentHandler }))
expect(screen.getAllByRole('checkbox', { name: 'Select record' })[0]).toBe(checkbox)
expect(checkbox).toHaveFocus()
expect(checkbox).toBeChecked()
fireEvent.click(checkbox)
expect(currentHandler).toHaveBeenCalledWith({})
expect(initialHandler).not.toHaveBeenCalled()
})
it('retains revealed cell state and focus while using updated field values', () => {
const tableMetaData = { ...TABLE, fields: { ...TABLE.fields, name: { ...TABLE.fields.name, adornments: [{ type: 'REVEAL' }] } } } as QTableMetaData
const { rerender } = render(grid({ tableMetaData, columnMenu: menu() }))
const reveal = screen.getAllByRole('button', { name: 'Reveal name' })[0]
reveal.focus()
fireEvent.click(reveal)
expect(reveal).toHaveAccessibleName('Hide name')
expect(reveal).toHaveTextContent('Ada')
rerender(grid({ tableMetaData, columnMenu: menu(), isFetching: true }))
expect(screen.getAllByRole('button', { name: 'Hide name' })[0]).toBe(reveal)
expect(reveal).toHaveFocus()
rerender(grid({ tableMetaData, columnMenu: menu(), records: [record(1, 'Current value'), ...RECORDS.slice(1)] }))
expect(reveal).toHaveTextContent('Current value')
expect(reveal).toHaveAccessibleName('Hide name')
})
})
+10 -3
View File
@@ -26,7 +26,6 @@ import React, { useMemo, useRef, useCallback, useEffect, useLayoutEffect, useSta
import {
useReactTable,
getCoreRowModel,
flexRender,
type ColumnDef,
type Row,
type SortingState,
@@ -818,9 +817,13 @@ export function DataGrid({
style={{ width: `${header.getSize()}px`, ...(pinned?.style ?? {}) }}
aria-sort={ariaSortValue}
>
{/* These locally defined headers are pure render callbacks. Calling them
preserves their child identity when current props rebuild the columns. */}
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
: typeof header.column.columnDef.header === 'function'
? header.column.columnDef.header(header.getContext())
: header.column.columnDef.header}
{/* Column resize handle */}
{!isSelectCol && (() => {
@@ -998,7 +1001,11 @@ const GridRow = React.memo(function GridRow({ row, isSelected, rowClass, cellCla
onCellKeyDown(e)
}}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
{/* Local pure render callbacks must not become new component types when
current grid props rebuild columns: retain focused and stateful children. */}
{typeof cell.column.columnDef.cell === 'function'
? cell.column.columnDef.cell(cell.getContext())
: cell.column.columnDef.cell}
</td>
)
})}
+5 -5
View File
@@ -414,7 +414,6 @@ function RecordViewContent({
}) {
const searchParams = useSearchParams()
const pathname = usePathname()
const router = useRouter()
const { preferences } = useUserPreferences()
// Persist tab and view mode in URL so back navigation restores state
@@ -441,15 +440,16 @@ function RecordViewContent({
* @param defaultValue - The "default" value; when matched the key is removed.
*/
const updateUrlParam = useCallback((key: string, value: string, defaultValue: string) => {
const params = new URLSearchParams(searchParams.toString())
const url = new URL(window.location.href)
const params = url.searchParams
if (value === defaultValue) {
params.delete(key)
} else {
params.set(key, value)
}
const qs = params.toString()
router.replace(`${pathname}${qs ? `?${qs}` : ''}`, { scroll: false })
}, [searchParams, pathname, router])
// Make URL state durable before another click, reload, or departure, without an RSC navigation.
window.history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`)
}, [])
/**
* Switches the active tab by updating the `tab` URL parameter.
@@ -99,6 +99,42 @@ describe('script code completions', () => {
expect(editor).toHaveValue('api.qu')
})
it('keeps current suggestions when a delayed scroll event reports their existing position', async () => {
const user = userEvent.setup()
render(<Editor initial={'const result = api.query("person");'} />)
const editor = screen.getByRole('textbox', { name: 'Code' }) as HTMLTextAreaElement
await user.click(editor)
editor.scrollLeft = 4
fireEvent.scroll(editor)
editor.scrollLeft = 0
fireEvent.change(editor, { target: { value: 'api.bu' } })
editor.setSelectionRange(6, 6)
await user.keyboard('{Control>} {/Control}{ArrowDown}')
expect(screen.getAllByRole('option')).toHaveLength(3)
fireEvent.scroll(editor)
expect(screen.getAllByRole('option')).toHaveLength(3)
expect(screen.getByRole('option', { name: /api.bulkUpdate/ })).toHaveAttribute('aria-selected', 'true')
await user.keyboard('{Tab}')
expect(editor).toHaveValue('api.bulkUpdate(')
expect(editor).toHaveFocus()
})
it.each(['scrollLeft', 'scrollTop'] as const)('dismisses suggestions when %s changes after they open', async (direction) => {
const user = userEvent.setup()
render(<Editor />)
const editor = screen.getByRole('textbox', { name: 'Code' }) as HTMLTextAreaElement
await user.type(editor, 'api.bu')
expect(screen.getAllByRole('option')).toHaveLength(3)
editor[direction] = 4
fireEvent.scroll(editor)
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
expect(editor).toHaveValue('api.bu')
})
it.each([[0, 0], [0, 6]])('rejects a stale suggestion after selection changes to %s–%s', async (start, end) => {
const user = userEvent.setup()
render(<Editor />)
+7 -3
View File
@@ -174,7 +174,7 @@ export function CodeEditor({
}: CodeEditorProps) {
const movesFocus = useSyncExternalStore(subscribeTabMode, readTabMode, readServerTabMode)
const [released, setReleased] = useState(false)
const [completion, setCompletion] = useState<(CodeCompletionMatch & { selected: number; top: number; left: number; height: number; caret: number; source: string }) | null>(null)
const [completion, setCompletion] = useState<(CodeCompletionMatch & { selected: number; top: number; left: number; height: number; caret: number; source: string; scrollTop: number; scrollLeft: number }) | null>(null)
const composing = useRef(false)
const metricsRef = useRef<HTMLSpanElement>(null)
const listRef = useRef<HTMLDivElement>(null)
@@ -211,7 +211,7 @@ export function CodeEditor({
const top = caretTop + lineHeight + height <= textarea.clientHeight ? caretTop + lineHeight : Math.max(0, caretTop - height)
const column = before.at(-1)!.replace(/\t/g, ' ').length
const left = Math.min(Math.max(0, 12 + column * characterWidth - textarea.scrollLeft), Math.max(0, textarea.clientWidth - 320))
setCompletion({ ...match, selected: 0, top, left, height, caret: textarea.selectionStart, source: textarea.value })
setCompletion({ ...match, selected: 0, top, left, height, caret: textarea.selectionStart, source: textarea.value, scrollTop: textarea.scrollTop, scrollLeft: textarea.scrollLeft })
}
/**
@@ -382,7 +382,11 @@ export function CodeEditor({
value={value}
onChange={(event) => { onChange?.(event.target.value); suggest(event.currentTarget) }}
onKeyDown={handleKeyDown}
onScroll={() => { syncScroll(); setCompletion(null) }}
onScroll={(event) => {
syncScroll()
// A deferred browser event can report the position already used to place suggestions.
if (shown && (shown.scrollTop !== event.currentTarget.scrollTop || shown.scrollLeft !== event.currentTarget.scrollLeft)) setCompletion(null)
}}
onClick={() => setCompletion(null)}
onCompositionStart={() => { composing.current = true; setCompletion(null) }}
onCompositionEnd={(event) => { composing.current = false; suggest(event.currentTarget) }}
+102 -1
View File
@@ -18,7 +18,7 @@
import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -30,6 +30,7 @@ vi.mock('@/lib/api/widgets', async (importOriginal) => {
import type { QWidgetMetaData, WidgetData } from '@/types'
import { fetchWidgetData, WidgetRequestError } from '@/lib/api/widgets'
import { ConnectedWidget, SeededWidget } from './ConnectedWidget'
import * as widgetUtils from './widget-utils'
const fetchMock = vi.mocked(fetchWidgetData)
@@ -69,6 +70,106 @@ describe('ConnectedWidget', () => {
fetchMock.mockImplementation(async (_name, params) => controlsPayload(params))
})
it('hydrates backend date and choice defaults without persisting caller defaults', async () => {
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', '2026-01-15'],
}))
renderWidget({ ...controls, storeDropdownSelections: false })
const day = await screen.findByLabelText('Select Day')
await waitFor(() => expect(day).toHaveValue('2026-01-15'))
expect(screen.getByLabelText('Select Choice')).toHaveValue('Alpha')
const sent = new Date(2026, 0, 15).toLocaleDateString()
await waitFor(() => expect(fetchMock).toHaveBeenLastCalledWith('accControls', { accChoice: 'alpha', accDate: sent }))
expect(await screen.findByText(`choice=alpha; day=${sent}`)).toBeInTheDocument()
expect(localStorage.length).toBe(0)
})
it('uses the configured date wire normalization for a backend default', async () => {
const normalize = vi.spyOn(widgetUtils, 'normalizeDropdownDate').mockImplementation((value) => value)
try {
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', '2026-01-15'],
}))
renderWidget({ ...controls, storeDropdownSelections: false })
await waitFor(() => expect(screen.getByLabelText('Select Day')).toHaveValue('2026-01-15'))
await waitFor(() => expect(fetchMock).toHaveBeenLastCalledWith('accControls', { accChoice: 'alpha', accDate: '2026-01-15' }))
expect(await screen.findByText('choice=alpha; day=2026-01-15')).toBeInTheDocument()
expect(localStorage.length).toBe(0)
} finally {
normalize.mockRestore()
}
})
it.each([undefined, null, '', 'not-a-date'])('leaves a missing or invalid date default blank (%s)', async (value) => {
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', value],
}))
renderWidget({ ...controls, storeDropdownSelections: false })
await waitFor(() => expect(screen.getByLabelText('Select Choice')).toHaveValue('Alpha'))
expect(screen.getByLabelText('Select Day')).toHaveValue('')
await waitFor(() => expect(fetchMock).toHaveBeenLastCalledWith('accControls', { accChoice: 'alpha' }))
})
it('keeps a user date when a late reload supplies a different default', async () => {
const user = userEvent.setup()
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', '2026-01-15'],
}))
renderWidget({ ...controls, storeDropdownSelections: false })
const day = await screen.findByLabelText('Select Day')
await waitFor(() => expect(day).toHaveValue('2026-01-15'))
fireEvent.change(day, { target: { value: '2026-01-20' } })
const sent = new Date(2026, 0, 20).toLocaleDateString()
await waitFor(() => expect(fetchMock).toHaveBeenLastCalledWith('accControls', { accChoice: 'alpha', accDate: sent }))
expect(await screen.findByText(`choice=alpha; day=${sent}`)).toBeInTheDocument()
let finishReload!: (value: WidgetData) => void
fetchMock.mockImplementationOnce(() => new Promise((resolve) => { finishReload = resolve }))
await user.click(screen.getByLabelText('Reload Owned Controls'))
await waitFor(() => expect(finishReload).toBeDefined())
finishReload({ ...controlsPayload({ accChoice: 'alpha', accDate: sent }), dropdownDefaultValueList: ['alpha', '2026-01-25'] })
await waitFor(() => expect(screen.getByLabelText('Reload Owned Controls')).not.toBeDisabled())
expect(day).toHaveValue('2026-01-20')
})
it('preserves an explicit clear when the backend still supplies a date default', async () => {
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', '2026-01-15'],
}))
renderWidget({ ...controls, storeDropdownSelections: false })
const day = await screen.findByLabelText('Select Day')
await waitFor(() => expect(day).toHaveValue('2026-01-15'))
fireEvent.change(day, { target: { value: '' } })
await waitFor(() => expect(screen.getByText('Please select a Day')).toBeInTheDocument())
expect(day).toHaveValue('')
expect(localStorage.length).toBe(0)
})
it('preserves a stored date instead of replacing it with a server default', async () => {
localStorage.setItem('qqq.widgets.dropdownData.accControls.accDate', JSON.stringify({ id: '2026-01-10' }))
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', '2026-01-15'],
}))
renderWidget()
await waitFor(() => expect(screen.getByLabelText('Select Choice')).toHaveValue('Alpha'))
expect(screen.getByLabelText('Select Day')).toHaveValue('2026-01-10')
expect(JSON.parse(localStorage.getItem('qqq.widgets.dropdownData.accControls.accDate')!)).toEqual({ id: '2026-01-10' })
expect(localStorage.getItem('qqq.widgets.dropdownData.accControls.accChoice')).toBeNull()
})
it('does not carry one caller default into a fresh caller widget without saved dates', async () => {
fetchMock.mockImplementation(async (_name, params) => ({
...controlsPayload(params), dropdownDefaultValueList: ['alpha', '2026-01-15'],
}))
const first = renderWidget({ ...controls, storeDropdownSelections: false })
await waitFor(() => expect(screen.getByLabelText('Select Day')).toHaveValue('2026-01-15'))
first.unmount()
fetchMock.mockImplementation(async (_name, params) => controlsPayload(params))
renderWidget({ ...controls, storeDropdownSelections: false })
expect(await screen.findByText('Please select a Choice and Day')).toBeInTheDocument()
expect(screen.getByLabelText('Select Day')).toHaveValue('')
expect(localStorage.length).toBe(0)
})
it('renders payload dropdowns, sends selections under their parameter names and persists them', async () => {
const user = userEvent.setup()
renderWidget()
+9 -3
View File
@@ -39,7 +39,7 @@ import { WidgetRenderer } from './WidgetRenderer'
import { ChildRecordExportButton } from './ChildRecordListWidget'
import type { ChildRecordListPayload } from './ChildRecordListWidget'
import {
CUSTOM_TIMEFRAME, TIMEFRAME_DROPDOWN, downloadText, dropdownStorageKey, storedDropdownParams, widgetCsvToString,
CUSTOM_TIMEFRAME, TIMEFRAME_DROPDOWN, downloadText, dropdownStorageKey, normalizeDropdownDate, parseDropdownDate, storedDropdownParams, widgetCsvToString,
widgetExportFileName, writeStoredSelection,
} from './widget-utils'
import { tableExportCsv } from './table-widget-utils'
@@ -174,9 +174,15 @@ export function ConnectedWidget({
names.forEach((name, index) => {
if (typeof name !== 'string') return
const meta = widgetMetaData.dropdowns?.[index]
if (meta?.type === 'DATE_PICKER') return
const ids = (Array.isArray(lists[index]) ? lists[index] : []).map((option: { id?: unknown }) => String(option?.id))
const selected = current[name]
if (meta?.type === 'DATE_PICKER') {
const value = defaults[index]
if (selected === undefined && typeof value === 'string' && parseDropdownDate(value)) {
next = { ...next, [name]: normalizeDropdownDate(value) }
}
return
}
const ids = (Array.isArray(lists[index]) ? lists[index] : []).map((option: { id?: unknown }) => String(option?.id))
// a custom timeframe range (custom,<start>,<end>) is offered by the timeframe's custom option
const offered = selected && (ids.includes(selected) || (name === TIMEFRAME_DROPDOWN && ids.includes(CUSTOM_TIMEFRAME) && selected.startsWith(`${CUSTOM_TIMEFRAME},`)))
if (selected && !offered) {
@@ -29,7 +29,11 @@ import { server } from '@/mocks/node'
import { EsbOverviewWidget } from './EsbOverviewWidget'
import { WidgetRenderer } from './WidgetRenderer'
const widgetMetaData = { name: 'esbOverview', label: 'ESB', type: 'ESB_OVERVIEW' } as QWidgetMetaData
const widgetMetaData = {
name: 'esbOverview',
label: 'ESB',
type: 'ESB_OVERVIEW',
} as QWidgetMetaData
/**
* Renders an element inside a fresh query client.
@@ -73,13 +77,16 @@ describe('EsbOverviewWidget', () => {
expect(bodyRows('Destinations')).toHaveLength(3)
expect(events).toHaveTextContent('orderEvents')
expect(events).toHaveTextContent('Topic')
expect(within(events).getByRole('link', { name: 'order' })).toHaveAttribute('href', '/app/order')
expect(within(events).getByRole('link', { name: 'order' })).toHaveAttribute(
'href',
'/app/order'
)
expect(events).toHaveTextContent('INSERT, UPDATE, DELETE')
expect(fulfillment).toHaveTextContent('Queue')
expect(within(fulfillment).getAllByRole('cell')[3]).toHaveTextContent(/^7$/)
expect(within(results).getByRole('link', { name: 'fulfillOrder' })).toHaveAttribute(
'href',
'/app/fulfillOrder'
'/app/fulfillOrder/dev'
)
})
@@ -105,7 +112,9 @@ describe('EsbOverviewWidget', () => {
)
renderWithClient(<EsbOverviewWidget widgetMetaData={widgetMetaData} />)
await screen.findByRole('table', { name: 'Triggers' })
expect(screen.queryByRole('button', { name: /^(Pause|Resume|Restart|Purge)/ })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: /^(Pause|Resume|Restart|Purge)/ })
).not.toBeInTheDocument()
})
it('says so when the ESB status is not available', async () => {
@@ -119,7 +128,9 @@ describe('EsbOverviewWidget', () => {
})
it('is rendered for the ESB_OVERVIEW widget type', async () => {
renderWithClient(<WidgetRenderer widgetMetaData={widgetMetaData} data={{ type: 'ESB_OVERVIEW' }} />)
renderWithClient(
<WidgetRenderer widgetMetaData={widgetMetaData} data={{ type: 'ESB_OVERVIEW' }} />
)
expect(await screen.findByRole('table', { name: 'Destinations' })).toBeInTheDocument()
})
+15 -4
View File
@@ -25,7 +25,12 @@ import React from 'react'
import Link from 'next/link'
import { useQuery } from '@tanstack/react-query'
import type { EsbOverviewDestination, EsbPermissions, EsbProviderType, QWidgetMetaData } from '@/types'
import type {
EsbOverviewDestination,
EsbPermissions,
EsbProviderType,
QWidgetMetaData,
} from '@/types'
import { getEsbOverview } from '@/lib/api/esb'
import { HANDLES_OWN_ERRORS, queryKeys } from '@/lib/query-client'
import { CHIP_COLOR_CLASSES } from '@/lib/utils/adornment-utils'
@@ -126,7 +131,11 @@ export function EsbOverviewWidget({ widgetMetaData }: { widgetMetaData: QWidgetM
))}
</EsbList>
<EsbList title="Triggers" columns={TRIGGER_COLUMNS} empty="No triggers on processes you can access.">
<EsbList
title="Triggers"
columns={TRIGGER_COLUMNS}
empty="No triggers on processes you can access."
>
{triggers.map((trigger) => (
<EsbTriggerRow key={trigger.name} trigger={trigger} permissions={data.permissions} />
))}
@@ -174,12 +183,14 @@ function DestinationRow({
{publisher.kind === 'TABLE' ? 'Table' : 'Process'}{' '}
</span>
<Link
href={`/app/${encodeURIComponent(publisher.name)}`}
href={`/app/${encodeURIComponent(publisher.name)}${publisher.kind === 'PROCESS' ? '/dev' : ''}`}
className="font-medium text-primary underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-ring"
>
{publisher.name}
</Link>
<span className="text-xs text-muted-foreground">: {publisher.events.join(', ')}</span>
<span className="text-xs text-muted-foreground">
: {publisher.events.join(', ')}
</span>
</li>
))}
</ul>
@@ -15,10 +15,18 @@
*/
import React, { useState } from 'react'
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
// jsdom does not implement native viewport scrolling; real menu geometry is covered in acceptance.
const originalScrollIntoView = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollIntoView')
beforeAll(() => Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }))
afterAll(() => {
if (originalScrollIntoView) Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView)
else Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView')
})
import type { QTableMetaData, QWidgetMetaData } from '@/types'
import type { WidgetFormContext } from './widget-types'
@@ -15,10 +15,18 @@
*/
import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
// jsdom does not implement native viewport scrolling; real menu geometry is covered in acceptance.
const originalScrollIntoView = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollIntoView')
beforeAll(() => Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: vi.fn() }))
afterAll(() => {
if (originalScrollIntoView) Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView)
else Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView')
})
const { previewRecords } = vi.hoisted(() => ({ previewRecords: [] as QRecord[] }))
vi.mock('@/lib/hooks/use-metadata', () => ({ useTableMetaData: vi.fn(), useMetaData: () => ({ data: undefined }) }))
+111 -10
View File
@@ -27,7 +27,7 @@ import {
orderFulfillmentMessages,
} from '@/mocks/fixtures/esb'
import { server } from '@/mocks/node'
import { processInit } from './processes'
import { processInit, processStatus } from './processes'
import {
getEsbDeadLetters,
getEsbForProcess,
@@ -37,7 +37,7 @@ import {
runEsbAction,
} from './esb'
vi.mock('./processes', () => ({ processInit: vi.fn() }))
vi.mock('./processes', () => ({ processInit: vi.fn(), processStatus: vi.fn() }))
describe('getEsbForTable', () => {
it('returns the table ESB section from GET /qqq/v1/esb/table/{table}', async () => {
@@ -166,13 +166,15 @@ describe('getEsbMessages and getEsbDeadLetters', () => {
return HttpResponse.json(orderFulfillmentMessages)
})
)
await expect(getEsbMessages('orderFulfillment', 50, 25)).resolves.toEqual(orderFulfillmentMessages)
await expect(getEsbMessages('orderFulfillment', 50, 25)).resolves.toEqual(
orderFulfillmentMessages
)
expect(url.pathname).toBe('/qqq/v1/esb/messages/orderFulfillment')
expect(url.searchParams.get('offset')).toBe('50')
expect(url.searchParams.get('limit')).toBe('25')
})
it('browse a trigger\'s dead letters, 50 at a time from the start by default', async () => {
it("browse a trigger's dead letters, 50 at a time from the start by default", async () => {
let url = new URL('http://localhost')
server.use(
http.get('/qqq/v1/esb/deadLetters/:trigger', ({ request }) => {
@@ -188,6 +190,33 @@ describe('getEsbMessages and getEsbDeadLetters', () => {
expect(url.searchParams.get('limit')).toBe('50')
})
it('browses the named topic subscription with the backend trigger parameter', async () => {
let url = new URL('http://localhost')
server.use(
http.get('/qqq/v1/esb/messages/:destination', ({ request }) => {
url = new URL(request.url)
return HttpResponse.json(orderFulfillmentMessages)
})
)
await expect(getEsbMessages('orderEvents', 50, 25, 'cancelOrder.orderEvents')).resolves.toEqual(
orderFulfillmentMessages
)
expect(url.pathname).toBe('/qqq/v1/esb/messages/orderEvents')
expect(url.searchParams.get('trigger')).toBe('cancelOrder.orderEvents')
expect(url.searchParams.get('offset')).toBe('50')
expect(url.searchParams.get('limit')).toBe('25')
})
it('serves the demo topic subscription and rejects missing or unrelated triggers', async () => {
await expect(getEsbMessages('orderEvents', 0, 50, 'cancelOrder.orderEvents')).resolves.toEqual(
orderFulfillmentMessages
)
await expect(getEsbMessages('orderEvents')).rejects.toThrow()
await expect(
getEsbMessages('orderEvents', 0, 50, 'fulfillOrder.orderFulfillment')
).rejects.toThrow()
})
it('rejects a body that is not a message page', async () => {
server.use(http.get('/qqq/v1/esb/messages/orderFulfillment', () => HttpResponse.json({})))
await expect(getEsbMessages('orderFulfillment')).rejects.toThrow('Invalid ESB message page')
@@ -206,6 +235,7 @@ describe('getEsbMessages and getEsbDeadLetters', () => {
describe('runEsbAction', () => {
beforeEach(() => {
vi.mocked(processInit).mockReset()
vi.mocked(processStatus).mockReset()
})
it('runs the operate process with the values and returns its count and message', async () => {
@@ -215,7 +245,10 @@ describe('runEsbAction', () => {
values: { count: 7, message: 'Purged 7 messages.' },
})
await expect(
runEsbAction('esbPurgeQueue', { providerName: 'artemis', brokerQueueName: 'orderFulfillment' })
runEsbAction('esbPurgeQueue', {
providerName: 'artemis',
brokerQueueName: 'orderFulfillment',
})
).resolves.toEqual({ count: 7, message: 'Purged 7 messages.' })
expect(processInit).toHaveBeenCalledWith('esbPurgeQueue', {
values: { providerName: 'artemis', brokerQueueName: 'orderFulfillment' },
@@ -243,11 +276,79 @@ describe('runEsbAction', () => {
await expect(runEsbAction('esbPurgeQueue', {})).rejects.toThrow('The broker refused the purge.')
})
it('says the action is still running when it continues as a job', async () => {
vi.mocked(processInit).mockResolvedValue({ type: 'JOB_STARTED', processUUID: 'uuid', jobUUID: 'job' })
await expect(runEsbAction('esbRestartTrigger', {})).resolves.toEqual({
count: null,
message: 'The action is still running.',
it.each(['process error', 'request failure'])(
'rejects an async %s instead of reporting success',
async (failure) => {
vi.useFakeTimers()
try {
vi.mocked(processInit).mockResolvedValue({
type: 'JOB_STARTED',
processUUID: 'uuid',
jobUUID: 'job',
})
if (failure === 'process error') {
vi.mocked(processStatus).mockResolvedValue({
type: 'ERROR',
error: 'Technical failure',
userFacingError: 'Replay failed; messages remain.',
})
} else {
vi.mocked(processStatus).mockRejectedValue(new Error('Status unavailable'))
}
const assertion = expect(
runEsbAction('esbReplayDeadLetters', { all: true })
).rejects.toThrow(
failure === 'process error' ? 'Replay failed; messages remain.' : 'Status unavailable'
)
await vi.runAllTimersAsync()
await assertion
} finally {
vi.useRealTimers()
}
}
)
it('does not report success for a running response with no job identifier', async () => {
vi.mocked(processInit).mockResolvedValue({ type: 'RUNNING', processUUID: 'uuid' })
await expect(runEsbAction('esbPurgeQueue', {})).rejects.toThrow('no job identifier')
})
it('does not report a completed intermediate step as the final action outcome', async () => {
vi.mocked(processInit).mockResolvedValue({
type: 'COMPLETE',
processUUID: 'uuid',
nextStep: 'confirm',
values: {},
})
await expect(runEsbAction('esbPurgeQueue', {})).rejects.toThrow('additional step')
})
it('waits for the final outcome through running job statuses', async () => {
vi.useFakeTimers()
try {
vi.mocked(processInit).mockResolvedValue({
type: 'JOB_STARTED',
processUUID: 'uuid',
jobUUID: 'job',
})
vi.mocked(processStatus)
.mockResolvedValueOnce({ type: 'RUNNING', processUUID: 'uuid' })
.mockResolvedValueOnce({
type: 'COMPLETE',
processUUID: 'uuid',
values: { count: 3, message: 'Replayed 3 messages.' },
})
const settled = vi.fn()
const result = runEsbAction('esbReplayDeadLetters', { all: true }).then(settled)
await Promise.resolve()
await Promise.resolve()
expect(settled).not.toHaveBeenCalled()
await vi.runAllTimersAsync()
await result
expect(processStatus).toHaveBeenCalledWith('esbReplayDeadLetters', 'uuid', 'job')
expect(settled).toHaveBeenCalledWith({ count: 3, message: 'Replayed 3 messages.' })
} finally {
vi.useRealTimers()
}
})
})
+31 -9
View File
@@ -26,7 +26,7 @@ import type {
} from '@/types'
import { getErrorStatusCode } from '@/lib/utils/error-utils'
import apiClient from './client'
import { processInit } from './processes'
import { processInit, processStatus } from './processes'
/** Messages per page when browsing, the backend's default. */
export const ESB_PAGE_SIZE = 50
@@ -87,15 +87,22 @@ export async function getEsbOverview(): Promise<EsbOverviewResponse | null> {
* @param destinationName - QQQ destination name.
* @param offset - Messages to skip.
* @param limit - Messages to return.
* @param triggerName - Required for a topic: the trigger whose subscription to browse.
* @returns The page of messages.
* @throws The request error, or an error when the body is not a message page.
*/
export async function getEsbMessages(
destinationName: string,
offset = 0,
limit = ESB_PAGE_SIZE
limit = ESB_PAGE_SIZE,
triggerName?: string
): Promise<EsbMessagePage> {
return getMessagePage(`/esb/messages/${encodeURIComponent(destinationName)}`, offset, limit)
return getMessagePage(
`/esb/messages/${encodeURIComponent(destinationName)}`,
offset,
limit,
triggerName
)
}
/**
@@ -120,19 +127,26 @@ export async function getEsbDeadLetters(
*
* @param processName - The operate process, e.g. `esbPurgeQueue`.
* @param values - Its input values, e.g. `providerName` and `brokerQueueName`.
* @returns The process's `count` and `message`; a generic message while it continues as a job.
* @returns The completed process's `count` and `message`.
* @throws An error with the process's user-facing message when it fails or is refused.
*/
export async function runEsbAction(
processName: string,
values: Record<string, string | boolean>
): Promise<EsbActionResult> {
const response = await processInit(processName, { values })
let response = await processInit(processName, { values })
let jobUUID: string | undefined
while (response.type === 'JOB_STARTED' || response.type === 'RUNNING') {
if (response.type === 'JOB_STARTED') jobUUID = response.jobUUID
if (!jobUUID) throw new Error('The action returned no job identifier to check its outcome.')
await new Promise((resolve) => setTimeout(resolve, 1000))
response = await processStatus(processName, response.processUUID, jobUUID)
}
if (response.type === 'ERROR') {
throw new Error(response.userFacingError ?? response.error)
}
if (response.type !== 'COMPLETE') {
return { count: null, message: 'The action is still running.' }
if (response.nextStep) {
throw new Error('The action requires an unexpected additional step.')
}
const count = Number(response.values.count)
const message = response.values.message
@@ -165,11 +179,19 @@ async function getOrNull(path: string): Promise<unknown> {
* @param path - Path under the API base URL.
* @param offset - Messages to skip.
* @param limit - Messages to return.
* @param triggerName - Optional topic trigger name.
* @returns The page.
* @throws The request error, or an error when the body is not a message page.
*/
async function getMessagePage(path: string, offset: number, limit: number): Promise<EsbMessagePage> {
const data = await apiClient.get<unknown>(path, { params: { offset, limit } })
async function getMessagePage(
path: string,
offset: number,
limit: number,
triggerName?: string
): Promise<EsbMessagePage> {
const data = await apiClient.get<unknown>(path, {
params: { offset, limit, ...(triggerName ? { trigger: triggerName } : {}) },
})
if (!hasArrays<EsbMessagePage>(data, 'messages')) {
throw new Error('Invalid ESB message page')
}
@@ -30,9 +30,10 @@ vi.mock('@/lib/api/auth', () => ({
clearAuthMetadataCache: vi.fn(),
}))
import { createPasswordSession, logout, manageSession, resumeSession } from '@/lib/api/auth'
import { createPasswordSession, getAuthenticationMetaData, logout, manageSession, resumeSession } from '@/lib/api/auth'
import { AuthProvider } from './auth-provider'
import { useAuth } from './use-auth'
import * as oidc from './oidc'
import { storeUser, getStoredUser, hasSessionHint, setSessionHint } from './auth-storage'
let auth: ReturnType<typeof useAuth> | null = null
@@ -102,6 +103,62 @@ describe('AuthProvider with TABLE_BASED authentication', () => {
write.mockRestore()
})
it.each([false, true])('keeps authentication loading until logout settles (failure: %s)', async (fails) => {
let finishLogout!: () => void
vi.mocked(logout).mockReturnValue(new Promise<void>((resolve, reject) => {
finishLogout = () => fails ? reject(new Error('Logout unavailable')) : resolve()
}))
vi.mocked(createPasswordSession).mockResolvedValue({ values: { user: { name: 'Tess Table', username: 'tess.table' } } })
render(<AuthProvider><Probe /></AuthProvider>)
await screen.findByText('signed out: no error')
await act(async () => { await auth?.signInWithPassword('tess.table', 'table:pass-2026') })
let pendingLogout: Promise<void> | undefined
await act(async () => { pendingLogout = auth?.logout() })
expect(screen.getByText('loading')).toBeInTheDocument()
expect(auth?.isAuthenticated).toBe(false)
expect(auth?.user).toBeNull()
await act(async () => { finishLogout(); await pendingLogout })
expect(screen.getByText('signed out: no error')).toBeInTheDocument()
expect(auth?.isLoading).toBe(false)
})
it('leaves loading when provider logout falls back to the local login page', async () => {
vi.mocked(getAuthenticationMetaData).mockResolvedValueOnce({ name: 'oauth', type: 'OAUTH2' })
vi.mocked(resumeSession).mockResolvedValue({ values: { user: { name: 'Tess Table', username: 'tess.table' } } })
vi.mocked(logout).mockResolvedValue(undefined)
setSessionHint(true)
const endSession = vi.spyOn(oidc, 'buildEndSessionUrl').mockRejectedValue(new Error('Provider unavailable'))
try {
render(<AuthProvider><Probe /></AuthProvider>)
await screen.findByText('Tess Table <tess.table>')
await act(async () => { await auth?.logout() })
expect(endSession).toHaveBeenCalled()
expect(screen.getByText('signed out: no error')).toBeInTheDocument()
expect(auth?.isLoading).toBe(false)
} finally {
endSession.mockRestore()
}
})
it('keeps loading after provider logout starts an external navigation', async () => {
vi.mocked(getAuthenticationMetaData).mockResolvedValueOnce({ name: 'oauth', type: 'OAUTH2' })
vi.mocked(resumeSession).mockResolvedValue({ values: { user: { name: 'Tess Table', username: 'tess.table' } } })
vi.mocked(logout).mockResolvedValue(undefined)
setSessionHint(true)
const endSession = vi.spyOn(oidc, 'buildEndSessionUrl').mockResolvedValue('https://idp.example/logout')
try {
render(<AuthProvider><Probe /></AuthProvider>)
await screen.findByText('Tess Table <tess.table>')
// jsdom leaves the document in place when location.assign starts navigation.
await act(async () => { await auth?.logout() })
expect(endSession).toHaveBeenCalled()
expect(screen.getByText('loading')).toBeInTheDocument()
expect(auth?.isLoading).toBe(true)
} finally {
endSession.mockRestore()
}
})
it('reports refused credentials and stays signed out', async () => {
vi.mocked(createPasswordSession).mockRejectedValue(refused('Incorrect username or password.'))
render(<AuthProvider><Probe /></AuthProvider>)
+49 -41
View File
@@ -102,7 +102,7 @@ export interface AuthUser {
export interface AuthContextType {
/** Whether the current user has an active, validated session. */
isAuthenticated: boolean
/** Whether an auth check or sign-in is in flight. */
/** True while checking authentication, signing in or signing out. */
isLoading: boolean
/** The authenticated user, or `null` while unauthenticated. */
user: AuthUser | null
@@ -385,50 +385,58 @@ export function AuthProvider({ children, onAuthError }: AuthProviderProps) {
}, [applySession])
const handleLogout = useCallback(async () => {
const metadata = authMetadata
const loginPath = `/login?returnTo=${encodeURIComponent(currentReturnTo())}`
const providerLogout = Boolean(metadata && PROVIDER_TYPES.has(metadata.type))
// Signed out first: protected pages unmount (no refetch with an ending session) and the
// login page shows the signed-out state instead of signing in again. Provider logouts
// leave the page for the identity provider instead, so no in-app navigation is started.
redirectingToLogin.current = true
setSignedOut(true)
setSessionHint(false)
if (!providerLogout) {
// Do not offer another sign-in until the old response has expired its cookies (#984).
let leavingForProvider = false
setIsLoading(true)
try {
const metadata = authMetadata
const loginPath = `/login?returnTo=${encodeURIComponent(currentReturnTo())}`
const providerLogout = Boolean(metadata && PROVIDER_TYPES.has(metadata.type))
// Signed out first: protected pages unmount (no refetch with an ending session) and the
// login page shows the signed-out state instead of signing in again. Provider logouts
// leave the page for the identity provider instead, so no in-app navigation is started.
redirectingToLogin.current = true
setSignedOut(true)
setSessionHint(false)
if (!providerLogout) {
setSignedOutState(true)
setIsAuthenticated(false)
setUser(null)
}
try {
// the backend also expires both session cookies (QRun-IO/qqq#674)
await apiLogout()
} catch (error) {
// The local sign-out still happens; the backend session is left to expire, and the
// next sign-in replaces its cookies (QRun-IO/qqq#733).
console.warn('[Auth] Backend logout failed:', error instanceof Error ? error.message : error)
}
resetReauthAttempts()
clearUserClientData()
// Forget the analytics identity with the session (Material resets its providers on logout)
analytics.reset()
clearAuthMetadataCache()
queryClient.clear()
if (metadata && PROVIDER_TYPES.has(metadata.type)) {
try {
const endSession = await buildEndSessionUrl(metadata, `${window.location.origin}/login`)
if (endSession) {
window.location.assign(endSession)
leavingForProvider = true
return
}
} catch (error) {
console.warn('[Auth] Identity provider sign-out unavailable:', error instanceof Error ? error.message : error)
}
}
setSignedOutState(true)
setIsAuthenticated(false)
setUser(null)
router.push(loginPath)
} finally {
if (!leavingForProvider) setIsLoading(false)
}
try {
// the backend also expires both session cookies (QRun-IO/qqq#674)
await apiLogout()
} catch (error) {
// The local sign-out still happens; the backend session is left to expire, and the
// next sign-in replaces its cookies (QRun-IO/qqq#733).
console.warn('[Auth] Backend logout failed:', error instanceof Error ? error.message : error)
}
resetReauthAttempts()
clearUserClientData()
// Forget the analytics identity with the session (Material resets its providers on logout)
analytics.reset()
clearAuthMetadataCache()
queryClient.clear()
if (metadata && PROVIDER_TYPES.has(metadata.type)) {
try {
const endSession = await buildEndSessionUrl(metadata, `${window.location.origin}/login`)
if (endSession) {
window.location.assign(endSession)
return
}
} catch (error) {
console.warn('[Auth] Identity provider sign-out unavailable:', error instanceof Error ? error.message : error)
}
}
setSignedOutState(true)
setIsAuthenticated(false)
setUser(null)
router.push(loginPath)
}, [authMetadata, router])
const handleOAuthCallback = useCallback(async (code: string, state: string, codeVerifier?: string) => {
+57
View File
@@ -15,6 +15,12 @@
*/
import { afterEach, describe, expect, it } from 'vitest'
import {
readCurrentSavedViewId,
readStoredQueryView,
writeCurrentSavedViewId,
writeStoredQueryView,
} from '@/lib/utils/query-view-storage'
import {
claimClientData,
clearUserClientData,
@@ -97,6 +103,57 @@ describe('auth-storage', () => {
expect(localStorage.getItem('accessToken')).toBeNull()
})
it('clears every table\'s remembered filters and saved-view selection without resetting machine preferences (QRun-IO/qqq#1006)', () => {
for (const table of ['person', 'pet']) {
writeStoredQueryView(table, {
queryFilter: { criteria: [{ fieldName: 'name', operator: 'EQUALS', values: ['Private Alice'] }] },
viewIdentity: 'empty',
})
writeCurrentSavedViewId(table, 7)
expect(readStoredQueryView(table)).toMatchObject({
queryFilter: { criteria: [{ fieldName: 'name', operator: 'EQUALS', values: ['Private Alice'] }] },
})
expect(readCurrentSavedViewId(table)).toBe(7)
}
const preferences = {
'qqq.density': 'compact',
'qqq-dark-mode': 'true',
'qqq-person-column-widths': '{"name":240}',
'qqq.recordQueryViews.person': 'unrelated plural key',
'another-application': 'keep',
}
for (const [key, value] of Object.entries(preferences)) localStorage.setItem(key, value)
clearUserClientData()
for (const table of ['person', 'pet']) {
expect(readStoredQueryView(table)).toBeNull()
expect(readCurrentSavedViewId(table)).toBeNull()
}
for (const [key, value] of Object.entries(preferences)) expect(localStorage.getItem(key)).toBe(value)
})
it('keeps remembered query state for the same identity and clears it before another identity claims the browser (QRun-IO/qqq#1006)', () => {
claimClientData({ name: 'Alice', email: 'alice@example.test' })
writeStoredQueryView('person', {
queryFilter: { criteria: [{ fieldName: 'name', operator: 'EQUALS', values: ['Private Alice'] }] },
viewIdentity: 'savedView:7',
})
writeCurrentSavedViewId('person', 7)
claimClientData({ name: 'Alice', email: 'alice@example.test' })
expect(readStoredQueryView('person')).toMatchObject({
queryFilter: { criteria: [{ fieldName: 'name', operator: 'EQUALS', values: ['Private Alice'] }] },
viewIdentity: 'savedView:7',
})
expect(readCurrentSavedViewId('person')).toBe(7)
claimClientData({ name: 'Bob', email: 'bob@example.test' })
expect(readStoredQueryView('person')).toBeNull()
expect(readCurrentSavedViewId('person')).toBeNull()
expect(localStorage.getItem('qqq.clientDataOwner')).toBe('bob@example.test')
})
it('clears the previous user\'s data when someone else signs in in this browser (QRun-IO/qqq#696)', () => {
claimClientData({ name: 'Alice', email: 'alice@example.com' })
localStorage.setItem('qqq-recent-records', JSON.stringify([{ path: '/app/pet/1', recordLabel: 'Alice private' }]))
+3 -1
View File
@@ -19,6 +19,7 @@
* re-authentication loop guard, and clearing per-user client data on sign-out.
*/
import { clearAllStoredQueryState } from '@/lib/utils/query-view-storage-cleanup'
import { clearRecentRecords } from '@/lib/utils/recent-records'
const SIGNED_OUT_KEY = 'qqq.signedOut'
@@ -192,9 +193,10 @@ export function resetReauthAttempts(): void {
storage('session')?.removeItem(REAUTH_KEY)
}
/** Removes per-user data kept in the browser (recently viewed records, stored identity and session values). */
/** Removes per-user browser data: recent records, query views, stored identity and session values. */
export function clearUserClientData(): void {
clearRecentRecords()
clearAllStoredQueryState()
storeUser(null)
storage('local')?.removeItem(SESSION_VALUES_KEY)
storage('local')?.removeItem('accessToken')
@@ -0,0 +1,193 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Tests for useRecordQuery hook
import { setTimeout as realSetTimeout } from 'node:timers'
import { act, cleanup, fireEvent, render, renderHook, screen, within } from '@testing-library/react'
import { QueryClientProvider } from '@tanstack/react-query'
import { http, HttpResponse } from 'msw'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { QTableMetaData } from '@/types'
import { RecordQueryContent } from '@/components/query/RecordQueryContent'
import { queryClient, queryKeys } from '@/lib/query-client'
import { getErrorStatusCode } from '@/lib/utils/error-utils'
import { qInstance } from '@/mocks/fixtures/q-instance'
import { server } from '@/mocks/node'
import { useRecordQuery } from './use-record-query'
const table: QTableMetaData = { ...qInstance.tables.person, capabilities: ['TABLE_QUERY', 'TABLE_COUNT'] }
const options = { tableName: table.name, tableMetaData: table, allTables: { [table.name]: table } }
const records = [{ tableName: table.name, recordLabel: 'Recovered row', values: { id: 1, firstName: 'Recovered row' } }]
function Wrapper({ children }: { children: React.ReactNode }) {
// Use the production client, including its retry predicate, delay and error cache callbacks.
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
function QueryContent() {
const rq = useRecordQuery(options)
return <RecordQueryContent
tableName={table.name} tableMetaData={table} viewMode="card" activeFilterCount={0}
{...rq.data} {...rq.pagination} {...rq.columns}
sortOrder={rq.filter.sortOrder} onSortChange={rq.filter.setSort}
onResetFilter={rq.filter.resetFilter} quickSearchTerm={rq.filter.quickSearchTerm}
rowSelection={rq.selection.rowSelection} onRowSelectionChange={rq.selection.setRowSelection}
onColumnWidthChange={rq.columns.setColumnWidth} density={rq.density}
onPageChange={rq.pagination.setPage} onPageSizeChange={rq.pagination.setPageSize}
/>
}
// Hold each real HTTP response independently, including the last automatic attempt.
function controlledEndpoint(endpoint: 'query' | 'count') {
const responses: Array<(response: Response) => void> = []
server.use(http.post(`*/qqq/v1/table/${table.name}/${endpoint}`, () =>
new Promise<Response>((resolve) => { responses.push(resolve) })))
return responses
}
// Flush HTTP/React work without advancing the retry clock. Real IO can require
// another event-loop turn; only zero-duration fake timers (query notifications) run.
async function settle(assertion: () => void) {
for (let turn = 0; turn < 100; turn++) {
await act(async () => {
await new Promise<void>((resolve) => { realSetTimeout(resolve, 1) })
await vi.advanceTimersByTimeAsync(0)
})
try { assertion(); return } catch (error) { if (turn === 99) throw error }
}
}
async function advance(milliseconds: number) {
await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) })
}
function failureCount(endpoint: 'query' | 'count') {
return queryClient.getQueryCache().findAll({ queryKey: queryKeys.tableRecords(table.name) })
.find((query) => query.queryKey[3] === endpoint)?.state.fetchFailureCount
}
async function exhaustServerErrors(responses: Array<(response: Response) => void>, endpoint: 'query' | 'count', message: string) {
for (let attempt = 0; attempt < 4; attempt++) {
await settle(() => { expect(responses).toHaveLength(attempt + 1) })
responses[attempt](HttpResponse.json({ error: message }, { status: 500 }))
await settle(() => { expect(failureCount(endpoint)).toBe(attempt + 1) })
if (attempt < 3) await advance([1000, 2000, 4000][attempt])
}
}
beforeEach(() => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
queryClient.clear()
localStorage.clear()
server.use(
http.post(`*/qqq/v1/table/${table.name}/query`, () => HttpResponse.json({ records })),
http.post(`*/qqq/v1/table/${table.name}/count`, () => HttpResponse.json({ count: 1 })),
)
})
afterEach(() => {
cleanup()
queryClient.clear()
vi.useRealTimers()
})
describe('record query production retry lifecycle', () => {
it('waits for the first attempt and three retries before an accessible terminal error, then recovers through Retry', async () => {
const responses = controlledEndpoint('query')
render(<QueryContent />, { wrapper: Wrapper })
for (const [attempt, delay] of [1000, 2000, 4000].entries()) {
await settle(() => { expect(responses).toHaveLength(attempt + 1) })
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
responses[attempt](HttpResponse.json({ error: 'Database query unavailable' }, { status: 500 }))
await settle(() => { expect(failureCount('query')).toBe(attempt + 1) })
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
await advance(delay - 1)
expect(responses).toHaveLength(attempt + 1)
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
await advance(1)
}
await settle(() => { expect(responses).toHaveLength(4) })
// A slow final response is still pending; reaching attempt four is not terminal.
await advance(5000)
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.queryByText('No records found')).not.toBeInTheDocument()
responses[3](HttpResponse.json({ error: 'Database query unavailable' }, { status: 500 }))
await settle(() => { expect(screen.getByRole('alert')).toHaveTextContent('Database query unavailable') })
const alert = screen.getByRole('alert')
expect(within(alert).getByRole('button', { name: 'Dismiss' })).toBeEnabled()
await advance(8000)
expect(responses).toHaveLength(4)
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
await settle(() => { expect(responses).toHaveLength(5) })
responses[4](HttpResponse.json({ records }))
await settle(() => { expect(screen.getByRole('heading', { name: 'Recovered row' })).toBeInTheDocument() })
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()
})
it('dismisses only the current terminal error without retrying or hiding a later distinct failure', async () => {
const responses = controlledEndpoint('query')
const view = render(<QueryContent />, { wrapper: Wrapper })
await exhaustServerErrors(responses, 'query', 'First backend failure')
await settle(() => { expect(screen.getByRole('alert')).toHaveTextContent('First backend failure') })
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
view.rerender(<QueryContent />)
await advance(8000)
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(responses).toHaveLength(4)
act(() => { void queryClient.invalidateQueries({ queryKey: queryKeys.tableRecords(table.name) }) })
await settle(() => { expect(responses).toHaveLength(5) })
// Keep the same controlled handler and collect subsequent retry responses.
for (let attempt = 0; attempt < 4; attempt++) {
await settle(() => { expect(responses).toHaveLength(5 + attempt) })
responses[4 + attempt](HttpResponse.json({ error: 'Later backend failure' }, { status: 500 }))
await settle(() => { expect(failureCount('query')).toBe(attempt + 1) })
if (attempt < 3) await advance([1000, 2000, 4000][attempt])
}
await settle(() => { expect(screen.getByRole('alert')).toHaveTextContent('Later backend failure') })
expect(screen.queryByText('First backend failure')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Retry' })).toBeEnabled()
})
it('keeps successful records when the separate count exhausts its server-error retries', async () => {
const responses = controlledEndpoint('count')
const { result } = renderHook(() => useRecordQuery(options), { wrapper: Wrapper })
await settle(() => { expect(result.current.data.records).toEqual(records) })
await exhaustServerErrors(responses, 'count', 'Count temporarily unavailable')
await settle(() => { expect(result.current.data.countError?.message).toBe('Count temporarily unavailable') })
expect(result.current.data.records).toEqual(records)
expect(result.current.data.isError).toBe(false)
expect(result.current.data.error).toBeNull()
expect(result.current.data.isLoading).toBe(false)
expect(getErrorStatusCode(result.current.data.countError)).toBe(500)
await advance(8000)
expect(responses).toHaveLength(4)
})
it.each([403, 404])('shows HTTP %i immediately without an automatic retry', async (status) => {
const responses = controlledEndpoint('query')
render(<QueryContent />, { wrapper: Wrapper })
await settle(() => { expect(responses).toHaveLength(1) })
responses[0](HttpResponse.json({ error: 'Backend access detail' }, { status }))
await settle(() => { expect(screen.getByRole('alert')).toHaveTextContent('Backend access detail') })
expect(screen.getByRole('alert')).toHaveTextContent(status === 403
? 'You do not have permission to view these records.' : 'This table could not be found.')
await advance(7000)
expect(responses).toHaveLength(1)
})
})
@@ -0,0 +1,36 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file Query-view storage keys and cleanup, independent of view parsing and API utilities. */
/** Root of the per-table key for the last view. */
export const VIEW_STORAGE_KEY_ROOT = 'qqq.recordQueryView'
/** Root of the per-table key for the last saved view's id. */
export const CURRENT_SAVED_VIEW_ID_STORAGE_KEY_ROOT = 'qqq.currentSavedViewId'
/** Forgets every table's remembered view and saved-view selection, preserving machine preferences. */
export function clearAllStoredQueryState(): void {
try {
for (let index = localStorage.length - 1; index >= 0; index--) {
const key = localStorage.key(index)
if (key?.startsWith(`${VIEW_STORAGE_KEY_ROOT}.`) || key?.startsWith(`${CURRENT_SAVED_VIEW_ID_STORAGE_KEY_ROOT}.`)) {
localStorage.removeItem(key)
}
}
} catch {
// persistence is best-effort
}
}
+2 -4
View File
@@ -23,11 +23,9 @@
*/
import { parseViewJson, type RecordQueryView } from './saved-view-utils'
import { CURRENT_SAVED_VIEW_ID_STORAGE_KEY_ROOT, VIEW_STORAGE_KEY_ROOT } from './query-view-storage-cleanup'
/** Root of the per-table key for the last view. */
export const VIEW_STORAGE_KEY_ROOT = 'qqq.recordQueryView'
/** Root of the per-table key for the last saved view's id. */
export const CURRENT_SAVED_VIEW_ID_STORAGE_KEY_ROOT = 'qqq.currentSavedViewId'
export { CURRENT_SAVED_VIEW_ID_STORAGE_KEY_ROOT, VIEW_STORAGE_KEY_ROOT } from './query-view-storage-cleanup'
/** The (global) row density key. */
export const DENSITY_STORAGE_KEY = 'qqq.density'
/** The `viewIdentity` of an ad-hoc (unsaved) view. */
+14 -7
View File
@@ -107,6 +107,7 @@ const fulfillOrderTrigger: EsbTrigger = {
lastError: 'Warehouse API timed out',
}),
deadLetter: { brokerName: 'orderFulfillment.dlq', messageCount: 1 },
subscription: null,
}
const cancelOrderTrigger: EsbTrigger = {
@@ -126,6 +127,7 @@ const cancelOrderTrigger: EsbTrigger = {
maxMs: 80,
}),
deadLetter: { brokerName: 'orderEvents.cancelOrder.orderEvents.dlq', messageCount: null },
subscription: { brokerName: 'cancelOrder.orderEvents', messageCount: null },
}
const fulfillmentResults: EsbDestination = {
@@ -189,11 +191,12 @@ export const orderFulfillmentMessages: EsbMessagePage = {
event: {
specversion: '1.0',
id: 'evt-1',
source: 'qqq/table/order',
type: 'qqq.table.order.INSERT',
source: 'qqq://demo/table/order',
type: 'qqq.table.order.inserted',
subject: '1001',
},
rawBody: '{"specversion":"1.0","id":"evt-1","type":"qqq.table.order.INSERT","subject":"1001"}',
rawBody:
'{"specversion":"1.0","id":"evt-1","source":"qqq://demo/table/order","type":"qqq.table.order.inserted","subject":"1001"}',
properties: {},
},
{
@@ -203,11 +206,12 @@ export const orderFulfillmentMessages: EsbMessagePage = {
event: {
specversion: '1.0',
id: 'evt-2',
source: 'qqq/table/order',
type: 'qqq.table.order.INSERT',
source: 'qqq://demo/table/order',
type: 'qqq.table.order.inserted',
subject: '1002',
},
rawBody: '{"specversion":"1.0","id":"evt-2","type":"qqq.table.order.INSERT","subject":"1002"}',
rawBody:
'{"specversion":"1.0","id":"evt-2","source":"qqq://demo/table/order","type":"qqq.table.order.inserted","subject":"1002"}',
properties: {},
},
],
@@ -222,7 +226,10 @@ export const fulfillOrderDeadLetters: EsbMessagePage = {
deliveryCount: 3,
event: null,
rawBody: 'not json',
properties: { qqqError: 'unparseable message', qqqFailedTrigger: 'fulfillOrder.orderFulfillment' },
properties: {
qqqError: 'unparseable message',
qqqFailedTrigger: 'fulfillOrder.orderFulfillment',
},
},
],
hasMore: false,
+12 -3
View File
@@ -71,9 +71,18 @@ export const esbHandlers = [
esbResponse(esbProcesses, String(params.processName), 'Process')
),
http.get(`${BASE}/esb/overview`, () => HttpResponse.json(esbOverview)),
http.get(`${BASE}/esb/messages/:destination`, ({ params }) =>
esbResponse(esbMessages, String(params.destination), 'Destination')
),
http.get(`${BASE}/esb/messages/:destination`, ({ params, request }) => {
if (params.destination === 'orderEvents') {
const trigger = new URL(request.url).searchParams.get('trigger')
if (!trigger)
return HttpResponse.json({ error: 'A topic requires a trigger.' }, { status: 400 })
if (trigger !== 'cancelOrder.orderEvents') {
return HttpResponse.json({ error: 'Trigger not found on orderEvents.' }, { status: 404 })
}
return HttpResponse.json(orderFulfillmentMessages)
}
return esbResponse(esbMessages, String(params.destination), 'Destination')
}),
http.get(`${BASE}/esb/deadLetters/:trigger`, ({ params }) =>
esbResponse(esbDeadLetters, String(params.trigger), 'Trigger')
),
+4
View File
@@ -79,6 +79,8 @@ export type EsbTriggerState = 'RUNNING' | 'PAUSED' | 'CONNECTING' | 'STOPPED'
/** A trigger's dead-letter queue. */
export interface EsbDeadLetter {
brokerName: string
/** Broker delivery state; absent on older backends, null without management data. */
paused?: boolean | null
/** Messages waiting in the dead-letter queue, or `null` when the broker cannot report it. */
messageCount: number | null
}
@@ -96,6 +98,8 @@ export interface EsbTrigger {
state: EsbTriggerState
counters: EsbCounter
deadLetter: EsbDeadLetter
/** Broker queue for a topic subscription; null for queue triggers. */
subscription: EsbDeadLetter | null
}
/** What the current user may do with the ESB objects in a response. */
+78
View File
@@ -0,0 +1,78 @@
/*
* Copyright 2026 QRun.IO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file Exact public branding aliases for the standalone Node server (QQQ #1009). */
import { realpath, stat } from 'node:fs/promises'
import path from 'node:path'
import { BACKEND_PREFIXES } from './security-headers.mjs'
const reserved = new Set(['app', 'login', 'callback', '_next', ...BACKEND_PREFIXES].map((part) => part.toLowerCase()))
const imageSuffix = /\.(png|jpe?g|gif|webp|avif|ico|svg)$/i
/** Canonical decoded root-relative image path, rejecting traversal before normalization. */
export function brandingImagePath(value) {
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) return null
const raw = value.split(/[?#]/, 1)[0]
if (/%(2f|5c)/i.test(raw)) return null
let decoded
try { decoded = decodeURIComponent(raw) } catch { return null }
if (/[\u0000-\u001f\u007f\ufffd\\%?#]/.test(decoded)) return null
const parts = decoded.slice(1).split('/')
if (parts.some((part) => !part || part === '.' || part === '..') || reserved.has(parts[0].toLowerCase())) return null
return imageSuffix.test(decoded) ? decoded : null
}
/** Keep existing regular public files with Next; never inspect a path outside that root. */
async function hasPublicFile(directory, image) {
try {
const root = await realpath(directory)
const file = await realpath(path.join(root, image.slice(1)))
return file.startsWith(root + path.sep) && (await stat(file)).isFile()
} catch { return false }
}
/**
* Maps at most the two public metadata fields to fixed backend roles. An expired cache
* refreshes before use; failed reads cannot keep stale asset authority. The caller bounds
* the metadata fetch. No browser URL, cookie, or body is passed to that fetch.
*/
export function createBrandingAssetAlias(loadAuthentication, publicDirectory) {
let aliases = new Map()
let expires = 0
let loading = null
const refresh = () => {
loading ??= Promise.resolve().then(loadAuthentication).then((authentication) => {
const next = new Map()
for (const role of ['logo', 'icon']) {
const image = brandingImagePath(authentication?.branding?.[role])
if (image && !next.has(image)) next.set(image, `/qqq/branding/${role}`)
}
aliases = next
expires = Date.now() + 60_000
}).catch(() => {
aliases = new Map()
expires = Date.now() + 5_000
}).finally(() => { loading = null })
return loading
}
return async (method, url) => {
if (method !== 'GET' && method !== 'HEAD') return null
const image = brandingImagePath(url)
if (!image || await hasPublicFile(publicDirectory, image)) return null
if (Date.now() >= expires) await refresh()
return aliases.get(image) ?? null
}
}
+20 -9
View File
@@ -19,19 +19,20 @@
* server (`server.js`, generated by `next build` next to this file) with the security headers
* the QQQ server sends with the export it hosts (QRun-IO/qqq#734, see security-headers.mjs).
*
* The identity provider origin comes from the backend's `GET /qqq/v1/metaData/authentication`
* (read through this server's own API rewrites). Other origins the dashboard must reach (a
* QuickSight embed, custom component bundles, image or media hosts) are added with
* `QQQ_DASHBOARD_CSP_SOURCES`, for example
* `frame-src https://*.quicksight.aws.amazon.com; script-src https://cdn.example.com`.
* Identity provider and application CSP sources come from the backend's
* `GET /qqq/v1/metaData/authentication`, through this server's own API rewrites.
* Additional operator-owned sources (or application sources on older backends) use
* `QQQ_DASHBOARD_CSP_SOURCES`, for example `img-src https://images.example.com`.
*/
import http from 'node:http'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { createBrandingAssetAlias } from './branding-assets.mjs'
import {
applyDashboardSecurityHeaders,
buildContentSecurityPolicy,
createIdentityProviderOrigins,
createDashboardPolicyInputs,
isBackendPath,
parseSourceAdditions,
} from './security-headers.mjs'
@@ -40,12 +41,20 @@ const additions = parseSourceAdditions(process.env.QQQ_DASHBOARD_CSP_SOURCES)
const port = parseInt(process.env.PORT ?? '', 10) || 3000
const listenHost = process.env.HOSTNAME || '0.0.0.0'
const selfHost = ['0.0.0.0', '::', ''].includes(listenHost) ? '127.0.0.1' : listenHost.includes(':') ? `[${listenHost}]` : listenHost
const identityProviderOrigins = createIdentityProviderOrigins(async () => {
const dashboardPolicyInputs = createDashboardPolicyInputs(async () => {
const response = await fetch(`http://${selfHost}:${port}/qqq/v1/metaData/authentication`, { signal: AbortSignal.timeout(5_000) })
if (!response.ok) throw new Error(`GET /qqq/v1/metaData/authentication answered ${response.status}`)
return response.json()
})
// These two fields are already public before sign-in. The fixed role endpoint requires
// a backend containing QQQ #1009; old backends retain their real 404, never a fallback UI.
const brandingAlias = createBrandingAssetAlias(async () => {
const response = await fetch(`http://${selfHost}:${port}/qqq/v1/metaData/authentication`, { signal: AbortSignal.timeout(5_000) })
if (!response.ok) throw new Error('Could not load public branding metadata')
return response.json()
}, fileURLToPath(new URL('./public', import.meta.url)))
// server.js creates one HTTP server; its request listener is wrapped to add the headers
const createServer = http.createServer
http.createServer = function (...args) {
@@ -54,9 +63,11 @@ http.createServer = function (...args) {
if (index < 0) throw new Error('The Next standalone server created its HTTP server without a request listener; the dashboard security headers cannot be added.')
const listener = args[index]
args[index] = async function (req, res) {
const asset = await brandingAlias(req.method, req.url ?? '/')
if (asset) req.url = asset
if (!isBackendPath(req.url ?? '/')) {
const connectOrigins = await identityProviderOrigins()
applyDashboardSecurityHeaders(req, res, (scriptHashes) => buildContentSecurityPolicy({ connectOrigins, additions, scriptHashes }))
const policyInputs = await dashboardPolicyInputs()
applyDashboardSecurityHeaders(req, res, (scriptHashes) => buildContentSecurityPolicy({ ...policyInputs, additions, scriptHashes }))
}
return listener.call(this, req, res)
}
+59 -9
View File
@@ -148,6 +148,48 @@ export function inlineScriptHashes(html) {
return [...hashes]
}
const SOURCE_FIELDS = { connectSrc: 'connect-src', scriptSrc: 'script-src', frameSrc: 'frame-src', styleSrc: 'style-src' }
const SPECIAL_SOURCES = {
connectSrc: new Set(['https://*.google-analytics.com', 'https://*.analytics.google.com', 'https://accounts.google.com/gsi/']),
scriptSrc: new Set(['https://accounts.google.com/gsi/client']),
frameSrc: new Set(['https://*.quicksight.aws.amazon.com', 'https://accounts.google.com/gsi/']),
styleSrc: new Set(['https://accounts.google.com/gsi/style']),
}
/**
* Copies four lists of at most 64 sources of 512 characters each. Invalid or
* oversized metadata is rejected as a whole; refresh retains the last valid inputs.
* Only origins and the backend's fixed wildcard/path constants are admitted.
* @param {unknown} value - The backend's optional source object.
* @returns {Record<string, string[]> | undefined} Validated source lists.
*/
function validatedDashboardSources(value) {
if (value === undefined) return undefined
const invalid = () => { throw new Error('Invalid dashboard CSP source metadata') }
if (value === null || typeof value !== 'object' || Array.isArray(value)) return invalid()
const fields = Object.keys(value)
if (fields.length !== 4 || fields.some((field) => !Object.hasOwn(SOURCE_FIELDS, field))) return invalid()
const copied = {}
for (const field of Object.keys(SOURCE_FIELDS)) {
const sources = value[field]
if (!Array.isArray(sources) || sources.length > 64) return invalid()
copied[field] = sources.map((source) => {
if (typeof source !== 'string' || source.length > 512 || /[\s;,'"?#@\\]/.test(source)) return invalid()
if (SPECIAL_SOURCES[field].has(source)) return source
if (source.includes('*')) return invalid()
try {
const url = new URL(source)
const origin = /^(https?):\/\/(\[[0-9a-f:.]+\]|[a-z0-9.-]+)(?::([0-9]{1,5}))?$/.exec(source)
if (!origin || !['http:', 'https:'].includes(url.protocol)) return invalid()
if (!origin[2].startsWith('[') && url.hostname !== origin[2]) return invalid()
if (origin[3] && Number(origin[3]) > 65535) return invalid()
} catch { return invalid() }
return source
})
}
return copied
}
/**
* Builds a document's Content-Security-Policy: the defaults, the identity provider origins
* (connect-src), the deployment's additions, then the document's inline script hashes.
@@ -155,12 +197,17 @@ export function inlineScriptHashes(html) {
* @param {object} options - The policy inputs.
* @param {string[]} [options.connectOrigins] - Identity provider origins.
* @param {[string, string[]][]} [options.additions] - The deployment's additions.
* @param {unknown} [options.dashboardCspSources] - Bounded source additions from public metadata.
* @param {string[]} [options.scriptHashes] - The document's inline script hashes.
* @returns {string} The header value.
*/
export function buildContentSecurityPolicy({ connectOrigins = [], additions = [], scriptHashes = [] } = {}) {
export function buildContentSecurityPolicy({ connectOrigins = [], additions = [], scriptHashes = [], dashboardCspSources } = {}) {
const directives = new Map(DEFAULT_DIRECTIVES.map(([name, sources]) => [name, new Set(sources)]))
for (const origin of connectOrigins) directives.get('connect-src').add(origin)
const metadataSources = validatedDashboardSources(dashboardCspSources)
for (const [field, sources] of Object.entries(metadataSources ?? {})) {
for (const source of sources) directives.get(SOURCE_FIELDS[field]).add(source)
}
for (const [name, sources] of additions) {
if (!directives.has(name)) directives.set(name, new Set())
for (const source of sources) directives.get(name).add(source)
@@ -170,28 +217,31 @@ export function buildContentSecurityPolicy({ connectOrigins = [], additions = []
}
/**
* Keeps the identity provider origins from the authentication metadata, refreshed in the
* Keeps validated policy inputs from authentication metadata, refreshed in the
* background once they are older than `ttlMs`; a failed refresh keeps the last value.
*
* @param {() => Promise<unknown>} loadAuthentication - Fetches the authentication metadata.
* @param {number} [ttlMs] - How long a value is fresh.
* @returns {() => Promise<string[]>} Resolves the current origins (waits only for the first load).
* @returns {() => Promise<{connectOrigins: string[], dashboardCspSources?: Record<string, string[]>}>} Current inputs; waits only for first load.
*/
export function createIdentityProviderOrigins(loadAuthentication, ttlMs = 60_000) {
let origins = null
export function createDashboardPolicyInputs(loadAuthentication, ttlMs = 60_000) {
let inputs = null
let loadedAt = 0
let loading = null
const load = () => {
loading ??= loadAuthentication()
.then((authentication) => { origins = identityProviderOrigins(authentication) })
.catch((error) => { console.warn('[qqq] Could not read the authentication metadata for the security policy:', error instanceof Error ? error.message : error) })
.then((authentication) => {
const dashboardCspSources = validatedDashboardSources(authentication?.dashboardCspSources)
inputs = { connectOrigins: identityProviderOrigins(authentication), dashboardCspSources }
})
.catch((error) => { console.warn('[qqq] Could not read the authentication metadata for the security policy:', error instanceof Error ? error.name : 'unknown') })
.finally(() => { loadedAt = Date.now(); loading = null })
return loading
}
return async () => {
if (origins === null) await load()
if (inputs === null) await load()
else if (Date.now() - loadedAt > ttlMs) void load()
return origins ?? []
return inputs ?? { connectOrigins: [] }
}
}
+136 -4
View File
@@ -33,16 +33,78 @@ QQQ_ACCEPTANCE_MODE=standalone pnpm test:acceptance # container-image build
- **javalin mode (default).** The static export (`pnpm build:export`, `out/`) goes on the
classpath as `next-dashboard/`, ahead of the sample jar. `QApplicationJavalinServer` then
serves it at `/`, which is exactly what a fresh application gets.
- **standalone mode.** Tests the Node standalone build that the container image uses.
- **standalone mode.** Tests the Node standalone build through the container's
`qqq-server.mjs` entrypoint. Builds twice from clean `.next` directories: a staged
authentication-variant build baked to the security backend, then the main build
baked to the shared backend. Next rewrites are build-time values; changing only a
server environment variable cannot retarget them. The variant validates its actual
route manifest and marker before startup, disables Java dashboard serving, and
restarts its owned Node server when authentication metadata changes. Javalin mode
still uses its export and does not start this second Node server.
- **API-versioned report setup.** The acceptance server loads the matching
`qqq-middleware-api` JAR from `~/.m2/repository/com/kingsrook/qqq/qqq-middleware-api/<version>/`.
Set `QQQ_MIDDLEWARE_API_JAR` to another path when Maven uses a different local repository.
The fixture registers one API-aware v1 version so WID-072 uses real metadata, query and count routes.
- **Ports.** Set them with `QQQ_ACCEPTANCE_BACKEND_PORT` (default 18765) and
`QQQ_ACCEPTANCE_FRONTEND_PORT` (default 13765). Use distinct ports for concurrent runs.
`QQQ_ACCEPTANCE_FRONTEND_PORT` (default 13765). The sample's embedded Artemis broker uses
`QQQ_ACCEPTANCE_ESB_PORT` (default 61616, passed as `qqq.sample.esb.port`). Use distinct
HTTP and broker ports for concurrent runs. The security variant uses
`QQQ_ACCEPTANCE_SECURITY_BACKEND_PORT` (default backend HTTP port + 10),
`QQQ_ACCEPTANCE_SECURITY_ESB_PORT` (default main ESB port + 1, normally 61617),
`QQQ_ACCEPTANCE_SECURITY_IDP_PORT` (default frontend HTTP port + 10), and
`QQQ_ACCEPTANCE_SECURITY_FRONTEND_PORT` (standalone browser origin, default frontend
HTTP port + 20). Browser redirects use the mode-specific UI origin; direct backend
control, SQL and permission/replay requests retain the security backend origin.
Its broker setting is passed as `qqq.sample.esb.port`; explicit variant
`options.properties` retain precedence over these defaults.
- **Results.** Output lands in `test-results/acceptance/`: `report.json`, `gate.json` (with
per-project counts in `byProject`), the HTML report, and a trace, video and screenshot for
each failure.
- **Transport evidence.** CI enables `QQQ_ACCEPTANCE_TRANSPORT_TRACE=1`; set it locally
to retain `QQQ_TRANSPORT` events in the acceptance server log for documents, static
chunks and versioned API requests. Events contain request/connection IDs, paths without
queries, status, write byte counts and failure classes; they omit headers, cookies and
bodies. A completed server write does not prove browser receipt or rendering. A write
can fail even when final completion reports HTTP 200, so inspect `firstWriteFailure`
separately. This observer is acceptance-only and adds synchronous logging overhead;
leave the variable unset for a control run with the original handler tree. Native and
ordinary server logs can still contain session data; keep raw evidence private.
- **Document/XHR evidence (opt-in).** Set `QQQ_ACCEPTANCE_BROWSER_TRACE=1` locally to
attach `browser-boundary.json` through the diagnostics fixture. CI uses `navigation`
mode only for the exact NAV023 unique-key and NAV056 application-theme-override cases
on WebKit/tablet; other cases, including SEC043, do not opt in through that mode.
By default, only `/app/person[/]`, `/app/person/key[/]`, `/app/person/2[/]`, and
`/app/person.bulkEdit[/]` documents on configured UI/API origins are observed. To also
capture dashboard documents at exactly `/app` and `/app/`, set
`QQQ_ACCEPTANCE_BROWSER_TRACE_SESSION=1` alongside `QQQ_ACCEPTANCE_BROWSER_TRACE=1`
locally. The session flag alone installs nothing and does not select additional tests;
other dashboard paths are not included. Requests are exact method/path matches:
GET person metadata, person record 2 and person.bulkEdit process metadata;
POST `/qqq/v1/manageSession`, querySavedView init, person query/count and person.bulkEdit init.
GET `/qqq/v1/manageSession` is excluded. The helper emits
fixed aliases, document UUID/sequence/clocks, native XHR send return/throw, status and
terminal events. It never emits URLs, query/hash values, headers, credentials, payloads,
error messages or stacks, and adds no request headers or interception. Disabled mode
installs no binding or init script. One listener set follows each reused XHR generation.
Native OPENED reentry or reuse before the recorder observes the prior `loadend`
emits one `xhr-incomplete` marker and suppresses attribution for that instance for
its remaining lifetime. This includes overlapping requests and earlier application
event listeners; no endpoint, generation or attempt is guessed. Excluded requests
retain only completion state so their old events cannot impersonate later selected
reuse; no excluded target data is emitted. Native calls and outcomes are preserved.
Each document is limited to 512 events plus an overflow marker and 256 selected XHRs;
Node retains at most 4096 validated events with invalid/drop counters. Missing delivery,
overflow or missing `ready` means incomplete evidence; zero counters do not prove
complete delivery. Lifecycle phase is the last
observed pagehide/pageshow state, not proof of browser-internal teardown; no unload or
beforeunload hooks are added. Snapshotting uses Node memory even after a page fails.
Existing diagnostics, assertions and timeouts are unchanged. RSC fetches and document
navigation are not XHRs: correlate existing Playwright/server/native traces instead.
Send-return disproves a synchronous throw for that invocation; a pageError alone does
not prove one. XHR load observes completion in JS, not UI rendering; successful server
writes still do not prove receipt. Binding delivery has nonzero overhead and can be
lost during destruction. Retain source/export/runner provenance and raw traces privately;
passing instrumented cells do not attribute historical failures or establish a fix.
- **Browsers.** `QQQ_ACCEPTANCE_BROWSERS` picks the Playwright projects (default `chromium`).
The documented matrix is `chromium,firefox,webkit,mobile`; results and the exact commands
are in `docs/acceptance/browser-matrix.md`.
@@ -76,7 +138,9 @@ there. Skipping them with `test.skip` is not allowed: skips fail the gate.
- **Use `test` and `expect` from `support/fixtures`.** Each test gets a freshly reset
database, its own mock session, and a persona (`test.use({ persona: 'viewer' })`).
- Personas are `admin`, `viewer` (reads only, no processes), `noPets`, `noProcesses`,
`noApps` and `expired` (401 with the cookie cleared). The sample sharing demo is enabled;
`noApps` and `expired` (401 with the cookie cleared). ESB personas are `noPersonRead`
(all permissions except `person.read`), `noEsbView`, `noEsbOperate`, `noEsbDelete`,
and `noSyncPerson` (each removes only its named access permission). The sample sharing demo is enabled;
choose its identity with `test.use({ user: 'bob' })` (alice by default).
- `backend.sql(select)` reads the owned H2 database directly. Use it to verify persisted
values independently of the UI and API.
@@ -93,11 +157,18 @@ there. Skipping them with `test.skip` is not allowed: skips fail the gate.
a navigation cancels are not failures: `ERR_ABORTED`/`NS_BINDING_ABORTED`/cancelled, and
WebKit's "… due to access control checks." for a same-origin Next.js route prefetch or
RSC payload reported within a second of a document navigation (listed under
`interruptedFetches` in the attached `diagnostics.json`).
`interruptedFetches` in the attached `diagnostics.json`). Firefox legacy-font diagnostics
are classified there only when the exact cancellation status matches a same-origin font
request from an earlier document near navigation (aborted, or HTTP 200 before decode was cancelled), and the final document successfully
loads and decodes that font. Every unmatched or failed-decode diagnostic still fails.
- **v1 only.** The `diagnostics` fixture also fails a test whose page calls an unversioned API
route of a QQQ server (`/data`, `/processes`, `/widget`, `/possibleValues`, `/download`,
`/reports`, `/metaData`, `/manageSession`, `/logout` outside `/qqq/v1`; QRun-IO/qqq#699).
`allow()` does not waive it. Node-side `backend.api` calls may still exercise legacy routes.
- **Transient feedback.** Arm `expectToastDuringAction` before the triggering action when
asserting a toast. It observes the visible exact text and notification count inside the
browser (plus header clearance when requested), so driver/trace delays cannot outlast the
notification before observation begins. Assert persistent form and database state afterwards.
- **Assert real behavior.** Check exact values, labels, counts and persisted rows. A 200
response or a visible container is not acceptance.
- **Fixtures.** Each area owns `fixture/<Area>Fixtures.java`: `define()` adds metadata;
@@ -106,3 +177,64 @@ there. Skipping them with `test.skip` is not allowed: skips fail the gate.
- **Matrix.** Each area owns `matrix/<area>.json` and its ID prefixes. A row has
`id, feature, source[], fixture, scenarios[], negative[], issues[], required`.
`docs/acceptance/feature-matrix.md` is generated from these files.
## Pinned Linux WebKit crash fix
The test runner is temporarily pinned to `@playwright/test@1.64.0-alpha-2026-10-01`: its WebKit 2369 bundle contains libsoup 3.6.6. The previous 1.58.2/WebKit 2248 bundle contains 3.6.5 and reproduced heap corruption during navigation; the same browser using the fixed library passed 110 targeted cases, and the official replacement passed 72 repeated WebKit/tablet cases against the native Linux fixture. The 110-case comparison also corrected an unrelated iframe forwarding problem; the reproduced heap crash occurred outside that iframe workflow. See [QQQ#904](https://github.com/QRun-IO/qqq/issues/904) and [upstream#42803](https://github.com/microsoft/playwright/issues/42803). This is test infrastructure, not a browser shipped with Next UI. Replace the dated pin with a stable release containing the fix after running the acceptance gate ([QQQ#973](https://github.com/QRun-IO/qqq/issues/973)); do not downgrade to the affected stable 1.63 merely to remove the prerelease suffix.
## ESB (QRun-IO/qqq#986)
The sample JAR must include its embedded Artemis broker, `personEvents` topic,
`syncPerson` subscriber, ESB app/widget, all nine management processes, and the ESB
module's real v1 routes. `EsbFixtures` requires that production wiring and fails startup
if it is absent; it never registers replacements. Its application step runs the sample subscriber, then writes an owned H2
receipt of the processed event; the failure control makes that step fail to exercise
real dead-lettering and replay. Production API responses and broker operations are
never mocked. All control routes remain on the loopback-only acceptance server.
Before each test, reset stops consumers, verifies they stopped, resumes then drains the owned
subscription and dead-letter queue, closes pooled connections, clears counters and
reseeds H2, then waits for both the subscriber and control channel to be ready.
Teardown stops and drains even when the test fails. The readiness route returns 200
only after initial fixture reset completes. The sample owns broker startup/shutdown.
The pause scenario reads actual Artemis consumer, delivery and message counts through
an owned support route: a PAUSED runner can still finish its outstanding receive,
so publishing waits until its broker consumer has closed. No fixed sleep or client
prefetch override is used.
```bash
# After building the sample JAR and production export; set QQQ_SAMPLE_JAR and
# QQQ_MIDDLEWARE_API_JAR as described above. Reserve both ports before starting.
QQQ_ACCEPTANCE_BACKEND_PORT=18961 QQQ_ACCEPTANCE_ESB_PORT=18962 \
QQQ_ACCEPTANCE_BROWSERS=chromium \
node scripts/acceptance.mjs --skip-build specs/esb --max-failures=1
```
`ESB-001`–`ESB-010` are required matrix rows. The sample has no management URL, so
these tests verify real trigger pause/resume/restart, topic-subscription browsing,
dead-letter replay, application/process/table permissions and unsupported-capability
hiding. Replay confirmation explicitly reports the unavailable broker count.
Successful broker-level purge/delete/move/pause and a numeric dead-letter count need
a broker management endpoint; this fixture does not claim to prove those operations.
The ESB table-probe blanket 404 diagnostic exemption is removed: unexpected failed
requests fail acceptance, and negative cases allow only their specific denial.
## Standalone security qualification (#734)
Preserve the original SEC-034..036 table-authentication requirements alongside the
header/enforcement rows SEC-038/040 and both SEC-039 provider-metadata cases:
```bash
QQQ_ACCEPTANCE_MODE=standalone \
QQQ_ACCEPTANCE_BROWSERS=chromium,firefox,webkit,mobile,tablet \
node scripts/acceptance.mjs --grep '\[SEC-(034|035|036|038|039|040)\]'
```
This bounded selection currently collects 43 cases (nine per desktop, eight per
phone/tablet; the Auth0 SEC-039 case is desktop-only). It uses the existing partial
matrix gate, zero retries and strict diagnostics. A passing Javalin run cannot
qualify this mode. Retain the actual Node response origins, both build identities,
frontend/backend source and artifact hashes, runtime versions, original failures
and raw reports. Never use a stale static export to make standalone variants pass.
The original loaded-branding assertion also remains required; missing standalone
assets must be investigated, not skipped. Local discovery or unit success is not
native qualification or issue closeout.
@@ -32,10 +32,8 @@ import com.kingsrook.qqq.backend.core.actions.permissions.AvailablePermission;
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
import com.kingsrook.qqq.backend.core.exceptions.QAuthenticationException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaDataInterface;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.session.QSession;
@@ -43,7 +41,6 @@ import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModu
import com.kingsrook.qqq.backend.module.rdbms.jdbc.ConnectionManager;
import com.kingsrook.qqq.frontend.materialdashboard.model.metadata.MaterialDashboardThemeMetaData;
import com.kingsrook.qqq.middleware.javalin.specs.v1.MiddlewareVersionV1;
import com.kingsrook.qqq.middleware.javalin.routeproviders.NextDashboardRouteProvider;
import com.kingsrook.qqq.middleware.javalin.routeproviders.NextDashboardSecurityHeaders;
import com.kingsrook.sampleapp.SampleJavalinServer;
import com.kingsrook.sampleapp.metadata.SampleMetaDataProvider;
@@ -64,6 +61,7 @@ public class AcceptanceSampleServer
private static final Map<String, String> USERS = new ConcurrentHashMap<>();
private static final ThreadLocal<String> REQUEST_SESSION_COOKIE = new ThreadLocal<>();
private static volatile QInstance instance;
private static volatile boolean ready;
@@ -108,6 +106,7 @@ public class AcceptanceSampleServer
QInstance defined = super.defineQInstance();
defined.setDefaultPermissionRules(QPermissionRules.defaultInstance().withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS));
defined.getAuthentication().setCustomizer(new QCodeReference(PersonaCustomizer.class));
EsbFixtures.define(defined);
NavigationFixtures.define(defined);
RecordsFixtures.define(defined);
FormAdjusterFixtures.define(defined);
@@ -126,7 +125,18 @@ public class AcceptanceSampleServer
server.withJavalinConfigCustomizer(config ->
{
config.jetty.host = "127.0.0.1";
config.routes.get("/acceptance/ready", context -> context.result("ready"));
AcceptanceTransportTrace.configure(config);
config.routes.get("/acceptance/ready", context -> context.status(ready ? 200 : 503).result(ready ? "ready" : "starting"));
config.routes.post("/acceptance/esb/failure", context ->
{
EsbFixtures.setFailure(new JSONObject(context.body()).getBoolean("fail"));
context.contentType("application/json").result("{}");
});
config.routes.post("/acceptance/esb/stop", context ->
{
EsbFixtures.stopAndDrain(instance);
context.contentType("application/json").result("{}");
});
//////////////////////////////////////////////////////////////////////////////
// manageSession creates a new mock session; keep the test's persona and user //
// by resolving them from the request's sessionId cookie for that request. //
@@ -160,6 +170,10 @@ public class AcceptanceSampleServer
}
context.contentType("application/json").result(new JSONObject().put("rows", select(query)).toString());
});
config.routes.post("/acceptance/esb/subscription-state", context ->
{
context.contentType("application/json").result(new JSONObject(EsbFixtures.subscriptionState(instance)).toString());
});
config.routes.post("/acceptance/quick-view", context ->
{
seedQuickView();
@@ -190,8 +204,18 @@ public class AcceptanceSampleServer
//////////////////////////////////////////////////////////////////////////////////
server.withNextDashboardSecurityHeadersCustomizer(WidgetsFixtures::allowFakeService);
Runtime.getRuntime().addShutdownHook(new Thread(server::stop));
server.start();
primeFixtures();
try
{
server.start();
EsbFixtures.awaitReady();
reset();
ready = true;
}
catch(Exception e)
{
server.stop();
throw e;
}
}
@@ -220,6 +244,7 @@ public class AcceptanceSampleServer
*******************************************************************************/
private static synchronized void reset() throws Exception
{
EsbFixtures.stopAndDrain(instance);
instance.getEnvironmentValues().remove("GOOGLE_APP_CLIENT_ID");
instance.getEnvironmentValues().remove("GOOGLE_APP_API_KEY");
if(instance.getSupplementalMetaData() != null)
@@ -229,6 +254,7 @@ public class AcceptanceSampleServer
SampleMetaDataProvider.primeTestDatabase("prime-test-database.sql");
SampleMetaDataProvider.primeTestDatabase("prime-sharing-database.sql");
primeFixtures();
EsbFixtures.start(instance);
}
@@ -244,6 +270,7 @@ public class AcceptanceSampleServer
{
throw new IllegalStateException("Acceptance fixtures require the sample in-memory H2 database.");
}
EsbFixtures.prime(connection);
NavigationFixtures.prime(connection);
RecordsFixtures.prime(connection);
FormAdjusterFixtures.prime(connection);
@@ -336,29 +363,13 @@ public class AcceptanceSampleServer
/*******************************************************************************
** The origins the QQQ server adds to the dashboard's Content-Security-Policy
** for this application (a QuickSight embed and custom component bundles from
** metadata, then the override hook's), written as QQQ_DASHBOARD_CSP_SOURCES:
** in standalone mode the container image's Node server serves the dashboard
** and takes them from that variable (QRun-IO/qqq#734).
** Only the explicit owned-service overrides. Application metadata sources
** must come from the production authentication metadata contract.
*******************************************************************************/
private static String dashboardCspSources()
{
NextDashboardSecurityHeaders defaults = new NextDashboardSecurityHeaders();
NextDashboardSecurityHeaders headers = new NextDashboardSecurityHeaders();
for(QWidgetMetaDataInterface widget : instance.getWidgets().values())
{
if(WidgetType.QUICK_SIGHT_CHART.getType().equals(widget.getType()))
{
headers.withSources("frame-src", NextDashboardRouteProvider.QUICKSIGHT_FRAME_SOURCE);
}
Object sourceUrl = widget.getDefaultValues() == null ? null : widget.getDefaultValues().get("componentSourceUrl");
String origin = sourceUrl == null ? null : NextDashboardSecurityHeaders.originOf(String.valueOf(sourceUrl));
if(WidgetType.CUSTOM_COMPONENT.getType().equals(widget.getType()) && origin != null)
{
headers.withSources(NextDashboardSecurityHeaders.SCRIPT_SRC, origin);
}
}
WidgetsFixtures.allowFakeService(headers);
List<String> parts = new ArrayList<>();
@@ -386,13 +397,22 @@ public class AcceptanceSampleServer
{
all.add(new AvailablePermission().withName(process + ".hasAccess").withObjectName(process).withObjectType("Process").withPermissionType("hasAccess"));
}
all.add(new AvailablePermission().withName("syncPerson.hasAccess").withObjectName("syncPerson").withObjectType("Process").withPermissionType("hasAccess"));
// Remove permission names, including grants shared by an app and a widget.
Set<String> appPermissions = all.stream().filter(permission -> "App".equals(permission.getObjectType()))
.map(AvailablePermission::getName).collect(Collectors.toSet());
Predicate<AvailablePermission> keep = switch(persona)
{
case "viewer" -> permission -> !"Process".equals(permission.getObjectType())
&& !permission.getName().matches(".*\\.(insert|edit|delete)$");
case "noPersonRead" -> permission -> !"person.read".equals(permission.getName());
case "noEsbView" -> permission -> !"esbView.hasAccess".equals(permission.getName());
case "noEsbOperate" -> permission -> !"esbOperate.hasAccess".equals(permission.getName());
case "noEsbDelete" -> permission -> !"esbDelete.hasAccess".equals(permission.getName());
case "noSyncPerson" -> permission -> !"syncPerson.hasAccess".equals(permission.getName());
case "noPets" -> permission -> !permission.getName().startsWith("pet.") && !permission.getName().startsWith("petNote.");
case "noProcesses" -> permission -> !"Process".equals(permission.getObjectType());
case "noApps" -> permission -> !"App".equals(permission.getObjectType());
case "noApps" -> permission -> !appPermissions.contains(permission.getName());
default -> permission -> true;
};
return all.stream().filter(keep).map(AvailablePermission::getName).collect(Collectors.toSet());
@@ -0,0 +1,151 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import io.javalin.config.JavalinConfig;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.io.Content;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.EventsHandler;
import org.json.JSONObject;
/*******************************************************************************
** Opt-in, metadata-only transport evidence for browser availability. This fixture
** observes Jetty write callbacks and final completion, after Javalin's request
** logger (which runs before output/compression closure). It never consumes a
** request/response buffer, changes headers, or logs cookie/body/query values.
*******************************************************************************/
public final class AcceptanceTransportTrace extends EventsHandler
{
private final AtomicLong sequence = new AtomicLong();
private final Map<Request, Observation> requests = new ConcurrentHashMap<>();
/***************************************************************************
** Javalin 7.2.3 applies this customizer before attaching its servlet context
** beneath the wrapper. Disabled runs retain the original handler tree.
***************************************************************************/
public static void configure(JavalinConfig config)
{
if("1".equals(System.getenv("QQQ_ACCEPTANCE_TRANSPORT_TRACE")))
{
config.jetty.modifyServer(server ->
{
AcceptanceTransportTrace observer = new AcceptanceTransportTrace();
observer.setHandler(server.getHandler());
server.setHandler(observer);
});
}
}
@Override
protected void onBeforeHandling(Request request)
{
String path = request.getHttpURI().getPath();
if(path.equals("/") || path.startsWith("/app/") || path.startsWith("/_next/static/") || path.startsWith("/qqq/v1/"))
{
requests.put(request, new Observation(sequence.incrementAndGet()));
emit(request, "start", 0, false, null);
}
}
@Override
protected void onResponseBegin(Request request, int status, HttpFields headers)
{
Observation observation = requests.get(request);
if(observation != null) observation.status = status;
emit(request, "response-begin", 0, false, null);
}
@Override
protected void onResponseWriteComplete(Request request, boolean last, ByteBuffer content, Throwable failure)
{
// Jetty supplies a read-only duplicate retaining the original write bounds.
// A failed write may have sent only part; its bytes are attempted, not delivered.
int bytes = content == null ? 0 : content.remaining();
Observation observation = requests.get(request);
if(observation != null && failure == null) observation.successfulWriteBytes.addAndGet(bytes);
if(observation != null && failure != null) observation.firstWriteFailure.compareAndSet(null, failure.getClass().getName());
emit(request, "write-complete", bytes, last, failure);
}
@Override
protected void onAfterHandling(Request request, boolean handled, Throwable failure)
{
emit(request, "handler-return", 0, false, failure);
}
@Override
protected void onComplete(Request request, int status, HttpFields headers, Throwable failure)
{
Observation observation = requests.get(request);
if(observation != null) observation.status = status;
emit(request, "complete", 0, true, failure);
requests.remove(request);
}
// Override payload-bearing default debug callbacks: even DEBUG must not dump
// request content, response buffers, headers, or trailers from this observer.
@Override
protected void onRequestRead(Request request, Content.Chunk chunk) { }
@Override
protected void onResponseWrite(Request request, boolean last, ByteBuffer content) { }
@Override
protected void onResponseTrailersComplete(Request request, HttpFields trailers) { }
private void emit(Request request, String event, int writeBytes, boolean last, Throwable failure)
{
Observation observation = requests.get(request);
if(observation == null) return;
System.out.println("QQQ_TRANSPORT " + new JSONObject()
.put("time", Instant.now().toString())
.put("nanoTime", System.nanoTime())
.put("pid", ProcessHandle.current().pid())
.put("requestId", observation.id)
.put("connectionId", request.getConnectionMetaData().getId())
.put("method", request.getMethod())
.put("path", request.getHttpURI().getPath())
.put("event", event)
.put("status", observation.status == 0 ? JSONObject.NULL : observation.status)
.put("writeBytes", writeBytes)
// Completed server writes do not prove client receipt, decode or paint.
.put("successfulWriteBytes", observation.successfulWriteBytes.get())
.put("last", last)
// Javalin can handle a failed write, leaving final completion's failure null.
.put("firstWriteFailure", observation.firstWriteFailure.get() == null ? JSONObject.NULL : observation.firstWriteFailure.get())
.put("failure", failure == null ? JSONObject.NULL : failure.getClass().getName()));
}
private static final class Observation
{
private final long id;
private final AtomicLong successfulWriteBytes = new AtomicLong();
private volatile int status;
private final AtomicReference<String> firstWriteFailure = new AtomicReference<>();
private Observation(long id)
{
this.id = id;
}
}
}
+265
View File
@@ -0,0 +1,265 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.esb.api.EsbRouteProvider;
import com.kingsrook.qqq.esb.metadata.EsbOverviewWidgetMetaDataProducer;
import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.module.rdbms.jdbc.ConnectionManager;
import com.kingsrook.qqq.esb.connection.EsbConnectionManager;
import com.kingsrook.qqq.esb.management.EsbBrokerNames;
import com.kingsrook.qqq.esb.model.EsbProcessMetaData;
import com.kingsrook.qqq.esb.model.EsbProviderType;
import com.kingsrook.qqq.esb.runtime.QEsbRuntime;
import com.kingsrook.qqq.esb.runtime.EsbTriggerState;
import com.kingsrook.qqq.esb.stats.EsbStats;
import com.kingsrook.qqq.esb.envelope.EsbEvent;
import com.kingsrook.sampleapp.metadata.SampleMetaDataProvider;
import com.kingsrook.sampleapp.processes.syncperson.SyncPersonStep;
import jakarta.jms.Message;
import jakarta.jms.MessageConsumer;
import jakarta.jms.MessageProducer;
import jakarta.jms.TemporaryQueue;
import org.apache.activemq.artemis.api.jms.management.JMSManagementHelper;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import jakarta.jms.Session;
/*******************************************************************************
** Uses the sample's real broker, publication, runtime and subscriber. Only the
** application step is augmented: record its effect in owned H2 and allow a
** controlled application failure to exercise real dead-lettering and replay.
*******************************************************************************/
public class EsbFixtures
{
private static final String PROVIDER = "sampleArtemis";
private static final String TRIGGER = "syncPerson.personEvents";
private static volatile boolean failSync;
public static void define(QInstance instance) throws QException
{
// Require production sample wiring; registering it here would conceal a
// stock sample integration defect and invalidate acceptance evidence.
if(instance.getApp("esb") == null || instance.getWidget(EsbOverviewWidgetMetaDataProducer.NAME) == null)
{
throw new QException("The sample JAR must register its ESB app and overview widget");
}
for(String name : List.of("esbPauseTrigger", "esbResumeTrigger", "esbRestartTrigger", "esbReplayDeadLetters",
"esbPauseQueue", "esbResumeQueue", "esbMoveMessages", "esbPurgeQueue", "esbDeleteMessages"))
{
if(instance.getProcess(name) == null)
{
throw new QException("The sample JAR must register its ESB process " + name);
}
}
List<QCodeReference> routes = QJavalinMetaData.ofOrWithNew(instance).getAdditionalRouteProviderReferences();
if(routes == null || routes.stream().noneMatch(route -> EsbRouteProvider.class.getName().equals(route.getName())))
{
throw new QException("The sample JAR must register EsbRouteProvider");
}
QBackendStepMetaData step = (QBackendStepMetaData) instance.getProcess("syncPerson").getStep("sync");
step.setCode(new QCodeReference(ReceiptStep.class));
EsbProcessMetaData.of(instance.getProcess("syncPerson")).getTriggers().get(0).setMaxAttempts(1);
}
public static void prime(Connection connection) throws Exception
{
failSync = false;
try(Statement statement = connection.createStatement())
{
statement.execute("DROP TABLE IF EXISTS acceptance_esb_receipt");
statement.execute("CREATE TABLE acceptance_esb_receipt (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, subject VARCHAR(100), event_type VARCHAR(200), first_name VARCHAR(200))");
}
}
public static void setFailure(boolean fail)
{
failSync = fail;
}
/*******************************************************************************
** Read the actual owned subscription's broker state. A PAUSED runner can
** still be finishing its outstanding receive; tests wait for zero consumers
** before publishing the message they require to remain on the broker.
*******************************************************************************/
public static Map<String, Long> subscriptionState(QInstance instance) throws Exception
{
QContext.init(instance, new QSession());
String subscription = EsbBrokerNames.subscriptionQueue(EsbProviderType.ACTIVEMQ_ARTEMIS, "personEvents", TRIGGER);
String queueName = subscription.substring(subscription.indexOf("::") + 2);
Map<String, Long> state = new java.util.LinkedHashMap<>();
try(Session session = EsbConnectionManager.getInstance().openSession(PROVIDER, false))
{
TemporaryQueue replies = session.createTemporaryQueue();
try(MessageConsumer consumer = session.createConsumer(replies);
MessageProducer producer = session.createProducer(session.createQueue("activemq.management")))
{
for(String attribute : List.of("consumerCount", "deliveringCount", "messageCount"))
{
Message request = session.createMessage();
JMSManagementHelper.putAttribute(request, ResourceNames.QUEUE + queueName, attribute);
request.setJMSReplyTo(replies);
producer.send(request);
Message reply = consumer.receive(5000);
if(reply == null || !JMSManagementHelper.hasOperationSucceeded(reply))
{
throw new IllegalStateException("Could not read owned subscription " + attribute);
}
state.put(attribute, ((Number) JMSManagementHelper.getResult(reply)).longValue());
}
}
finally
{
replies.delete();
}
}
return state;
}
/*******************************************************************************
** Stop first so no subscriber can race H2 reseeding or leave a delivery in
** flight. Drain only this fixture's queues; never touch unrelated brokers.
*******************************************************************************/
public static void stopAndDrain(QInstance instance) throws Exception
{
QEsbRuntime runtime = QEsbRuntime.getInstance();
runtime.stop();
if(runtime.getRunners().stream().anyMatch(runner -> runner.getState() != EsbTriggerState.STOPPED))
{
throw new IllegalStateException("ESB consumers did not stop before acceptance reset");
}
QContext.init(instance, new QSession());
try(Session session = EsbConnectionManager.getInstance().openSession(PROVIDER, true))
{
String subscription = EsbBrokerNames.subscriptionQueue(EsbProviderType.ACTIVEMQ_ARTEMIS, "personEvents", TRIGGER);
for(String name : List.of(subscription, "personEvents." + TRIGGER + ".dlq"))
{
try(MessageConsumer consumer = session.createConsumer(EsbConnectionManager.getInstance().resolveQueue(session, PROVIDER, name)))
{
resumeQueue(name);
int count = 0;
while(consumer.receive(100) != null)
{
session.commit();
if(++count > 10000)
{
throw new IllegalStateException("Acceptance queue drain exceeded its bound: " + name);
}
}
session.commit();
}
}
}
EsbConnectionManager.getInstance().closeAll();
EsbStats.getInstance().reset();
failSync = false;
}
/*******************************************************************************
** Reset uses Artemis's real management-message API (no HTTP adapter or mock).
** Queue consumers are created before this call so an empty DLQ exists too.
*******************************************************************************/
private static void resumeQueue(String brokerName) throws Exception
{
String queueName = brokerName.contains("::") ? brokerName.substring(brokerName.indexOf("::") + 2) : brokerName;
try(Session session = EsbConnectionManager.getInstance().openSession(PROVIDER, false))
{
TemporaryQueue replies = session.createTemporaryQueue();
try(MessageConsumer consumer = session.createConsumer(replies);
MessageProducer producer = session.createProducer(session.createQueue("activemq.management")))
{
Message request = session.createMessage();
JMSManagementHelper.putOperationInvocation(request, ResourceNames.QUEUE + queueName, "resume");
request.setJMSReplyTo(replies);
producer.send(request);
Message reply = consumer.receive(5000);
if(reply == null || !JMSManagementHelper.hasOperationSucceeded(reply))
{
throw new IllegalStateException("Could not resume owned acceptance queue " + queueName + ": " +
(reply == null ? "management response timed out" : JMSManagementHelper.getResult(reply)));
}
}
finally
{
replies.delete();
}
}
}
public static void start(QInstance instance) throws Exception
{
QEsbRuntime runtime = QEsbRuntime.getInstance();
runtime.start(instance);
awaitReady();
}
public static void awaitReady() throws Exception
{
QEsbRuntime runtime = QEsbRuntime.getInstance();
long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(15);
while(!runtime.isRunning() || runtime.getRunner(TRIGGER).getState() != EsbTriggerState.RUNNING)
{
if(System.nanoTime() >= deadline)
{
throw new IllegalStateException("Sample ESB trigger/control subscription was not ready within 15 seconds");
}
Thread.sleep(25);
}
}
public static class ReceiptStep extends SyncPersonStep
{
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
if(failSync)
{
throw new QException("Owned acceptance sync failure");
}
super.run(input, output);
@SuppressWarnings("unchecked")
List<EsbEvent> events = (List<EsbEvent>) input.getValue("esbMessages");
try(Connection connection = ConnectionManager.getConnection(SampleMetaDataProvider.defineRdbmsBackend());
PreparedStatement statement = connection.prepareStatement("INSERT INTO acceptance_esb_receipt (subject, event_type, first_name) VALUES (?, ?, ?)"))
{
for(EsbEvent event : events)
{
Map<?, ?> values = (Map<?, ?>) event.getData().get("record");
statement.setString(1, event.getSubject());
statement.setString(2, event.getType());
statement.setString(3, values == null ? null : String.valueOf(values.get("firstName")));
statement.executeUpdate();
}
}
catch(Exception e)
{
throw new QException("Failed to record the owned subscriber effect", e);
}
}
}
}
@@ -117,6 +117,21 @@ public class SecurityAcceptanceServer
}
default -> throw new QException("Unknown qqq.security.auth: " + AUTH);
}
String analyticsOrigin = System.getProperty("qqq.security.analytics.origin");
if(analyticsOrigin != null)
{
if(!analyticsOrigin.matches("http://127\\.0\\.0\\.1:[0-9]{1,5}"))
{
throw new QException("The owned analytics fixture requires a loopback origin.");
}
Map<String, String> environment = new java.util.LinkedHashMap<>(defined.getEnvironmentValues());
environment.put("ANALYTICS_PROVIDERS", "posthog");
environment.put("ANALYTICS_PLUGIN_SCRIPTS", analyticsOrigin + "/owned-plugin.js");
environment.put("POSTHOG_ENABLED", "true");
environment.put("POSTHOG_PROJECT_API_KEY", "owned-test-key");
environment.put("POSTHOG_HOST", analyticsOrigin);
defined.setEnvironmentValues(environment);
}
instance = defined;
return defined;
}
@@ -311,13 +326,16 @@ public class SecurityAcceptanceServer
static Set<String> permissionsFor(String persona)
{
Collection<AvailablePermission> all = PermissionsHelper.getAllAvailablePermissions(instance);
// Remove permission names, including grants shared by an app and a widget.
Set<String> appPermissions = all.stream().filter(permission -> "App".equals(permission.getObjectType()))
.map(AvailablePermission::getName).collect(Collectors.toSet());
Predicate<AvailablePermission> keep = switch(persona)
{
case "viewer" -> permission -> !"Process".equals(permission.getObjectType())
&& !permission.getName().matches(".*\\.(insert|edit|delete)$");
case "noPets" -> permission -> !permission.getName().startsWith("pet.") && !permission.getName().startsWith("petNote.");
case "noProcesses" -> permission -> !"Process".equals(permission.getObjectType());
case "noApps" -> permission -> !"App".equals(permission.getObjectType());
case "noApps" -> permission -> !appPermissions.contains(permission.getName());
default -> permission -> true;
};
return all.stream().filter(keep).map(AvailablePermission::getName).collect(Collectors.toSet());
+214
View File
@@ -0,0 +1,214 @@
{
"area": "esb",
"prefixes": [
"ESB"
],
"description": "Real embedded Artemis ESB workflows, permissions and supported management actions",
"rows": [
{
"id": "ESB-001",
"feature": "Admin overview and real table-to-process delivery",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Admin sees personEvents topic and syncPerson trigger",
"Create Person in the UI uses the real v1 API and increments consumed and succeeded; H2 receipt contains the inserted person"
],
"negative": [
"Fresh test starts with zero consumed and no receipts"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-002",
"feature": "Developer publications, subscribers and safe process links",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Person Developer view shows INSERT UPDATE DELETE and Sync Person subscriber",
"Following the process link opens its Developer view and exposes trigger metadata"
],
"negative": [
"No process init request or receipt from navigating metadata"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-003",
"feature": "Person READ permission",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"All-except-person-READ persona retains ESB app and process access"
],
"negative": [
"Table section is absent; its browser request and direct backend request return 403"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-004",
"feature": "ESB app permission",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Table READ independently allows the table section"
],
"negative": [
"No ESB navigation link and direct overview is 403 without esbView"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-005",
"feature": "Subscriber process permission",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Person publication remains visible without syncPerson access"
],
"negative": [
"Subscriber is omitted; process and dead-letter endpoints return 403"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-006",
"feature": "Trigger lifecycle and topic subscription",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Pause queues a real event; subscription browsing shows its body without consumption",
"Resume delivers and writes a receipt; restart completes and delivers the next event"
],
"negative": [
"No receipt while paused; each action reports its final completion"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-007",
"feature": "Operate permission enforcement",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Delete permission remains independent when operate is denied"
],
"negative": [
"Pause resume restart replay queue pause queue resume and move all return 403; controls absent"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-008",
"feature": "Delete permission enforcement",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Operate remains available without delete"
],
"negative": [
"Purge and delete requests return 403; destructive controls absent"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-009",
"feature": "Broker capability gating",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Real JMS subscription browsing works without managementUrl"
],
"negative": [
"Queue pause resume purge delete and move controls are absent when capabilities are false"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
},
{
"id": "ESB-010",
"feature": "Dead-letter replay confirmation and delivery",
"source": [
"QRun-IO/qqq#986 (transferred from frontend#10; task 18 and addendum)",
"qqq/docs/specs/2026-09-25-qqq-esb-design.md sections 7-9,12"
],
"fixture": "SampleJavalinServer embedded Artemis + EsbFixtures receipt/failure/reset support",
"scenarios": [
"Intentional application failure produces a real dead letter",
"Confirmed replay removes the dead letter and records successful subscriber effect"
],
"negative": [
"Unknown broker count is disclosed in confirmation",
"Opening and cancelling confirmation issues no replay and preserves the message"
],
"issues": [
"QRun-IO/qqq#986",
"QRun-IO/qqq#990"
],
"required": true
}
]
}
+243
View File
@@ -0,0 +1,243 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import { test, expect, open, type Backend } from '../../support/fixtures'
import type { EsbOverviewResponse, EsbTableResponse, EsbProcessResponse } from '../../../../src/types/esb'
const TRIGGER = 'syncPerson.personEvents'
const triggerRow = `[data-qqq-id="esb-trigger-${TRIGGER}"]`
async function overview(backend: Backend): Promise<EsbOverviewResponse> {
const response = await backend.api.get('/qqq/v1/esb/overview')
expect(response.status()).toBe(200)
expect(response.headers()['content-type'], 'ESB must return JSON, not an API docs or SPA fallback').toContain('application/json')
return response.json()
}
async function personStatus(backend: Backend): Promise<EsbTableResponse> {
const response = await backend.api.get('/qqq/v1/esb/table/person')
expect(response.status()).toBe(200)
expect(response.headers()['content-type'], 'ESB must return JSON, not an API docs or SPA fallback').toContain('application/json')
return response.json()
}
async function insertPerson(backend: Backend, firstName: string) {
const response = await backend.api.post('/qqq/v1/table/person', {
multipart: { firstName, lastName: 'ESB Acceptance', email: `${firstName.toLowerCase()}@example.invalid` },
})
expect(response.status()).toBe(200)
return response.json()
}
async function receipts(backend: Backend) {
return backend.sql('SELECT subject, event_type, first_name FROM acceptance_esb_receipt ORDER BY id')
}
test('[ESB-001] admin sees the real topic and trigger; inserting a person runs its subscriber @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/esb')
await expect(page.locator('[data-qqq-id="esb-destination-personEvents"]')).toContainText('Topic')
const row = page.locator(triggerRow)
await expect(row).toContainText('Sync Person')
await expect(row).toContainText('Running')
const before = (await overview(backend)).destinations.find((destination) => destination.name === 'personEvents')!
expect(before.triggers[0].counters.consumed).toBe(0)
expect(await receipts(backend)).toEqual([])
await open(page, '/app/person/create')
await page.locator('#field-firstName').fill('River')
await page.locator('#field-lastName').fill('ESB Acceptance')
await page.locator('#field-email').fill('river@example.invalid')
await page.getByRole('button', { name: 'Save', exact: true }).click()
await expect(page.getByRole('heading', { level: 1, name: 'River ESB Acceptance' })).toBeVisible()
await expect.poll(async () => (await personStatus(backend)).subscribers[0].counters.succeeded).toBe(1)
const status = await personStatus(backend)
expect(status.subscribers[0].counters).toMatchObject({ consumed: 1, succeeded: 1, failed: 0, inFlight: 0 })
const people = await backend.sql("SELECT id FROM person WHERE first_name = 'River'")
expect(await receipts(backend)).toEqual([{ subject: people[0].id, event_type: 'qqq.table.person.inserted', first_name: 'River' }])
await open(page, '/app/esb')
await expect(row.locator('div').filter({ has: page.locator('dt').filter({ hasText: /^Consumed$/ }) }).locator('dd')).toHaveText('1')
})
test('[ESB-002] table and process Developer views expose publications and subscribers without running a process @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
const processInits: string[] = []
page.on('request', (request) => {
if (request.method() === 'POST' && /\/qqq\/v1\/processes\/.*\/init$/.test(new URL(request.url()).pathname)) processInits.push(request.url())
})
await open(page, '/app/person/dev')
const section = page.locator('[data-qqq-id="esb-section-person"]')
await expect(section.getByRole('table', { name: 'Publications', exact: true })).toContainText('INSERT, UPDATE, DELETE')
await expect(section.getByRole('table', { name: 'Subscribers', exact: true })).toContainText('Sync Person')
const link = section.getByRole('link', { name: 'Sync Person', exact: true })
await expect(link).toHaveAttribute('href', /^\/app\/syncPerson\/dev\/?$/)
await link.click()
await expect(page).toHaveURL(/\/app\/syncPerson\/dev\/?$/)
await expect(page.locator('[data-qqq-id="esb-section-syncPerson"]')).toContainText('personEvents')
const response = await backend.api.get('/qqq/v1/esb/process/syncPerson')
expect(response.status()).toBe(200)
const process: EsbProcessResponse = await response.json()
expect(process.triggers.map((trigger) => trigger.name)).toEqual([TRIGGER])
expect(processInits).toEqual([])
expect(await receipts(backend)).toEqual([])
})
test.describe('table READ enforcement', () => {
test.use({ persona: 'noPersonRead' })
test('[ESB-003] no person READ hides the section and the server refuses its data @mobile', async ({ page, backend, diagnostics }) => {
diagnostics.allow(/^request: GET \/qqq\/v1\/esb\/table\/person 403$/)
diagnostics.allow(/^console: Failed to load resource: the server responded with a status of 403 \(Forbidden\)$/)
const denied = page.waitForResponse((response) => new URL(response.url()).pathname === '/qqq/v1/esb/table/person')
await open(page, '/app/person/dev')
expect((await denied).status()).toBe(403)
await expect(page.locator('[data-qqq-id="esb-section-person"]')).toHaveCount(0)
expect((await backend.api.get('/qqq/v1/esb/table/person')).status()).toBe(403)
// This persona still has ESB app and process access; only person.read is removed.
expect((await overview(backend)).destinations.map((destination) => destination.name)).toContain('personEvents')
expect((await backend.api.get('/qqq/v1/esb/process/syncPerson')).status()).toBe(200)
})
})
test.describe('app enforcement', () => {
test.use({ persona: 'noEsbView' })
test('[ESB-004] no ESB app access hides navigation and denies overview while table READ still works @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/person/dev')
await expect(page.locator('[data-qqq-id="esb-section-person"]')).toBeVisible()
await expect(page.getByRole('link', { name: 'ESB', exact: true })).toHaveCount(0)
expect((await backend.api.get('/qqq/v1/esb/overview')).status()).toBe(403)
expect((await personStatus(backend)).subscribers[0].name).toBe(TRIGGER)
})
})
test.describe('subscriber enforcement', () => {
test.use({ persona: 'noSyncPerson' })
test('[ESB-005] a denied process is omitted from subscribers and its endpoints refuse access @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/person/dev')
const section = page.locator('[data-qqq-id="esb-section-person"]')
await expect(section).toContainText('personEvents')
await expect(section).toContainText('No processes you can access are triggered by these destinations.')
await expect(section.getByRole('link', { name: 'Sync Person', exact: true })).toHaveCount(0)
expect((await personStatus(backend)).subscribers).toEqual([])
expect((await backend.api.get('/qqq/v1/esb/process/syncPerson')).status()).toBe(403)
expect((await backend.api.get(`/qqq/v1/esb/deadLetters/${TRIGGER}`)).status()).toBe(403)
})
})
test('[ESB-006] pause holds a real message in the topic subscription; resume and restart complete @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/esb')
const row = page.locator(triggerRow)
await row.getByRole('button', { name: 'Pause Sync Person', exact: true }).click()
await expect.poll(async () => (await personStatus(backend)).subscribers[0].state).toBe('PAUSED')
await expect(page.getByText('esbPauseTrigger completed.', { exact: true })).toBeVisible()
// PAUSED is a requested state: the runner closes its consumer after the
// outstanding receive finishes. Observe the real broker boundary, not time.
await expect.poll(() => backend.esbSubscriptionState()).toEqual({ consumerCount: 0, deliveringCount: 0, messageCount: 0 })
await insertPerson(backend, 'Paused')
await expect.poll(() => backend.esbSubscriptionState()).toEqual({ consumerCount: 0, deliveringCount: 0, messageCount: 1 })
await row.getByRole('button', { name: /Browse subscription/ }).click()
const dialog = page.getByRole('dialog')
await expect(dialog.getByRole('table', { name: 'Messages', exact: true })).toContainText('qqq.table.person.inserted')
await dialog.getByText('Body', { exact: true }).click()
await expect(dialog.locator('pre')).toContainText('Paused')
expect((await personStatus(backend)).subscribers[0].counters.consumed).toBe(0)
expect(await receipts(backend)).toEqual([])
await dialog.getByRole('button', { name: 'Close', exact: true }).click()
await row.getByRole('button', { name: 'Resume Sync Person', exact: true }).click()
await expect(page.getByText('esbResumeTrigger completed.', { exact: true })).toBeVisible()
await expect.poll(async () => (await personStatus(backend)).subscribers[0].counters.succeeded).toBe(1)
expect((await receipts(backend)).map((receipt) => receipt.first_name)).toEqual(['Paused'])
await row.getByRole('button', { name: 'Restart Sync Person', exact: true }).click()
await expect(page.getByText('esbRestartTrigger completed.', { exact: true })).toBeVisible()
await expect.poll(async () => (await personStatus(backend)).subscribers[0].state).toBe('RUNNING')
await insertPerson(backend, 'Restarted')
await expect.poll(async () => (await receipts(backend)).map((receipt) => receipt.first_name)).toEqual(['Paused', 'Restarted'])
})
test.describe('operate permission', () => {
test.use({ persona: 'noEsbOperate' })
test('[ESB-007] operate controls are absent and every operate process denies direct invocation @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/esb')
const row = page.locator(triggerRow)
await expect(row).toContainText('Sync Person')
await expect(row.getByRole('button', { name: /^(Pause|Resume|Restart|Replay)/ })).toHaveCount(0)
expect((await overview(backend)).permissions).toEqual({ canOperate: false, canDelete: true })
for (const process of ['esbPauseTrigger', 'esbResumeTrigger', 'esbRestartTrigger', 'esbReplayDeadLetters', 'esbPauseQueue', 'esbResumeQueue', 'esbMoveMessages']) {
const response = await backend.api.post(`/qqq/v1/processes/${process}/init`, { multipart: { values: JSON.stringify({ triggerName: TRIGGER, providerName: 'sampleArtemis', brokerQueueName: 'personEvents', all: true }) } })
expect(response.status(), process).toBe(403)
}
expect((await personStatus(backend)).subscribers[0].state).toBe('RUNNING')
expect(await receipts(backend)).toEqual([])
})
})
test.describe('delete permission', () => {
test.use({ persona: 'noEsbDelete' })
test('[ESB-008] delete permission is independent of operate and enforced by both destructive processes @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/esb')
const row = page.locator(triggerRow)
await expect(row.getByRole('button', { name: 'Pause Sync Person', exact: true })).toBeVisible()
expect((await overview(backend)).permissions).toEqual({ canOperate: true, canDelete: false })
await row.getByRole('button', { name: 'Browse dead letters for Sync Person', exact: true }).click()
const dialog = page.getByRole('dialog')
await expect(dialog.getByText('No messages.', { exact: true })).toBeVisible()
await expect(dialog.getByRole('button', { name: /^(Purge|Delete)/ })).toHaveCount(0)
for (const process of ['esbPurgeQueue', 'esbDeleteMessages']) {
const response = await backend.api.post(`/qqq/v1/processes/${process}/init`, { multipart: { values: JSON.stringify({ providerName: 'sampleArtemis', brokerQueueName: `personEvents.${TRIGGER}.dlq`, olderThan: '2099-01-01T00:00:00Z' }) } })
expect(response.status(), process).toBe(403)
}
})
})
test('[ESB-009] unavailable broker capabilities hide queue mutations, while JMS browsing remains usable @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await open(page, '/app/esb')
const status = await overview(backend)
expect(status.providers.find((provider) => provider.name === 'sampleArtemis')).toMatchObject({ connected: true, managementEnabled: false })
expect(status.destinations.find((destination) => destination.name === 'personEvents')?.capabilities).toEqual({ browse: true, pauseQueue: false, purge: false, deleteSelected: false, deleteOlderThan: false, move: false })
await page.locator(triggerRow).getByRole('button', { name: /Browse subscription/ }).click()
await expect(page.getByRole('dialog').getByText('No messages.', { exact: true })).toBeVisible()
await expect(page.getByRole('button', { name: /^(Pause queue|Resume queue|Purge|Delete older|Delete selected|Move selected)/ })).toHaveCount(0)
})
test('[ESB-010] real dead letters require replay-all confirmation; cancel preserves them and confirm runs the subscriber @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await backend.failEsbSync(true)
await insertPerson(backend, 'Replay')
await expect.poll(async () => (await personStatus(backend)).subscribers[0].counters.deadLettered).toBe(1)
const deadLetters = async () => {
const response = await backend.api.get(`/qqq/v1/esb/deadLetters/${TRIGGER}`)
expect(response.status()).toBe(200)
return response.json()
}
expect((await deadLetters()).messages).toHaveLength(1)
expect(await receipts(backend)).toEqual([])
await backend.failEsbSync(false)
await open(page, '/app/esb')
const row = page.locator(triggerRow)
const replays: string[] = []
page.on('request', (request) => { if (new URL(request.url()).pathname === '/qqq/v1/processes/esbReplayDeadLetters/init') replays.push(request.postData() ?? '') })
await row.getByRole('button', { name: 'Replay dead letters for Sync Person', exact: true }).click()
const confirmation = page.getByRole('alertdialog')
await expect(confirmation).toContainText(/dead letters/i)
// No management API: the dialog must acknowledge an unknown count, never invent zero.
await expect(confirmation).toContainText(/unknown|unavailable|cannot.*count/i)
expect(replays).toEqual([])
await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click()
expect((await deadLetters()).messages).toHaveLength(1)
expect(await receipts(backend)).toEqual([])
await row.getByRole('button', { name: 'Replay dead letters for Sync Person', exact: true }).click()
await confirmation.locator('[data-qqq-id="button-esb-confirm"]').click()
await expect(page.getByText('esbReplayDeadLetters completed.', { exact: true })).toBeVisible()
expect(replays).toHaveLength(1)
await expect.poll(async () => (await deadLetters()).messages.length).toBe(0)
expect((await receipts(backend)).map((receipt) => receipt.first_name)).toEqual(['Replay'])
})
@@ -0,0 +1,18 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import { expect, type Page } from '@playwright/test'
/** Wait for the upstream report setup renderer before clicking a pivot control it can move. */
export async function openReadyPivotEditor(page: Page) {
const setup = page.locator('[data-qqq-id="form-widget-reportSetupWidget"]')
const edit = setup.getByRole('button', { name: 'Edit Filters and Columns', exact: true })
await expect(edit).toBeVisible()
await expect(edit).toBeEnabled()
await expect(setup.getByRole('status', { name: 'Loading widget' })).toHaveCount(0)
await page.getByRole('button', { name: 'Edit Pivot Table', exact: true }).click()
}
@@ -6,6 +6,8 @@
*/
import type { Page } from '@playwright/test'
import { armGreetRouteResponses } from '../../support/greet-route-readiness'
import { ACCEPTANCE_UI_URL } from '../../support/ports'
import { expect, open, test, type Backend } from '../../support/fixtures'
import { expectNoHorizontalScroll, expectTouchReady, expectTouchTargets } from '../../support/touch'
import { allowQuickSight, appNavigation, expectBreadcrumbs, expectRecords, findNode, recordCollection, recordItems, v1MetaData, waitForShell } from './nav-helpers'
@@ -55,6 +57,8 @@ test.describe('routing', () => {
await page.getByRole('navigation', { name: 'Breadcrumb' }).getByRole('link', { name: 'Greetings App' }).click()
await expect(page).toHaveURL(/\/app\/greetingsApp\/?$/)
await expect(page.getByRole('heading', { level: 1, name: 'Greetings App' })).toBeVisible()
// Complete this destination before the next hard navigation tears down its owned iframe (#972).
await expect(page.frameLocator('[data-qqq-id="quicksight-QuickSightChartRenderer"]').getByRole('heading', { name: 'Owned embedded chart' })).toBeVisible()
// The dashboard root has no breadcrumbs
await open(page, '/app')
@@ -91,6 +95,8 @@ test.describe('routing', () => {
test('[NAV-016] the site root replaces itself with the dashboard @mobile', async ({ page, backend, diagnostics }) => {
await open(page, '/app/person')
await waitForShell(page)
// Let the initial document finish rendering its fonts before navigation tears it down (#951).
await page.evaluate(() => document.fonts.ready.then(() => undefined))
await open(page, '/')
await expect(page).toHaveURL(/\/app\/?$/)
await expect(page.getByText(/Here's an overview of your QQQ Sample system\./)).toBeVisible()
@@ -116,12 +122,26 @@ test.describe('routing', () => {
{ path: `/app/person/savedView/${view.id}`, crumbs: ['People App', 'Greetings App', 'Person', 'Saved View'], active: 'Person', content: (p) => expect(p.locator('#main-content')).toBeVisible() },
]
for (const { path, crumbs, content, active } of cases) {
await open(page, path)
await content(page)
await expectBreadcrumbs(page, crumbs)
const nav = await appNavigation(page)
await expect(nav.getByRole('link', { name: active, exact: true }), path).toBeVisible()
await expect(nav.getByRole('link', { name: active, exact: true }), path).toHaveAttribute('aria-current', 'page')
const processResponses = path === '/app/greetInteractive'
? armGreetRouteResponses(page, new URL(ACCEPTANCE_UI_URL).origin)
: undefined
try {
await open(page, path)
await content(page)
await expectBreadcrumbs(page, crumbs)
const nav = await appNavigation(page)
await expect(nav.getByRole('link', { name: active, exact: true }), path).toBeVisible()
await expect(nav.getByRole('link', { name: active, exact: true }), path).toHaveAttribute('aria-current', 'page')
if (processResponses) {
// The bare process URL completes with the same validation error asserted by PRC-004.
await processResponses.wait
await expect(page.locator('[data-qqq-id="process-error-message"]')).toBeVisible()
await expect(page.locator('[data-qqq-id="process-error-message"]')).toHaveText('Missing input records.')
await expect(page.locator('[data-qqq-id="process-run-greetInteractive"]')).toHaveAttribute('data-process-phase', 'error')
}
} finally {
processResponses?.dispose()
}
}
})
@@ -8,6 +8,7 @@
import AxeBuilder from '@axe-core/playwright'
import type { Page } from '@playwright/test'
import { appNavigation } from './nav-helpers'
import { openReadyPivotEditor } from './pivot-readiness'
import { expect, open, test } from '../../support/fixtures'
// Theme metadata is instance-wide; every scenario needs the backend reset before navigation.
@@ -44,7 +45,7 @@ for (const mode of ['light', 'dark', 'application'] as const) {
if (mode === 'application') {
await expect.poll(() => page.locator('html').evaluate(root => getComputedStyle(root).getPropertyValue('--color-destructive').trim())).toBe('#f97316')
}
await page.getByRole('button', { name: 'Edit Pivot Table', exact: true }).click()
await openReadyPivotEditor(page)
await page.locator('[data-qqq-id="pivot-editor-add-row"]').click()
await page.locator('[data-qqq-id="pivot-editor-ok"]').click()
await expect(page.locator('[data-qqq-id="pivot-editor-error"]')).toContainText('Missing value in 1 field.')
@@ -24,6 +24,7 @@ async function fillMixed(page: Page, name: string, count: string) {
await mixed.getByLabel('Lab Name').fill(name)
await mixed.getByLabel('Sample Count').fill(count)
await choosePossibleValue(page, 'Lab Color', 'Green')
await expect(page.getByRole('combobox', { name: 'Lab Color' })).toContainText('Green')
await advance(page, 'Next')
}
+4 -2
View File
@@ -7,6 +7,7 @@
import { readFileSync } from 'node:fs'
import type { APIRequestContext, Page } from '@playwright/test'
import { expectedDownloadFilename } from '../../support/downloads'
import { expect, test } from '../../support/fixtures'
import { advance, expectRunTouchReady, expectScreen, openProcess } from './process-helpers'
@@ -365,16 +366,17 @@ test.describe('Bulk load', () => {
expect(await backend.sql('select count(*) as n from saved_bulk_load_profile')).toEqual([{ n: '0' }])
})
test('[PRC-034] upload instructions offer a downloadable template file @mobile', async ({ page, diagnostics }) => {
test('[PRC-034] upload instructions offer a downloadable template file @mobile', async ({ page, browserName, diagnostics }) => {
void diagnostics
await openProcess(page, 'person.bulkInsert')
const upload = await expectScreen(page, 'upload', 'Upload File')
await upload.getByText('File Upload Instructions').click()
const template = upload.getByRole('link', { name: 'Person - Flat.csv' })
await expect(template).toBeVisible()
await expect(template).toHaveAttribute('download', 'Person - Flat.csv')
await expectRunTouchReady(page, 'person.bulkInsert')
const [download] = await Promise.all([page.waitForEvent('download'), template.click()])
expect(download.suggestedFilename()).toBe('Person - Flat.csv')
expect(download.suggestedFilename()).toBe(expectedDownloadFilename('Person - Flat.csv', browserName))
expect(readFileSync(await download.path(), 'utf8').split('\n')[0]).toBe('Email,First Name,Last Name,Annual Salary,Birth Date,Days Worked,Is Employed')
})
})
@@ -0,0 +1,48 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import { expect, open, test } from '../../support/fixtures'
import { expectColumn, sqlColumn } from './query-helpers'
for (const action of ['selection', 'refresh']) {
test(`[QRY-030] body checkbox retains keyboard focus after ${action}`, async ({ page, backend, diagnostics }, testInfo) => {
void diagnostics
await page.setViewportSize({ width: 1280, height: 720 })
await open(page, '/app/qryItem')
const ids = await sqlColumn(backend, 'select id from qry_item order by id desc')
await expectColumn(page, 'id', ids)
const checkbox = page.locator('[data-qqq-id="grid-select-row-0"]')
await expect(checkbox).not.toBeChecked()
await checkbox.focus()
await expect(checkbox).toBeFocused()
const original = await checkbox.elementHandle()
expect(original).not.toBeNull()
const navigation = await page.evaluate(() => ({ url: location.href, length: history.length }))
if (action === 'selection') {
await page.keyboard.press('Space')
await expect(checkbox).toBeChecked()
await expect(page.locator('[data-qqq-id="bulk-selection-text"]')).toHaveText('1 record is selected.')
} else {
const query = page.waitForResponse(response => response.request().method() === 'POST' && new URL(response.url()).pathname === '/qqq/v1/table/qryItem/query')
await page.keyboard.press('r')
const response = await query
expect(response.status()).toBe(200)
expect(await response.finished()).toBeNull()
await expectColumn(page, 'id', ids)
await expect(checkbox).not.toBeChecked()
}
await testInfo.attach('cell-focus-boundary', { body: JSON.stringify({
action,
original: await original!.evaluate(element => ({ connected: element.isConnected, focused: document.activeElement === element })),
current: await checkbox.evaluate(element => ({ focused: document.activeElement === element, checked: (element as HTMLInputElement).checked })),
navigationUnchanged: JSON.stringify(await page.evaluate(() => ({ url: location.href, length: history.length }))) === JSON.stringify(navigation),
}), contentType: 'application/json' })
expect(await page.evaluate(() => ({ url: location.href, length: history.length }))).toEqual(navigation)
await expect(checkbox).toBeFocused()
expect(await original!.evaluate(element => element.isConnected)).toBe(true)
})
}
@@ -8,6 +8,7 @@
// Backend exports (CSV, XLSX, JSON) of the query's filter, sort and visible columns.
import { readFileSync } from 'node:fs'
import type { Page } from '@playwright/test'
import { expectedDownloadFilename } from '../../support/downloads'
import { expect, open, test } from '../../support/fixtures'
import { expectWithinViewport } from '../../support/touch'
import { addCondition, closeFilterSheet, expectColumn, grid, openFilter, showTable, sqlColumn } from './query-helpers'
@@ -34,11 +35,12 @@ function parseCsv(text: string): string[][] {
async function download(page: Page, format: 'CSV' | 'XLSX' | 'JSON') {
await page.getByRole('button', { name: 'Export records' }).click()
await expectWithinViewport(page.getByRole('menu', { name: 'Export options' }))
const [file] = await Promise.all([
const [file, request] = await Promise.all([
page.waitForEvent('download'),
page.waitForRequest((request) => request.method() === 'POST' && /\/table\/[^/]+\/export$/.test(new URL(request.url()).pathname)),
page.getByRole('menuitem', { name: new RegExp(`^Export ${format}`) }).click(),
])
return { name: file.suggestedFilename(), body: readFileSync((await file.path())!) }
return { name: file.suggestedFilename(), requestedName: request.postDataJSON().filename as string, body: readFileSync((await file.path())!) }
}
/** Grid header labels in display order. */
@@ -46,7 +48,7 @@ async function headers(page: Page, tableLabel: string) {
return grid(page, tableLabel).locator('thead th button[data-qqq-id^="grid-header-"]').allTextContents()
}
test('[QRY-040] CSV export has the visible columns in order and exactly the filtered, sorted rows @mobile', async ({ page, backend, diagnostics }) => {
test('[QRY-040] CSV export has the visible columns in order and exactly the filtered, sorted rows @mobile', async ({ page, backend, browserName, diagnostics }) => {
void diagnostics
await open(page, '/app/qryItem')
await showTable(page)
@@ -67,7 +69,8 @@ test('[QRY-040] CSV export has the visible columns in order and exactly the filt
await expectColumn(page, 'id', ids)
const file = await download(page, 'CSV')
expect(file.name).toMatch(/^Query Item Export \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(file.requestedName).toMatch(/^Query Item Export \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(file.name).toBe(expectedDownloadFilename(file.requestedName, browserName))
const [header, ...rows] = parseCsv(file.body.toString('utf8'))
// The backend adds a "<label> Name" column after each possible-value field
const expectedHeader = (await headers(page, 'Query Item')).flatMap((label) => ['Owner', 'Species'].includes(label) ? [label, `${label} Name`] : [label])
@@ -8,6 +8,7 @@
// Phone and tablet query behavior (QRun-IO/qqq#708): the card list, the filter sheet, column
// configuration by touch, bulk actions from a phone selection, and the toolbar menus.
import type { Locator, Page } from '@playwright/test'
import { expectedDownloadFilename } from '../../support/downloads'
import { expect, open, test } from '../../support/fixtures'
import { expectNoHorizontalScroll, expectTouchReady, expectTouchTargets, expectWithinViewport } from '../../support/touch'
import { addCondition, columnCells, expectColumn, isPhone, sqlColumn } from './query-helpers'
@@ -183,7 +184,7 @@ test.describe('on a phone', () => {
expect(sent.values.map(String).sort()).toEqual([ids[0], ids[2]].sort())
})
test('[QRY-055] saved views and export menus fit the phone and are touch-sized @mobile', async ({ page, backend, diagnostics }) => {
test('[QRY-055] saved views and export menus fit the phone and are touch-sized @mobile', async ({ page, backend, browserName, diagnostics }) => {
void diagnostics
await open(page, '/app/person')
await expectColumn(page, 'firstName', await sqlColumn(backend, 'select first_name from person order by id desc'))
@@ -202,8 +203,14 @@ test.describe('on a phone', () => {
await expectOnScreen(page, exportMenu)
await expectTouchTargets(exportMenu)
await expectNoHorizontalScroll(page)
const [file] = await Promise.all([page.waitForEvent('download'), page.getByRole('menuitem', { name: /^Export CSV/ }).tap()])
expect(file.suggestedFilename()).toMatch(/^Person Export .*\.csv$/)
const [file, request] = await Promise.all([
page.waitForEvent('download'),
page.waitForRequest((request) => request.method() === 'POST' && new URL(request.url()).pathname === '/qqq/v1/table/person/export'),
page.getByRole('menuitem', { name: /^Export CSV/ }).tap(),
])
const requestedName = request.postDataJSON().filename as string
expect(requestedName).toMatch(/^Person Export \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(file.suggestedFilename()).toBe(expectedDownloadFilename(requestedName, browserName))
})
})
+4 -2
View File
@@ -7,10 +7,11 @@
import { readFileSync } from 'node:fs'
import type { Request } from '@playwright/test'
import { expectedDownloadFilename } from '../../support/downloads'
import { expect, open, test } from '../../support/fixtures'
import { expectColumn, sqlColumn } from './query-helpers'
test('[QRY-065] export streams from the v1 export route and the route enforces the export capability @mobile', async ({ page, backend, diagnostics }) => {
test('[QRY-065] export streams from the v1 export route and the route enforces the export capability @mobile', async ({ page, backend, browserName, diagnostics }) => {
void diagnostics
const exports: Request[] = []
page.on('request', (request) => { if (/\/export(\/|$)/.test(new URL(request.url()).pathname)) exports.push(request) })
@@ -27,7 +28,8 @@ test('[QRY-065] export streams from the v1 export route and the route enforces t
// The page used the v1 route with a JSON body naming the format, file and columns.
expect(exports.map((request) => `${request.method()} ${new URL(request.url()).pathname}`)).toEqual(['POST /qqq/v1/table/qryItem/export'])
const body = exports[0].postDataJSON()
expect(body).toMatchObject({ format: 'csv', filename: file.suggestedFilename() })
expect(body).toMatchObject({ format: 'csv', filename: expect.stringMatching(/^Query Item Export \d{4}-\d{2}-\d{2} \d{4}\.csv$/) })
expect(file.suggestedFilename()).toBe(expectedDownloadFilename(body.filename, browserName))
expect(body.fieldNames).toContain('id')
// The v1 route streams the same rows, and refuses a table whose export capability is off.
+3 -6
View File
@@ -8,7 +8,7 @@
import { expect, test } from '../../support/fixtures'
import { listCell } from '../security/support/ui'
import {
expectToastBelowHeader,
expectToastDuringAction,
VIEWER, control, expandOnPhone, fieldValue, multipartFields, openForm, openRecord, recordAction, recordIdFromUrl, recordRequests, sqlCount, sqlOne, toasts,
} from './helpers'
@@ -51,12 +51,10 @@ test('[REC-006] create persists the entered values and opens the new record @mob
await control(page, 'annualSalary').fill('64250.75')
await control(page, 'daysWorked').fill('321')
await page.getByRole('checkbox', { name: 'Is Employed' }).click()
await page.getByRole('button', { name: 'Save' }).click()
await expectToastDuringAction(page, 'Person created successfully.', () => page.getByRole('button', { name: 'Save' }).click(), true)
await expect(page.getByRole('heading', { level: 1, name: 'Quinn Acceptance' })).toBeVisible()
const id = recordIdFromUrl(page, 'person')
await expect(toasts(page).filter({ hasText: 'Person created successfully.' })).toBeVisible()
await expectToastBelowHeader(page, toasts(page).filter({ hasText: 'Person created successfully.' }))
await expandOnPhone(page, 'Employment Info')
const row = await sqlOne(backend, `select first_name, last_name, email, birth_date, annual_salary, days_worked, is_employed from person where id = ${id}`)
expect(row).toEqual({ first_name: 'Quinn', last_name: 'Acceptance', email: 'quinn@example.invalid', birth_date: '1988-07-04',
@@ -129,11 +127,10 @@ test('[REC-009] edit prefills stored values, saves only the change and shows the
await control(page, 'email').fill('avery.updated@example.invalid')
await expect(page.getByRole('button', { name: 'Save' })).toBeEnabled()
await page.getByRole('button', { name: 'Save' }).click()
await expectToastDuringAction(page, 'Person saved successfully.', () => page.getByRole('button', { name: 'Save' }).click())
await expect(page.getByRole('heading', { level: 1, name: 'Avery Sample' })).toBeVisible()
await expect(fieldValue(page, 'email')).toHaveText('avery.updated@example.invalid')
await expect(toasts(page).filter({ hasText: 'Person saved successfully.' })).toBeVisible()
const put = writes.filter((request) => request.method() === 'PATCH')
expect(put).toHaveLength(1)
@@ -105,14 +105,17 @@ async function revisions(backend: Backend) {
test.describe('table developer view', () => {
test('[REC-053] keeps the metadata sections and shows API Docs & Playground with no application APIs @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
diagnostics.allow(/^request: GET \/qqq\/v1\/esb\/table\/recordLab 404$/)
diagnostics.allow(/^console: Failed to load resource: the server responded with a status of 404 \(Not Found\)$/)
const table = await (await backend.api.get('/qqq/v1/metaData/table/recordLab')).json()
const catalog = await backend.api.get('/apis.json?tableName=recordLab')
expect(catalog.status()).toBe(200)
expect(await catalog.json()).toEqual({ apis: [] })
const specRequests = requestsMatching(page, /(versions|openapi)\.json$/)
const esbResponse = page.waitForResponse((response) => new URL(response.url()).pathname === '/qqq/v1/esb/table/recordLab')
await open(page, '/app/recordLab/dev')
expect((await esbResponse).status()).toBe(404)
await expect(page.getByRole('heading', { level: 2, name: `Table Developer View: ${table.label}` })).toBeVisible()
await expectNoSidewaysScroll(page)
await expectTouchTargets(page.locator('#main-content'))
@@ -144,7 +147,7 @@ test.describe('table developer view', () => {
expect(json.label).toBe(table.label)
expect(Object.keys(json.fields).sort()).toEqual(Object.keys(table.fields).sort())
expect(diagnostics.failedRequests).toEqual([])
expect(diagnostics.failedRequests).toEqual(['GET /qqq/v1/esb/table/recordLab 404'])
expect(specRequests.map((request) => request.url())).toEqual([])
})
@@ -152,7 +155,8 @@ test.describe('table developer view', () => {
test.use({ persona: 'viewer' })
test('[REC-053] a viewer sees the same empty state and cannot fetch any table spec @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
diagnostics.allow(/^request: GET \/qqq\/v1\/esb\/table\/recordLab 404$/)
diagnostics.allow(/^console: Failed to load resource: the server responded with a status of 404 \(Not Found\)$/)
const table = await (await backend.api.get('/qqq/v1/metaData/table/recordLab')).json()
expect([table.insertPermission, table.editPermission, table.deletePermission]).toEqual([false, false, false])
// No API lists the table for this session either, so there is no spec URL to fetch.
@@ -161,7 +165,9 @@ test.describe('table developer view', () => {
expect(await catalog.json()).toEqual({ apis: [] })
const specRequests = requestsMatching(page, /(versions|openapi)\.json$/)
const esbResponse = page.waitForResponse((response) => new URL(response.url()).pathname === '/qqq/v1/esb/table/recordLab')
await open(page, '/app/recordLab/dev')
expect((await esbResponse).status()).toBe(404)
await expect(page.getByRole('heading', { level: 2, name: `Table Developer View: ${table.label}` })).toBeVisible()
await expect(page.locator('p', { hasText: /^Capabilities$/ }).locator('xpath=following-sibling::p')).toHaveText('Read-only')
const docs = byId(page, 'table-dev-api-docs')
@@ -172,7 +178,7 @@ test.describe('table developer view', () => {
await expect(byId(page, 'table-dev-api-reference')).toHaveCount(0)
await expect(page.locator('rapi-doc')).toHaveCount(0)
expect(diagnostics.failedRequests).toEqual([])
expect(diagnostics.failedRequests).toEqual(['GET /qqq/v1/esb/table/recordLab 404'])
expect(specRequests.map((request) => request.url())).toEqual([])
})
})
@@ -6,10 +6,11 @@
*/
import type { Page } from '@playwright/test'
import { expectedDownloadFilename } from '../../support/downloads'
import { expect, test, type Backend } from '../../support/fixtures'
import {
VIEWER, control, expandOnPhone, fieldValue, multipartFields, openForm, openRecord, recordIdFromUrl, recordRequests, showSection, shown, sqlCount,
sqlOne, toasts,
sqlOne, expectToastDuringAction,
} from './helpers'
test.use(VIEWER)
@@ -275,7 +276,7 @@ test('[REC-021] PASSWORD is masked on read and never overwritten by the mask @mo
expect((await sqlOne(backend, `select password_value from field_lab where id = ${id}`)).password_value).toBe('secret-two')
})
test('[REC-022] BLOB upload stores the bytes and the view downloads them @mobile', async ({ page, backend, diagnostics }) => {
test('[REC-022] BLOB upload stores the bytes and the view downloads them @mobile', async ({ page, backend, browserName, diagnostics }) => {
void diagnostics
await openForm(page, '/app/fieldLab/create', 'Create Field Lab')
await control(page, 'name').fill('Binary')
@@ -290,9 +291,11 @@ test('[REC-022] BLOB upload stores the bytes and the view downloads them @mobile
await expandOnPhone(page, 'Field Types')
const downloadPromise = page.waitForEvent('download')
await shown(page, '[data-qqq-id="field-value-blobValue-download"]').click()
const link = shown(page, '[data-qqq-id="field-value-blobValue-download"]')
await expect(link).toHaveAttribute('download', `Field Lab ${id} Blob Value`)
await link.click()
const download = await downloadPromise
expect(download.suggestedFilename()).toBe(`Field Lab ${id} Blob Value`)
expect(download.suggestedFilename()).toBe(expectedDownloadFilename(`Field Lab ${id} Blob Value`, browserName))
const chunks: Buffer[] = []
for await (const chunk of await download.createReadStream()) chunks.push(chunk as Buffer)
expect(Buffer.concat(chunks).equals(Buffer.from(stored, 'base64'))).toBe(true)
@@ -404,13 +407,11 @@ test('[REC-027] unique keys are enforced with the backend message on create and
test('[REC-048] a server validation error is shown once with the backend message and keeps the form @mobile', async ({ page, backend, diagnostics }) => {
for (const pattern of FIELD_LAB_ERRORS) diagnostics.allow(pattern)
await createFieldLab(page, { name: 'Kept Values', decimalValue: '42.25', boundedValue: '101' })
await openForm(page, '/app/fieldLab/create', 'Create Field Lab')
for (const [name, value] of Object.entries({ name: 'Kept Values', decimalValue: '42.25', boundedValue: '101' })) await control(page, name).fill(value)
const message = 'Error inserting Field Lab: The value for Bounded Value is too large (maximum allowed value is 100)'
await expectToastDuringAction(page, `Failed to create Field Lab: ${message}`, () => page.getByRole('button', { name: 'Save' }).click())
await expect(page.getByRole('alert').filter({ hasText: message })).toBeVisible()
await expect(toasts(page).filter({ hasText: `Failed to create Field Lab: ${message}` })).toBeVisible()
await expect(toasts(page)).toHaveCount(1)
await expect(toasts(page).filter({ hasText: 'Something went wrong' })).toHaveCount(0)
await expect(toasts(page).filter({ hasText: 'Request failed with status code' })).toHaveCount(0)
await expect(control(page, 'name')).toHaveValue('Kept Values')
await expect(control(page, 'decimalValue')).toHaveValue('42.25')
await expect(page).toHaveURL(/\/app\/fieldLab\/create\/?$/)
+14
View File
@@ -7,6 +7,7 @@
import type { Locator, Page, Request } from '@playwright/test'
import { expect, type Backend } from '../../support/fixtures'
import { visibleToastObservation } from '../../support/toast-observation'
import { expectNoHorizontalScroll } from '../../support/touch'
import { isPhone } from '../query/query-helpers'
@@ -77,6 +78,19 @@ export async function expectToastBelowHeader(page: Page, toast: Locator) {
await expect.poll(async () => (await toast.boundingBox())?.y ?? -1).toBeGreaterThanOrEqual(header!.y + header!.height)
}
/**
* Observe transient feedback before triggering its action. Browser-side polling captures
* the visible message, count and geometry even when the driver returns after dismissal.
*/
export async function expectToastDuringAction(page: Page, message: string, action: () => Promise<unknown>, belowHeader = false) {
const [observation] = await Promise.all([
page.waitForFunction(visibleToastObservation, { message, belowHeader }, { timeout: 15_000 }),
action(),
])
expect(await observation.jsonValue(), 'one visible notification with the exact message').toEqual([message])
await observation.dispose()
}
/** Reads exactly one row with an independent SQL query. */
export async function sqlOne(backend: Backend, query: string): Promise<Record<string, string | null>> {
const rows = await backend.sql(query)
@@ -0,0 +1,25 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import { expect, test } from '../../support/fixtures'
import { control, expectToastDuringAction, openForm, sqlCount, toasts } from './helpers'
test('[REC-006] success feedback is observed when action delivery returns after dismissal @mobile', async ({ page, backend, diagnostics }) => {
void diagnostics
await openForm(page, '/app/person/create', 'Create Person')
await control(page, 'firstName').fill('Feedback')
await control(page, 'lastName').fill('Observation')
await control(page, 'email').fill('feedback@example.invalid')
await expectToastDuringAction(page, 'Person created successfully.', async () => {
await page.getByRole('button', { name: 'Save' }).click()
await expect(page.getByRole('heading', { level: 1, name: 'Feedback Observation' })).toBeVisible()
// Model the hosted trace/driver delay without extending the product notification lifetime.
await expect(toasts(page)).toHaveCount(0)
}, true)
expect(await sqlCount(backend, "select count(*) as n from person where email = 'feedback@example.invalid'")).toBe(1)
})
@@ -0,0 +1,120 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { expect, open, test as acceptanceTest } from '../../support/fixtures'
import { allowBlockedByPolicy, parsePolicy } from './support/csp'
import { listCell } from './support/ui'
import { resetVariant, SECURITY_UI_URL, startVariant, stopVariant } from './support/variant'
interface OwnedAnalytics {
origin: string
deniedOrigin: string
counts: { scripts: number; initialize: number; record: number; denied: number }
close: () => Promise<void>
}
async function listen(server: Server): Promise<string> {
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
return `http://127.0.0.1:${(server.address() as AddressInfo).port}`
}
async function ownedAnalytics(): Promise<OwnedAnalytics> {
const counts = { scripts: 0, initialize: 0, record: 0, denied: 0 }
const cors = { 'Access-Control-Allow-Origin': SECURITY_UI_URL }
const denied = createServer((request, response) => {
counts.denied++
request.resume()
response.writeHead(200, cors)
response.end('owned endpoint')
})
const deniedOrigin = await listen(denied)
let origin = ''
const allowed = createServer((request, response) => {
request.resume()
if (request.url === '/owned-plugin.js') {
counts.scripts++
response.writeHead(200, { ...cors, 'Content-Type': 'text/javascript' })
// The normal application hook loads this plugin, then creates this registered provider.
// Fixed aliases only: no user, record, URL, event or session payload is transmitted.
response.end(`window.QQQAnalytics.register('posthog', () => ({
initialize() {
fetch(${JSON.stringify(origin)} + '/collect/initialize', { method: 'POST', body: 'initialize' });
fetch(${JSON.stringify(deniedOrigin)} + '/collect', { method: 'POST', body: 'blocked-control' }).catch(() => {});
},
record() { fetch(${JSON.stringify(origin)} + '/collect/record', { method: 'POST', body: 'record' }); },
reset() {}
}));`)
} else if (request.method === 'POST' && request.url === '/collect/initialize') {
counts.initialize++
response.writeHead(200, cors)
response.end('ok')
} else if (request.method === 'POST' && request.url === '/collect/record') {
counts.record++
response.writeHead(200, cors)
response.end('ok')
} else {
response.writeHead(404, cors)
response.end()
}
})
origin = await listen(allowed)
return {
origin, deniedOrigin, counts,
close: async () => {
await Promise.all([allowed, denied].map((server) => new Promise<void>((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve())
// The browser can still own preconnected or incomplete HTTP sockets during teardown.
server.closeAllConnections()
})))
},
}
}
const test = acceptanceTest.extend<{ analytics: OwnedAnalytics }>({
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
analytics: async ({}, provide) => {
const service = await ownedAnalytics()
try {
await startVariant('FULLY_ANONYMOUS', { properties: { 'qqq.security.analytics.origin': service.origin } })
await resetVariant()
await provide(service)
} finally {
try { await stopVariant() } finally { await service.close() }
}
},
})
test('[SEC-040] metadata-configured analytics loads through the application hook and cannot contact an unconfigured origin @mobile', async ({ page, analytics, diagnostics }, testInfo) => {
let policy: Record<string, string[]> = {}
try {
policy = parsePolicy((await page.request.get('/login')).headers()['content-security-policy'])
expect(policy['connect-src']).toEqual(["'self'", analytics.origin])
expect(policy['script-src'].filter((source) => !source.startsWith("'sha256-"))).toEqual(["'self'", analytics.origin])
allowBlockedByPolicy(diagnostics, analytics.deniedOrigin)
await open(page, '/app/person')
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
await expect.poll(() => analytics.counts.initialize).toBe(1)
await expect.poll(() => analytics.counts.record).toBeGreaterThan(0)
expect(analytics.counts.scripts).toBe(1)
await expect.poll(() => diagnostics.cspViolations.some((entry) => entry === `connect-src ${analytics.deniedOrigin}` || entry.startsWith(`connect-src ${analytics.deniedOrigin}/`))).toBe(true)
expect(analytics.counts.denied).toBe(0)
expect(diagnostics.cspViolations.every((entry) => entry === `connect-src ${analytics.deniedOrigin}` || entry.startsWith(`connect-src ${analytics.deniedOrigin}/`))).toBe(true)
} finally {
await testInfo.attach('owned-analytics-csp', {
body: JSON.stringify({
counts: { ...analytics.counts },
configuredOrigin: analytics.origin,
deniedOrigin: analytics.deniedOrigin,
policy,
}),
contentType: 'application/json',
})
}
})
@@ -11,7 +11,7 @@
import type { Page } from '@playwright/test'
import { expect, open, test as acceptanceTest } from '../../support/fixtures'
import { startFakeOidc, type FakeOidcProvider } from '../../support/fake-oidc'
import { IDP_PORT, resetVariant, SECURITY_URL, startVariant, stopVariant, variantSql } from './support/variant'
import { IDP_PORT, resetVariant, SECURITY_URL, SECURITY_UI_URL, startVariant, stopVariant, variantSql } from './support/variant'
import { listCell, navigation, openUserMenu, recordRequests } from './support/ui'
import { parsePolicy } from './support/csp'
@@ -29,18 +29,18 @@ const AUTH0_VARIANT = {
}
const auth0Test = acceptanceTest.extend<{ auth0: FakeOidcProvider }, { auth0Provider: FakeOidcProvider }>({
auth0Provider: [async ({}, use) => {
const provider = await startFakeOidc({ port: IDP_PORT, clientId: AUTH0_CLIENT, clientSecret: 'unused-by-spa-flow', audience: AUDIENCE, allowedRedirectPrefix: `${SECURITY_URL}/` })
await use(provider)
auth0Provider: [async ({}, provide) => {
const provider = await startFakeOidc({ port: IDP_PORT, clientId: AUTH0_CLIENT, clientSecret: 'unused-by-spa-flow', audience: AUDIENCE, auth0Issuer: true, allowedRedirectPrefix: `${SECURITY_UI_URL}/` })
await provide(provider)
await stopVariant()
await provider.close()
}, { scope: 'worker' }],
baseURL: async ({}, use) => { await use(SECURITY_URL) },
auth0: async ({ auth0Provider }, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
auth0: async ({ auth0Provider }, provide) => {
await startVariant('AUTH_0', AUTH0_VARIANT)
await resetVariant()
auth0Provider.reset()
await use(auth0Provider)
await provide(auth0Provider)
},
})
@@ -50,14 +50,14 @@ auth0Test.describe('AUTH_0 (owned Auth0-compatible provider)', () => {
await open(page, '/app/person')
await expect(page.getByRole('heading', { name: 'QRun Test Identity Provider' })).toBeVisible()
const authorize = auth0.requests.find((request) => request.path === '/authorize')
expect(authorize?.query).toMatchObject({ client_id: AUTH0_CLIENT, audience: AUDIENCE, code_challenge_method: 'S256', redirect_uri: `${SECURITY_URL}/` })
expect(authorize?.query).toMatchObject({ client_id: AUTH0_CLIENT, audience: AUDIENCE, code_challenge_method: 'S256', redirect_uri: `${SECURITY_UI_URL}/` })
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
// a public SPA client: the browser redeems the code with its PKCE verifier, no secret
const [token] = auth0.requests.filter((request) => request.path === '/oauth/token')
expect(token.authorization).toBeUndefined()
expect(token.form).toMatchObject({ grant_type: 'authorization_code', client_id: AUTH0_CLIENT, redirect_uri: `${SECURITY_URL}/` })
expect(token.form).toMatchObject({ grant_type: 'authorization_code', client_id: AUTH0_CLIENT, redirect_uri: `${SECURITY_UI_URL}/` })
expect(token.form.code_verifier).toMatch(/^[A-Za-z0-9_-]{43}$/)
// the backend fetched the provider keys to verify the access token
expect(auth0.requests.some((request) => request.path === '/.well-known/jwks.json')).toBe(true)
@@ -72,7 +72,7 @@ auth0Test.describe('AUTH_0 (owned Auth0-compatible provider)', () => {
const menu = await openUserMenu(page)
await menu.getByRole('menuitem', { name: 'Log Out' }).click()
await expect(page.getByRole('heading', { name: 'You have signed out' })).toBeVisible()
await expect.poll(() => auth0.requests.some((request) => request.path === '/v2/logout' && request.query.client_id === AUTH0_CLIENT && request.query.returnTo === `${SECURITY_URL}/login`)).toBe(true)
await expect.poll(() => auth0.requests.some((request) => request.path === '/v2/logout' && request.query.client_id === AUTH0_CLIENT && request.query.returnTo === `${SECURITY_UI_URL}/login`)).toBe(true)
await expect.poll(() => auth0.activeSessions()).toBe(0)
expect((await context.cookies()).map((cookie) => cookie.name)).not.toContain('sessionUUID')
await open(page, '/app/person')
@@ -107,7 +107,7 @@ auth0Test.describe('AUTH_0 (owned Auth0-compatible provider)', () => {
auth0Test('[SEC-039] the policy allows the browser token exchange with the configured Auth0 domain only', async ({ page, auth0, diagnostics }) => {
const policy = parsePolicy((await page.request.get('/login')).headers()['content-security-policy'])
expect(policy['connect-src']).toEqual(["'self'", auth0.issuer])
expect(policy['connect-src']).toEqual(["'self'", auth0.origin])
await open(page, '/app/person')
await page.getByRole('button', { name: 'Sign in' }).click()
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
@@ -118,11 +118,11 @@ auth0Test.describe('AUTH_0 (owned Auth0-compatible provider)', () => {
})
const anonymousTest = acceptanceTest.extend<{ anonymous: void }>({
baseURL: async ({}, use) => { await use(SECURITY_URL) },
anonymous: async ({}, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
anonymous: async ({}, provide) => {
await startVariant('FULLY_ANONYMOUS')
await resetVariant()
await use()
await provide()
},
})
@@ -95,12 +95,11 @@ test.describe('dashboard security headers', () => {
expect(framed.status()).toBe(200)
expect(parsePolicy(framed.headers()['content-security-policy'])['frame-ancestors']).toEqual(["'none'"])
expect(framed.headers()['x-frame-options']).toBe('DENY')
await page.waitForTimeout(1_000)
await expect(page.frameLocator('#victim').locator('[data-qqq-id="login-card"]')).toHaveCount(0)
await expect(page.frameLocator('#victim').getByText(/Signing in|Unable to sign in|You have signed out/)).toHaveCount(0)
for (const frame of page.frames().filter((candidate) => candidate !== page.mainFrame())) {
expect(await frame.locator('[data-qqq-id="login-card"]').count()).toBe(0)
}
// A denied Firefox frame may have no script context to query (#981). Require its actual
// refusal, in addition to the response headers, without entering that blocked document.
await expect.poll(() => diagnostics.consoleErrors.some((message) =>
/frame-ancestors|X-Frame-Options/i.test(message) && /blocked|refused|violates/i.test(message),
), { message: 'the browser must report refusing the dashboard frame' }).toBe(true)
} finally {
await otherSite.close()
}
@@ -216,9 +215,20 @@ test.describe('security review fixes (QRun-IO/qqq#696)', () => {
await open(page, '/app')
await expect(recentPet).toBeVisible()
await expect(recentPet).toHaveAttribute('href', /^\/app\/pet\/1\/?$/)
await page.evaluate(() => {
localStorage.setItem('qqq.recordQueryView.person', JSON.stringify({
queryFilter: { criteria: [{ fieldName: 'firstName', operator: 'EQUALS', values: ['Alice private filter'] }] },
viewIdentity: 'empty',
}))
localStorage.setItem('qqq.currentSavedViewId.person', '7')
})
// the same identity keeps its list across a reload
await page.reload()
await expect(recentPet).toBeVisible()
expect(await page.evaluate(() => JSON.parse(localStorage.getItem('qqq.recordQueryView.person') ?? 'null'))).toMatchObject({
queryFilter: { criteria: [{ fieldName: 'firstName', operator: 'EQUALS', values: ['Alice private filter'] }] },
})
expect(await page.evaluate(() => localStorage.getItem('qqq.currentSavedViewId.person'))).toBe('7')
// no logout: the next session in this browser belongs to someone else
await backend.setPersona('admin', 'bob')
@@ -227,6 +237,8 @@ test.describe('security review fixes (QRun-IO/qqq#696)', () => {
await expect((await navigation(page)).locator('[data-qqq-id="sidebar-user-name"]')).toContainText('Bob')
await expect(page.locator('[data-qqq-id^="dashboard-recent-"]')).toHaveCount(0)
expect(await page.evaluate(() => localStorage.getItem('qqq-recent-records') ?? '')).not.toContain('/app/pet/1')
expect(await page.evaluate(() => localStorage.getItem('qqq.recordQueryView.person'))).toBeNull()
expect(await page.evaluate(() => localStorage.getItem('qqq.currentSavedViewId.person'))).toBeNull()
await open(page, '/app/person')
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
})
@@ -13,7 +13,7 @@ import type { BrowserContext, Page } from '@playwright/test'
import { expect, open, test } from '../../support/fixtures'
import { startFakeOidc, type FakeOidcProvider } from '../../support/fake-oidc'
import { ACCEPTANCE_UI_URL } from '../../support/ports'
import { expireTableSessions, IDP_PORT, resetVariant, SECURITY_URL, startVariant, stopVariant, variantSql } from './support/variant'
import { expireTableSessions, IDP_PORT, resetVariant, SECURITY_URL, SECURITY_UI_URL, startVariant, stopVariant, variantSql } from './support/variant'
import { listCell, navigation, openUserMenu } from './support/ui'
const SESSION_COOKIES = ['sessionId', 'sessionUUID']
@@ -102,11 +102,11 @@ test('[SEC-048] script in the page can neither read the session cookies nor obta
})
const tableTest = test.extend<{ tableBased: void }>({
baseURL: async ({}, use) => { await use(SECURITY_URL) },
tableBased: async ({}, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
tableBased: async ({}, provide) => {
await startVariant('TABLE_BASED')
await resetVariant()
await use()
await provide()
},
})
@@ -185,6 +185,54 @@ tableTest('[SEC-048] [SEC-049] TABLE_BASED sign-in, reload resume, idle expiry a
expect(sessionRequests).toEqual([])
})
tableTest('[SEC-049] a pending logout finishes cookie expiry before another user can sign in @mobile', async ({ page, tableBased, diagnostics, context }) => {
void tableBased
void diagnostics
await open(page, '/app/person')
await submitCredentials(page, TESS)
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
let releaseLogout!: () => void
let reportLogoutStarted!: () => void
const logoutGate = new Promise<void>((resolve) => { releaseLogout = resolve })
const logoutStarted = new Promise<void>((resolve) => { reportLogoutStarted = resolve })
await page.route('**/qqq/v1/logout', async (route) => {
reportLogoutStarted()
await logoutGate
await route.continue()
})
const logoutResponse = page.waitForResponse((response) => new URL(response.url()).pathname === '/qqq/v1/logout')
try {
const menu = await openUserMenu(page)
await menu.getByRole('menuitem', { name: 'Log Out' }).click()
await logoutStarted
// Hold the real logout request; its eventual response must expire the old cookies first.
await expect(page.getByRole('status', { name: 'Loading', exact: true })).toBeVisible()
await expect(page.getByLabel('Username', { exact: true })).toHaveCount(0)
await expect(page.getByRole('button', { name: 'Sign in', exact: true })).toHaveCount(0)
releaseLogout()
const response = await logoutResponse
expect(response.status()).toBe(200)
expect(await response.finished()).toBeNull()
await expect(page.getByRole('heading', { name: 'You have signed out' })).toBeVisible()
expect((await context.cookies()).filter((cookie) => SESSION_COOKIES.includes(cookie.name))).toEqual([])
await submitCredentials(page, RAVI)
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
const sessions = await tableSessions()
expect(sessions.map((row) => row.username)).toEqual([RAVI.username])
if (!sessions[0]?.id) throw new Error('Expected the new user session after logout')
await expectHttpOnlySession(page, context, sessions[0].id)
await page.reload()
await expect(listCell(page, 'Person', 'Avery')).toBeVisible()
await expectUserAndCloseNavigation(page, RAVI.name)
await expectHttpOnlySession(page, context, sessions[0].id)
} finally {
releaseLogout()
await page.unrouteAll({ behavior: 'wait' })
}
})
tableTest('[SEC-049] a sign-in after a logout that never reached the server uses only the new session @mobile', async ({ page, tableBased, diagnostics, context }) => {
void tableBased
diagnostics.allow('/qqq/v1/logout 503')
@@ -222,18 +270,18 @@ const OAUTH2_VARIANT = {
}
const oauthTest = test.extend<{ idp: FakeOidcProvider }, { httpOnlyOauthProvider: FakeOidcProvider }>({
httpOnlyOauthProvider: [async ({}, use) => {
const provider = await startFakeOidc({ port: IDP_PORT, clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, allowedRedirectPrefix: `${SECURITY_URL}/` })
await use(provider)
httpOnlyOauthProvider: [async ({}, provide) => {
const provider = await startFakeOidc({ port: IDP_PORT, clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, allowedRedirectPrefix: `${SECURITY_UI_URL}/` })
await provide(provider)
await stopVariant()
await provider.close()
}, { scope: 'worker' }],
baseURL: async ({}, use) => { await use(SECURITY_URL) },
idp: async ({ httpOnlyOauthProvider }, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
idp: async ({ httpOnlyOauthProvider }, provide) => {
await startVariant('OAUTH2', OAUTH2_VARIANT)
await resetVariant()
httpOnlyOauthProvider.reset()
await use(httpOnlyOauthProvider)
await provide(httpOnlyOauthProvider)
},
})
+10 -10
View File
@@ -10,7 +10,7 @@
import type { Page } from '@playwright/test'
import { expect, open, test as acceptanceTest } from '../../support/fixtures'
import { startFakeOidc, type FakeOidcProvider } from '../../support/fake-oidc'
import { IDP_PORT, resetVariant, SECURITY_URL, startVariant, stopVariant, variantSql } from './support/variant'
import { IDP_PORT, resetVariant, SECURITY_URL, SECURITY_UI_URL, startVariant, stopVariant, variantSql } from './support/variant'
import { listCell, navigation, openUserMenu } from './support/ui'
import { allowBlockedByPolicy, parsePolicy } from './support/csp'
@@ -21,18 +21,18 @@ const VARIANT = {
}
const test = acceptanceTest.extend<{ idp: FakeOidcProvider }, { oauthProvider: FakeOidcProvider }>({
oauthProvider: [async ({}, use) => {
const provider = await startFakeOidc({ port: IDP_PORT, clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, allowedRedirectPrefix: `${SECURITY_URL}/` })
await use(provider)
oauthProvider: [async ({}, provide) => {
const provider = await startFakeOidc({ port: IDP_PORT, clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, allowedRedirectPrefix: `${SECURITY_UI_URL}/` })
await provide(provider)
await stopVariant()
await provider.close()
}, { scope: 'worker' }],
baseURL: async ({}, use) => { await use(SECURITY_URL) },
idp: async ({ oauthProvider }, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
idp: async ({ oauthProvider }, provide) => {
await startVariant('OAUTH2', VARIANT)
await resetVariant()
oauthProvider.reset()
await use(oauthProvider)
await provide(oauthProvider)
},
})
@@ -53,7 +53,7 @@ test.describe('OAUTH2 with PKCE', () => {
await expect(page).toHaveURL(new RegExp(`^${idp.issuer}/authorize\\?`))
const [authorize] = authorizeRequests(idp)
expect(authorize.query).toMatchObject({
response_type: 'code', client_id: CLIENT_ID, redirect_uri: `${SECURITY_URL}/token`,
response_type: 'code', client_id: CLIENT_ID, redirect_uri: `${SECURITY_UI_URL}/token`,
code_challenge_method: 'S256', scope: 'openid profile email',
})
expect(authorize.query.code_challenge).toMatch(/^[A-Za-z0-9_-]{43}$/)
@@ -68,7 +68,7 @@ test.describe('OAUTH2 with PKCE', () => {
const token = idp.requests.filter((request) => request.path === '/oauth/token')
expect(token).toHaveLength(1)
expect(token[0].authorization).toBe(`Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`)
expect(token[0].form).toMatchObject({ grant_type: 'authorization_code', redirect_uri: `${SECURITY_URL}/token` })
expect(token[0].form).toMatchObject({ grant_type: 'authorization_code', redirect_uri: `${SECURITY_UI_URL}/token` })
expect(token[0].form.code_verifier).toMatch(/^[A-Za-z0-9_-]{43}$/)
expect(await variantSql('select user_id from user_session')).toEqual([{ user_id: 'oidc|dana' }])
@@ -142,7 +142,7 @@ test.describe('OAUTH2 with PKCE', () => {
expect((await backendLogout).status()).toBe(200)
await expect(page).toHaveURL(/\/login\/?$/)
await expect(page.getByRole('heading', { name: 'You have signed out' })).toBeVisible()
await expect.poll(() => idp.requests.some((request) => request.path === '/logout' && request.query.post_logout_redirect_uri === `${SECURITY_URL}/login`)).toBe(true)
await expect.poll(() => idp.requests.some((request) => request.path === '/logout' && request.query.post_logout_redirect_uri === `${SECURITY_UI_URL}/login`)).toBe(true)
expect(await sessions()).toBe(0)
await expect.poll(() => idp.activeSessions()).toBe(0)
@@ -66,9 +66,22 @@ test.describe('MOCK sessions', () => {
await expect(page.getByRole('heading', { name: /Charlie/ }).first()).toBeVisible()
await open(page, '/app/person/1')
await expect(page.getByRole('heading', { name: /Avery/ }).first()).toBeVisible()
await page.evaluate(() => {
for (const table of ['person', 'pet']) {
localStorage.setItem(`qqq.recordQueryView.${table}`, JSON.stringify({
queryFilter: { criteria: [{ fieldName: 'name', operator: 'EQUALS', values: ['Alice private filter'] }] },
viewIdentity: 'empty',
}))
localStorage.setItem(`qqq.currentSavedViewId.${table}`, '7')
}
})
const menu = await openUserMenu(page)
await menu.getByRole('menuitem', { name: 'Log Out' }).click()
await expect(page.getByRole('heading', { name: 'You have signed out' })).toBeVisible()
expect(await page.evaluate(() => ['person', 'pet'].flatMap((table) => [
localStorage.getItem(`qqq.recordQueryView.${table}`),
localStorage.getItem(`qqq.currentSavedViewId.${table}`),
]))).toEqual([null, null, null, null])
// a different, less privileged identity signs in on the same browser
// (mock sessions are keyed by the sessionId cookie the harness assigns)
@@ -8,22 +8,26 @@
// Security-area backend variants (tests/acceptance/fixture/SecurityAcceptanceServer.java).
// One variant runs at a time on the security port; specs that need a different
// authentication module stop the running one first. The variant serves the same
// static Next export as the shared acceptance backend (javalin mode).
// static Next export in Javalin mode, or its own immutable Node build in standalone mode.
import { spawn, spawnSync, type ChildProcess } from 'node:child_process'
import { existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import { test as base, type APIRequestContext } from '@playwright/test'
import { ACCEPTANCE_BACKEND_PORT, ACCEPTANCE_FRONTEND_PORT } from '../../../support/ports'
import type { Diagnostics, Persona, SampleUser } from '../../../support/fixtures'
import { test as acceptanceTest } from '../../../support/fixtures'
import { resolveFixtureClasspath } from '../../../../../scripts/acceptance-paths.mjs'
import { ACCEPTANCE_MODE, SECURITY_BACKEND_PORT, SECURITY_BACKEND_URL, SECURITY_FRONTEND_PORT, SECURITY_IDP_PORT, SECURITY_STANDALONE, SECURITY_UI_URL, resolveFixtureClasspath } from '../../../../../scripts/acceptance-paths.mjs'
import { assertStandaloneTarget } from '../../../../../scripts/acceptance-standalone.mjs'
export { SECURITY_UI_URL }
export type AuthMode = 'MOCK' | 'OAUTH2' | 'AUTH_0' | 'FULLY_ANONYMOUS' | 'TABLE_BASED' | 'UNSUPPORTED'
export const SECURITY_PORT = Number(process.env.QQQ_ACCEPTANCE_SECURITY_BACKEND_PORT ?? ACCEPTANCE_BACKEND_PORT + 10)
export const IDP_PORT = Number(process.env.QQQ_ACCEPTANCE_SECURITY_IDP_PORT ?? ACCEPTANCE_FRONTEND_PORT + 10)
export const SECURITY_URL = `http://127.0.0.1:${SECURITY_PORT}`
export const SECURITY_PORT = SECURITY_BACKEND_PORT
export const SECURITY_ESB_PORT = Number(process.env.QQQ_ACCEPTANCE_SECURITY_ESB_PORT ?? Number(process.env.QQQ_ACCEPTANCE_ESB_PORT ?? 61616) + 1)
export const IDP_PORT = SECURITY_IDP_PORT
export const SECURITY_URL = SECURITY_BACKEND_URL
export const IDP_URL = `http://127.0.0.1:${IDP_PORT}`
const EXPORT_CLASSPATH = path.resolve('test-results/acceptance/export-classpath')
@@ -42,21 +46,24 @@ function compileFixtures(classpath: string) {
mkdirSync(CLASSES, { recursive: true })
const directory = path.resolve('tests/acceptance/fixture')
const sources = readdirSync(directory).filter((name) => name.endsWith('.java')).map((name) => path.join(directory, name))
const result = spawnSync('javac', ['-proc:none', '-encoding', 'UTF-8', '-cp', classpath, '-d', CLASSES, ...sources], { encoding: 'utf8' })
const result = spawnSync('javac', ['-proc:none', '-sourcepath', '', '-encoding', 'UTF-8', '-cp', classpath, '-d', CLASSES, ...sources], { encoding: 'utf8' })
if (result.status !== 0) throw new Error(`Security fixture compilation failed:\n${result.stderr}`)
compiled = true
}
interface Running { mode: AuthMode; key: string; process: ChildProcess; output: string[] }
interface Running { mode: AuthMode; key: string; process: ChildProcess; frontend?: ChildProcess; output: string[] }
let running: Running | null = null
process.on('exit', () => { if (running?.process.exitCode === null) running.process.kill('SIGKILL') })
process.on('exit', () => {
if (running?.frontend?.exitCode === null) running.frontend.kill('SIGKILL')
if (running?.process.exitCode === null) running.process.kill('SIGKILL')
})
async function waitForReady(child: Running, timeoutMs = 120_000) {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (child.process.exitCode !== null) throw new Error(`Security variant exited (${child.process.exitCode}):\n${child.output.slice(-40).join('')}`)
try {
const response = await fetch(`${SECURITY_URL}/acceptance/ready`)
const response = await fetch(`${SECURITY_URL}/acceptance/ready`, { signal: AbortSignal.timeout(5_000) })
if (response.ok) return
} catch {
// not listening yet
@@ -70,12 +77,66 @@ export async function stopVariant() {
if (!running) return
const current = running
running = null
if (current.process.exitCode === null) {
const exited = new Promise((resolve) => current.process.once('exit', resolve))
current.process.kill('SIGTERM')
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 15_000))])
if (current.process.exitCode === null) current.process.kill('SIGKILL')
// Stop the browser-facing server first; its metadata cache belongs to this backend mode.
let stopped = true
for (const child of [current.frontend, current.process]) {
if (!child || child.exitCode !== null || child.signalCode) continue
let onExit: () => void
const exited = new Promise<boolean>((resolve) => { onExit = () => resolve(true); child.once('exit', onExit) })
const wait = async (milliseconds: number) => {
let timer: ReturnType<typeof setTimeout> | undefined
const result = await Promise.race([exited, new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(false), milliseconds) })])
clearTimeout(timer)
return result
}
child.kill('SIGTERM')
if (!await wait(15_000)) {
child.kill('SIGKILL')
if (!await wait(5_000)) stopped = false
}
child.removeListener('exit', onExit!)
}
if (!stopped) {
current.key = '' // failed teardown must never be eligible for same-mode reuse
running = current // retain ownership for final cleanup; no new variant can bypass this child
throw new Error('An owned security server did not exit; refusing to start another variant on its port.')
}
}
/** Starts the actual container entrypoint, with a separately baked variant rewrite target. */
async function startStandalone(current: Running) {
assertStandaloneTarget(SECURITY_STANDALONE, SECURITY_URL)
// A retained export must not turn this into a Javalin qualification.
const backendDocument = await fetch(`${SECURITY_URL}/login`, { signal: AbortSignal.timeout(5_000) })
if (backendDocument.ok && /text\/html/i.test(backendDocument.headers.get('content-type') ?? '')) {
throw new Error('Standalone security backend unexpectedly serves a dashboard document.')
}
const authentication = await fetch(`${SECURITY_URL}/qqq/v1/metaData/authentication`, { signal: AbortSignal.timeout(5_000) })
if (!authentication.ok) throw new Error('Security authentication metadata request failed.')
const metadata = await authentication.json()
if (metadata.type !== (current.mode === 'UNSUPPORTED' ? 'ACCEPTANCE_UNKNOWN' : current.mode)) {
throw new Error('Security backend authentication mode does not match the selected variant.')
}
current.frontend = spawn(process.execPath, ['qqq-server.mjs'], {
cwd: SECURITY_STANDALONE,
env: { ...process.env, NODE_ENV: 'production', HOSTNAME: '127.0.0.1', PORT: String(SECURITY_FRONTEND_PORT), QQQ_DASHBOARD_CSP_SOURCES: '' },
stdio: ['ignore', 'pipe', 'pipe'],
})
const keep = (chunk: Buffer) => { current.output.push(chunk.toString()); if (current.output.length > 400) current.output.shift() }
current.frontend.stdout?.on('data', keep)
current.frontend.stderr?.on('data', keep)
const deadline = Date.now() + 120_000
while (Date.now() < deadline) {
if (current.frontend.exitCode !== null || current.frontend.signalCode) throw new Error(`Standalone security server exited (${current.frontend.exitCode})`)
try {
const response = await fetch(`${SECURITY_UI_URL}/login`, { signal: AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))) })
if (response.ok && new URL(response.url).origin === SECURITY_UI_URL && /text\/html/i.test(response.headers.get('content-type') ?? '')) return
} catch {
// the Node server is still starting
}
await new Promise((resolve) => setTimeout(resolve, 250))
}
throw new Error('Standalone security server did not become ready on its own browser origin.')
}
/**
@@ -84,9 +145,10 @@ export async function stopVariant() {
*/
export async function startVariant(mode: AuthMode, options: { env?: Record<string, string>; properties?: Record<string, string> } = {}) {
const key = JSON.stringify({ mode, ...options })
if (running?.key === key && running.process.exitCode === null) return
if (running?.key === key && running.process.exitCode === null && !running.process.signalCode
&& (ACCEPTANCE_MODE === 'javalin' || (running.frontend?.exitCode === null && !running.frontend.signalCode))) return
await stopVariant()
if (!existsSync(path.join(EXPORT_CLASSPATH, 'next-dashboard', 'index.html'))) {
if (ACCEPTANCE_MODE === 'javalin' && !existsSync(path.join(EXPORT_CLASSPATH, 'next-dashboard', 'index.html'))) {
throw new Error('No Next export on the acceptance classpath; run node scripts/acceptance.mjs (javalin mode) first.')
}
const classpath = resolveFixtureClasspath(sampleJar())
@@ -97,11 +159,12 @@ export async function startVariant(mode: AuthMode, options: { env?: Record<strin
`-Dqqq.sample.mockAuthentication=${mock}`,
`-Dqqq.sample.sharing=${mode === 'MOCK'}`,
`-Dqqq.sample.port=${SECURITY_PORT}`,
`-Dqqq.sample.esb.port=${SECURITY_ESB_PORT}`,
`-Dqqq.security.auth=${mode}`,
'-Duser.timezone=UTC',
'-Dqqq.javalin.frontend=next',
`-Dqqq.javalin.frontend=${ACCEPTANCE_MODE === 'standalone' ? 'none' : 'next'}`,
...Object.entries(options.properties ?? {}).map(([name, value]) => `-D${name}=${value}`),
'-cp', [EXPORT_CLASSPATH, CLASSES, classpath].join(path.delimiter),
'-cp', [...(ACCEPTANCE_MODE === 'javalin' ? [EXPORT_CLASSPATH] : []), CLASSES, classpath].join(path.delimiter),
'SecurityAcceptanceServer',
]
const child = spawn('java', args, { env: { ...process.env, ...options.env }, stdio: ['ignore', 'pipe', 'pipe'] })
@@ -110,7 +173,13 @@ export async function startVariant(mode: AuthMode, options: { env?: Record<strin
child.stdout?.on('data', keep)
child.stderr?.on('data', keep)
running = { mode, key, process: child, output }
await waitForReady(running)
try {
await waitForReady(running)
if (ACCEPTANCE_MODE === 'standalone') await startStandalone(running)
} catch (error) {
await stopVariant()
throw error
}
}
async function control(pathName: string, body: unknown) {
@@ -144,7 +213,7 @@ export const test = acceptanceTest.extend<{ security: SecurityBackend }, { secur
await provide()
await stopVariant()
}, { scope: 'worker' }],
baseURL: async ({ securityVariant }, provide) => { void securityVariant; await provide(SECURITY_URL) },
baseURL: async ({ securityVariant }, provide) => { void securityVariant; await provide(SECURITY_UI_URL) },
security: async ({ context, persona, user, playwright, securityVariant }, provide) => {
void securityVariant
await startVariant('MOCK')
@@ -11,18 +11,18 @@
// a session row (SecurityFixtures.primeTableBased seeds the users).
import type { Page } from '@playwright/test'
import { expect, open, test as acceptanceTest } from '../../support/fixtures'
import { expireTableSessions, resetVariant, SECURITY_URL, startVariant, variantSql } from './support/variant'
import { expireTableSessions, resetVariant, SECURITY_URL, SECURITY_UI_URL, startVariant, variantSql } from './support/variant'
import { listCell, navigation, openUserMenu, recordRequests } from './support/ui'
const TESS = { username: 'tess.table', password: 'table:pass-2026', name: 'Tess Table (table-based)' }
const RAVI = { username: 'ravi.rows', password: 'rows-pass-2026', name: 'Ravi Rows (table-based)' }
const test = acceptanceTest.extend<{ tableBased: void }>({
baseURL: async ({}, use) => { await use(SECURITY_URL) },
tableBased: async ({}, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
tableBased: async ({}, provide) => {
await startVariant('TABLE_BASED')
await resetVariant()
await use()
await provide()
},
})
@@ -202,10 +202,10 @@ test('[SEC-037] logout deletes the stored session, keeps protected pages on the
})
const unsupportedTest = acceptanceTest.extend<{ unsupported: void }>({
baseURL: async ({}, use) => { await use(SECURITY_URL) },
unsupported: async ({}, use) => {
baseURL: async ({}, provide) => { await provide(SECURITY_UI_URL) },
unsupported: async ({}, provide) => {
await startVariant('UNSUPPORTED')
await use()
await provide()
},
})
@@ -7,10 +7,11 @@
// Widget chrome and header controls: dropdowns, stored selections, reload, export, help, card chrome.
import type { Page } from '@playwright/test'
import { expectedDownloadFilename, nextDownloadAttribute } from '../../support/downloads'
import { expect, open, test } from '../../support/fixtures'
import { expectTouchReady } from '../../support/touch'
import {
chooseOption, downloadText, dropdown, dropdownOptions, expectLoaded, localeDay, requestParam, widget, widgetBody,
allowMissingExtension, chooseOption, downloadText, dropdown, dropdownOptions, expectLoaded, localeDay, requestParam, widget, widgetBody,
} from './widget-support'
const EXPECTED_CSV = '"Label","Value"\n"A,""B""",7\n"Beta","0"\n'
@@ -123,16 +124,18 @@ test('[WID-045] reload re-renders the widget from the backend @mobile', async ({
await expect(page.locator('[data-qqq-id="button-widget-reload-accHelp"]')).toHaveCount(0)
})
test('[WID-046] export downloads the payload csvData with Material quoting; no data shows a message @mobile', async ({ page, diagnostics }) => {
test('[WID-046] export downloads the payload csvData with Material quoting; no data shows a message @mobile', async ({ page, browserName, diagnostics }) => {
void diagnostics
await openControls(page)
await expectLoaded(page, 'accExport')
const [download] = await Promise.all([page.waitForEvent('download'), page.getByRole('button', { name: 'Export Owned Export' }).click()])
expect(download.suggestedFilename()).toMatch(/^Owned Export \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
const [download, downloadName] = await Promise.all([page.waitForEvent('download'), nextDownloadAttribute(page), page.getByRole('button', { name: 'Export Owned Export' }).click()])
expect(downloadName).toMatch(/^Owned Export \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(download.suggestedFilename()).toBe(expectedDownloadFilename(downloadName, browserName))
expect(await downloadText(download)).toBe(EXPECTED_CSV)
// the parent widget exports its own csvData too
const [parentDownload] = await Promise.all([page.waitForEvent('download'), page.getByRole('button', { name: 'Export Owned Controls' }).click()])
expect(parentDownload.suggestedFilename()).toMatch(/^Owned Controls \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
const [parentDownload, parentDownloadName] = await Promise.all([page.waitForEvent('download'), nextDownloadAttribute(page), page.getByRole('button', { name: 'Export Owned Controls' }).click()])
expect(parentDownloadName).toMatch(/^Owned Controls \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(parentDownload.suggestedFilename()).toBe(expectedDownloadFilename(parentDownloadName, browserName))
expect(await downloadText(parentDownload)).toBe(EXPECTED_CSV)
// nothing to export: a message, and no download
let downloaded = false
@@ -198,8 +201,7 @@ test.describe('on a phone', () => {
test('[WID-041] plain (non-card) widgets drop the card chrome and show metadata footers; payload sublabels render @mobile', async ({ page, diagnostics }) => {
// the gallery deliberately includes a custom component whose bundle is missing
diagnostics.allow('/missing-extension.js 404')
diagnostics.allow('Failed to load resource: the server responded with a status of 404')
allowMissingExtension(page, diagnostics)
await openControls(page)
await expectLoaded(page, 'accPlain')
const plain = widget(page, 'accPlain')
@@ -8,13 +8,12 @@
// Owned widgets of the remaining canonical display types (WidgetsFixtures widgetGallery).
import { expect, open, test } from '../../support/fixtures'
import { expectTouchReady } from '../../support/touch'
import { chartTable, expectLoaded, widget, widgetPayload } from './widget-support'
import { allowMissingExtension, chartTable, expectLoaded, widget, widgetPayload } from './widget-support'
test.describe('widget gallery', () => {
test.beforeEach(async ({ page, diagnostics }) => {
// the gallery deliberately includes a custom component whose bundle is missing (WID-062)
diagnostics.allow('/missing-extension.js 404')
diagnostics.allow('Failed to load resource: the server responded with a status of 404')
allowMissingExtension(page, diagnostics)
await open(page, '/app/widgetGallery')
await expect(page.getByRole('heading', { level: 1, name: 'Widget Gallery' })).toBeVisible()
})
@@ -0,0 +1,21 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
/** Whether Firefox's failed script is the gallery's deliberate HTTP 404. */
export function expectedMissingExtensionFailure(request: {
url: string
method: string
resourceType: string
status: number | undefined
errorText: string
}): boolean {
const url = new URL(request.url)
return url.protocol === 'http:' && url.hostname === '127.0.0.1'
&& url.pathname === '/missing-extension.js' && !url.search
&& request.method === 'GET' && request.resourceType === 'script'
&& request.status === 404 && request.errorText === 'NS_ERROR_DOM_NETWORK_ERR'
}
@@ -48,3 +48,66 @@ for (const height of [320, 720]) {
await expect(cells).toHaveText(sorted.map(row => row.first_name!))
})
}
// Focus can remain on a column header after the user scrolls its container away.
// Opening with the keyboard must bring the reference back before positioning the menu.
test('[WID-073] a focused report column scrolled out of view still opens a reachable menu', async ({ page, backend, diagnostics }, testInfo) => {
void diagnostics
await page.setViewportSize({ width: 1280, height: 720 })
expect((await backend.api.put('/data/savedReport/1', { multipart: {
tableName: 'person', queryFilterJson: JSON.stringify({ orderBys: [{ fieldName: 'id', isAscending: true }] }),
columnsJson: JSON.stringify({ columns: ['id', 'firstName'].map(name => ({ name, isVisible: true })) }),
} })).status()).toBe(200)
const people = await backend.sql('select first_name from person order by id')
await open(page, '/app/savedReport/1')
const preview = byId(page, 'filter-preview-reportSetupWidget')
await expect(preview.getByRole('gridcell').and(preview.locator('[data-qqq-id="grid-cell-firstName"]'))).toHaveText(people.map(row => row.first_name!))
await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
writeText: async (text: string) => { document.documentElement.dataset.copiedReportValues = text },
} }))
const trigger = preview.getByRole('button', { name: 'First Name column menu', exact: true })
const main = byId(page, 'main-content')
const menu = page.getByRole('menu', { name: 'First Name column menu', exact: true })
const navigation = await page.evaluate(() => ({ url: location.href, length: history.length }))
await trigger.scrollIntoViewIfNeeded()
await trigger.focus()
await expect(trigger).toBeInViewport()
const visibleScroll = await main.evaluate(element => element.scrollTop)
await page.keyboard.press('Enter')
await expect(menu).toBeVisible()
expect(await main.evaluate(element => element.scrollTop)).toBe(visibleScroll)
await page.keyboard.press('Escape')
await expect(menu).toBeHidden()
await expect(trigger).toBeFocused()
// A wheel gesture changes scroll without refocusing the offscreen trigger.
const mainBounds = await main.boundingBox()
expect(mainBounds).not.toBeNull()
await page.mouse.move(mainBounds!.x + 20, mainBounds!.y + 20)
await page.mouse.wheel(0, -2000)
await expect.poll(() => main.evaluate(element => element.scrollTop)).toBe(0)
await expect(trigger).toBeFocused()
expect((await trigger.boundingBox())!.y).toBeGreaterThan(720)
await page.keyboard.press('Enter')
await expect(menu).toBeVisible()
try {
await expect.poll(async () => {
const bounds = await menu.boundingBox()
return Boolean(bounds && bounds.y >= 8 && bounds.y + bounds.height <= 712)
}).toBe(true)
} finally {
await testInfo.attach('scrolled-column-menu-bounds', { body: JSON.stringify({
trigger: await trigger.boundingBox(), menu: await menu.boundingBox(),
scrollTop: await main.evaluate(element => element.scrollTop),
}), contentType: 'application/json' })
}
await page.keyboard.press('Escape')
await expect(menu).toBeHidden()
await expect(trigger).toBeFocused()
await page.keyboard.press('Enter')
await expect(menu).toBeVisible()
await menu.getByRole('menuitem', { name: 'Copy full query values', exact: true }).click()
await expect(page.locator('html')).toHaveAttribute('data-copied-report-values', people.map(row => row.first_name!).join('\n') + '\n')
await expect(menu).toBeHidden()
expect(await page.evaluate(() => ({ url: location.href, length: history.length }))).toEqual(navigation)
})
@@ -0,0 +1,63 @@
/*
* Copyright 2026 QRun.IO, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
*/
import { expect, open, test } from '../../support/fixtures'
import { byId } from './widget-support'
for (const { copy, offscreen } of [{ copy: 'page', offscreen: false }, { copy: 'full query', offscreen: false }, { copy: 'full query', offscreen: true }]) {
test(`[WID-073] report column ${copy} copy${offscreen ? ' from an offscreen trigger' : ''} preserves keyboard focus after its notice`, async ({ page, backend, diagnostics }) => {
void diagnostics
await page.setViewportSize({ width: 1280, height: 720 })
expect((await backend.api.put('/data/savedReport/1', { multipart: {
tableName: 'person', queryFilterJson: JSON.stringify({ orderBys: [{ fieldName: 'id', isAscending: true }] }),
columnsJson: JSON.stringify({ columns: ['id', 'firstName'].map(name => ({ name, isVisible: true })) }),
} })).status()).toBe(200)
const people = await backend.sql('select first_name from person order by id')
await open(page, '/app/savedReport/1')
const preview = byId(page, 'filter-preview-reportSetupWidget')
const cells = preview.getByRole('gridcell').and(preview.locator('[data-qqq-id="grid-cell-firstName"]'))
await expect(cells).toHaveText(people.map(row => row.first_name!))
await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
writeText: async (text: string) => { document.documentElement.dataset.copiedReportValues = text },
} }))
const navigation = await page.evaluate(() => ({ url: location.href, length: history.length }))
const trigger = preview.getByRole('button', { name: 'First Name column menu', exact: true })
await trigger.scrollIntoViewIfNeeded()
await trigger.focus()
const triggerId = await trigger.getAttribute('id')
if (offscreen) {
const main = page.getByRole('main')
const bounds = await main.boundingBox()
expect(bounds).not.toBeNull()
await page.mouse.move(bounds!.x + 20, bounds!.y + 20)
await page.mouse.wheel(0, -2000)
await expect.poll(() => main.evaluate(element => element.scrollTop)).toBe(0)
await expect(trigger).toBeFocused()
expect((await trigger.boundingBox())!.y).toBeGreaterThan(720)
}
await page.keyboard.press('Enter')
const menu = page.getByRole('menu', { name: 'First Name column menu', exact: true })
await expect(menu).toBeVisible()
await page.keyboard.press('End')
await expect(menu.getByRole('menuitem', { name: 'Copy full query values', exact: true })).toBeFocused()
if (copy === 'page') await page.keyboard.press('ArrowUp')
await expect(menu.getByRole('menuitem', { name: `Copy ${copy} values`, exact: true })).toBeFocused()
await page.keyboard.press('Enter')
await expect(page.locator('html')).toHaveAttribute('data-copied-report-values', people.map(row => row.first_name!).join('\n') + '\n')
await expect(preview.getByText(`Copied ${people.length} First Name values.`, { exact: true })).toBeVisible()
await expect(menu).toBeHidden()
await expect(trigger).toBeFocused()
await expect(trigger).toHaveAttribute('id', triggerId!)
await page.keyboard.press('Enter')
await expect(menu).toBeVisible()
await page.keyboard.press('Escape')
await expect(menu).toBeHidden()
await expect(trigger).toBeFocused()
await expect(cells).toHaveText(people.map(row => row.first_name!))
expect(await page.evaluate(() => ({ url: location.href, length: history.length }))).toEqual(navigation)
})
}
@@ -25,6 +25,7 @@ for (const hidePreview of [true, false]) {
})
await open(page, '/app/savedReport/1')
await expectLoaded(page, 'reportSetupWidget')
await expect(byId(page, 'report-column-reportSetupWidget-firstName')).toHaveText('First Name')
const preview = byId(page, 'filter-preview-reportSetupWidget')
const cells = preview.getByRole('gridcell').and(preview.locator('[data-qqq-id="grid-cell-firstName"]'))
if (hidePreview) await expect(preview).toHaveCount(0)
@@ -53,6 +54,7 @@ for (const hidePreview of [true, false]) {
const saved = await backend.sql('select query_filter_json from saved_report where id = 1')
expect(JSON.parse(saved[0].query_filter_json!).orderBys).toEqual([{ fieldName: 'id', isAscending: false }])
await expectLoaded(page, 'reportSetupWidget')
await expect(byId(page, 'report-column-reportSetupWidget-firstName')).toHaveText('First Name')
if (hidePreview) await expect(preview).toHaveCount(0)
else await expect(cells).toHaveText(people.map(row => row.first_name!).reverse())
await open(page, '/app/savedReport/1/edit')
@@ -7,10 +7,11 @@
// Reports: run through the basic report process in each format, input fields, permissions, navigation.
import type { Download, Page } from '@playwright/test'
import { expectedDownloadFilename } from '../../support/downloads'
import { expect, open, test } from '../../support/fixtures'
import { expectTouchReady } from '../../support/touch'
import { navigation } from '../security/support/ui'
import { downloadBytes, downloadText, parseCsv, readZip, sqlRows, xlsxRows } from './widget-support'
import { allowMissingExtension, downloadBytes, downloadText, parseCsv, readZip, sqlRows, xlsxRows } from './widget-support'
/** Runs a report in a format and returns the downloaded file. */
async function runReport(page: Page, reportName: string, format: 'CSV' | 'XLSX' | 'JSON'): Promise<Download> {
@@ -32,11 +33,13 @@ async function downloadResult(page: Page): Promise<Download> {
const PEOPLE = 'select id, first_name, last_name, email from person order by id'
test('[RPT-001] a table report downloads CSV with every row from the database @mobile', async ({ page, backend, diagnostics }) => {
test('[RPT-001] a table report downloads CSV with every row from the database @mobile', async ({ page, backend, browserName, diagnostics }) => {
void diagnostics
const people = await sqlRows(backend, PEOPLE)
const download = await runReport(page, 'accPersonReport', 'CSV')
expect(download.suggestedFilename()).toMatch(/^Owned Person Report - \d{4}-\d{2}-\d{2}-\d{4}\.csv$/)
const filename = await page.locator('[data-qqq-id="report-download-link-accPersonReport"]').getAttribute('download')
expect(filename).toMatch(/^Owned Person Report - \d{4}-\d{2}-\d{2}-\d{4}\.csv$/)
expect(download.suggestedFilename()).toBe(expectedDownloadFilename(filename!, browserName))
const rows = parseCsv(await downloadText(download))
expect(rows[0]).toEqual(['Id', 'First Name', 'Last Name', 'Email'])
expect(rows.slice(1)).toEqual(people.map((person) => [person.id, person.first_name, person.last_name, person.email]))
@@ -142,8 +145,7 @@ test('[RPT-011] a report without a process streams from the report route @mobile
})
test('[RPT-008] reports appear in app navigation and open their run page @mobile', async ({ page, diagnostics }) => {
diagnostics.allow('/missing-extension.js 404')
diagnostics.allow('Failed to load resource: the server responded with a status of 404')
allowMissingExtension(page, diagnostics)
await open(page, '/app/widgetGallery')
const nav = await navigation(page)
await nav.getByRole('button', { name: 'Expand Acceptance Reports' }).click()
@@ -6,6 +6,7 @@
*/
// The stock sample's widget dashboard and greetings app: every sample widget renders its real payload.
import { readChartLabelBoxes, type ChartLabelBox } from '../../support/chart-label-geometry'
import { expect, open, test } from '../../support/fixtures'
import { expectNoHorizontalScroll, expectTouchReady } from '../../support/touch'
import { chartTable, expectLoaded, isLargeLayout, widget, widgetPayload } from './widget-support'
@@ -217,7 +218,12 @@ test.describe('sample widgets dashboard', () => {
const labels = card.locator('.recharts-xAxis .recharts-cartesian-axis-tick-value')
await expect(labels).toHaveText(payload.chartData.labels)
for (const label of await labels.all()) await expect(label).not.toHaveAttribute('transform', /rotate/)
const boxes = await labels.evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().toJSON()))
let boxes: ChartLabelBox[] = []
await expect.poll(async () => {
const sample = await labels.evaluateAll(readChartLabelBoxes, payload.chartData.labels)
boxes = sample ?? []
return sample !== null
}).toBe(true)
for (let i = 1; i < boxes.length; i++) expect(boxes[i].left).toBeGreaterThan(boxes[i - 1].right)
}
@@ -7,6 +7,7 @@
// Material table and chart widget extras (QRun-IO/qqq#728): WidgetTableChartFixtures widgetTableCharts.
import type { Locator, Page } from '@playwright/test'
import { expectedDownloadFilename, nextDownloadAttribute } from '../../support/downloads'
import { expect, open, test } from '../../support/fixtures'
import { expectTouchReady } from '../../support/touch'
import { byId, downloadText, expectLoaded, widget, widgetPayload } from './widget-support'
@@ -149,14 +150,15 @@ test.describe('table and chart extras', () => {
await expectTouchReady(page, card)
})
test('[WID-068] export without csvData downloads the Material CSV of the columns and rows, without icon text @mobile', async ({ page, backend, diagnostics }) => {
test('[WID-068] export without csvData downloads the Material CSV of the columns and rows, without icon text @mobile', async ({ page, backend, browserName, diagnostics }) => {
void diagnostics
const payload = await widgetPayload(backend.api, 'accTableCells')
expect(payload.csvData ?? null).toBeNull()
const image = payload.rows[0].imageUrl
await expectLoaded(page, 'accTableCells')
const [download] = await Promise.all([page.waitForEvent('download'), page.getByRole('button', { name: 'Export Owned Typed Cells' }).click()])
expect(download.suggestedFilename()).toMatch(/^Owned Typed Cells \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
const [download, downloadName] = await Promise.all([page.waitForEvent('download'), nextDownloadAttribute(page), page.getByRole('button', { name: 'Export Owned Typed Cells' }).click()])
expect(downloadName).toMatch(/^Owned Typed Cells \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(download.suggestedFilename()).toBe(expectedDownloadFilename(downloadName, browserName))
const csv = await downloadText(download)
expect(csv).toBe([
'"Name","Count","Status","Product","Detail","Tooltip","Image URL","Image Label","Image Total","Image Total Type"',
@@ -167,7 +169,7 @@ test.describe('table and chart extras', () => {
expect(csv).not.toContain('open_in_new')
})
test('[WID-068] each table of a multi-table widget has its own export button and footer @mobile', async ({ page, diagnostics }) => {
test('[WID-068] each table of a multi-table widget has its own export button and footer @mobile', async ({ page, browserName, diagnostics }) => {
void diagnostics
await expectLoaded(page, 'accMultiTableExtras')
const card = widget(page, 'accMultiTableExtras')
@@ -180,11 +182,13 @@ test.describe('table and chart extras', () => {
await expect(second.locator('[data-qqq-id="table-footer-accMultiTableExtras-1"] b')).toHaveText('Owned second footer')
await expect(first.locator('[data-qqq-id^="table-footer-"]')).toHaveCount(1)
const [firstDownload] = await Promise.all([page.waitForEvent('download'), first.getByRole('button', { name: 'Export Owned first table' }).click()])
expect(firstDownload.suggestedFilename()).toMatch(/^Owned first table \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
const [firstDownload, firstDownloadName] = await Promise.all([page.waitForEvent('download'), nextDownloadAttribute(page), first.getByRole('button', { name: 'Export Owned first table' }).click()])
expect(firstDownloadName).toMatch(/^Owned first table \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(firstDownload.suggestedFilename()).toBe(expectedDownloadFilename(firstDownloadName, browserName))
expect(await downloadText(firstDownload)).toBe('"Name","Qty"\n"Owned alpha","1500"\n')
const [secondDownload] = await Promise.all([page.waitForEvent('download'), second.getByRole('button', { name: 'Export Owned second table' }).click()])
expect(secondDownload.suggestedFilename()).toMatch(/^Owned second table \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
const [secondDownload, secondDownloadName] = await Promise.all([page.waitForEvent('download'), nextDownloadAttribute(page), second.getByRole('button', { name: 'Export Owned second table' }).click()])
expect(secondDownloadName).toMatch(/^Owned second table \d{4}-\d{2}-\d{2} \d{4}\.csv$/)
expect(secondDownload.suggestedFilename()).toBe(expectedDownloadFilename(secondDownloadName, browserName))
expect(await downloadText(secondDownload)).toBe('"Owned CSV header"\n"Owned CSV value"\n')
await expectTouchReady(page, card)
})
@@ -8,9 +8,27 @@
// Helpers for the widgets & reports acceptance specs.
import { readFileSync } from 'node:fs'
import { inflateRawSync } from 'node:zlib'
import type { APIRequestContext, Download, Locator, Page } from '@playwright/test'
import type { APIRequestContext, Download, Locator, Page, Request } from '@playwright/test'
import { expect } from '../../support/fixtures'
import type { Backend } from '../../support/fixtures'
import { expectedMissingExtensionFailure } from './missing-extension'
import type { Backend, Diagnostics } from '../../support/fixtures'
/** Allows only the gallery's deliberate missing bundle, including Firefox's 404 script failure. */
export function allowMissingExtension(page: Page, diagnostics: Diagnostics) {
diagnostics.allow('/missing-extension.js 404')
diagnostics.allow('Failed to load resource: the server responded with a status of 404')
const statuses = new WeakMap<Request, number>()
page.on('response', (response) => statuses.set(response.request(), response.status()))
page.on('requestfailed', (request) => {
if (!expectedMissingExtensionFailure({
url: request.url(), method: request.method(), resourceType: request.resourceType(),
status: statuses.get(request), errorText: request.failure()?.errorText ?? '',
})) return
// Bind the allowance to the same Request's observed response and exact URL.
const message = `request: GET ${request.url()} NS_ERROR_DOM_NETWORK_ERR`
diagnostics.allow(new RegExp(`^${message.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`))
})
}
/** Reads rows whose selected columns are all non-null (fails otherwise). */
export async function sqlRows(backend: Backend, query: string): Promise<Array<Record<string, string>>> {
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more