Compare commits

...
Author SHA1 Message Date
james.maes 38b91745dc Merge pull request 'feat(assistant): a card for a set of records says how many and lists them all on request' (#220) from feat/assistant-card-lists-its-set into main
maven / build (push) Successful in 4m36s
build / maven (push) Successful in 4m41s
2026-11-18 20:48:41 +00:00
james.maesandClaude Fable 5.2 d5f7b8ec8d perf(assistant): the names of a set are not prefetched
maven / build (push) Successful in 10m46s
build / maven (push) Successful in 10m52s
Every name of a set is a link, and a set can hold 500. A link that scrolls
into view asks for its page ahead of the click by default, so reading down
the whole list would have requested up to 500 record pages. The links of the
list are followed only when chosen, as the search results' are.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 14:36:22 -06:00
james.maesandClaude Fable 5.2 f148c72ca4 docs(releases): note the assistant card for a set of records
maven / build (push) Successful in 4m57s
build / maven (push) Successful in 4m57s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 14:34:13 -06:00
james.maesandClaude Fable 5.2 fe3b2d67b7 feat(assistant): a card for a set of records says how many and lists them all on request
maven / build (push) Successful in 4m58s
build / maven (push) Successful in 4m58s
The assistant can propose one confirmation card for a set of records (one
run over many). The server sends the total and every record of the set by
name with a link, but the panel drew only the card's lines, which name five.
A person confirmed 27 while seeing 5.

A card for a set now:

- says, before its buttons, how many records it acts on and how many of
  them are named in view ("27 Printer records · showing 5");
- carries the count on its confirm button ("Delete 27", "Save 27",
  "Run on 27"), and a table's own bulk delete confirms as a delete;
- opens the whole list on "See all 27": every record by name, a link into
  the application when its address passes the internal-link check and plain
  text otherwise, in a keyboard-reachable scroll area of bounded height,
  with "Show fewer" to go back. Nothing past the first five names is drawn
  until it is asked for, so a set of 500 costs nothing up front;
- keeps the count and the list after it is confirmed, rejected or expired;
- shows the server's count and says so when the list does not hold that
  many names ("showing 20 of 27 names", "The list holds 20 names, not 27.").

The render normalizer keeps the new fields (actionKind, processName,
processLabel, recordCount, records); it dropped them before. A card for one
record, and a card from a server that sends no records, are drawn exactly
as before (asserted against the earlier markup).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 14:33:21 -06:00
james.maes 722e5b775a Merge pull request 'feat(query): a table can declare the sort its record list opens with' (#219) from feature/table-default-sort into main
maven / build (push) Successful in 5m23s
build / maven (push) Successful in 5m23s
2026-11-15 10:24:04 +00:00
james.maes d49c4a5899 Merge pull request 'feat(account-menu): applications can declare a group of links for the account menu' (#217) from feature/account-menu-host-links into main
maven / build (push) Successful in 10m52s
build / maven (push) Successful in 10m52s
2026-11-15 10:23:56 +00:00
james.maes 9b59908629 Merge pull request 'fix(audits): the audit dialog holds a long record identifier and re-sorts without a request' (#218) from fix/audit-dialog-layout-and-requests into main
maven / build (push) Successful in 10m49s
build / maven (push) Successful in 10m49s
2026-11-15 10:23:48 +00:00
james.maes 2f82a1fe83 Merge pull request 'fix(presence): a presence outage is quiet, backs off and recovers on its own' (#216) from fix/presence-outage-quiet into main
maven / build (push) Successful in 10m51s
build / maven (push) Successful in 10m51s
2026-11-15 10:23:41 +00:00
james.maes d7cca33152 Merge pull request 'fix(explore): explore views show in the breadcrumb and leave a way back to the list' (#215) from fix/explore-views-way-back into main
maven / build (push) Successful in 6m1s
build / maven (push) Successful in 6m1s
2026-11-15 10:23:26 +00:00
james.maesandClaude Fable 5.2 5c7dbe2e52 fix(audits): the audit dialog holds a long record identifier and re-sorts without a request
maven / build (push) Successful in 12m6s
build / maven (push) Successful in 12m6s
Layout. With a long unbroken record label (a 64 character identifier) the
dialog heading had no min-width of zero and no break opportunity, so it took
its full text width in the header row and pushed the sort and close buttons
out of the card. Measured in a browser at 768 and 1440 px: the descending
sort button and the close button ended 15 to 59 px past the card edge.

- Header is a two-column grid (minmax(0,1fr) auto): the heading shrinks and
  wraps at any character, is cut after three lines, and keeps its whole text
  in its title attribute and the dialog name. A copy button beside the sort
  buttons copies the full label.
- An empty history is one block: a small icon over the sentence, inside the
  status element. The separate body with a large icon is gone, and loading
  and error states no longer render an empty body band.

Requests. Opening makes one request. Every change of sort order made another,
because the order was part of the query key.

- A history under the 1,000 row cap is complete, so the other order is the
  loaded entries reversed and is shown without a request. A capped history
  still goes back to the server, because its first rows differ by direction.
- The audit process is given 25 seconds to answer in the same request. The
  server default is 3 seconds, after which it answers that the run continues
  as a job; the dialog did not follow the job and showed an error.

Tests: hook and dialog unit tests, and a mocked e2e spec that checks every
control is inside the card at 320, 390, 768 and 1440 px in light and dark,
runs axe, and counts requests on open and on re-sort.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 03:15:27 -06:00
james.maesandClaude Fable 5.2 a4ed5de745 feat(account-menu): applications can declare a group of links for the account menu
maven / build (push) Successful in 12m8s
build / maven (push) Successful in 12m8s
Applications want a small group of links to the tools that go with one
environment (on a local development stack: the mail capture inbox, the
identity provider admin page, the message broker console), shown under the
account menu only when the application declares them. The menu had no such
extension point.

Contract: a widget of type ACCOUNT_MENU_LINKS in the instance metadata. Its
label is the group heading and defaultValues.links is a list of
{ label, url, icon? }. A widget is the carrier because an application can
declare one without a change to QQQ itself, and the metadata response already
publishes a widget type, label, hasPermission and defaultValues (the Tools
shortcut in the same menu is found the same way). Supplemental instance
metadata is published from an allow-list, so it cannot carry this.

Safety: only an absolute https: URL, or http: to localhost, 127.0.0.1 or
[::1], without credentials. Any other link, and any link without a label, is
dropped and never rendered. Icon names must be well-formed Material names.

Each link is a menuitem that opens in a new tab with rel="noopener
noreferrer"; the arrow keys reach it; its accessible name says it opens in a
new tab. A group is role="group" named by its heading. Nothing is rendered
when the application declares no links. The account menu scrolls within the
space it has when it is taller than the window.

Documented in the README under "Account menu links".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 03:03:16 -06:00
james.maesandClaude Fable 5.2 e3f3fc8045 fix(presence): a presence outage is quiet, backs off and recovers on its own
maven / build (push) Successful in 4m56s
build / maven (push) Successful in 4m56s
The collaboration presence endpoint answers 503 on purpose for a while after
its shared store restarts. Every table and record with presence showed that as
a red "Server error - retrying..." banner, repeatedly: the presence poll went
through the global error handler like a request the person had started, with
three automatic retries and a fixed 20 second interval.

The rule: a request the page makes on its own, for something the page works
without, is a background request (meta: BACKGROUND_REQUEST). It is logged to
the console and never raises the global error banner.

- query-client: BACKGROUND_REQUEST, honoured for queries and mutations.
- Presence: the poll is a background request with one attempt per poll; the
  poll and the lease renewal back off with jitter after a failure (2.5 to 5 s,
  doubling to a minute) and return to 20 s on the first success.
- Presence indicator: "Presence is reconnecting..." as muted text with
  role="status" in place of a table's viewer count; on a record or edit form
  only when other people were shown when the connection was lost, else nothing.
- The same rule for the other background requests that raised the banner: the
  notification bell's summary poll, the header's jobs count, the break-glass
  status check and the note of a recently viewed table or record.
- backoffDelay (exponential, equal jitter) in src/lib/utils/backoff.ts.

Measured in a unit test over a 45 second outage on one table: 11 presence
requests and 2 banners before, about 8 requests and no banner after.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 02:59:36 -06:00
james.maesandClaude Fable 5.2 b2752ac74a fix(explore): explore views show in the breadcrumb and leave a way back to the list
maven / build (push) Successful in 10m51s
build / maven (push) Successful in 10m51s
The explore views (pivot, compare, correlation, crosstab, shift) and the saved
analysis viewer are states of a table's record list, named by the query string.
The breadcrumb read only the path, so inside a view it kept showing the table
as the current page, with no link back to the list.

- table-sub-views: one registry of the query-string views (label, own
  parameters, back control). The list opens a view only through it, the
  breadcrumb reads it, and the tests walk it.
- Breadcrumbs: an open view is the last crumb; the table before it links to
  the list with the rest of the query string (filter, sort, page, search).
  The query string is read inside a Suspense boundary for the static export.
- RecordQuery: "Back to records" is one step back in history when the list it
  returns to is the one the view was opened from, so Back does not meet the
  same list twice; otherwise it replaces the view in place, as before.
- use-record-query: a Back or Forward step restores page and page size from
  the address as well as filter, sort and search, and changes nothing when the
  address already matches. Steps to another path are ignored.
- The Explore menu is built from the shared view list.

Tests: registry, breadcrumb and record list tests for every view (link opens
it, back control, breadcrumb, browser Back, Forward), with a next/navigation
stand-in that follows the history; mocked e2e for all five explore views.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 02:44:55 -06:00
48 changed files with 2724 additions and 125 deletions

No files matched your search

+54
View File
@@ -78,6 +78,60 @@ Set `supplementalAppMetaData.nextUi.showChildGrid` on the app to override this d
widgets already cover its sections and child apps.
Only boolean values override the default. Existing visibility and permission rules still apply.
### Account menu links
An application can add a small, labelled group of links to the account menu (the avatar at the
right of the header), for the tools that go with one environment: on a local development stack,
the mail capture inbox, the identity provider's admin page, the message broker's console. The
group is shown only when the application declares it, under Preferences and above Sign out.
Declare a widget of type `ACCOUNT_MENU_LINKS` in the instance. Nothing in QQQ itself changes: the
metadata response already publishes every widget's `type`, `label`, `hasPermission` and
`defaultValues`, and the Tools shortcut in the same menu is found the same way. The frontend reads
this from `GET /qqq/v1/metaData`:
```json
{
"widgets": {
"localTools": {
"name": "localTools",
"label": "Local tools",
"type": "ACCOUNT_MENU_LINKS",
"hasPermission": true,
"defaultValues": {
"links": [
{ "label": "Mail inbox", "url": "http://localhost:8025/", "icon": "mail" },
{ "label": "Identity provider", "url": "https://id.example.com/admin/", "icon": "admin_panel_settings" },
{ "label": "Message broker", "url": "http://127.0.0.1:15672/" }
]
}
}
}
}
```
| Part | Meaning |
|---|---|
| widget `type` | `ACCOUNT_MENU_LINKS`. Each such widget is one group; groups appear in metadata order. |
| widget `label` | The group's heading (`Links` when blank). |
| widget `hasPermission` | `false` hides the group, so a group can be limited with the widget's permission rules. |
| `defaultValues.links` | An array of links, shown in order; at most 12 are shown. |
| link `label` | Required text of the menu item. |
| link `url` | Required. An absolute `https:` URL, or `http:` to `localhost`, `127.0.0.1` or `[::1]`. No user name or password. |
| link `icon` | Optional Material icon name (`mail`, `key`, `dns`, ...), as for other metadata icons. Without one the item shows an external-link icon. |
A link with any other URL (plain `http:` to another host, `javascript:`, `data:`, a relative path,
credentials in the URL), or without a label, is dropped and never rendered; the rest of the group
still shows, and a group left without links does not show. Each link opens in a new tab with
`rel="noopener noreferrer"` and is a keyboard-reachable menu item. Do not put a secret in a URL:
the metadata response reaches every signed-in user who may see the widget.
On the backend the widget needs a name, the type, a label and a code reference like any other
widget (a renderer that returns no data is enough: the menu never asks for the widget's data), and
`defaultValues.links` as a list of maps. Do not add the widget to an app: it is not a dashboard
widget. Declare it only in the environments that have the tools, for example from an environment
variable.
### Known limitations
- Release candidates only; final 1.0 is held for application soak and owner approval ([#712](https://github.com/QRun-IO/qqq/issues/712), tracker [#713](https://github.com/QRun-IO/qqq/issues/713)).
+23
View File
@@ -101,6 +101,28 @@ status, code, name, request, area })`: the HTTP status, the axios error code (`E
`ECONNABORTED`, `ERR_BAD_REQUEST`), the error's name, the request as above and the query namespace.
It never logs a message, body, header or query string, because those can carry record data.
**Background requests show no banner.** A request the page makes on its own, for something the page
works without, sets `meta: BACKGROUND_REQUEST`: a poll that keeps an indicator fresh, or a write nobody
asked for. Its failure is logged to the console as above (with `background: true`) and never raises the
banner: the person did nothing that failed and can do nothing about it, and a poll would raise the banner
again on every attempt. The indicator shows its own quiet state, or nothing, until a later attempt
succeeds. A request the person started (opening a page, saving, running something) is never a background
request. Today's background requests:
| Request | Where | While it fails |
|---|---|---|
| Presence poll (`GET …/collaboration/presence`) | `use-collaboration-presence.ts` | `Presence is reconnecting…` in place of the viewer count on a table; on a record, the same line only if other people were shown when the connection was lost, otherwise nothing. Presence leases are renewed outside TanStack Query and never raised a banner. |
| Notification bell summary | `AlertsBell.tsx` (`useAlertsInbox`) | the bell keeps its last count, or stays hidden |
| Jobs count in the header | `use-my-jobs.ts` (`background` argument, set by `JobsHeaderButton`) | the button keeps its last count; the Jobs page itself still reports its failures |
| Break-glass session status | `BreakGlassBanner.tsx` | no banner |
| Recently viewed (`POST …/collaboration/recents`) | `use-collaboration-core.ts` (`useRecordRecentView`) | the visit is not added to recents |
A background poll should also back off while it fails. `backoffDelay` in `src/lib/utils/backoff.ts`
gives the wait: a ceiling that doubles per consecutive failure, half of it random, so clients that failed
together (a server restart) do not all return together. Presence waits 2.5 to 5 s after the first failure
and up to a minute after many, instead of its healthy 20 s interval, and does not use the automatic
retries described below.
**Implication for components:** For most queries and mutations, you do not need `onError` at all. The global handler covers toasting. Add per-query handling only when you need to do something the global handler cannot — such as mapping a 400 error's field messages back to form fields.
---
@@ -294,5 +316,6 @@ export function EditOrderForm({ orderId, schema, defaultValues }: Props) {
|---|---|---|
| Axios interceptor | `src/lib/api/client.ts` | 401 → redirect to login |
| Global query handler | `src/lib/query-client.ts` | Every status but 401, no response, page errors → one toast per failure, naming the request |
| `meta: BACKGROUND_REQUEST` | `src/lib/query-client.ts` | A poll or write the page makes on its own → logged, no toast |
| Per-component `onError` | Your component | 400 field errors, custom empty states, navigation |
| `getErrorStatusCode` | `src/lib/utils/error-utils.ts` | Normalize `AxiosError` and plain-object errors to HTTP status code |
+1 -1
View File
@@ -94,7 +94,7 @@ Permissions apply to metadata and data: check table capabilities and the corresp
| `/app/search?q=...` | Navigation, recent-record, and available record search results. |
| `/app/developer` | Developer information available to permitted users. |
The header search and `/` dialog locate navigation targets and recent records; record search is offered when the backend supports it. RC8 includes the search-focus correction: Tab/Shift+Tab remain within the search dialog, Clear returns focus to the search input, and Escape or backdrop dismissal restores focus to the opener. A pointer-opened phone search restores focus to its actual button in verified Chromium/mobile cases. RC8 tablet WebKit has two open Clear-search focus failures; see the release notes for remaining browser issues. RC7 does not include this correction. The command palette opens with `.` or Cmd/Ctrl+K and has a header button; `?` opens keyboard help. Keyboard shortcuts on query and record pages are listed in the [feature matrix](../acceptance/feature-matrix.md). The sidebar has a phone drawer, nested app groups, banners, and a user menu. Branding can add a company footer and a themed bar above the shell. `?helpHelp` reveals help-slot keys for content authors.
The header search and `/` dialog locate navigation targets and recent records; record search is offered when the backend supports it. RC8 includes the search-focus correction: Tab/Shift+Tab remain within the search dialog, Clear returns focus to the search input, and Escape or backdrop dismissal restores focus to the opener. A pointer-opened phone search restores focus to its actual button in verified Chromium/mobile cases. RC8 tablet WebKit has two open Clear-search focus failures; see the release notes for remaining browser issues. RC7 does not include this correction. The command palette opens with `.` or Cmd/Ctrl+K and has a header button; `?` opens keyboard help. Keyboard shortcuts on query and record pages are listed in the [feature matrix](../acceptance/feature-matrix.md). The sidebar has a phone drawer, nested app groups, banners, and a user menu. An application can add a labelled group of external links to the account menu (an environment's companion tools) by declaring a widget of type `ACCOUNT_MENU_LINKS`; the contract and its URL rules are in the README under [Account menu links](../../README.md#account-menu-links). Branding can add a company footer and a themed bar above the shell. `?helpHelp` reveals help-slot keys for content authors.
Material's nested `/{app}/{table}/{id}` URLs are not the native Next route. A not-found page now checks the signed-in instance metadata, applies exact or `/*` redirect rules, and resolves nested Material app paths to `/app/...` while preserving query/hash ([`legacy-paths.ts`](../../src/lib/utils/legacy-paths.ts), [`LegacyPathRedirect.tsx`](../../src/components/layout/LegacyPathRedirect.tsx)). Verify a specific old bookmark rather than assuming arbitrary legacy URLs match. For links generated by widgets use [`material-links.ts`](../../src/lib/utils/material-links.ts), which normalizes supported legacy links and preserves a trailing slash for static-export routes.
+11
View File
@@ -6,6 +6,8 @@
- **Tools:** the `QQQ_TOOLS` widget provides a shared setup workspace for CLI/TUI, mobile scanners and Print Client, with platform-specific install commands, copyable scripts and instance connection details. An account-menu shortcut follows visible Tools metadata. Requires the Tools Qbit; existing device enrollment and permissions remain unchanged.
- **Application-declared links in the account menu.** An application can add a labelled group of links to the tools that go with one environment (a mail capture inbox, an identity provider's admin page, a message broker's console) by declaring a widget of type `ACCOUNT_MENU_LINKS` whose `defaultValues.links` is a list of `{ "label", "url", "icon" }`. No QQQ change is needed: the metadata response already publishes a widget's type, label, permission and default values. Only absolute `https:` URLs, or `http:` to `localhost`, `127.0.0.1` or `[::1]`, without credentials, are shown; any other link is dropped. Links open in a new tab with `rel="noopener noreferrer"`, are keyboard-reachable menu items, and the group renders nothing when the application declares none. The account menu now scrolls within the space it has when it is taller than the window. Contract: README, [Account menu links](../../README.md#account-menu-links).
- **UI API 1.6.0 (QQQ 4.1.0-RC.15).** Next reads the typed `clientCapabilities` of table metadata for saved views, sharing, bulk processes and audits, applies `field.validation` (required, length, inclusive and exclusive bounds, patterns) before a request, reads client-neutral `uiSettings` setting by setting with the deprecated `materialDashboard` values as fallback, and shows the process error `traceId`. The full `materialDashboardTheme` still wins over the `uiSettings.theme` subset. Error messages keep their order (`userFacingError`, `error`, then the new `message`). Audits fall back to the permission-filtered instance metadata when a table's capability is unavailable, since RC.15 marks unaudited tables unavailable although explicit audits can exist. Off-spec calls stay at 0.
- **What's new:** a paged release history with new badges, safe links and screenshots, notification deep links, and an unread count in the user menu. Uses UI API extension `release-notes` 1.0.0; requires qbit-release-notes 0.1.0-RC.1+.
- **Profile photo and avatars everywhere** (QQQ 4.1.0-RC.17, UI API 1.8.0 `avatars`):
@@ -21,12 +23,21 @@
- **Preferences says how a connection ended.** A flow that left the dashboard returns to `/app/preferences?section=<name>&result=<code>` when it succeeded or `&error=<code>` when it did not. The section now shows the outcome once, above its form, as the section's label and the code as words (`Slack: connected.`, `Slack: authorization denied.`), as a status or an alert, and takes it off the address so a reload does not repeat it. Only a fixed lowercase code is read from the address, never a sentence.
- **Links in process HTML look like links.** An `HTML` process component rendered links in the text color with no underline, so a link the backend put on a screen (a bulk load template, a "Continue to Slack" link) could not be told from the words around it. They now use the link color and an underline; a link's own inline style still wins.
- **Explore views leave a way back.** Pivot, Compare, Correlation, Crosstab, Shift over time and a saved analysis are states of a table's record list, named by the query string (`?view=correlation`), so the breadcrumb, which read only the path, kept showing the table as the current page and offered no link back to the list. The breadcrumb now ends with the view (`… / People / Correlation`) and the table before it links to the list with its filter, sort, page and quick search as they were. "Back to records" is one step back in history when the list it returns to is the one the view was opened from, so the view stays one Forward away and the browser's Back button no longer meets the same list twice; after a drill changed the filter, or on a link straight to a view, it replaces the view with the list in place, as before. A Back or Forward step between the list and a view now takes the page and page size from the address as well as the filter and search, instead of returning the list to page 1. The views are registered in one place (`src/lib/utils/table-sub-views.ts`), which the list, the breadcrumb and the tests read, so a new view cannot ship without a label and a way back.
- **The Ask button's activity dot sits on its icon.** While a reply was being written, the dot was placed in the bottom-right corner of the button's hit area, which has no visible edge and, from 1440 px, extends past the "Ask" label, so the dot floated under and to the right of the label. The dot and the unread badge are now positioned against the sparkles icon, at every width and with the panel open or closed. The bell and Jobs badges use the same anchor and keep their place.
- **A presence outage is no longer shown as a server error.** The collaboration presence endpoint answers 503 on purpose for a while after its shared store restarts, and every table and record with presence showed that as a red `Server error — retrying…` banner, again and again. Presence is not essential to the page, so its failures now raise no banner. On a table the viewer count reads `Presence is reconnecting…` in muted text (a polite status, not an alert) until the server answers; on a record or an edit form that line appears only when other people were shown at the moment the connection was lost, and otherwise nothing changes. The poll and the lease renewal no longer repeat at a fixed 20 seconds or retry three times in seven: after a failure the next attempt waits 2.5 to 5 seconds, then twice as long per failure up to a minute, with jitter, and the first success restores the usual rhythm. In a 45 second outage one table made eleven presence requests and raised the banner twice; it now makes about eight and raises none.
- **Background requests do not raise the error banner.** The rule behind the presence fix is general: a request the page makes on its own for something the page works without (`meta: BACKGROUND_REQUEST`) is logged to the console and shows no banner. It now also covers the notification bell's summary poll, the header's jobs count, the break-glass status check and the note of a recently viewed table or record. Requests a person starts are unchanged. See `docs/API-ERROR-HANDLING.md`.
- **Logout no longer races an in-flight request.** Logout ends the API client's session generation first: every request still in flight (axios and the realtime and assistant streams) is aborted, and any response of the old generation that still arrives is discarded, so none can refresh the `sessionId` cookie the logout expires or change client auth state (SEC-037, SEC-048).
- **The audit dialog holds a long record identifier, and sorts without asking again.** With a long unbroken record label (a 64 character identifier) the dialog's heading could not shrink or wrap, so it filled the card and pushed the sort and close buttons out of it, to its right. The heading now takes the space the controls leave, wraps at any character and is cut after three lines, with the whole text in its tooltip and a copy button beside the sort buttons; the controls stay inside the card from 320 px up, in both themes. An empty history is one block (a small icon over `No audits were found for this record.`) instead of a status line with a large icon in a band of its own below it; loading and error states no longer leave an empty band either. Opening the dialog makes one request, as before. Changing the sort order made another request every time; a history under the 1,000 row cap is complete, so the other order is now shown at once from what is loaded, and only a capped history goes back to the server. The audit process is given 25 seconds to answer in the same request instead of the server's default 3, after which the server answers that the run continues as a job, which the dialog showed as `Error loading audits`.
- **The error banner says what failed, and no longer stacks.** The banner for a failed request used to read "Something went wrong" for every failure without an expected status, and a polling request that kept failing added one banner per attempt. It now reads `No response from the server`, `The server took too long to respond`, the server's own message, or `Request failed (HTTP 409)`, and names the request below it (`POST /qqq/v1/table/order/query`, without the query string, with ids shown as `{id}`). A repeat of the same failure updates the banner on screen; a lost connection shows one banner whichever requests met it. The 403, 404 and 5xx banners keep their wording and gain the request line; a 403 without a server message reads `Permission denied`. A cancelled request, an aborted `fetch` and a 401 show no banner. Each banner logs its status, axios code, error name and request to the console once (`[API] Request failed:`), never a message, body, header or query string.
- **An assistant card for a set of records says how many, and lists them all.** The assistant can propose one confirmation card for a set of records (one run over many, for example a table's bulk delete). The server sends the total and every record of the set by name with a link (qbit-assistant 0.1.0-RC.32 and later), but the panel drew only the card's lines, which name five, so a person confirmed 27 records while seeing 5. The card now says before its buttons how many records it acts on and how many are named in view (`27 Printer records · showing 5`), and its confirm button carries the count (`Delete 27`, `Save 27`, `Run on 27`); a table's own bulk delete confirms as a delete, where it used to read "Save". `See all 27` opens every record by name inside the card, in a scroll area of bounded height that the keyboard reaches, and `Show fewer` closes it; a name is a link when its address passes the panel's internal-link check and plain text otherwise. Only the first five names are drawn until the list is asked for, so a set of 500 costs nothing up front. The count and the list stay on the card after it is confirmed, rejected or expired. When the list does not hold as many names as the count, the card shows the server's count and says so (`showing 20 of 27 names`, `The list holds 20 names, not 27.`). A card for one record, and a card from a server that sends no list, are unchanged.
## Browser testing and infrastructure
None yet.
+3 -1
View File
@@ -32,7 +32,7 @@ import { useQuery } from '@tanstack/react-query'
import { useUiApiExtensionInstalled, UI_API_EXTENSION } from '@/lib/api/ui-api-extensions'
import { getAlertsInboxSummary } from '@/lib/api/alerts'
import { queryKeys } from '@/lib/query-client'
import { BACKGROUND_REQUEST, queryKeys } from '@/lib/query-client'
import type { AlertsInboxSummary } from '@/types/alerts'
import type { QInstance } from '@/types/metadata'
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
@@ -99,6 +99,8 @@ export function useAlertsInbox(enabled: boolean) {
staleTime: 30_000,
refetchInterval: (query) => pollDelay(query.state.data, failures),
refetchIntervalInBackground: false,
// A poll for the bell's badge: a failure leaves the bell as it was and raises no banner.
meta: BACKGROUND_REQUEST,
refetchOnWindowFocus: (query) => (query.state.data === null ? false : 'always'),
})
}
@@ -0,0 +1,113 @@
/*
* 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.
*/
/**
* AssistantPendingActionCard stories — the confirmation card of a proposed write: a change to
* one record, and one run over a set of records (its count, the names in view, the whole list
* on request, and a count the list does not match). The action's state is served by the story.
*/
import React from 'react'
import type { Meta, StoryObj } from '@storybook/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { AssistantPendingAction, AssistantPendingActionRender } from '@/types/assistant'
import apiClient from '@/lib/api/client'
import AssistantPendingActionCard from './AssistantPendingActionCard'
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } })
/** The action as the card loads it, and as it is after a decision. */
const ACTION: AssistantPendingAction = { id: 7, status: 'PENDING', toolName: 'update_record', tableName: 'printer', summary: 'Proposed change' }
const meta = {
title: 'Assistant/AssistantPendingActionCard',
component: AssistantPendingActionCard,
parameters: { layout: 'padded' },
tags: ['autodocs'],
decorators: [
(Story) => (
<QueryClientProvider client={queryClient}>
<div className="@container w-full max-w-[390px] space-y-4 bg-card p-3">
<Story />
</div>
</QueryClientProvider>
),
],
// no server behind a story: the card's own requests are answered here
beforeEach: () => {
const { get, post } = apiClient
apiClient.get = (async () => ACTION) as typeof apiClient.get
apiClient.post = (async (url: string) => (
url.endsWith('/confirm') ? { ...ACTION, status: 'EXECUTED', resultSummary: 'Ran to its end' } : { ...ACTION, status: 'REJECTED' }
)) as typeof apiClient.post
return () => {
apiClient.get = get
apiClient.post = post
}
},
} satisfies Meta<typeof AssistantPendingActionCard>
export default meta
type Story = StoryObj<typeof meta>
/**
* A card for one run over a set of records, as the server sends it.
*
* @param count - How many records the set has.
* @param listed - How many of them the list holds.
* @returns The render.
*/
function setOf(count: number, listed = count): AssistantPendingActionRender {
const names = ['Dock 1', 'Dock 2', 'Dock 3', 'Dock 4', 'Dock 5'].slice(0, count).join(', ')
return {
type: 'pending_action',
actionId: 7,
toolName: 'update_record',
actionKind: 'process_run',
processName: 'printer.bulkDelete',
processLabel: 'Printer Bulk Delete',
tableName: 'printer',
tableLabel: 'Printer',
summary: `Run Printer Bulk Delete on ${count} Printer records`,
changes: [
{ field: 'process', label: 'Process', value: 'Printer Bulk Delete' },
{ field: 'records', label: 'Records', value: `${count} Printer records: ${names}${count > 5 ? ` and ${count - 5} more` : ''} (Status equals Retired)` },
{ field: 'runs', label: 'Runs', value: 'When you confirm, to its end.' },
],
recordCount: count,
records: Array.from({ length: listed }, (_, index) => ({ id: String(index + 1), label: `Dock ${index + 1}`, href: `/app/printer/${index + 1}` })),
}
}
/** A change to one record: no count and no list. */
export const OneRecord: Story = {
args: {
render: {
type: 'pending_action', actionId: 7, toolName: 'update_record', tableName: 'printer', tableLabel: 'Printer', recordId: '4',
summary: 'Update Printer Dock 4: Location = Bay 2',
changes: [{ field: 'location', label: 'Location', value: 'Bay 2' }],
},
},
}
/** One run over 27 records: the count, five names in view, "See all 27", and "Delete 27". */
export const SetOfRecords: Story = { args: { render: setOf(27) } }
/** The largest set a server sends: the list is drawn only when asked for, and scrolls inside the card. */
export const FiveHundredRecords: Story = { args: { render: setOf(500) } }
/** The list holds fewer names than the count: the card shows the count and says so. */
export const CountAndListDisagree: Story = { args: { render: setOf(27, 20) } }
@@ -15,7 +15,7 @@
*/
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -87,3 +87,321 @@ describe('AssistantPendingActionCard', () => {
expect(calls).not.toContain('confirm')
})
})
/** The lines a card for a run over a set carries, as the server writes them. */
const SET_LINES = [
{ field: 'process', label: 'Process', value: 'Printer Bulk Delete' },
{ field: 'records', label: 'Records', value: '27 Printer records: Dock 1, Dock 2, Dock 3, Dock 4, Dock 5 and 22 more' },
{ field: 'runs', label: 'Runs', value: 'When you confirm, to its end.' },
]
/**
* A card for one run over a set of records, as the server sends it: an update by tool name, a
* process run by kind, the count, and every record with its name and link.
*
* @param count - How many records the set has.
* @param overrides - Fields to replace.
* @returns The render.
*/
function setRender(count: number, overrides: Partial<AssistantPendingActionRender> = {}): AssistantPendingActionRender {
return {
type: 'pending_action',
actionId: 7,
toolName: 'update_record',
actionKind: 'process_run',
processName: 'printer.bulkDelete',
processLabel: 'Printer Bulk Delete',
tableName: 'printer',
tableLabel: 'Printer',
summary: `Run Printer Bulk Delete on ${count} Printer records`,
changes: SET_LINES,
recordCount: count,
records: Array.from({ length: count }, (_, index) => ({ id: String(index + 1), label: `Dock ${index + 1}`, href: `/app/printer/${index + 1}` })),
...overrides,
}
}
/**
* Serves the action of a card for a set.
*
* @param loaded - The status the card loads with.
* @returns The calls made, by kind.
*/
function serveSet(loaded: 'PENDING' | 'EXPIRED' = 'PENDING') {
const calls: string[] = []
const action = { id: 7, toolName: 'update_record', tableName: 'printer', summary: 'Run Printer Bulk Delete' }
server.use(
http.get('*/assistant/actions/7', () => {
calls.push('get')
return HttpResponse.json({ ...action, status: loaded })
}),
http.post('*/assistant/actions/7/confirm', () => {
calls.push('confirm')
return HttpResponse.json({ ...action, status: 'EXECUTED', resultSummary: 'Printer Bulk Delete ran to its end', outcome: 'OK' })
}),
http.post('*/assistant/actions/7/reject', () => {
calls.push('reject')
return HttpResponse.json({ ...action, status: 'REJECTED', resultSummary: 'Cancelled by the user; nothing changed.' })
})
)
return calls
}
/**
* Draws a card and waits for it to load its action.
*
* @param card - The render to draw.
* @param loaded - The status the card loads with.
* @returns The container and the calls made.
*/
async function draw(card: AssistantPendingActionRender, loaded: 'PENDING' | 'EXPIRED' = 'PENDING') {
const calls = serveSet(loaded)
const { container } = render(<QueryClientProvider client={new QueryClient()}><AssistantPendingActionCard render={card} /></QueryClientProvider>)
await waitFor(() => expect(calls).toContain('get'))
return { container, calls }
}
/** The names the card draws now, in order, links and plain text alike. */
function drawnNames(container: HTMLElement): string[] {
return Array.from(container.querySelectorAll('[data-qqq-id="assistant-pending-action-record"]')).map((name) => name.textContent ?? '')
}
/** What the card says of its set, before its buttons. */
function countText(container: HTMLElement): string {
return container.querySelector('[data-qqq-id="assistant-pending-action-record-count"]')?.textContent ?? ''
}
/**
* The card's markup as it was before cards for a set existed, for a pending update with the
* given summary and lines. Icons are reduced to their classes.
*
* @param summary - The card's summary.
* @param lines - The markup of its lines, inside the list.
* @returns The markup.
*/
function markupBeforeSets(summary: string, lines: string): string {
return `<div class="rounded-lg border border-border bg-card" data-qqq-id="assistant-pending-action" role="group" aria-label="Proposed change: ${summary}">`
+ '<div class="flex items-start gap-2 border-b border-border px-3 py-2"><svg class="lucide lucide-pencil-line mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"/>'
+ `<div class="min-w-0 flex-1"><p class="text-sm font-medium text-foreground break-words">${summary}</p>`
+ '<p class="text-xs text-muted-foreground" aria-live="polite" data-qqq-id="assistant-pending-action-status">Waiting for your confirmation</p></div></div>'
+ `<dl class="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-1 px-3 py-2 text-xs">${lines}</dl>`
+ '<div class="flex flex-wrap items-center gap-2 border-t border-border px-3 py-2">'
+ '<button type="button" class="inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-medium pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 bg-primary text-primary-foreground hover:bg-primary/90" data-qqq-id="assistant-pending-action-confirm"><svg class="lucide lucide-check h-3.5 w-3.5"/>Save</button>'
+ '<button type="button" class="inline-flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-accent pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60" data-qqq-id="assistant-pending-action-cancel"><svg class="lucide lucide-x h-3.5 w-3.5"/>Cancel</button>'
+ '</div></div>'
}
/** A card's markup with each icon reduced to its classes (an icon's drawing is not the card's). */
function markupOf(container: HTMLElement): string {
return container.innerHTML.replace(/<svg[^>]*class="([^"]*)"[^>]*>.*?<\/svg>/g, '<svg class="$1"/>')
}
describe('AssistantPendingActionCard for a set of records', () => {
it('says how many records it acts on and how many it names, before its buttons', async () => {
const { container } = await draw(setRender(27))
expect(countText(container)).toBe('27 Printer records · showing 5')
expect(drawnNames(container)).toEqual(['Dock 1', 'Dock 2', 'Dock 3', 'Dock 4', 'Dock 5'])
expect(screen.getAllByRole('link').map((link) => link.getAttribute('href'))).toEqual(['/app/printer/1', '/app/printer/2', '/app/printer/3', '/app/printer/4', '/app/printer/5'])
const count = container.querySelector('[data-qqq-id="assistant-pending-action-record-count"]') as HTMLElement
const confirm = container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]') as HTMLElement
expect(count.compareDocumentPosition(confirm) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(container.querySelector('[data-qqq-id="assistant-pending-action-record-mismatch"]')).toBeNull()
expect(await axe(container)).toHaveNoViolations()
})
it.each([
['a bulk delete', {}, 'Delete 27', 'Delete 27 Printer records', true],
['a bulk edit', { processName: 'printer.bulkEdit' }, 'Save 27', 'Save 27 Printer records', false],
['another process', { processName: 'reprintLabels' }, 'Run on 27', 'Run on 27 Printer records', false],
['a set of one', { recordCount: 1, records: [{ id: '1', label: 'Dock 1', href: '/app/printer/1' }] }, 'Delete 1', 'Delete 1 Printer record', true],
['a set of a table with no label', { tableLabel: '' }, 'Delete 27', 'Delete 27 records', true],
])('carries the count on the confirm button of %s', async (_name, overrides, text, name, destructive) => {
const { container } = await draw(setRender(27, overrides))
const confirm = container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]') as HTMLElement
expect(confirm).toHaveTextContent(text)
expect(confirm).toHaveAccessibleName(name)
expect(confirm.className.includes('bg-destructive')).toBe(destructive)
})
it('lists every record with a link into the application on request, and goes back', async () => {
const { container } = await draw(setRender(27))
const toggle = screen.getByRole('button', { name: 'See all 27' })
expect(toggle).toHaveAttribute('aria-expanded', 'false')
await userEvent.click(toggle)
expect(countText(container)).toBe('27 Printer records · showing all 27')
expect(drawnNames(container)).toEqual(Array.from({ length: 27 }, (_, index) => `Dock ${index + 1}`))
const list = screen.getByRole('group', { name: 'All 27 names' })
expect(within(list).getAllByRole('link').map((link) => link.getAttribute('href'))).toEqual(Array.from({ length: 27 }, (_, index) => `/app/printer/${index + 1}`))
// a scroll area of bounded height that the keyboard reaches
expect(list).toHaveAttribute('tabindex', '0')
expect(list).toHaveClass('max-h-48', 'overflow-y-auto')
expect(toggle).toHaveAttribute('aria-expanded', 'true')
expect(toggle).toHaveAttribute('aria-controls', list.id)
expect(toggle).toHaveTextContent('Show fewer')
expect(await axe(container)).toHaveNoViolations()
await userEvent.click(screen.getByRole('button', { name: 'Show fewer' }))
expect(countText(container)).toBe('27 Printer records · showing 5')
expect(drawnNames(container)).toHaveLength(5)
expect(screen.queryByRole('group', { name: 'All 27 names' })).not.toBeInTheDocument()
})
it('opens and closes the list from the keyboard', async () => {
const { container } = await draw(setRender(27))
const toggle = screen.getByRole('button', { name: 'See all 27' })
toggle.focus()
await userEvent.keyboard('{Enter}')
expect(drawnNames(container)).toHaveLength(27)
await userEvent.tab()
expect(screen.getByRole('group', { name: 'All 27 names' })).toHaveFocus()
await userEvent.tab()
expect(screen.getByRole('link', { name: 'Dock 1' })).toHaveFocus()
toggle.focus()
await userEvent.keyboard(' ')
expect(drawnNames(container)).toHaveLength(5)
expect(toggle).toHaveFocus()
})
it('never makes a link of an address outside the application or a malformed one', async () => {
const records = [
{ id: '1', label: 'Inside', href: '/app/printer/1' },
{ id: '2', label: 'Other site', href: 'https://example.com/app/printer/2' },
{ id: '3', label: 'Protocol relative', href: '//example.com/app/printer/3' },
{ id: '4', label: 'Script', href: 'javascript:alert(1)' },
{ id: '5', label: 'Outside the app', href: '/elsewhere/printer/5' },
{ id: '6', label: 'Backslashes', href: '/app\\printer\\6' },
{ id: '7', label: 'No link' },
{ id: '8', label: '', href: '/app/printer/8' },
]
const { container } = await draw(setRender(8, { records }))
await userEvent.click(screen.getByRole('button', { name: 'See all 8' }))
// every record is named, also the ones without a link; a record with no name goes by its id
expect(drawnNames(container)).toEqual(['Inside', 'Other site', 'Protocol relative', 'Script', 'Outside the app', 'Backslashes', 'No link', '8'])
expect(screen.getAllByRole('link').map((link) => [link.textContent, link.getAttribute('href')])).toEqual([['Inside', '/app/printer/1'], ['8', '/app/printer/8']])
expect(container.querySelector('a[href*="example.com"], a[href^="javascript"]')).toBeNull()
})
it('holds 500 records without drawing the list until it is asked for', async () => {
const { container } = await draw(setRender(500))
expect(countText(container)).toBe('500 Printer records · showing 5')
expect(drawnNames(container)).toHaveLength(5)
expect(container.querySelectorAll('a')).toHaveLength(5)
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 500')
await userEvent.click(screen.getByRole('button', { name: 'See all 500' }))
expect(countText(container)).toBe('500 Printer records · showing all 500')
const list = screen.getByRole('group', { name: 'All 500 names' })
expect(within(list).getAllByRole('link')).toHaveLength(500)
expect(within(list).getByRole('link', { name: 'Dock 500' })).toHaveAttribute('href', '/app/printer/500')
// the list scrolls inside the card: its height is bounded however many records it holds
expect(list).toHaveClass('max-h-48', 'overflow-y-auto')
})
it('offers no "See all" when every name is already in view', async () => {
const { container } = await draw(setRender(3))
expect(countText(container)).toBe('3 Printer records · showing all 3')
expect(drawnNames(container)).toEqual(['Dock 1', 'Dock 2', 'Dock 3'])
expect(screen.queryByRole('button', { name: /see all/i })).not.toBeInTheDocument()
})
it('keeps the count and the list readable after it is confirmed; only the buttons go', async () => {
const { container, calls } = await draw(setRender(27))
await userEvent.click(screen.getByRole('button', { name: 'Delete 27 Printer records' }))
await waitFor(() => expect(screen.getByText(/Done · Printer Bulk Delete ran to its end/)).toBeInTheDocument())
expect(calls.filter((call) => call === 'confirm')).toHaveLength(1)
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toBeNull()
expect(container.querySelector('[data-qqq-id="assistant-pending-action-cancel"]')).toBeNull()
expect(countText(container)).toBe('27 Printer records · showing 5')
await userEvent.click(screen.getByRole('button', { name: 'See all 27' }))
expect(drawnNames(container)).toHaveLength(27)
expect(await axe(container)).toHaveNoViolations()
})
it('keeps the count and the list readable after it is rejected', async () => {
const { container, calls } = await draw(setRender(27))
await userEvent.click(screen.getByRole('button', { name: 'See all 27' }))
await userEvent.click(screen.getByRole('button', { name: /cancel/i }))
await waitFor(() => expect(screen.getByText(/Cancelled, nothing changed/)).toBeInTheDocument())
expect(calls).not.toContain('confirm')
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toBeNull()
// the list the person had open stays open
expect(countText(container)).toBe('27 Printer records · showing all 27')
expect(drawnNames(container)).toHaveLength(27)
})
it('keeps the count and the list readable on a card that has expired', async () => {
const { container } = await draw(setRender(27), 'EXPIRED')
await waitFor(() => expect(screen.getByText(/Expired, nothing changed/)).toBeInTheDocument())
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toBeNull()
expect(countText(container)).toBe('27 Printer records · showing 5')
await userEvent.click(screen.getByRole('button', { name: 'See all 27' }))
expect(drawnNames(container)).toHaveLength(27)
})
it('shows the count the server sent and says so when the list holds fewer names', async () => {
const { container } = await draw(setRender(20, { recordCount: 27 }))
expect(countText(container)).toBe('27 Printer records · showing 5 of 27 names')
expect(screen.getByText('The list holds 20 names, not 27.')).toBeInTheDocument()
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 27')
await userEvent.click(screen.getByRole('button', { name: 'See all 20' }))
expect(countText(container)).toBe('27 Printer records · showing 20 of 27 names')
expect(drawnNames(container)).toHaveLength(20)
expect(screen.getByText('The list holds 20 names, not 27.')).toBeInTheDocument()
expect(countText(container)).not.toContain('all')
})
it.each([
['more names than the count', setRender(6, { recordCount: 3 }), '3 Printer records · showing 5 names', 'The list holds 6 names, not 3.', 'Delete 3'],
['one name for many records', setRender(1, { recordCount: 27 }), '27 Printer records · showing 1 of 27 names', 'The list holds 1 name, not 27.', 'Delete 27'],
['names and a count of none', setRender(2, { recordCount: 0 }), '0 Printer records · showing 2 names', 'The list holds 2 names, not 0.', 'Delete 0'],
])('says so when the list holds %s', async (_name, card, count, note, button) => {
const { container } = await draw(card)
expect(countText(container)).toBe(count)
expect(screen.getByText(note)).toBeInTheDocument()
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent(button)
})
it('says that no names are listed when the server sent a count and no list', async () => {
const { container } = await draw(setRender(0, { recordCount: 27 }))
expect(countText(container)).toBe('27 Printer records · no names listed')
expect(drawnNames(container)).toEqual([])
expect(screen.queryByRole('button', { name: /see all/i })).not.toBeInTheDocument()
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 27')
})
it('counts its list when the server sent the records and no count', async () => {
const { container } = await draw(setRender(8, { recordCount: undefined }))
expect(countText(container)).toBe('8 Printer records · showing 5')
expect(container.querySelector('[data-qqq-id="assistant-pending-action-confirm"]')).toHaveTextContent('Delete 8')
})
})
describe('AssistantPendingActionCard without a set', () => {
it('draws a card for one record exactly as before', async () => {
const { container } = await draw({
type: 'pending_action', actionId: 7, toolName: 'update_record', tableName: 'printer', tableLabel: 'Printer', recordId: '4',
summary: 'Update Printer 4: Location = Dock 2',
changes: [{ field: 'location', label: 'Location', value: 'Dock 2' }, { field: 'note', label: 'Note', value: null }],
records: [],
})
expect(markupOf(container)).toBe(markupBeforeSets(
'Update Printer 4: Location = Dock 2',
'<dt class="truncate text-muted-foreground">Location</dt><dd class="break-words text-foreground">Dock 2</dd>'
+ '<dt class="truncate text-muted-foreground">Note</dt><dd class="break-words text-foreground"><span class="text-muted-foreground">(empty)</span></dd>'
))
})
it('draws a run over a set from an older server, which sends no records, exactly as before', async () => {
const { container } = await draw(setRender(27, { recordCount: undefined, records: undefined }))
expect(markupOf(container)).toBe(markupBeforeSets(
'Run Printer Bulk Delete on 27 Printer records',
'<dt class="truncate text-muted-foreground">Process</dt><dd class="break-words text-foreground">Printer Bulk Delete</dd>'
+ '<dt class="truncate text-muted-foreground">Records</dt><dd class="break-words text-foreground">27 Printer records: Dock 1, Dock 2, Dock 3, Dock 4, Dock 5 and 22 more</dd>'
+ '<dt class="truncate text-muted-foreground">Runs</dt><dd class="break-words text-foreground">When you confirm, to its end.</dd>'
))
expect(container.querySelector('[data-qqq-id="assistant-pending-action-records"]')).toBeNull()
})
})
@@ -19,16 +19,20 @@
* record). Nothing changes until the user confirms; the server then runs the write through the
* UI API with the user's own session, so the same permissions, record locks and validation apply.
* The card loads the action's current state, so a reloaded conversation shows the outcome.
*
* A card for a set of records (one run over many) states how many records it acts on and how
* many of them it names, carries that count on its confirm button, and lists every record of
* the set on request. The count and the list stay on the card after it is decided.
*/
'use client'
import React, { useEffect, useState } from 'react'
import React, { useEffect, useId, useState } from 'react'
import Link from 'next/link'
import { useQueryClient } from '@tanstack/react-query'
import { Check, PencilLine, Plus, Trash2, X } from 'lucide-react'
import type { AssistantPendingAction, AssistantPendingActionRender } from '@/types/assistant'
import type { AssistantPendingAction, AssistantPendingActionRecord, AssistantPendingActionRender } from '@/types/assistant'
import { confirmAssistantAction, getAssistantAction, rejectAssistantAction } from '@/lib/api/assistant'
import { internalAppHref } from '@/lib/utils/assistant-links'
import { getErrorMessage } from '@/lib/utils/error-utils'
@@ -43,6 +47,108 @@ const STATUS_TEXT: Record<AssistantPendingAction['status'], string> = {
EXPIRED: 'Expired, nothing changed',
}
/** How many names of a set a card shows before the person asks for all of them. */
const NAMES_IN_VIEW = 5
/** How a table's own bulk delete and bulk edit processes are named (`<table>.bulkDelete`). */
const BULK_DELETE_SUFFIX = '.bulkDelete'
const BULK_EDIT_SUFFIX = '.bulkEdit'
/**
* How many of a set's names are in view, in words. When the list does not hold as many names as
* the count says, the words never read as if it did.
*
* @param shown - Names drawn now.
* @param listed - Names the list holds.
* @param total - Records the card acts on.
* @returns The words that follow the count.
*/
function showingText(shown: number, listed: number, total: number): string {
if (listed === 0) return 'no names listed'
if (listed === total) return shown === total && total > 1 ? `showing all ${total}` : `showing ${shown}`
return listed < total ? `showing ${shown} of ${total} names` : `showing ${shown} names`
}
/**
* One record of a set by its name: a link into the application when its href passes the
* internal-link check, plain text otherwise.
*
* @param props - Component properties.
* @param props.record - The record.
* @returns The link or the name.
*/
function RecordName({ record }: { record: AssistantPendingActionRecord }) {
const name = record.label || String(record.id)
const href = internalAppHref(record.href)
if (!href) return <span className="break-words text-foreground" data-qqq-id="assistant-pending-action-record">{name}</span>
// not prefetched: scrolling a list of hundreds of names must not request hundreds of pages
return (
<Link href={href} prefetch={false} className="rounded break-words font-medium text-primary hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-ring" data-qqq-id="assistant-pending-action-record">
{name}
</Link>
)
}
/**
* The records a card for a set acts on: how many, how many of them are named in view, the first
* few by name, and on request every one of them in a scroll area of bounded height. The rest of
* the list is not drawn until it is asked for.
*
* @param props - Component properties.
* @param props.records - Every record the server listed.
* @param props.total - How many records the card acts on (the server's count).
* @param props.noun - What the records are called, e.g. "Printer records".
* @returns The block.
*/
function RecordSet({ records, total, noun }: { records: AssistantPendingActionRecord[]; total: number; noun: string }) {
const [expanded, setExpanded] = useState(false)
const listId = useId()
const listed = records.length
const visible = expanded ? records : records.slice(0, NAMES_IN_VIEW)
return (
<div className="border-t border-border px-3 py-2 text-xs" data-qqq-id="assistant-pending-action-records">
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
<p className="font-medium text-foreground" data-qqq-id="assistant-pending-action-record-count">
{total} {noun} · {showingText(visible.length, listed, total)}
</p>
{listed > NAMES_IN_VIEW && (
<button
type="button"
aria-expanded={expanded}
aria-controls={listId}
onClick={() => setExpanded((open) => !open)}
className="rounded text-xs font-medium text-primary hover:underline pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
data-qqq-id="assistant-pending-action-records-toggle"
>
{expanded ? 'Show fewer' : `See all ${listed}`}
</button>
)}
</div>
{listed > 0 && listed !== total && (
<p className="mt-0.5 text-amber-800 dark:text-amber-300" data-qqq-id="assistant-pending-action-record-mismatch">
The list holds {listed} {listed === 1 ? 'name' : 'names'}, not {total}.
</p>
)}
{listed > 0 && (
<div
id={listId}
{...(expanded ? { role: 'group', 'aria-label': `All ${listed} names`, tabIndex: 0 } : {})}
className={expanded ? 'mt-1.5 max-h-48 overflow-y-auto rounded-md border border-border px-2 py-1 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring' : 'mt-1.5'}
>
<ul className="space-y-0.5">
{visible.map((record, index) => (
<li key={`${index}:${record.id}`} className="min-w-0 pointer-coarse:flex pointer-coarse:min-h-11 pointer-coarse:items-center">
<RecordName record={record} />
</li>
))}
</ul>
</div>
)}
</div>
)
}
/**
* The confirmation card of one proposed write.
*
@@ -72,8 +178,18 @@ export default function AssistantPendingActionCard({ render }: { render: Assista
const status = action?.status ?? 'PENDING'
const pending = status === 'PENDING'
const Icon = render.toolName === 'delete_record' ? Trash2 : render.toolName === 'create_record' ? Plus : PencilLine
const verb = render.toolName === 'delete_record' ? 'Delete' : render.toolName === 'create_record' ? 'Create' : 'Save'
// a card for a set: the server sent how many records it acts on, or the records themselves
const records = render.records ?? []
const total = render.recordCount ?? records.length
const isSet = total > 0 || records.length > 0
const noun = `${render.tableLabel ? `${render.tableLabel} ` : ''}${total === 1 ? 'record' : 'records'}`
// a run over a set arrives as an update; a table's own bulk delete is still a delete
const deletes = render.toolName === 'delete_record' || (isSet && (render.processName ?? '').endsWith(BULK_DELETE_SUFFIX))
const Icon = deletes ? Trash2 : render.toolName === 'create_record' ? Plus : PencilLine
const verb = deletes ? 'Delete' : render.toolName === 'create_record' ? 'Create' : 'Save'
const runsOther = isSet && render.actionKind === 'process_run' && !deletes && !(render.processName ?? '').endsWith(BULK_EDIT_SUFFIX)
// the number being confirmed is on the control itself
const confirmText = !isSet ? verb : runsOther ? `Run on ${total}` : `${verb} ${total}`
const resultHref = internalAppHref(action?.href ?? render.href)
const tone = status === 'EXECUTED' ? 'text-emerald-700 dark:text-emerald-400' : status === 'FAILED' ? 'text-destructive' : 'text-muted-foreground'
@@ -120,6 +236,7 @@ export default function AssistantPendingActionCard({ render }: { render: Assista
))}
</dl>
)}
{isSet && <RecordSet records={records} total={total} noun={noun} />}
{(error || action?.message) && status !== 'EXECUTED' && (
<p className="px-3 pb-2 text-xs text-destructive" role="alert">{error ?? action?.message}</p>
)}
@@ -130,11 +247,12 @@ export default function AssistantPendingActionCard({ render }: { render: Assista
type="button"
disabled={busy}
onClick={() => decide(true)}
className={`inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-medium pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 ${render.toolName === 'delete_record' ? 'bg-destructive text-white hover:bg-destructive/90' : 'bg-primary text-primary-foreground hover:bg-primary/90'}`}
className={`inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-medium pointer-coarse:min-h-11 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 ${deletes ? 'bg-destructive text-white hover:bg-destructive/90' : 'bg-primary text-primary-foreground hover:bg-primary/90'}`}
data-qqq-id="assistant-pending-action-confirm"
{...(isSet && !busy ? { 'aria-label': `${confirmText} ${noun}` } : {})}
>
<Check className="h-3.5 w-3.5" aria-hidden="true" />
{busy ? 'Working…' : verb}
{busy ? 'Working…' : confirmText}
</button>
<button
type="button"
@@ -28,7 +28,7 @@ import { useCollaborationPresence } from '@/lib/hooks/use-collaboration-presence
import { getErrorStatusCode } from '@/lib/utils/error-utils'
import { recordVersion } from '@/lib/utils/record-version'
import { CollaborationDialog, collaborationButton } from './CollaborationDialog'
import { PresenceAvatars } from './PresenceAvatars'
import { PresenceAvatars, PresenceReconnecting } from './PresenceAvatars'
export interface CollaborationEditProps {
table: QTableMetaData
@@ -167,7 +167,7 @@ export function CollaborationEdit({
return (
<div className="space-y-3">
<PresenceAvatars viewers={presence.viewers} />
{presence.unavailable && <span role="status">Presence temporarily unavailable</span>}
{presence.hadViewers && <PresenceReconnecting />}
{conflict && (
<div
role="alert"
@@ -20,6 +20,22 @@ import { Pencil } from 'lucide-react'
import * as Tooltip from '@radix-ui/react-tooltip'
import type { PresenceViewer } from '@/types/collaboration'
import { UserAvatar } from '@/components/ui/UserAvatar'
/**
* The quiet state of a presence indicator while the server cannot answer: one muted line.
*
* Accessibility: `role="status"` is a polite live region, so a screen reader says it once when it
* appears and never interrupts; it is plain muted text, not an alert, and takes no focus.
*
* @returns The line.
*/
export function PresenceReconnecting() {
return (
<span role="status" className="text-xs text-muted-foreground" data-qqq-id="presence-reconnecting">
Presence is reconnecting…
</span>
)
}
/** Other viewers' avatars (photo or initials), wrapping at narrow widths.
* @param props - Merged people.
* @returns Avatars.
@@ -0,0 +1,90 @@
/*
* 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.
*/
// What a presence indicator shows while presence is reconnecting: a quiet status where the
// indicator always shows something, and nothing where it shows nothing when nobody else is there.
import { render, screen } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { axe } from 'jest-axe'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { QRecord, QTableMetaData } from '@/types'
import type { PresenceViewer } from '@/types/collaboration'
import { useCollaborationPresence } from '@/lib/hooks/use-collaboration-presence'
import { qInstance } from '@/mocks/fixtures/q-instance'
import { PresenceReconnecting } from './PresenceAvatars'
import { RecordCollaborationHeader, TablePresence } from './RecordCollaborationHeader'
vi.mock('@/lib/hooks/use-collaboration-presence', () => ({ useCollaborationPresence: vi.fn() }))
vi.mock('@/lib/hooks/use-realtime-channel', () => ({ useRealtimeChannel: vi.fn() }))
vi.mock('@/lib/api/collaboration', () => ({ getRecordFeatures: vi.fn(async () => ({})), putAssignment: vi.fn() }))
const sam: PresenceViewer = { userId: 'sam', displayName: 'Sam', mode: 'VIEWING' }
const table: QTableMetaData = { ...structuredClone(qInstance.tables.person), recordFeatures: { features: ['PRESENCE'] } } as QTableMetaData
const record = { tableName: 'person', recordLabel: 'Alice', values: { id: 1 } } as QRecord
type Presence = ReturnType<typeof useCollaborationPresence>
const presence = (state: { reconnecting: boolean; hadViewers?: boolean; viewers?: PresenceViewer[] }) =>
vi.mocked(useCollaborationPresence).mockReturnValue({ hadViewers: false, viewers: [], ...state } as unknown as Presence)
function mount(node: React.ReactNode) {
return render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>{node}</QueryClientProvider>)
}
describe('presence while reconnecting', () => {
beforeEach(() => vi.mocked(useCollaborationPresence).mockReset())
it('is one muted, polite status line: no alert, no error color, nothing to focus', async () => {
const { container } = render(<PresenceReconnecting />)
const line = screen.getByRole('status')
expect(line).toHaveTextContent('Presence is reconnecting…')
expect(line).toHaveAttribute('data-qqq-id', 'presence-reconnecting')
expect(line).toHaveClass('text-muted-foreground')
expect(line.className).not.toMatch(/destructive|red/)
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(container.querySelector('button, a, [tabindex]')).toBeNull()
expect(await axe(container)).toHaveNoViolations()
})
it('a table shows it in place of the viewer count, and the count again once presence is back', () => {
presence({ reconnecting: true })
const { rerender } = mount(<TablePresence table={table} available />)
expect(screen.getByRole('status')).toHaveTextContent('Presence is reconnecting…')
expect(screen.queryByText(/viewing/)).not.toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
presence({ reconnecting: false, viewers: [sam] })
rerender(<QueryClientProvider client={new QueryClient()}><TablePresence table={table} available /></QueryClientProvider>)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
expect(screen.getByText('1 person viewing')).toBeInTheDocument()
})
it('a record shows nothing when nobody else was there, as when nobody else is there', () => {
presence({ reconnecting: true, hadViewers: false })
const { container } = mount(<RecordCollaborationHeader table={table} record={record} available />)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
expect(screen.queryByText(/presence/i)).not.toBeInTheDocument()
expect(container.querySelector('[data-qqq-id="presence-avatars"]')).toBeNull()
})
it('a record says so when the people it showed had to be taken away', () => {
presence({ reconnecting: true, hadViewers: true })
mount(<RecordCollaborationHeader table={table} record={record} available />)
expect(screen.getByRole('status')).toHaveTextContent('Presence is reconnecting…')
expect(screen.queryByRole('button', { name: /Sam/ })).not.toBeInTheDocument()
})
})
@@ -27,7 +27,7 @@ import { queryKeys } from '@/lib/query-client'
import { updateRecord } from '@/lib/api/tables'
import { recordVersion } from '@/lib/utils/record-version'
import { pluralize } from '@/lib/utils/string-utils'
import { PresenceAvatars } from './PresenceAvatars'
import { PresenceAvatars, PresenceReconnecting } from './PresenceAvatars'
import { CollaborationDialog, collaborationButton } from './CollaborationDialog'
import { PeoplePicker } from './PeoplePicker'
const Share = dynamic(() => import('./ShareDialog').then((m) => m.ShareDialog), { ssr: false })
@@ -107,7 +107,9 @@ export function RecordCollaborationHeader({
data-qqq-id="record-collaboration-header"
>
{presence.viewers.length > 0 && <PresenceAvatars viewers={presence.viewers} />}
{presence.unavailable && <span role="status">Presence temporarily unavailable</span>}
{/* Nobody else here looks like nothing, so a lost connection does too; it is only said when
the people who were shown had to be taken away. */}
{presence.hadViewers && <PresenceReconnecting />}
{(owner != null || assignee != null) && (
<dl className="flex flex-wrap items-center gap-x-3 gap-y-1">
{owner != null && (
@@ -195,11 +197,12 @@ export function TablePresence({ table, available }: { table: QTableMetaData; ava
return (
<div className="flex flex-wrap items-center gap-2 text-sm" data-qqq-id="table-presence">
<PresenceAvatars viewers={presence.viewers} />
<span role={presence.unavailable ? 'status' : undefined}>
{presence.unavailable
? 'Presence temporarily unavailable'
: `${pluralize(presence.viewers.length, 'person', 'people')} viewing`}
</span>
{/* The count is always here, so its place says when the count is not known for now. */}
{presence.reconnecting ? (
<PresenceReconnecting />
) : (
<span>{`${pluralize(presence.viewers.length, 'person', 'people')} viewing`}</span>
)}
</div>
)
}
+1 -1
View File
@@ -34,7 +34,7 @@ const JobsPopover = lazy(() => import('./JobsPopover'))
*/
export function JobsHeaderButton() {
const installed = useJobsInstalled()
const active = useMyJobs(installed, { scope: 'mine', state: 'active', limit: 20 })
const active = useMyJobs(installed, { scope: 'mine', state: 'active', limit: 20 }, true)
const [open, setOpen] = useState(false)
const recent = useMyJobs(installed && open, { scope: 'mine', state: 'recent', limit: 5 })
const trigger = useRef<HTMLButtonElement>(null)
+106 -1
View File
@@ -18,8 +18,9 @@
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render as renderWithoutProviders, screen } from '@testing-library/react'
import { render as renderWithoutProviders, screen, waitFor, within } from '@testing-library/react'
import { userEvent } from '@testing-library/user-event'
import { axe } from 'jest-axe'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { http, HttpResponse } from 'msw'
@@ -32,6 +33,7 @@ vi.mock('next/navigation', () => ({
import { server } from '@/mocks/node'
import { uiApiVersionHandler } from '@/mocks/ui-api-version'
import { preferencesFixture } from '@/mocks/fixtures/preferences'
import { qInstance } from '@/mocks/fixtures/q-instance'
import { ThemeProvider } from '@/lib/theme/theme-provider'
import { setSingleKeyShortcutsEnabled } from '@/lib/keyboard/single-key-shortcuts'
import { AccountMenu } from './AccountMenu'
@@ -106,6 +108,109 @@ describe('AccountMenu', () => {
})
})
describe('AccountMenu application-declared links', () => {
/**
* Serves instance metadata with one more widget.
*
* @param widgets - Widgets to add, by name.
*/
function declare(widgets: Record<string, unknown>) {
const named = Object.fromEntries(Object.entries(widgets).map(([name, widget]) => [name, { name, hasPermission: true, ...(widget as object) }]))
server.use(http.get('/qqq/v1/metaData', () => HttpResponse.json({ ...qInstance, widgets: { ...qInstance.widgets, ...named } })))
}
const localTools = {
label: 'Local tools',
type: 'ACCOUNT_MENU_LINKS',
defaultValues: {
links: [
{ label: 'Mail inbox', url: 'http://localhost:8025/', icon: 'mail' },
{ label: 'Identity provider', url: 'https://id.example.com/admin/' },
{ label: 'Plain http elsewhere', url: 'http://tools.example.com/' },
{ label: 'Script', url: 'javascript:alert(1)' },
{ label: 'Credentials', url: 'https://admin:secret@id.example.com/' },
{ label: 'Message broker', url: 'http://127.0.0.1:15672/' },
],
},
}
it('shows a declared group under the account menu: safe links only, each a menu item that opens in a new tab', async () => {
declare({ localTools })
const user = userEvent.setup()
render(<AccountMenu userName="Alice" logout={vi.fn()} />)
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
const group = await screen.findByRole('group', { name: 'Local tools' })
expect(group).toHaveAttribute('data-qqq-id', 'account-menu-links-localTools')
const items = within(group).getAllByRole('menuitem')
expect(items.map((item) => [item.textContent, item.getAttribute('href')])).toEqual([
['Mail inbox(opens in a new tab)', 'http://localhost:8025/'],
['Identity provider(opens in a new tab)', 'https://id.example.com/admin/'],
['Message broker(opens in a new tab)', 'http://127.0.0.1:15672/'],
])
for (const item of items) {
expect(item).toHaveAttribute('target', '_blank')
expect(item).toHaveAttribute('rel', 'noopener noreferrer')
expect(item.tagName).toBe('A')
}
expect(items[0]).toHaveAccessibleName('Mail inbox (opens in a new tab)')
expect(items[0]).toHaveAttribute('data-qqq-id', 'menu-item-link-localTools-0')
// the declared icon, from the set the menu's other metadata icons use
expect(items[0].querySelector('[data-qqq-icon="mail"]')).not.toBeNull()
// nothing of a refused link reaches the page
const menu = screen.getByRole('menu', { name: 'Account: Alice' })
expect(menu).not.toHaveTextContent(/Plain http elsewhere|Script|Credentials/)
expect(menu.innerHTML).not.toMatch(/javascript:|secret|tools\.example\.com/)
expect(await axe(menu)).toHaveNoViolations()
})
it('reaches the links with the arrow keys, between Preferences and Sign out, and closes when one is chosen', async () => {
declare({ localTools })
const user = userEvent.setup()
render(<AccountMenu userName="Alice" logout={vi.fn()} />)
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
const mail = await screen.findByRole('menuitem', { name: /Mail inbox/ })
await user.keyboard('{End}')
expect(screen.getByRole('menuitem', { name: 'Sign out' })).toHaveFocus()
await user.keyboard('{ArrowUp}')
expect(screen.getByRole('menuitem', { name: /Message broker/ })).toHaveFocus()
await user.keyboard('{ArrowUp}{ArrowUp}')
expect(mail).toHaveFocus()
await user.keyboard('{ArrowUp}')
expect(screen.getByRole('menuitemcheckbox', { name: 'Dark mode' })).toHaveFocus()
mail.addEventListener('click', (event) => event.preventDefault())
await user.click(mail)
expect(screen.queryByRole('menu')).toBeNull()
})
it('renders nothing for links when the application declares none', async () => {
const user = userEvent.setup()
render(<AccountMenu userName="Alice" logout={vi.fn()} />)
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
await screen.findByRole('menuitem', { name: 'Preferences' })
await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Sign out' })).toBeInTheDocument())
expect(screen.queryByRole('group')).toBeNull()
expect(document.querySelector('[data-qqq-id^="account-menu-links"], [data-qqq-id^="menu-item-link"]')).toBeNull()
expect(document.querySelector('a[target="_blank"]')).toBeNull()
})
it('renders nothing for a group whose links are all refused, or that the user may not see', async () => {
declare({
allBad: { label: 'Refused', type: 'ACCOUNT_MENU_LINKS', defaultValues: { links: [{ label: 'Script', url: 'javascript:alert(1)' }, { label: 'Http', url: 'http://example.com/' }] } },
denied: { ...localTools, label: 'Hidden', hasPermission: false },
})
const user = userEvent.setup()
render(<AccountMenu userName="Alice" />)
await user.click(screen.getByRole('button', { name: 'Account: Alice' }))
await screen.findByRole('menuitem', { name: 'Preferences' })
// metadata has loaded once the instance's own widgets are known; give the menu a turn to use it
await new Promise((resolve) => setTimeout(resolve, 50))
expect(screen.queryByRole('group')).toBeNull()
expect(screen.getByRole('menu')).not.toHaveTextContent(/Refused|Hidden|Mail inbox/)
})
})
describe('HelpMenu', () => {
it('opens help, not shortcuts: Keyboard shortcuts is one of its items (WCAG 3.2.6)', async () => {
const user = userEvent.setup()
+31 -2
View File
@@ -17,7 +17,7 @@
/**
* @file AccountMenu — the signed-in user's avatar at the far right of the header (the usual
* "my account" place): name and email, Preferences and the sections that opt into the menu,
* dark mode, QA mode status, and sign out.
* dark mode, QA mode status, the links the application declares for its environment, and sign out.
*/
'use client'
@@ -25,7 +25,7 @@
import React from 'react'
import Link from 'next/link'
import { useQuery } from '@tanstack/react-query'
import { Bug, ChevronDown, LogOut, Moon, Settings, Wrench } from 'lucide-react'
import { Bug, ChevronDown, ExternalLink, LogOut, Moon, Settings, Wrench } from 'lucide-react'
import { useMetaData } from '@/lib/hooks/use-metadata'
import { toolsTarget } from '@/components/tools/tools-catalog'
@@ -39,6 +39,7 @@ import { cn } from '@/lib/utils/cn'
import { useMyProfile } from '@/lib/hooks/use-my-profile'
import { UserAvatar } from '@/components/ui/UserAvatar'
import { MetadataIcon } from './MetadataIcon'
import { accountMenuLinkGroups } from './account-menu-links'
import { HEADER_MENU_ITEM_CLASS, HeaderMenu, HeaderMenuSeparator } from './HeaderMenu'
/** Below this width the header shows only Search, Jobs, Notifications and the avatar. */
@@ -80,6 +81,8 @@ export function AccountMenu({ userName, userEmail, logout, compactItems }: Accou
label={qaMode ? `Account: ${displayName} (QA mode on)` : `Account: ${displayName}`}
qqqId="button-account"
triggerClassName="gap-1 px-1"
// declared links can make the menu taller than a phone: it scrolls within the space it has
menuClassName="max-h-[var(--radix-popover-content-available-height)] overflow-y-auto"
trigger={(
<>
<span className="relative">
@@ -112,6 +115,7 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
const { theme, isDarkMode, setDarkMode } = useTheme()
const metadata = useMetaData()
const tools = toolsTarget(metadata.data)
const linkGroups = accountMenuLinkGroups(metadata.data)
const capability = useQaCaptureCapability()
const preferences = useQuery({ queryKey: queryKeys.preferencesIndex(), queryFn: getPreferences, retry: false })
const qaSection = capability?.enabled && capability.reason === 'QA_MODE' ? capability.qaMode.preferenceSection : undefined
@@ -177,6 +181,31 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
</p>
)
)}
{/* Links the application declares for this environment (`account-menu-links`): nothing is
rendered when it declares none. Accessibility: each group is a `group` named by its
heading; each link is a `menuitem`, so the arrow keys, Home and End reach it like any
other item; it opens in a new tab, which its name says ("opens in a new tab") and a
trailing icon shows; `rel="noopener noreferrer"` keeps the opened page from reaching
back into this one or learning the address it came from. */}
{linkGroups.map((group) => (
<div key={group.name} role="group" aria-labelledby={`account-menu-links-${group.name}`} data-qqq-id={`account-menu-links-${group.name}`}>
<HeaderMenuSeparator />
<p id={`account-menu-links-${group.name}`} className="truncate px-4 pb-1 pt-2 text-xs font-semibold text-muted-foreground" data-qqq-id="account-menu-links-label">
{group.label}
</p>
{group.links.map((link, index) => (
<a key={`${index}:${link.href}`} href={link.href} target="_blank" rel="noopener noreferrer" role="menuitem" onClick={() => close()}
className={HEADER_MENU_ITEM_CLASS} data-qqq-id={`menu-item-link-${group.name}-${index}`}>
{link.icon
? <MetadataIcon iconName={link.icon} kind="section" className="h-4 w-4 text-muted-foreground" />
: <ExternalLink className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />}
<span className="min-w-0 flex-1 truncate" title={link.label}>{link.label}</span>
<span className="sr-only">(opens in a new tab)</span>
{link.icon && <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />}
</a>
))}
</div>
))}
{logout && (
<>
<HeaderMenuSeparator />
@@ -21,13 +21,16 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen } from '@testing-library/react'
let currentPathname = '/app/person'
let currentSearch = ''
vi.mock('next/navigation', () => ({
usePathname: () => currentPathname,
useSearchParams: () => new URLSearchParams(currentSearch),
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}))
import Breadcrumbs, { buildBreadcrumbs, buildDocumentTitle, humanizeSegment } from './Breadcrumbs'
import type { ParentAppInfo } from '@/lib/hooks/use-routes'
import { TABLE_SUB_VIEWS } from '@/lib/utils/table-sub-views'
beforeEach(() => vi.stubGlobal('ResizeObserver', class {
observe() {}
@@ -102,6 +105,30 @@ describe('buildBreadcrumbs', () => {
})
})
describe('buildBreadcrumbs with a sub-view in the query string', () => {
const list = 'page=3&filter=abc&q=smith'
it.each(Object.values(TABLE_SUB_VIEWS))('$name is the last crumb and the table links back to the list as it was', (view) => {
const search = `${list}&view=${view.name}&${view.params.map((name) => `${name}=layout`).join('&')}`
const crumbs = buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap, search)
expect(crumbs.map((crumb) => crumb.label)).toEqual(['People App', 'Greetings App', 'Person', view.label])
expect(crumbs.at(-2)).toEqual({ path: '/app/person', label: 'Person', href: `/app/person?${list}` })
})
it('links back to a saved view with its own path, and to a bare list without a query string', () => {
const saved = buildBreadcrumbs('/app/person/savedView/3', pathToLabelMap, ancestorAppMap, new URLSearchParams('view=pivot&pivot=x'))
expect(saved.slice(-2).map((crumb) => crumb.label)).toEqual(['Saved View', 'Pivot'])
expect(saved.at(-2)?.href).toBe('/app/person/savedView/3')
})
it('leaves the trail alone for the list, an unknown view, and a record page that has its own view parameter', () => {
const plain = buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap)
expect(buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap, 'page=3&filter=abc')).toEqual(plain)
expect(buildBreadcrumbs('/app/person', pathToLabelMap, ancestorAppMap, 'view=nope')).toEqual(plain)
expect(buildBreadcrumbs('/app/person/7', pathToLabelMap, ancestorAppMap, 'view=pivot').map((crumb) => crumb.label)).toEqual(['People App', 'Greetings App', 'Person', '7'])
})
})
describe('buildDocumentTitle', () => {
const crumbs = buildBreadcrumbs('/app/person/1', pathToLabelMap, ancestorAppMap)
@@ -121,6 +148,14 @@ describe('buildDocumentTitle', () => {
describe('Breadcrumbs', () => {
beforeEach(() => {
currentPathname = '/app/person'
currentSearch = ''
})
it.each(Object.values(TABLE_SUB_VIEWS))('inside $name the view is the current page and the table is a link back to the list', (view) => {
currentSearch = `page=2&filter=abc&view=${view.name}`
render(<Breadcrumbs pathToLabelMap={pathToLabelMap} ancestorAppMap={ancestorAppMap} />)
expect(screen.getByText(view.label)).toHaveAttribute('aria-current', 'page')
expect(screen.getByRole('link', { name: 'Person' })).toHaveAttribute('href', '/app/person?page=2&filter=abc')
})
it('renders the app hierarchy as links and the current page as text', () => {
+54 -7
View File
@@ -20,12 +20,13 @@
'use client'
import React from 'react'
import React, { Suspense } from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { usePathname, useSearchParams } from 'next/navigation'
import { Home } from 'lucide-react'
import type { ParentAppInfo } from '@/lib/hooks/use-routes'
import { listSearch, tableSubView } from '@/lib/utils/table-sub-views'
/**
* Props for the Breadcrumbs component.
@@ -47,6 +48,8 @@ export interface Breadcrumb {
path: string
/** Human-readable label. */
label: string
/** Where the crumb links when that is more than its path: the list behind a sub-view keeps its query string. */
href?: string
}
/** Labels for the fixed sub-page segments under a table or record. */
@@ -102,15 +105,21 @@ export function humanizeSegment(segment: string): string {
* and `/app/{table}/{id}/{process}` URLs) takes that object's label; other
* segments without a label are humanized, except a record id, which stays as is.
*
* A sub-view of a record list lives in the query string, not the path (`?view=correlation`, see
* `table-sub-views`). With `search`, an open sub-view becomes the last crumb, and the list's own
* crumb before it links back to the list with the rest of the query string (filter, sort, page).
*
* @param pathname - Current browser path.
* @param pathToLabelMap - Route path → label.
* @param ancestorAppMap - Node path → enclosing apps.
* @param search - Current query string; omit to build the trail from the path alone.
* @returns Breadcrumbs from the outermost app to the current page.
*/
export function buildBreadcrumbs(
pathname: string,
pathToLabelMap: Record<string, string>,
ancestorAppMap: Record<string, ParentAppInfo[]> = {}
ancestorAppMap: Record<string, ParentAppInfo[]> = {},
search?: URLSearchParams | string | null
): Breadcrumb[] {
const segments = pathname.split('/').filter(Boolean)
if (segments[0] !== 'app' || segments.length < 2) return []
@@ -133,6 +142,14 @@ export function buildBreadcrumbs(
?? (index === 0 ? decoded : humanizeSegment(decoded))
crumbs.push({ path, label })
}
// Only a record list hosts sub-views: the table itself, or one of its saved views.
const subView = rest.length === 0 || rest[0] === 'savedView' ? tableSubView(search) : undefined
if (subView) {
const list = crumbs[crumbs.length - 1]
crumbs[crumbs.length - 1] = { ...list, href: `${list.path}${listSearch(search)}` }
crumbs.push({ path: `${list.path}?view=${subView.name}`, label: subView.label })
}
return crumbs
}
@@ -155,14 +172,43 @@ export function buildDocumentTitle(crumbs: Breadcrumb[], pageTitle: string | und
/**
* Renders a horizontal breadcrumb trail for the current page.
*
* The trail follows the query string as well as the path, so a sub-view of a record list shows as
* the current page with the list as a link back. The query string is read inside a Suspense
* boundary (a static export cannot prerender it); until it is known the trail is built from the
* path alone.
*
* @param props - Component properties.
* @returns A `<nav aria-label="Breadcrumb">` element with slash-separated
* `<Link>` crumbs (ancestor pages) followed by a `<span aria-current="page">`
* for the current page, or `null` on the dashboard root and before labels load.
*/
export default function Breadcrumbs({ pathToLabelMap, ancestorAppMap = {}, homePath = '/app' }: BreadcrumbsProps) {
export default function Breadcrumbs(props: BreadcrumbsProps) {
return (
<Suspense fallback={<BreadcrumbTrail {...props} search={null} />}>
<BreadcrumbsForLocation {...props} />
</Suspense>
)
}
/**
* Reads the query string for {@link Breadcrumbs}.
*
* @param props - Component properties.
* @returns The trail for the current path and query string.
*/
function BreadcrumbsForLocation(props: BreadcrumbsProps) {
return <BreadcrumbTrail {...props} search={useSearchParams()} />
}
/**
* The trail itself.
*
* @param props - Component properties, and the query string when it is known.
* @returns The `<nav>`, or `null`.
*/
function BreadcrumbTrail({ pathToLabelMap, ancestorAppMap = {}, homePath = '/app', search }: BreadcrumbsProps & { search: URLSearchParams | null }) {
const pathname = usePathname()
const breadcrumbs = buildBreadcrumbs(pathname, pathToLabelMap, ancestorAppMap)
const breadcrumbs = buildBreadcrumbs(pathname, pathToLabelMap, ancestorAppMap, search)
const hasLabels = Object.keys(pathToLabelMap).length > 0
// Until metadata supplies labels, raw URL segments would flash in place of labels
@@ -186,7 +232,8 @@ export default function Breadcrumbs({ pathToLabelMap, ancestorAppMap = {}, homeP
<Home className="h-4 w-4" aria-hidden="true" />
</Link>
{/* Every crumb stays a link, in order. A long label truncates with an ellipsis (full text in the title) and the
trail wraps onto another line instead of scrolling or hiding crumbs. */}
trail wraps onto another line instead of scrolling or hiding crumbs. Accessibility: the last crumb is text
with aria-current="page"; every crumb before it, including the list behind an open sub-view, is a link. */}
{breadcrumbs.map((crumb, index) => (
<React.Fragment key={crumb.path + index}>
<span className="shrink-0 text-muted-foreground/60" aria-hidden="true">/</span>
@@ -202,7 +249,7 @@ export default function Breadcrumbs({ pathToLabelMap, ancestorAppMap = {}, homeP
) : (
<Link
title={crumb.label}
href={crumb.path}
href={crumb.href ?? crumb.path}
className="min-w-0 max-w-[10rem] truncate text-muted-foreground hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-w-11 pointer-coarse:py-3 pointer-coarse:text-center"
data-qqq-id={`breadcrumb-link-${index}`}
>
@@ -0,0 +1,147 @@
/*
* 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.
*/
import { describe, expect, it } from 'vitest'
import type { QInstance, QWidgetMetaData } from '@/types'
import { ACCOUNT_MENU_LINKS_MAX, ACCOUNT_MENU_LINKS_WIDGET_TYPE, accountMenuLinkGroups, accountMenuLinkHref } from './account-menu-links'
/**
* Instance metadata with the given widgets.
*
* @param widgets - Widgets by name.
* @returns The metadata slice the reader takes.
*/
function instance(widgets: Record<string, Partial<QWidgetMetaData>>): Pick<QInstance, 'widgets'> {
return { widgets: Object.fromEntries(Object.entries(widgets).map(([name, widget]) => [name, { name, label: name, hasPermission: true, ...widget }])) } as Pick<QInstance, 'widgets'>
}
const links = (...declared: unknown[]) => ({ type: ACCOUNT_MENU_LINKS_WIDGET_TYPE, label: 'Local tools', defaultValues: { links: declared } })
describe('accountMenuLinkHref', () => {
it.each([
['https://mail.example.com/inbox?folder=1#top', 'https://mail.example.com/inbox?folder=1#top'],
['https://example.com', 'https://example.com/'],
[' https://example.com/a ', 'https://example.com/a'],
['http://localhost:8025/', 'http://localhost:8025/'],
['http://LOCALHOST:8025', 'http://localhost:8025/'],
['http://127.0.0.1:15672/#/queues', 'http://127.0.0.1:15672/#/queues'],
['http://[::1]:9000/admin', 'http://[::1]:9000/admin'],
['https://localhost:8443/', 'https://localhost:8443/'],
])('allows %s', (declared, href) => {
expect(accountMenuLinkHref(declared)).toBe(href)
})
it.each([
['plain http to another host', 'http://mail.example.com/'],
['http to a name that only starts like this machine', 'http://localhost.example.com/'],
['http to an address that only starts like this machine', 'http://127.0.0.1.example.com/'],
['http to another loopback spelling', 'http://127.0.0.2/'],
['http to a private address', 'http://192.168.1.10/'],
['a user name and password', 'https://admin:secret@id.example.com/'],
['a user name alone', 'https://admin@id.example.com/'],
['credentials on this machine', 'http://admin:secret@localhost:8025/'],
['a script', 'javascript:alert(1)'],
['a script with odd spelling', ' JaVaScRiPt:alert(1)'],
['a data URL', 'data:text/html,<script>alert(1)</script>'],
['a file', 'file:///etc/passwd'],
['another scheme', 'ftp://files.example.com/'],
['a relative path', '/app/person'],
['a protocol-relative URL', '//example.com/'],
['a bare host', 'example.com'],
['an empty string', ''],
['blank space', ' '],
['a number', 8025],
['nothing', undefined],
['an object', { href: 'https://example.com/' }],
])('refuses %s', (_what, declared) => {
expect(accountMenuLinkHref(declared)).toBeUndefined()
})
})
describe('accountMenuLinkGroups', () => {
it('reads a declared group: label, links in order, and well-formed icon names', () => {
const groups = accountMenuLinkGroups(instance({
localTools: links(
{ label: 'Mail inbox', url: 'http://localhost:8025/', icon: 'mail' },
{ label: ' Identity provider ', url: 'https://id.example.com/admin/' },
{ label: 'Message broker', url: 'http://127.0.0.1:15672/', icon: '<svg onload=alert(1)>' },
),
}))
expect(groups).toEqual([{
name: 'localTools',
label: 'Local tools',
links: [
{ label: 'Mail inbox', href: 'http://localhost:8025/', icon: 'mail' },
{ label: 'Identity provider', href: 'https://id.example.com/admin/' },
{ label: 'Message broker', href: 'http://127.0.0.1:15672/' },
],
}])
})
it('is empty when the application declares nothing, and before metadata loads', () => {
expect(accountMenuLinkGroups(undefined)).toEqual([])
expect(accountMenuLinkGroups({ widgets: {} })).toEqual([])
expect(accountMenuLinkGroups(instance({ chart: { type: 'chart', defaultValues: { links: [{ label: 'x', url: 'https://example.com/' }] } } }))).toEqual([])
})
it('drops every link that is not a label and an allowed URL, and keeps the rest', () => {
const [group] = accountMenuLinkGroups(instance({
tools: links(
{ label: 'Good', url: 'https://example.com/' },
{ label: 'Plain http', url: 'http://example.com/' },
{ label: 'Script', url: 'javascript:alert(1)' },
{ label: 'Credentials', url: 'https://user:pw@example.com/' },
{ label: '', url: 'https://example.com/' },
{ label: ' ', url: 'https://example.com/' },
{ url: 'https://example.com/' },
{ label: 'No address' },
{ label: { text: 'Object' }, url: 'https://example.com/' },
'https://example.com/',
null,
['Array', 'https://example.com/'],
{ label: 'Also good', url: 'http://[::1]:3000/' },
),
}))
expect(group.links.map((link) => link.label)).toEqual(['Good', 'Also good'])
})
it('shows no group that is left without links, is hidden by permission, or is malformed', () => {
expect(accountMenuLinkGroups(instance({
empty: links(),
allBad: links({ label: 'Script', url: 'javascript:alert(1)' }),
denied: { ...links({ label: 'Good', url: 'https://example.com/' }), hasPermission: false },
notAList: { type: ACCOUNT_MENU_LINKS_WIDGET_TYPE, defaultValues: { links: { label: 'Good', url: 'https://example.com/' } } },
aString: { type: ACCOUNT_MENU_LINKS_WIDGET_TYPE, defaultValues: { links: '[{"label":"Good","url":"https://example.com/"}]' } },
noValues: { type: ACCOUNT_MENU_LINKS_WIDGET_TYPE },
}))).toEqual([])
})
it('keeps several groups in metadata order, names a group without a label, and caps a long one', () => {
const many = Array.from({ length: ACCOUNT_MENU_LINKS_MAX + 5 }, (_, index) => ({ label: `Tool ${index + 1}`, url: `https://example.com/${index + 1}` }))
const groups = accountMenuLinkGroups(instance({
second: { ...links({ label: 'B', url: 'https://example.com/b' }), label: 'Second' },
first: { ...links(...many), label: ' ' },
}))
expect(groups.map((group) => [group.name, group.label, group.links.length])).toEqual([['second', 'Second', 1], ['first', 'Links', ACCOUNT_MENU_LINKS_MAX]])
expect(groups[1].links.at(-1)?.label).toBe(`Tool ${ACCOUNT_MENU_LINKS_MAX}`)
})
it('shortens an overlong label instead of trusting it', () => {
const [group] = accountMenuLinkGroups(instance({ tools: links({ label: 'x'.repeat(500), url: 'https://example.com/' }) }))
expect(group.links[0].label).toHaveLength(80)
})
})
+141
View File
@@ -0,0 +1,141 @@
/*
* 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 account-menu-links — links an application declares for the account menu: a labelled
* group of links to the tools that go with one environment (a mail capture inbox, an identity
* provider's admin page, a message broker's console).
*
* The contract is a widget in the instance metadata, the same carrier the Tools shortcut uses,
* because an application can declare a widget without any change to QQQ itself and the metadata
* response already publishes a widget's `type`, `label`, `hasPermission` and `defaultValues`:
*
* ```json
* "widgets": {
* "localTools": {
* "name": "localTools",
* "label": "Local tools",
* "type": "ACCOUNT_MENU_LINKS",
* "hasPermission": true,
* "defaultValues": {
* "links": [
* { "label": "Mail inbox", "url": "http://localhost:8025/", "icon": "mail" },
* { "label": "Identity provider", "url": "https://id.example.com/admin/" }
* ]
* }
* }
* }
* ```
*
* Everything that arrives is untrusted: a link that is not exactly a label and a safe URL is
* dropped, never repaired and never rendered.
*/
import type { QInstance } from '@/types'
/** Widget `type` that declares a group of account menu links. */
export const ACCOUNT_MENU_LINKS_WIDGET_TYPE = 'ACCOUNT_MENU_LINKS'
/** Most links one group shows; the menu is a menu, not a directory. */
export const ACCOUNT_MENU_LINKS_MAX = 12
/** Longest label kept, in characters. */
const LABEL_MAX = 80
/** A Material icon name, as the menu's other metadata icons use. */
const ICON_NAME = /^[a-z0-9_]{1,40}$/
/** Hosts that are this machine. */
const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '[::1]']
/** One link, ready to render. */
export interface AccountMenuLink {
/** Text of the menu item. */
label: string
/** The normalized, safe URL. */
href: string
/** Material icon name, when the application named a well-formed one. */
icon?: string
}
/** One labelled group of links. */
export interface AccountMenuLinkGroup {
/** The declaring widget's name (a stable key and CSS hook). */
name: string
/** The group's heading. */
label: string
/** Its links, in declared order; never empty. */
links: AccountMenuLink[]
}
/**
* The house rule for a link an application supplies: `https:` anywhere, or `http:` to this
* machine (`localhost`, `127.0.0.1`, `[::1]`), absolute, and without credentials. Everything else
* (`javascript:`, `data:`, plain `http:` to another host, a relative path, a URL with a user name
* or password) is refused.
*
* @param value - The declared URL.
* @returns The normalized URL, or undefined when it is not allowed.
*/
export function accountMenuLinkHref(value: unknown): string | undefined {
if (typeof value !== 'string' || !value.trim()) return undefined
try {
const url = new URL(value.trim())
const loopback = LOOPBACK_HOSTS.includes(url.hostname)
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return undefined
if (url.username || url.password) return undefined
return url.href
} catch {
return undefined
}
}
/**
* Reads one declared link.
*
* @param value - An entry of `defaultValues.links`.
* @returns The link, or undefined when it has no label or no allowed URL.
*/
function readLink(value: unknown): AccountMenuLink | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
const { label, url, icon } = value as Record<string, unknown>
const text = typeof label === 'string' ? label.trim().slice(0, LABEL_MAX) : ''
const href = accountMenuLinkHref(url)
if (!text || !href) return undefined
return { label: text, href, ...(typeof icon === 'string' && ICON_NAME.test(icon) ? { icon } : {}) }
}
/**
* The link groups an instance declares for the account menu: every widget of type
* {@link ACCOUNT_MENU_LINKS_WIDGET_TYPE} the user may see, in metadata order, with the links
* that pass {@link accountMenuLinkHref}. A group left without links is not a group.
*
* @param metadata - Permission-filtered instance metadata, when loaded.
* @returns The groups; empty when the application declares none.
*/
export function accountMenuLinkGroups(metadata: Pick<QInstance, 'widgets'> | undefined): AccountMenuLinkGroup[] {
const groups: AccountMenuLinkGroup[] = []
for (const [name, widget] of Object.entries(metadata?.widgets ?? {})) {
if (widget?.type !== ACCOUNT_MENU_LINKS_WIDGET_TYPE || widget.hasPermission === false) continue
const declared = widget.defaultValues?.links
if (!Array.isArray(declared)) continue
const links = declared.flatMap((entry) => readLink(entry) ?? []).slice(0, ACCOUNT_MENU_LINKS_MAX)
if (links.length === 0) continue
const label = typeof widget.label === 'string' && widget.label.trim() ? widget.label.trim().slice(0, LABEL_MAX) : 'Links'
groups.push({ name, label, links })
}
return groups
}
@@ -0,0 +1,167 @@
/*
* 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.
*/
// Every sub-view of the record list (the explore views and the saved analysis viewer) must leave
// a way back to the list it was opened from: its own back control, the table's breadcrumb and the
// browser's Back button. The tests walk the registry, so a view added to it without a way back,
// or one that loses the list's filter or page, fails here.
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { http, HttpResponse } from 'msw'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { qInstance } from '@/mocks/fixtures/q-instance'
import { server } from '@/mocks/node'
import { QContextProvider } from '@/lib/context/q-context'
import { EXPLORE_LABELS, EXPLORE_VIEWS } from '@/lib/utils/data-analysis-explore'
import { serializeFilter } from '@/lib/utils/filter-utils'
import { listSearch, TABLE_SUB_VIEWS, type TableSubView } from '@/lib/utils/table-sub-views'
import Breadcrumbs from '@/components/layout/Breadcrumbs'
import { relationshipCapabilities } from '../../../tests/fixtures/data-analysis-compare'
import { RecordQuery } from './RecordQuery'
vi.mock('next/navigation', async () => (await import('../../../tests/helpers/history-navigation')).historyNavigation)
vi.mock('@/lib/api/data-analysis', async (original) => ({
...(await original<typeof import('@/lib/api/data-analysis')>()),
getCapabilities: vi.fn(async () => relationshipCapabilities),
listSavedAnalyses: vi.fn(async () => ({ analyses: [] })),
runSavedAnalysis: vi.fn(() => new Promise(() => undefined)),
}))
const LIST = '[data-qqq-id="record-query-person"]'
const criteria = [{ fieldName: 'firstName', operator: 'EQUALS' as const, values: ['Alice'] }]
const orderBys = [{ fieldName: 'firstName', isAscending: true }]
const filter = serializeFilter({ criteria, booleanOperator: 'AND', orderBys })
/** The list as the person left it: page 2 of a filtered, sorted, searched query. */
const listAddress = `/app/person?${new URLSearchParams({ page: '2', pageSize: '25', filter, q: 'ali' })}`
/**
* The page: the header's breadcrumb and the record list, on one address.
*
* @returns Both.
*/
function Page() {
const tables = structuredClone(qInstance.tables)
return (
<>
<Breadcrumbs pathToLabelMap={{ '/app/person': tables.person.label }} />
<RecordQuery tableName="person" tableMetaData={tables.person} allTables={tables} />
</>
)
}
function renderAt(address: string) {
// a new entry, so no test starts with another test's Forward entries
window.history.pushState(null, '', address)
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(<QueryClientProvider client={client}><QContextProvider><Page /></QContextProvider></QueryClientProvider>)
}
/**
* What the address says about the list.
*
* @returns Its page, page size, search, and the filter with its sort.
*/
function listState() {
const params = new URLSearchParams(window.location.search)
const encoded = params.get('filter')
const decoded = encoded ? JSON.parse(atob(encoded)) as { criteria?: unknown; orderBys?: unknown } : {}
return { path: window.location.pathname, page: params.get('page'), pageSize: params.get('pageSize'), q: params.get('q'), criteria: decoded.criteria, orderBys: decoded.orderBys, view: params.get('view') }
}
const asLeft = { path: '/app/person', page: '2', pageSize: '25', q: 'ali', view: null, criteria, orderBys }
const viewAddress = (view: TableSubView) => `${listAddress}&view=${view.name}${view.name === 'saved' ? '&saved=7' : ''}`
const backControl = (view: TableSubView) => document.querySelector<HTMLElement>(`[data-qqq-id="${view.backId}"]`)
const listShown = () => waitFor(() => expect(document.querySelector(LIST)).toBeInTheDocument())
const viewShown = (view: TableSubView) => waitFor(() => expect(backControl(view)).toBeInTheDocument(), { timeout: 5000 })
describe('RecordQuery sub-views leave a way back', () => {
beforeEach(() => {
localStorage.clear()
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })
server.use(
http.post('/qqq/v1/table/person/:action', ({ params }) =>
HttpResponse.json(params.action === 'query' ? { records: [{ tableName: 'person', recordLabel: 'Alice', values: { id: 1, firstName: 'Alice' } }] } : { count: 30 })),
http.get('/qqq/v1/table/data_analysis_saved/:id', () => HttpResponse.json({ error: 'not found' }, { status: 404 })),
)
})
it.each(Object.values(TABLE_SUB_VIEWS))('a link to $name opens it; its back control and the breadcrumb return to the list as it was', async (view) => {
const user = userEvent.setup()
renderAt(viewAddress(view))
await viewShown(view)
expect(document.querySelector(LIST)).not.toBeInTheDocument()
// The breadcrumb names the view, and the table is a link to the list behind it
expect(screen.getByText(view.label, { selector: '[aria-current="page"]' })).toBeInTheDocument()
const crumb = screen.getByRole('link', { name: 'People' })
expect(crumb).toHaveAttribute('href', `/app/person${listSearch(window.location.search)}`)
expect(new URLSearchParams(crumb.getAttribute('href')!.split('?')[1]).get('page')).toBe('2')
// Its own control
expect(backControl(view)).toHaveAccessibleName('Back to records')
await user.click(backControl(view)!)
await listShown()
expect(backControl(view)).not.toBeInTheDocument()
expect(screen.getByText('People', { selector: '[aria-current="page"]' })).toBeInTheDocument()
await waitFor(() => expect(listState()).toEqual(asLeft))
// Following the breadcrumb link from the view gives the same list
act(() => window.history.pushState(null, '', viewAddress(view)))
await viewShown(view)
const href = screen.getByRole('link', { name: 'People' }).getAttribute('href')!
act(() => window.history.pushState(null, '', href))
await listShown()
await waitFor(() => expect(listState()).toEqual(asLeft))
})
it.each(EXPLORE_VIEWS.map((name) => TABLE_SUB_VIEWS[name]))('$name opened from the list: browser Back, then its back control, return to the list as it was', async (view) => {
const user = userEvent.setup()
renderAt(listAddress)
await listShown()
await waitFor(() => expect(listState()).toEqual(asLeft))
const entries = window.history.length
const open = async () => {
await user.click(await screen.findByRole('button', { name: 'Explore' }))
await user.click(await screen.findByRole('menuitem', { name: EXPLORE_LABELS[view.name as keyof typeof EXPLORE_LABELS] }))
await viewShown(view)
}
// Browser Back
await open()
expect(window.history.length).toBe(entries + 1)
expect(listState().view).toBe(view.name)
act(() => window.history.back())
await listShown()
await waitFor(() => expect(listState()).toEqual(asLeft))
// the list does not rewrite the address after the step back (that would drop the page)
await new Promise((resolve) => setTimeout(resolve, 50))
expect(listState()).toEqual(asLeft)
// The view's own control is one step back too: the view stays one Forward away
await open()
await user.click(backControl(view)!)
await listShown()
await waitFor(() => expect(listState()).toEqual(asLeft))
expect(window.history.length).toBe(entries + 1)
act(() => window.history.forward())
await viewShown(view)
expect(listState().view).toBe(view.name)
})
})
+49 -30
View File
@@ -26,7 +26,7 @@ import { canSortField } from '@/lib/utils/secured-data'
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
import Link from 'next/link'
import dynamic from 'next/dynamic'
import { useRouter, useSearchParams } from 'next/navigation'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { X, ArrowLeft, Loader2 } from 'lucide-react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
@@ -39,9 +39,9 @@ import { getCapabilities } from '@/lib/api/data-analysis'
import type { PageSize } from '@/lib/hooks/use-record-query'
import { QUERY_SCREEN_HELP_ROLES } from '@/lib/utils/help-utils'
import { encodeExplore, EXPLORE_VIEWS, type RelationshipView, type ExploreLayout } from '@/lib/utils/data-analysis-explore'
import { encodeExplore, type RelationshipView, type ExploreLayout } from '@/lib/utils/data-analysis-explore'
import { listSearch, tableSubView, TABLE_SUB_VIEW_PARAM, type TableSubViewName } from '@/lib/utils/table-sub-views'
import { encodePivot, type PivotLayout } from '@/lib/utils/data-analysis-pivot'
import { deserializeFilter } from '@/lib/utils/filter-utils'
import { queryRecords, type TableVariant } from '@/lib/api/tables'
import { useRecordQuery, hasCapability } from '@/lib/hooks/use-record-query'
import { useSavedViews, useSavedView } from '@/lib/hooks/use-saved-views'
@@ -122,6 +122,7 @@ interface RecordQueryProps {
export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, allTables, processes, metaData, savedViewId }: RecordQueryProps) {
const tableMetaData = useMemo(() => withReadableExposedJoins(sourceTableMetaData, allTables), [sourceTableMetaData, allTables])
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const fromPath = searchParams.get('from')
const fromLabel = searchParams.get('fromLabel')
@@ -324,36 +325,59 @@ export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, all
const openAnalysis = (field?: { name: string; label: string }) => setAnalysis({ field, filter: rq.filter.baseFilter, returnFocus: field ? document.querySelector<HTMLElement>(`[data-qqq-id="grid-column-menu-${CSS.escape(field.name)}"]`) : document.activeElement instanceof HTMLElement ? document.activeElement : null })
const closeAnalysis = () => { const target = analysis?.returnFocus; setAnalysis(null); requestAnimationFrame(() => target?.focus()) }
const canAnalyze = capabilities.data?.canAnalyze === true
const pivotOpen = searchParams.get('view') === 'pivot'
const relationshipView = EXPLORE_VIEWS.find(v => v !== 'pivot' && v === searchParams.get('view')) as RelationshipView | undefined
const explorerOpen = pivotOpen || Boolean(relationshipView)
const { setUserFilter: restorePivotFilter, setQuickSearch: restorePivotSearch } = rq.filter
// Sub-views (the explore views and the saved analysis viewer) are states of this route, named by
// the query string. `table-sub-views` is their registry: a view opens only through it, so the
// breadcrumb knows every one of them.
const subView = tableSubView(searchParams)
const pivotOpen = subView?.name === 'pivot'
const relationshipView = subView && subView.name !== 'pivot' && subView.name !== 'saved' ? subView.name as RelationshipView : undefined
const { restoreFromUrl } = rq
// Browser Back and Forward between the list and a sub-view (or two states of the list) change the
// address without remounting this page: take the filter, sort, quick search and page from it, so
// the list is the one that address names. A step to another page is not this page's to follow.
useEffect(() => {
const samePath = (a: string, b: string) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '')
const restore = () => {
if (!samePath(window.location.pathname, pathname)) return
const params = new URLSearchParams(window.location.search)
if (!explorerOpen && !EXPLORE_VIEWS.some(v => v === params.get('view'))) return
restorePivotFilter(deserializeFilter(params.get('filter') ?? '', rq.viewState.pageSize))
restorePivotSearch(params.get('q') ?? '')
restoreFromUrl(window.location.search)
setLocalSearchTerm(params.get('q') ?? '')
}
window.addEventListener('popstate', restore)
return () => window.removeEventListener('popstate', restore)
}, [explorerOpen, restorePivotFilter, restorePivotSearch, rq.viewState.pageSize])
const updatePivotUrl = (open: boolean, request?: PivotLayout) => {
}, [pathname, restoreFromUrl])
// The list address a sub-view was opened from, while that list is the previous history entry.
const openedFromRef = useRef<string | null>(null)
// Opens a sub-view, or updates the open one's layout, in the address (a new history entry only
// when a view opens, so Back returns to the list and a re-run does not pile up entries).
const openSubView = (view: TableSubViewName, layout?: string) => {
const url = new URL(window.location.href)
if (open) url.searchParams.set('view', 'pivot')
else { url.searchParams.delete('view'); url.searchParams.delete('pivot') }
if (request) url.searchParams.set('pivot', encodePivot(request))
if (open && !pivotOpen) window.history.pushState(null, '', url)
else window.history.replaceState(null, '', url)
url.searchParams.set(TABLE_SUB_VIEW_PARAM, view)
if (layout !== undefined) url.searchParams.set(view, layout)
if (subView) window.history.replaceState(null, '', url)
else {
openedFromRef.current = `${window.location.pathname}${window.location.search}`
window.history.pushState(null, '', url)
}
}
// Returns to the list, with whatever filter, sort and page the address now carries. When that is
// still the list this view was opened from, it is one step back in history, so the view stays
// one Forward away and Back does not meet the same list twice; otherwise (a deep link, or a
// drill changed the filter) the list replaces the view in place.
const closeSubView = () => {
const list = `${window.location.pathname}${listSearch(window.location.search)}`
const openedFrom = openedFromRef.current
openedFromRef.current = null
if (openedFrom === list) window.history.back()
else window.history.replaceState(null, '', `${list}${window.location.hash}`)
}
const updatePivotUrl = (open: boolean, request?: PivotLayout) => {
if (open) openSubView('pivot', request ? encodePivot(request) : undefined)
else closeSubView()
}
const updateExploreUrl = (view?: RelationshipView, layout?: ExploreLayout) => {
const url = new URL(window.location.href)
if (view) url.searchParams.set('view', view)
else { url.searchParams.delete('view'); EXPLORE_VIEWS.forEach(v => url.searchParams.delete(v)) }
if (view && layout) url.searchParams.set(view, encodeExplore(view, layout))
if (view && !explorerOpen) window.history.pushState(null, '', url)
else window.history.replaceState(null, '', url)
if (view) openSubView(view, layout ? encodeExplore(view, layout) : undefined)
else closeSubView()
}
// A drill on this table applies its filter here: this page reads the URL only on mount.
const applyAnalysisDrill = (drill: DataAnalysisDrillV1) => {
@@ -608,13 +632,8 @@ export function RecordQuery({ tableName, tableMetaData: sourceTableMetaData, all
</>
)
if (searchParams.get('view') === 'saved') {
const closeSaved = () => {
const url = new URL(window.location.href)
url.searchParams.delete('view')
url.searchParams.delete('saved')
window.history.replaceState(null, '', url)
}
if (subView?.name === 'saved') {
const closeSaved = closeSubView
return <AnalysisDrillContext.Provider value={drill => {
if (!applyAnalysisDrill(drill)) return false
closeSaved()
+4 -3
View File
@@ -42,6 +42,7 @@ import type { Density } from '@/lib/hooks/use-record-query'
import type { TableVariant } from '@/lib/api/tables'
import type { ColumnPins } from '@/lib/utils/query-columns'
import { MATERIAL_BUTTON_VARIANTS } from '@/lib/utils/qqq-id'
import { EXPLORE_LABELS, EXPLORE_VIEWS } from '@/lib/utils/data-analysis-explore'
import { LazyFavoriteToggle } from '@/components/collaboration/LazyFavoriteToggle'
import { GotoRecordButton } from '@/components/records/GotoRecordDialog'
@@ -189,7 +190,7 @@ export interface RecordQueryToolbarProps {
/** Opens table analysis when capabilities permit it. */
onAnalyzeTable?: () => void
/** Opens an explorer under the table's analysis capability. */
onExplore?: (view: 'pivot' | 'compare' | 'correlation' | 'crosstab' | 'shift') => void
onExplore?: (view: (typeof EXPLORE_VIEWS)[number]) => void
/** The backend table name used in API calls and URL routing. */
tableName: string
/** Full table metadata from the QQQ backend. */
@@ -467,9 +468,9 @@ export function RecordQueryToolbar({
</DropdownMenuPrimitive.Trigger>
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content align="start" sideOffset={4} className="z-[200] min-w-44 rounded border border-border bg-popover p-1 text-popover-foreground shadow-md">
{(['pivot', 'compare', 'correlation', 'crosstab', 'shift'] as const).map(view => (
{EXPLORE_VIEWS.map(view => (
<DropdownMenuPrimitive.Item key={view} onSelect={() => onExplore(view)} className="cursor-pointer rounded px-3 py-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground" data-qqq-id={`explore-${view}`}>
{view === 'shift' ? 'Shift over time' : view[0].toUpperCase() + view.slice(1)}
{EXPLORE_LABELS[view]}
</DropdownMenuPrimitive.Item>
))}
</DropdownMenuPrimitive.Content>
@@ -15,7 +15,8 @@
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { act, fireEvent, render, screen, within } from '@testing-library/react'
import { axe } from 'jest-axe'
import type { QAuditRecord, QTableMetaData } from '@/types'
import { useAuditRecords } from '@/lib/hooks/use-audit-records'
@@ -55,3 +56,89 @@ describe('AuditHistoryDialog', () => {
expect(vi.mocked(useAuditRecords)).toHaveBeenLastCalledWith(expect.objectContaining({ isSortAscending: false }))
})
})
describe('AuditHistoryDialog layout', () => {
const LONG_ID = 'a3f9c2e17b5d4086a3f9c2e17b5d4086a3f9c2e17b5d4086a3f9c2e17b5d4086'
const history = (state: Partial<ReturnType<typeof useAuditRecords>>) =>
vi.mocked(useAuditRecords).mockReturnValue({ auditRecords: [], total: null, isLoading: false, isError: false, error: null, refetch: vi.fn(), ...state } as unknown as ReturnType<typeof useAuditRecords>)
const open = (recordLabel = LONG_ID, primaryKey: string | number = LONG_ID) =>
render(<AuditHistoryDialog open onOpenChange={vi.fn()} source="process" tableMetaData={tableMetaData} primaryKey={primaryKey} recordLabel={recordLabel} />)
it('keeps a 64 character identifier inside the header: it may shrink and wrap, the controls may not', () => {
open()
const dialog = screen.getByRole('dialog', { name: `Audit for Record Lab: ${LONG_ID}` })
const header = dialog.querySelector('[data-qqq-id="audit-history-header"]')!
const title = screen.getByRole('heading', { level: 2 })
const controls = header.querySelector('[data-qqq-id="audit-history-controls"]')!
// the heading's column is allowed to be narrower than its text, and the text breaks anywhere
expect(header).toHaveClass('grid', 'grid-cols-[minmax(0,1fr)_auto]')
expect(title).toHaveClass('min-w-0', '[overflow-wrap:anywhere]', 'line-clamp-3')
// cut text stays available: in the title attribute and in the dialog's name
expect(title).toHaveAttribute('title', `Audit for Record Lab: ${LONG_ID}`)
expect(title).toHaveTextContent(LONG_ID)
// every control is in the header, in the column that keeps its size
expect(controls).toHaveClass('shrink-0')
expect(controls.parentElement).toBe(header)
for (const name of ['Copy record ID', 'Sort by time ascending (oldest to newest)', 'Sort by time descending (newest to oldest)', 'Close audit history']) {
expect(within(controls as HTMLElement).getByRole('button', { name })).toBeInTheDocument()
}
})
it('copies the full identifier, and names what it copies', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
open()
await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Copy record ID' })) })
expect(writeText).toHaveBeenCalledWith(LONG_ID)
expect(screen.getByRole('button', { name: 'Copy record ID: copied' })).toBeInTheDocument()
})
it('names the copy button for a label that is not the record ID', () => {
open('Alice Johnson', 7)
expect(screen.getByRole('button', { name: 'Copy record label' })).toBeInTheDocument()
})
it('shows an empty history as one block: icon and sentence together, no list and no band below', async () => {
history({ auditRecords: [] })
open()
const dialog = screen.getByRole('dialog')
const status = screen.getByRole('status')
expect(status).toHaveTextContent('No audits were found for this record.')
expect(status).toHaveAttribute('data-empty', 'true')
expect(status).toHaveClass('flex', 'flex-col', 'items-center', 'text-center')
// the icon belongs to the sentence, and is the only one outside the header
expect(status.querySelectorAll('svg')).toHaveLength(1)
expect(status.querySelector('svg')).toHaveAttribute('aria-hidden', 'true')
expect(status).not.toHaveClass('border-b')
// header and status are the whole dialog
expect(dialog.children).toHaveLength(2)
expect(dialog.lastElementChild).toBe(status)
expect(screen.queryByRole('list', { name: 'Audits' })).not.toBeInTheDocument()
expect(await axe(dialog)).toHaveNoViolations()
})
it('shows loading and an error as a line, without the empty-state icon or an empty body', () => {
history({ isLoading: true })
const { unmount } = open()
expect(screen.getByRole('status')).toHaveTextContent('Loading audits...')
expect(screen.getByRole('status').querySelector('svg')).toBeNull()
expect(screen.getByRole('dialog').children).toHaveLength(2)
unmount()
history({ isError: true, error: new Error('boom') })
open()
expect(screen.getByRole('alert')).toHaveTextContent('Error loading audits')
expect(screen.getByRole('alert').querySelector('svg')).toBeNull()
expect(screen.getByRole('dialog').children).toHaveLength(2)
})
it('keeps the count line above the list when there are audits', () => {
history({ auditRecords: records, total: null })
open('Record 7', 7)
const status = screen.getByRole('status')
expect(status).toHaveTextContent('Showing all 3 audits for this record')
expect(status).toHaveClass('border-b')
expect(status.querySelector('svg')).toBeNull()
expect(screen.getByRole('list', { name: 'Audits' })).toBeInTheDocument()
})
})
+37 -10
View File
@@ -22,7 +22,7 @@
import React, { useEffect, useState } from 'react'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import { ArrowDown, ArrowUp, History, X } from 'lucide-react'
import { ArrowDown, ArrowUp, Check, Copy, History, X } from 'lucide-react'
import type { QAuditRecord, QTableMetaData } from '@/types'
import type { AuditSource } from '@/lib/api/audits'
@@ -127,11 +127,21 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
const { auditRecords, total, isLoading, isError, error } = useAuditRecords({ capabilities: tableMetaData.clientCapabilities,
source, tableName: tableMetaData.name, primaryKey, enabled: open && sortReady, isSortAscending,
})
const [copied, setCopied] = useState(false)
useEffect(() => {
if (!copied) return
const timer = setTimeout(() => setCopied(false), 2000)
return () => clearTimeout(timer)
}, [copied])
let status: string
if (isLoading) status = 'Loading audits...'
else if (isError) status = getErrorStatusCode(error) === 403 ? 'You do not have permission to view audits' : 'Error loading audits'
else status = countSentence(auditRecords.length, total)
const isEmpty = !isLoading && !isError && auditRecords.length === 0
const heading = `Audit for ${tableMetaData.label}: ${recordLabel}`
// what the copy button copies is what the heading may have cut short
const copyLabel = recordLabel === String(primaryKey) ? 'Copy record ID' : 'Copy record label'
return (
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
@@ -152,10 +162,23 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
'rounded-xl border border-border bg-card shadow-lg focus:outline-none'
)}
>
<div className="flex items-center justify-between gap-3 border-b border-border px-6 py-4">
<DialogPrimitive.Title className="text-lg font-semibold tracking-tight text-foreground">
Audit for {tableMetaData.label}: {recordLabel}
{/* The heading takes the space the controls leave (`minmax(0,1fr)` lets it shrink below its
text), so a long record identifier wraps inside the card, at any character, instead of
pushing the sort and close buttons out of it. Past three lines it is cut with an
ellipsis; the whole text stays in its `title`, in the dialog's accessible name, and on
the copy button. */}
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2 border-b border-border px-4 py-4 sm:gap-x-3 sm:px-6" data-qqq-id="audit-history-header">
<DialogPrimitive.Title title={heading} data-qqq-id="audit-history-title"
className="line-clamp-3 min-w-0 pt-1 text-lg font-semibold leading-snug tracking-tight text-foreground [overflow-wrap:anywhere]">
{heading}
</DialogPrimitive.Title>
<div className="flex shrink-0 items-center gap-1" data-qqq-id="audit-history-controls">
<button type="button" aria-label={copied ? `${copyLabel}: copied` : copyLabel} title={copyLabel}
onClick={() => { void navigator.clipboard?.writeText(recordLabel).then(() => setCopied(true), () => setCopied(false)) }}
data-qqq-id="button-audit-copy-record"
className="rounded-lg p-2 text-muted-foreground hover:bg-accent hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring">
{copied ? <Check className="h-4 w-4 text-green-600 dark:text-green-400" aria-hidden="true" /> : <Copy className="h-4 w-4" aria-hidden="true" />}
</button>
<div className="flex shrink-0 items-center gap-1" role="group" aria-label="Audit sort order">
<button type="button" aria-label="Sort by time ascending (oldest to newest)" aria-pressed={isSortAscending}
onClick={() => { setSortAscending(true); localStorage.setItem('audit.sortDirection', 'true') }}
@@ -177,17 +200,21 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
>
<X className="h-4 w-4" aria-hidden="true" />
</DialogPrimitive.Close>
</div>
</div>
{/* One status element for every state (the dialog is described by it). With audits it is a
line above the list. With none it is the whole body: a small icon and the sentence as
one centered block, with no list and no empty band under it. */}
<p id="audit-history-status" role={isError ? 'alert' : 'status'} data-qqq-id="audit-history-status"
className={cn('border-b border-border px-6 py-3 text-sm', isError ? 'text-destructive' : 'text-muted-foreground')}>
data-empty={isEmpty ? 'true' : undefined}
className={cn('px-4 text-sm sm:px-6', isError ? 'text-destructive' : 'text-muted-foreground',
isEmpty ? 'flex flex-col items-center gap-2 py-8 text-center' : 'py-3', auditRecords.length > 0 && 'border-b border-border')}>
{isEmpty && <History className="h-6 w-6 text-muted-foreground/60" aria-hidden="true" />}
{status}
</p>
<div className="flex-1 overflow-y-auto px-6 py-4">
{!isLoading && !isError && auditRecords.length === 0 && (
<History className="mx-auto h-10 w-10 text-muted-foreground/30" aria-hidden="true" />
)}
{auditRecords.length > 0 && <div className="flex-1 overflow-y-auto px-4 py-4 sm:px-6">
<ol aria-label="Audits">
{groupAuditsByDate(auditRecords).map((group) => (
<li key={`${localAuditDate(group[0].timestamp)}-${group[0].id}`}>
@@ -197,7 +224,7 @@ export function AuditHistoryDialog({ open, onOpenChange, source, tableMetaData,
</li>
))}
</ol>
</div>
</div>}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
@@ -21,7 +21,7 @@ import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { getSecuredDataStatus, type BreakGlassSession } from '@/lib/api/secured-data'
import { queryKeys } from '@/lib/query-client'
import { BACKGROUND_REQUEST, queryKeys } from '@/lib/query-client'
import { countdownText, remainingSeconds } from '@/lib/utils/secured-data'
/**
@@ -36,6 +36,8 @@ export default function BreakGlassBanner() {
staleTime: 0,
gcTime: 0,
refetchOnWindowFocus: false,
// Asked on every navigation and then on a timer, for a banner: a failure raises no error banner.
meta: BACKGROUND_REQUEST,
refetchInterval: (query) =>
query.state.data?.breakGlass && remainingSeconds(query.state.data.breakGlass.expiresAt) > 0
? 60_000
+26
View File
@@ -57,6 +57,32 @@ describe('normalizeAssistantRender', () => {
expect(normalizeAssistantRender('nonsense')).toMatchObject({ type: 'unknown', originalType: '' })
expect(normalizeAssistantRender(null)).toBeUndefined()
})
it('keeps the count and the records of a card for a set, dropping what is not a record', () => {
const render = normalizeAssistantRender({
type: 'pending_action', actionId: 7, toolName: 'update_record', actionKind: 'process_run', processName: 'printer.bulkDelete', processLabel: 'Printer Bulk Delete',
tableName: 'printer', tableLabel: 'Printer', summary: 'Run Printer Bulk Delete on 3 Printer records', changes: [],
recordCount: 3,
records: [{ id: '1', label: 'Dock 1', href: '/app/printer/1' }, { id: 2, label: 2 }, 'nonsense', null, { id: '3', label: 'Dock 3', href: 9 }],
recordsBefore: { count: 3, sampleCap: 20, sample: [] },
})
expect(render).toMatchObject({
type: 'pending_action', actionKind: 'process_run', processName: 'printer.bulkDelete', processLabel: 'Printer Bulk Delete', recordCount: 3,
records: [{ id: '1', label: 'Dock 1', href: '/app/printer/1' }, { id: 2, label: '2' }, { id: '3', label: 'Dock 3' }],
})
expect((render as { records: Array<{ href?: string }> }).records[2].href).toBeUndefined()
})
it('reads a card for one record, or from an older server, as having no set', () => {
const base = { type: 'pending_action', actionId: 7, toolName: 'update_record', tableName: 'printer', tableLabel: 'Printer', summary: 'Update Printer 4', changes: [] }
expect(normalizeAssistantRender(base)).toMatchObject({ type: 'pending_action', records: [] })
expect((normalizeAssistantRender(base) as { recordCount?: number }).recordCount).toBeUndefined()
// a count that is not a whole number of records is no count: the card then counts its list
for (const recordCount of [-1, 2.5, '27', null]) {
expect(normalizeAssistantRender({ ...base, recordCount, records: 'nonsense' })).toMatchObject({ type: 'pending_action', records: [] })
expect((normalizeAssistantRender({ ...base, recordCount }) as { recordCount?: number }).recordCount).toBeUndefined()
}
})
})
describe('parts and messages', () => {
+4
View File
@@ -99,6 +99,10 @@ const RENDER_SCHEMAS = {
type: z.literal('pending_action'), actionId: z.number().int(), toolName: z.enum(['create_record', 'update_record', 'delete_record']),
tableName: text, tableLabel: text, recordId: nullableText.optional(), summary: text,
changes: list(z.object({ field: text, label: text, value: nullableText })), href: optionalText,
actionKind: optionalText, processName: optionalText, processLabel: optionalText,
// a run over a set of records: the count the card states, and every record for the card to list
recordCount: z.number().int().nonnegative().optional().catch(undefined),
records: list(z.object({ id: idValue, label: text, href: optionalText })),
}),
} as const
+11
View File
@@ -32,6 +32,13 @@ export const AUDIT_PROCESS_NAME = 'GetAuditsForRecord'
export const AUDIT_TABLE_NAME = 'audit'
/** Most audit rows read for one record, as in the Material dashboard. */
export const AUDIT_LIMIT = 1000
/**
* How long the server may take to answer the audit process in the same request. Without it the
* server waits 3 seconds and then answers that the run continues as a job, which this read does
* not follow, so a history that took longer than 3 seconds ended as an error. 25 seconds is under
* the API client's own 30 second limit.
*/
export const AUDIT_STEP_TIMEOUT_MILLIS = 25_000
/** How a record's audits can be read by the current user, if at all. */
export type AuditSource = 'process' | 'table' | null
@@ -63,6 +70,8 @@ interface ProcessCompleteResponse {
values?: Record<string, unknown>
error?: string
userFacingError?: string
/** Present when the run outlived the step timeout and continues as a job. */
jobUUID?: string
}
/** Audit entries plus the optional count when the 1,000-detail cap was reached. */
@@ -90,9 +99,11 @@ export async function getAuditRecords(source: Exclude<AuditSource, null>, tableN
if (!processName) throw new Error('Audit process is unavailable.')
const formData = new FormData()
formData.append('values', JSON.stringify({ tableName, recordId: String(primaryKey), isSortAscending, limit: AUDIT_LIMIT }))
formData.append('stepTimeoutMillis', String(AUDIT_STEP_TIMEOUT_MILLIS))
const response = await apiClient.post<ProcessCompleteResponse>(`/processes/${encodeURIComponent(processName)}/init`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
if (response?.jobUUID && !response.values) throw new Error('The audit history is taking too long to load.')
if (response?.type === 'ERROR' || (response?.type !== 'COMPLETE' && !response?.values)) {
throw new Error(getErrorMessage(response, 'Error loading audits'))
}
+66 -4
View File
@@ -23,7 +23,7 @@ import React from 'react'
import type { QInstance, QRecord } from '@/types'
import apiClient from '@/lib/api/client'
import { AUDIT_LIMIT, getAuditRecords, auditSource, groupAuditRows } from '@/lib/api/audits'
import { AUDIT_LIMIT, AUDIT_STEP_TIMEOUT_MILLIS, getAuditRecords, auditSource, groupAuditRows } from '@/lib/api/audits'
import { useAuditRecords } from './use-audit-records'
vi.mock('@/lib/api/client', () => ({ default: { post: vi.fn(), get: vi.fn() } }))
@@ -55,7 +55,10 @@ const rows = [
auditRow(1, 'Record was Inserted'),
]
beforeEach(() => vi.mocked(apiClient.post).mockReset())
// a block body: a function returned from beforeEach is run as a cleanup hook, and mockReset returns the mock
beforeEach(() => {
vi.mocked(apiClient.post).mockReset()
})
describe('groupAuditRows', () => {
it('groups detail rows into one entry per audit, keeping order and backend sentences', () => {
@@ -93,7 +96,21 @@ describe('useAuditRecords', () => {
expect(JSON.parse((body as FormData).get('values') as string)).toEqual({ tableName: 'recordLab', recordId: '7', isSortAscending: false, limit: 1000 })
})
it('requests oldest first and uses a separate query key for that order', async () => {
it('gives the server longer than its 3 second default to answer in the same request', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ type: 'COMPLETE', values: { audits: rows } })
await getAuditRecords('process', 'recordLab', 7)
const body = vi.mocked(apiClient.post).mock.calls[0][1] as FormData
expect(body.get('stepTimeoutMillis')).toBe(String(AUDIT_STEP_TIMEOUT_MILLIS))
expect(AUDIT_STEP_TIMEOUT_MILLIS).toBeGreaterThan(3_000)
expect(AUDIT_STEP_TIMEOUT_MILLIS).toBeLessThan(30_000)
})
it('reports a run that continues as a job as too slow, not as an empty history', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ type: 'JOB_STARTED', processUUID: 'p-1', jobUUID: 'j-1' })
await expect(getAuditRecords('process', 'recordLab', 7)).rejects.toThrow('The audit history is taking too long to load.')
})
it('opens with one request, and re-sorts a complete history without asking the server again', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ type: 'COMPLETE', values: { audits: rows } })
const wrapper = createWrapper()
const { result, rerender } = renderHook(
@@ -101,12 +118,57 @@ describe('useAuditRecords', () => {
{ wrapper, initialProps: { ascending: false } }
)
await waitFor(() => expect(result.current.isLoading).toBe(false))
expect(apiClient.post).toHaveBeenCalledTimes(1)
expect(result.current.auditRecords.map((entry) => entry.id)).toEqual([2, 1])
// each audit keeps its details in their own order
expect(result.current.auditRecords[0].fieldChanges.map((change) => change.fieldName)).toEqual(['title', 'hint'])
rerender({ ascending: true })
await waitFor(() => expect(apiClient.post).toHaveBeenCalledTimes(2))
expect(result.current.isLoading).toBe(false)
expect(result.current.auditRecords.map((entry) => entry.id)).toEqual([1, 2])
expect(result.current.auditRecords[1].fieldChanges.map((change) => change.fieldName)).toEqual(['title', 'hint'])
rerender({ ascending: false })
expect(result.current.auditRecords.map((entry) => entry.id)).toEqual([2, 1])
rerender({ ascending: true })
await new Promise((resolve) => setTimeout(resolve, 20))
expect(apiClient.post).toHaveBeenCalledTimes(1)
})
it('asks the server for the other order when the history was capped, because its first rows differ', async () => {
vi.mocked(apiClient.post).mockImplementation(async (_url, body) => {
const ascending = JSON.parse((body as FormData).get('values') as string).isSortAscending
return { type: 'COMPLETE', values: { audits: ascending ? [auditRow(1, 'Record was Inserted')] : [auditRow(9, 'Record was Edited')], distinctCount: 5000 } }
})
const wrapper = createWrapper()
const { result, rerender } = renderHook(
({ ascending }) => useAuditRecords({ source: 'process', tableName: 'recordLab', primaryKey: 7, isSortAscending: ascending }),
{ wrapper, initialProps: { ascending: false } }
)
await waitFor(() => expect(result.current.auditRecords.map((entry) => entry.id)).toEqual([9]))
expect(result.current.total).toBe(5000)
rerender({ ascending: true })
await waitFor(() => expect(result.current.auditRecords.map((entry) => entry.id)).toEqual([1]))
expect(apiClient.post).toHaveBeenCalledTimes(2)
const body = vi.mocked(apiClient.post).mock.calls[1][1] as FormData
expect(JSON.parse(body.get('values') as string).isSortAscending).toBe(true)
})
it('asks for the chosen order when it changes before anything has loaded', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ type: 'COMPLETE', values: { audits: rows } })
const wrapper = createWrapper()
const { result, rerender } = renderHook(
({ ascending, enabled }) => useAuditRecords({ source: 'process', tableName: 'recordLab', primaryKey: 7, isSortAscending: ascending, enabled }),
{ wrapper, initialProps: { ascending: false, enabled: false } }
)
rerender({ ascending: true, enabled: false })
expect(apiClient.post).not.toHaveBeenCalled()
rerender({ ascending: true, enabled: true })
await waitFor(() => expect(result.current.isLoading).toBe(false))
expect(apiClient.post).toHaveBeenCalledTimes(1)
const body = vi.mocked(apiClient.post).mock.calls[0][1] as FormData
expect(JSON.parse(body.get('values') as string).isSortAscending).toBe(true)
})
it('queries the audit table joined to its details without process permission', async () => {
vi.mocked(apiClient.post).mockResolvedValue({ records: rows })
const { result } = renderHook(
+20 -3
View File
@@ -20,6 +20,7 @@
import type { TableCapabilitiesV1 } from '@/types'
import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getAuditRecords, type AuditSource } from '@/lib/api/audits'
@@ -45,20 +46,36 @@ interface UseAuditRecordsOptions {
/**
* Loads a record's audit history in the requested order.
*
* One request loads the history. Changing the order asks the server again only when it has to:
* a history under the row cap is complete, so the other order is the same entries reversed (the
* server sorts audits by time and id in one direction, and each audit's details always ascending)
* and is shown at once without a request. A capped history (`total` is set) is a different first
* 1,000 rows in each direction, so only then does the order go back to the server.
*
* @param options - See {@link UseAuditRecordsOptions}.
* @returns The entries plus loading and error state (the caller renders errors).
*/
export function useAuditRecords({ source, capabilities, tableName, primaryKey, enabled = true, isSortAscending = false }: UseAuditRecordsOptions) {
// the order the server is asked for; it follows the requested order only while that is needed
const [serverAscending, setServerAscending] = useState(isSortAscending)
const { data, isLoading, isError, error, refetch } = useQuery({
queryKey: [...queryKeys.audits(tableName, primaryKey), isSortAscending, capabilities],
queryFn: () => getAuditRecords(source!, tableName, primaryKey, isSortAscending, capabilities),
queryKey: [...queryKeys.audits(tableName, primaryKey), serverAscending, capabilities],
queryFn: () => getAuditRecords(source!, tableName, primaryKey, serverAscending, capabilities),
enabled: enabled && source !== null,
staleTime: 0,
meta: HANDLES_OWN_ERRORS,
})
const complete = data !== undefined && data.total === null
// Nothing loaded yet, or a capped history: the server sorts. (Adjusting state while rendering
// restarts this render with the new order, before anything is shown or fetched for the old one.)
if (serverAscending !== isSortAscending && !complete) setServerAscending(isSortAscending)
const auditRecords = useMemo(
() => (data ? (serverAscending === isSortAscending ? data.records : [...data.records].reverse()) : []),
[data, serverAscending, isSortAscending]
)
return {
auditRecords: data?.records ?? [],
auditRecords,
total: data?.total ?? null,
isLoading,
isError,
+4 -1
View File
@@ -25,7 +25,7 @@
import { useEffect, useRef } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { CollaborationTarget } from '@/types/collaboration'
import { queryKeys } from '@/lib/query-client'
import { BACKGROUND_REQUEST, queryKeys } from '@/lib/query-client'
/** The API module, imported once (concurrent first calls share one import). */
let apiModule: Promise<typeof import('@/lib/api/collaboration')> | undefined
@@ -66,6 +66,9 @@ export function useRecordRecentView(target: CollaborationTarget) {
const { mutate } = useMutation({
mutationFn: async (recent: CollaborationTarget) => (await api()).recordRecent(recent),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.collaborationRecentsRoot() }),
// Written on every table and record the person opens, without their asking: a failure costs
// one entry in their recents and raises no error banner.
meta: BACKGROUND_REQUEST,
})
const { targetType, targetName, recordId } = target
useEffect(() => {
@@ -0,0 +1,167 @@
/*
* 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.
*/
// A presence outage: the server answers 503 on purpose for a while after its shared store
// restarts. These tests run the hook on the application's own query client, with its real global
// error handler, so they fail if a presence failure ever reaches the error banner again.
import React from 'react'
import { act, renderHook } from '@testing-library/react'
import { QueryClientProvider } from '@tanstack/react-query'
import { AxiosError, AxiosHeaders, type InternalAxiosRequestConfig } from 'axios'
import { toast } from 'sonner'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import * as api from '@/lib/api/collaboration'
import { queryClient } from '@/lib/query-client'
import { PRESENCE_INTERVAL_MS, useCollaborationPresence } from './use-collaboration-presence'
vi.mock('@/lib/context/q-context', async () => {
const { createContext } = await import('react')
return { useQContext: () => ({ userId: 'me' }), QContext: createContext({ userId: 'me' }) }
})
vi.mock('./use-realtime-channel', () => ({ useRealtimeChannel: vi.fn() }))
vi.mock('@/lib/api/collaboration', () => ({
openPresenceLease: vi.fn(),
renewPresence: vi.fn(),
leavePresence: vi.fn(),
getPresence: vi.fn(),
beaconPresence: vi.fn(),
}))
/**
* The answer of a presence endpoint while its store recovers.
*
* @param method - The request's method.
* @param url - The request's path under the API base.
* @returns The axios error a 503 becomes.
*/
function recovering(method: string, url: string): AxiosError {
const config = { method, url, baseURL: '/qqq/v1', headers: new AxiosHeaders() } as InternalAxiosRequestConfig
const data = { error: 'Presence is recovering; active viewers are rejoining. Please retry.' }
return new AxiosError('Request failed with status code 503', 'ERR_BAD_RESPONSE', config, {}, { status: 503, data, statusText: '', headers: {}, config })
}
const sam = { userId: 'sam', displayName: 'Sam', mode: 'VIEWING' as const }
const banner = vi.spyOn(toast, 'error')
const warn = vi.spyOn(console, 'warn')
const wrapper = ({ children }: { children: React.ReactNode }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
/** Calls of a mocked API function so far. */
const calls = (fn: unknown) => vi.mocked(fn as () => unknown).mock.calls.length
beforeEach(() => {
vi.useFakeTimers()
// the middle of the jitter range: waits of 3.75 s, 7.5 s, 15 s, 30 s, then 45 s
vi.spyOn(Math, 'random').mockReturnValue(0.5)
banner.mockClear()
warn.mockClear().mockImplementation(() => undefined)
let lease = 0
vi.mocked(api.openPresenceLease).mockImplementation(async () => ({ connectionId: `lease:${++lease}` }))
vi.mocked(api.getPresence).mockResolvedValue({ table: 'person', viewers: [sam] })
vi.mocked(api.renewPresence).mockResolvedValue({ table: 'person', viewers: [sam] })
vi.mocked(api.leavePresence).mockResolvedValue({})
})
afterEach(() => {
queryClient.clear()
vi.useRealTimers()
vi.mocked(Math.random).mockRestore()
vi.clearAllMocks()
})
it('an outage raises no error banner, shows as reconnecting, backs off with jitter and recovers on its own', async () => {
let down = true
vi.mocked(api.getPresence).mockImplementation(async () => {
if (down) throw recovering('get', '/qbit/collaboration/presence')
return { table: 'person', viewers: [sam] }
})
vi.mocked(api.openPresenceLease).mockImplementation(async () => {
if (down) throw recovering('post', '/qbit/collaboration/presence/leases')
return { connectionId: 'lease:1' }
})
const hook = renderHook(() => useCollaborationPresence('person'), { wrapper })
// First attempts fail: one request each, no automatic retries on top
await act(() => vi.advanceTimersByTimeAsync(10))
expect(hook.result.current.reconnecting).toBe(true)
expect(hook.result.current.viewers).toEqual([])
expect(hook.result.current.hadViewers).toBe(false)
expect([calls(api.getPresence), calls(api.openPresenceLease)]).toEqual([1, 1])
// The next attempts come after 3.75 s, then 7.5 s more, then 15 s more: not every few seconds,
// and not at the fixed interval of a healthy poll
await act(() => vi.advanceTimersByTimeAsync(3700))
expect([calls(api.getPresence), calls(api.openPresenceLease)]).toEqual([1, 1])
await act(() => vi.advanceTimersByTimeAsync(100))
expect([calls(api.getPresence), calls(api.openPresenceLease)]).toEqual([2, 2])
await act(() => vi.advanceTimersByTimeAsync(7400))
expect([calls(api.getPresence), calls(api.openPresenceLease)]).toEqual([2, 2])
await act(() => vi.advanceTimersByTimeAsync(200))
expect([calls(api.getPresence), calls(api.openPresenceLease)]).toEqual([3, 3])
await act(() => vi.advanceTimersByTimeAsync(14700))
expect([calls(api.getPresence), calls(api.openPresenceLease)]).toEqual([3, 3])
expect(hook.result.current.reconnecting).toBe(true)
// 26 seconds of 503 answers put nothing over the page; each failure is in the console for a developer
expect(banner).not.toHaveBeenCalled()
expect(warn).toHaveBeenCalledWith('[API] Request failed:', expect.objectContaining({ status: 503, background: true, request: 'GET /qqq/v1/qbit/collaboration/presence' }))
// The store is back: the next attempt succeeds without anyone doing anything
down = false
await act(() => vi.advanceTimersByTimeAsync(300))
expect(calls(api.openPresenceLease)).toBe(4)
expect(calls(api.renewPresence)).toBe(1)
expect(hook.result.current.reconnecting).toBe(false)
expect(hook.result.current.viewers).toEqual([sam])
// and the healthy rhythm returns: one renewal per interval, which carries the snapshot
const polls = calls(api.getPresence)
await act(() => vi.advanceTimersByTimeAsync(PRESENCE_INTERVAL_MS - 1000))
expect(calls(api.renewPresence)).toBe(1)
await act(() => vi.advanceTimersByTimeAsync(1100))
expect(calls(api.renewPresence)).toBe(2)
expect(calls(api.getPresence) - polls).toBeLessThanOrEqual(1)
expect(banner).not.toHaveBeenCalled()
hook.unmount()
})
it('says that people were shown when the connection was lost, and does not show them while it is', async () => {
const hook = renderHook(() => useCollaborationPresence('person', '1'), { wrapper })
await act(() => vi.advanceTimersByTimeAsync(10))
expect(hook.result.current).toMatchObject({ reconnecting: false, hadViewers: false, viewers: [sam] })
vi.mocked(api.getPresence).mockRejectedValue(recovering('get', '/qbit/collaboration/presence'))
vi.mocked(api.renewPresence).mockRejectedValue(recovering('post', '/qbit/collaboration/presence/leases/renew'))
await act(() => vi.advanceTimersByTimeAsync(PRESENCE_INTERVAL_MS + 10))
expect(hook.result.current).toMatchObject({ reconnecting: true, hadViewers: true, viewers: [] })
expect(banner).not.toHaveBeenCalled()
hook.unmount()
})
it('a renewal that keeps failing backs off instead of repeating every 20 seconds', async () => {
vi.mocked(api.renewPresence).mockRejectedValue(recovering('post', '/qbit/collaboration/presence/leases/renew'))
const hook = renderHook(() => useCollaborationPresence('person', '1'), { wrapper })
await act(() => vi.advanceTimersByTimeAsync(10))
expect(calls(api.renewPresence)).toBe(1)
// 3.75 s, 7.5 s, 15 s, 30 s, then 45 s apart: five attempts in the first 100 seconds and ten in
// five minutes, where a fixed 20 second interval made six and sixteen
await act(() => vi.advanceTimersByTimeAsync(100_000))
expect(calls(api.renewPresence)).toBe(5)
await act(() => vi.advanceTimersByTimeAsync(200_000))
expect(calls(api.renewPresence)).toBe(10)
expect(calls(api.openPresenceLease)).toBe(1)
expect(hook.result.current.reconnecting).toBe(true)
hook.unmount()
})
@@ -98,10 +98,10 @@ it('reports failed renewals even when reads succeed, and recovers on a successfu
)
const hook = renderHook(() => useCollaborationPresence('person', '1'), { wrapper })
await act(() => vi.advanceTimersByTimeAsync(10))
expect(hook.result.current.unavailable).toBe(true)
expect(hook.result.current.reconnecting).toBe(true)
expect(hook.result.current.viewers).toEqual([])
await act(() => vi.advanceTimersByTimeAsync(20000))
expect(hook.result.current.unavailable).toBe(false)
expect(hook.result.current.reconnecting).toBe(false)
expect(api.openPresenceLease).toHaveBeenCalledTimes(1)
hook.unmount()
})
@@ -127,7 +127,7 @@ it('ignores a failed renewal from the previous record', async () => {
await act(async () => {
rejectOld(new Error('Old request failed'))
})
expect(hook.result.current.unavailable).toBe(false)
expect(hook.result.current.reconnecting).toBe(false)
hook.unmount()
})
@@ -174,7 +174,7 @@ it('rejoins once with a new handle after an explicit lease expiry', async () =>
['lease:1', 1],
['lease:2', 1],
])
expect(hook.result.current.unavailable).toBe(false)
expect(hook.result.current.reconnecting).toBe(false)
hook.unmount()
})
@@ -207,7 +207,7 @@ it('bounds immediate rejoin attempts when replacement leases also expire', async
const hook = renderHook(() => useCollaborationPresence('person', '1'), { wrapper })
await act(() => vi.advanceTimersByTimeAsync(0))
expect(api.openPresenceLease).toHaveBeenCalledTimes(2)
expect(hook.result.current.unavailable).toBe(true)
expect(hook.result.current.reconnecting).toBe(true)
hook.unmount()
})
+64 -15
View File
@@ -14,7 +14,14 @@
* limitations under the License.
*/
/** @file Ephemeral presence leases with focus changes, polling fallback and realtime refresh. */
/**
* @file Ephemeral presence leases with focus changes, polling fallback and realtime refresh.
*
* Presence is not essential to the page it sits on. Its requests are background requests (no
* global error banner), and while the server cannot answer (it answers 503 for a while after its
* shared store restarts) the hook reports `reconnecting` and tries again with backoff and jitter
* until an attempt succeeds.
*/
'use client'
import { useContext, useEffect, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
@@ -27,10 +34,16 @@ import {
getPresence,
beaconPresence,
} from '@/lib/api/collaboration'
import { queryKeys } from '@/lib/query-client'
import { BACKGROUND_REQUEST, queryKeys } from '@/lib/query-client'
import { QContext } from '@/lib/context/q-context'
import { backoffDelay } from '@/lib/utils/backoff'
import { useRealtimeChannel } from './use-realtime-channel'
/** A healthy presence poll, and a healthy lease renewal, repeat at this interval. */
export const PRESENCE_INTERVAL_MS = 20_000
/** After a failure the next attempt waits 2.5 to 5 s, then twice as long per failure, up to a minute. */
export const PRESENCE_BACKOFF = { baseMs: 5_000, maxMs: 60_000 } as const
/** Deduplicates tabs, excludes the current user, and prefers editing leases.
* @param viewers - Snapshot entries.
* @param userId - Current identity.
@@ -49,7 +62,8 @@ export function otherViewers(viewers: PresenceViewer[], userId?: string) {
* @param editing - Form open.
* @param fieldName - Focused form field.
* @param enabled - PRESENCE is installed and enabled.
* @returns Other viewers and query state.
* @returns Other viewers and query state; `reconnecting` while the server cannot answer, and
* `hadViewers` when other people were shown at the moment the connection was lost.
*/
export function useCollaborationPresence(
table: string,
@@ -66,11 +80,27 @@ export function useCollaborationPresence(
const userId = useContext(QContext)?.userId
const cache = useQueryClient()
const key = queryKeys.collaborationResource(table, pk ?? '', 'presence')
// The wait before the next poll is decided once per attempt (the jitter must not change on a
// re-render): the usual interval after a success, a longer and longer one after failures.
const poll = useRef({ failures: 0, delay: PRESENCE_INTERVAL_MS as number })
const query = useQuery({
queryKey: key,
queryFn: () => getPresence({ table, pk }),
queryFn: async () => {
try {
const snapshot = await getPresence({ table, pk })
poll.current = { failures: 0, delay: PRESENCE_INTERVAL_MS }
return snapshot
} catch (error) {
const failures = poll.current.failures + 1
poll.current = { failures, delay: backoffDelay(failures, PRESENCE_BACKOFF) }
throw error
}
},
enabled: enabled && !ended,
refetchInterval: 20000,
// One attempt per poll: the next poll is the retry, and it backs off.
retry: false,
refetchInterval: () => poll.current.delay,
meta: BACKGROUND_REQUEST,
})
useRealtimeChannel(
pk ? `record:${table}:${pk}` : `table:${table}`,
@@ -101,10 +131,20 @@ export function useCollaborationPresence(
let sequence = 0
let generation = 0
let opening = false
let failures = 0
let timer: ReturnType<typeof setTimeout> | undefined
// Every beat schedules the next one: the usual interval after a success, backoff with jitter
// after a failure (a fixed short interval would keep knocking on a server that is recovering).
const schedule = (delay: number) => {
clearTimeout(timer)
if (active && visible) timer = setTimeout(() => void heartbeat(), delay)
}
const heartbeat = async (rejoining = false) => {
if (!active || !visible || opening) return
clearTimeout(timer)
const requestGeneration = generation
let requestSequence = sequence
let next: number = PRESENCE_INTERVAL_MS
try {
if (!connectionId) {
opening = true
@@ -129,6 +169,9 @@ export function useCollaborationPresence(
fieldName: focus.current.fieldName,
})
if (active && visible && generation === requestGeneration && sequence === requestSequence) {
failures = 0
// a renewal carries the snapshot too, so the poll is healthy again as well
poll.current = { failures: 0, delay: PRESENCE_INTERVAL_MS }
setRenewalFailed(false)
cache.setQueryData(queryKeys.collaborationResource(table, pk ?? '', 'presence'), snapshot)
}
@@ -144,17 +187,21 @@ export function useCollaborationPresence(
) {
connectionId = undefined
generation++
if (!rejoining) void heartbeat(true)
// An expired lease is rejoined at once; only a rejoin that fails too backs off.
if (!rejoining) {
void heartbeat(true)
return
}
}
next = backoffDelay(++failures, PRESENCE_BACKOFF)
} finally {
schedule(next)
}
}
refresh.current = () => {
void heartbeat()
}
void heartbeat()
const timer = setInterval(() => {
void heartbeat()
}, 20000)
const release = (beacon: boolean) => {
generation++
opening = false
@@ -172,6 +219,7 @@ export function useCollaborationPresence(
}
const hide = () => {
visible = false
clearTimeout(timer)
release(true)
}
const show = () => {
@@ -186,7 +234,7 @@ export function useCollaborationPresence(
active = false
release(false)
refresh.current = () => undefined
clearInterval(timer)
clearTimeout(timer)
window.removeEventListener('pagehide', hide)
window.removeEventListener('pageshow', show)
document.removeEventListener('visibilitychange', visibility)
@@ -195,12 +243,13 @@ export function useCollaborationPresence(
useEffect(() => {
refresh.current()
}, [editing, fieldName])
const reconnecting = enabled && !ended && (query.isError || renewalFailed)
// the last snapshot the server gave; while reconnecting it may no longer be true, so it is not shown
const known = enabled && !ended ? otherViewers(query.data?.viewers ?? [], userId) : []
return {
...query,
unavailable: enabled && !ended && (query.isError || renewalFailed),
viewers:
enabled && !ended && !query.isError && !renewalFailed
? otherViewers(query.data?.viewers ?? [], userId)
: [],
reconnecting,
hadViewers: reconnecting && known.length > 0,
viewers: reconnecting ? [] : known,
}
}
+6 -2
View File
@@ -20,7 +20,7 @@ import { useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { listJobs } from '@/lib/api/jobs'
import { useUiApiFeatureSupported } from '@/lib/api/ui-api-extensions'
import { queryKeys } from '@/lib/query-client'
import { BACKGROUND_REQUEST, queryKeys } from '@/lib/query-client'
import { useMetaData } from './use-metadata'
import { useRealtimeChannel } from './use-realtime-channel'
import { jobAccessDenied, useJobVisibility } from './use-job-progress'
@@ -41,11 +41,14 @@ export function useJobsInstalled() {
/** Observes a job list with realtime refresh and a ten-second visible-tab fallback.
* @param enabled - Capability/access gate.
* @param filter - Mine by default; admin scope is explicitly requested by the Jobs page.
* @param background - True for the header's count, which is polled on every page: its failures
* raise no error banner. The Jobs page, which the person opened, leaves it false.
* @returns Query state.
*/
export function useMyJobs(
enabled: boolean,
filter: JobListFilter = { scope: 'mine', state: 'all', limit: 20 }
filter: JobListFilter = { scope: 'mine', state: 'all', limit: 20 },
background = false
) {
const visible = useJobVisibility()
const query = useQuery({
@@ -67,6 +70,7 @@ export function useMyJobs(
visible && q.state.data !== null && !jobAccessDenied(q.state.error) ? 10_000 : false,
refetchIntervalInBackground: false,
refetchOnWindowFocus: false,
meta: background ? BACKGROUND_REQUEST : undefined,
})
const { refetch } = query
const denied = query.data === null || jobAccessDenied(query.error)
+56 -12
View File
@@ -142,6 +142,40 @@ export type RecordQueryAction =
| { type: 'TOGGLE_FILTER_PANEL' }
| { type: 'RESET_FILTER' }
| { type: 'APPLY_VIEW'; view: ViewState }
| { type: 'RESTORE_URL'; url: UrlQueryState }
/** The part of the query state the address carries: `page`, `pageSize`, `filter` (with a non-default sort) and `q`. */
export interface UrlQueryState {
pageNum: number
pageSize: PageSize
userFilter: QQueryFilter
sortOrder: QFilterOrderBy[]
quickSearchTerm: string
}
/**
* Reads the query state an address carries, the inverse of the hook's URL sync.
*
* @param params - The address' query parameters.
* @param fallbackPageSize - Page size when the address names none (the sync omits the default).
* @param defaultSort - Sort when the filter carries none (the sync omits the default).
* @param fallbackFilter - Filter when the address carries none; an empty filter by default.
* @returns The state.
*/
export function readUrlQueryState(params: URLSearchParams, fallbackPageSize: PageSize, defaultSort: QFilterOrderBy[], fallbackFilter?: QQueryFilter | null): UrlQueryState {
const pageSizeParam = Number(params.get('pageSize'))
const pageSize: PageSize = (PAGE_SIZE_OPTIONS as readonly unknown[]).includes(pageSizeParam) ? pageSizeParam as PageSize : fallbackPageSize
const filterParam = params.get('filter')
const filter = filterParam ? deserializeFilter(filterParam, pageSize) : fallbackFilter ?? emptyFilter(pageSize)
const pageParam = parseInt(params.get('page') ?? '', 10)
return {
pageNum: Number.isFinite(pageParam) && pageParam > 0 ? pageParam : 1,
pageSize,
userFilter: { ...filter, orderBys: [] },
sortOrder: filter.orderBys?.length ? filter.orderBys : defaultSort,
quickSearchTerm: params.get('q') ?? '',
}
}
/**
* Pure reducer for `RecordQueryState`. Any change to the result set returns to page 1.
@@ -211,13 +245,20 @@ function recordQueryReducer(state: RecordQueryState, action: RecordQueryAction):
selectionMode: 'rows',
subsetSize: null,
}
case 'RESTORE_URL': {
// The address is the source here (a history step), so the page is kept, not reset.
const { url } = action
const unchanged = state.pageNum === url.pageNum && state.pageSize === url.pageSize && state.quickSearchTerm === url.quickSearchTerm
&& JSON.stringify(state.userFilter) === JSON.stringify(url.userFilter) && JSON.stringify(state.sortOrder) === JSON.stringify(url.sortOrder)
return unchanged ? state : { ...state, ...url }
}
default:
return state
}
}
/** Actions after which basic mode is checked against the filter again. */
const BASIC_MODE_ACTIONS: ReadonlySet<RecordQueryAction['type']> = new Set(['SET_USER_FILTER', 'SET_FILTER_MODE', 'APPLY_VIEW', 'RESET_FILTER'])
const BASIC_MODE_ACTIONS: ReadonlySet<RecordQueryAction['type']> = new Set(['SET_USER_FILTER', 'SET_FILTER_MODE', 'APPLY_VIEW', 'RESET_FILTER', 'RESTORE_URL'])
/**
* Keeps basic mode consistent with the filter (Material's
@@ -303,7 +344,7 @@ interface UseRecordQueryOptions {
*
* @param options - Configuration including table name, metadata, page size and variant.
* @returns Grouped state and actions: `pagination`, `filter`, `columns`, `selection`, `data`,
* `joins`, `density`, and `viewState`/`applyView` for saved views.
* `joins`, `density`, `viewState`/`applyView` for saved views, and `restoreFromUrl` for history steps.
*/
export function useRecordQuery({
tableName,
@@ -339,25 +380,19 @@ export function useRecordQuery({
const initialStateRef = useRef<RecordQueryState | null>(null)
if (!initialStateRef.current) {
const isPageSize = (value: unknown): value is PageSize => (PAGE_SIZE_OPTIONS as readonly unknown[]).includes(value)
const pageSizeParam = Number(searchParams.get('pageSize'))
const pageSize: PageSize = isPageSize(pageSizeParam) ? pageSizeParam : isPageSize(initialView?.pageSize) ? initialView.pageSize : initialPageSize
const filterParam = searchParams.get('filter')
const viewPageSize: PageSize = isPageSize(initialView?.pageSize) ? initialView.pageSize : initialPageSize
const pageSize: PageSize = isPageSize(Number(searchParams.get('pageSize'))) ? Number(searchParams.get('pageSize')) as PageSize : viewPageSize
const viewFilter = initialView ? { ...initialView.userFilter, orderBys: initialView.sortOrder, skip: 0, limit: pageSize } : null
const initialFilter = filterParam ? deserializeFilter(filterParam, pageSize) : viewFilter ?? emptyFilter(pageSize)
const pageParam = parseInt(searchParams.get('page') ?? '', 10)
const fromUrl = readUrlQueryState(new URLSearchParams(searchParams.toString()), viewPageSize, defaultSort, viewFilter)
// the mode and added quick filters are remembered per table (Material keeps them in the stored view)
const storedMode = readStored(filterModeKey, (v): v is 'basic' | 'advanced' => v === 'basic' || v === 'advanced')
const storedQuickFilters = readStored(quickFilterFieldsKey, (v): v is string[] => Array.isArray(v) && v.every((name) => typeof name === 'string'))
// Columns: the view's, else what earlier versions stored per table
const legacy = initialView ? null : readLegacyColumnState(tableName)
initialStateRef.current = reconcileState({
pageNum: Number.isFinite(pageParam) && pageParam > 0 ? pageParam : 1,
pageSize,
userFilter: { ...initialFilter, orderBys: [] },
quickSearchTerm: searchParams.get('q') ?? '',
...fromUrl,
filterMode: initialView?.filterMode ?? storedMode ?? 'basic',
quickFilterFieldNames: (initialView?.quickFilterFieldNames ?? storedQuickFilters ?? []).filter((name) => Boolean(tableMetaData && resolveField(tableMetaData, name))),
sortOrder: initialFilter.orderBys?.length ? initialFilter.orderBys : defaultSort,
columnVisibility: initialView?.columnVisibility ?? legacy?.columnVisibility ?? (tableMetaData ? defaultColumnVisibility(tableMetaData) : {}),
columnOrder: initialView?.columnOrder ?? legacy?.columnOrder ?? [],
columnWidths: initialView?.columnWidths ?? legacy?.columnWidths ?? {},
@@ -582,6 +617,14 @@ export function useRecordQuery({
const toggleFilterPanel = useCallback(() => dispatch({ type: 'TOGGLE_FILTER_PANEL' }), [])
const resetFilter = useCallback(() => dispatch({ type: 'RESET_FILTER' }), [])
const applyView = useCallback((view: ViewState) => dispatch({ type: 'APPLY_VIEW', view }), [])
/**
* Takes the filter, sort, quick search, page and page size from an address the browser moved to
* (Back or Forward). Only a history step calls it: the hook's own changes go the other way.
*/
const restoreFromUrl = useCallback(
(search: string) => dispatch({ type: 'RESTORE_URL', url: readUrlQueryState(new URLSearchParams(search), initialPageSize, defaultSort) }),
[initialPageSize, defaultSort]
)
const viewState = useMemo<ViewState>(() => ({
userFilter: state.userFilter,
@@ -654,5 +697,6 @@ export function useRecordQuery({
setDensity,
viewState,
applyView,
restoreFromUrl,
}
}
+30 -3
View File
@@ -22,7 +22,7 @@ import { act, cleanup, render, waitFor } from '@testing-library/react'
import { AxiosError, AxiosHeaders, CanceledError, type InternalAxiosRequestConfig } from 'axios'
import { Toaster, toast } from 'sonner'
import { HANDLES_OWN_ERRORS, queryClient, queryKeys } from './query-client'
import { BACKGROUND_REQUEST, HANDLES_OWN_ERRORS, queryClient, queryKeys } from './query-client'
describe('queryKeys factory', () => {
it('all() returns root key', () => {
@@ -145,9 +145,10 @@ async function failQuery(error: unknown, queryKey: readonly unknown[] = queryKey
* Fails a mutation through the shared client, as a component's `useMutation` would.
*
* @param error - What the mutation function rejects with.
* @param meta - The mutation's meta.
*/
async function failMutation(error: unknown): Promise<void> {
await queryClient.getMutationCache().build(queryClient, { mutationFn: () => Promise.reject(error) }).execute(undefined).catch(() => undefined)
async function failMutation(error: unknown, meta?: Record<string, unknown>): Promise<void> {
await queryClient.getMutationCache().build(queryClient, { mutationFn: () => Promise.reject(error), meta }).execute(undefined).catch(() => undefined)
}
describe('global error banner', () => {
@@ -291,6 +292,32 @@ describe('global error banner', () => {
expect(warn).not.toHaveBeenCalled()
})
it('shows no banner for a background request, whatever failed, and still logs it', async () => {
const PRESENCE = { method: 'get', url: '/qbit/collaboration/presence?table=order' }
const recovering = { status: 503, data: { error: 'Presence is recovering; active viewers are rejoining. Please retry.' } }
await failQuery(axiosError(PRESENCE, recovering), queryKeys.collaborationResource('order', '', 'presence'), BACKGROUND_REQUEST)
await failQuery(axiosError(PRESENCE), queryKeys.collaborationResource('order', '', 'presence'), BACKGROUND_REQUEST)
await failQuery(axiosError(PRESENCE, { status: 403, data: { error: 'Not yours' } }), queryKeys.collaborationResource('order', '', 'presence'), BACKGROUND_REQUEST)
await failMutation(axiosError({ method: 'post', url: '/qbit/collaboration/recents' }, recovering), BACKGROUND_REQUEST)
render(React.createElement(Toaster))
await act(() => new Promise((resolve) => setTimeout(resolve, 20)))
expect(banner).not.toHaveBeenCalled()
expect(shown()).toEqual([])
expect(warn.mock.calls).toEqual([
['[API] Request failed:', { context: 'query', status: 503, code: 'ERR_BAD_REQUEST', name: 'AxiosError', request: 'GET /qqq/v1/qbit/collaboration/presence', area: 'collaboration', background: true }],
['[API] Request failed:', { context: 'query', status: undefined, code: 'ERR_NETWORK', name: 'AxiosError', request: 'GET /qqq/v1/qbit/collaboration/presence', area: 'collaboration', background: true }],
['[API] Request failed:', { context: 'query', status: 403, code: 'ERR_BAD_REQUEST', name: 'AxiosError', request: 'GET /qqq/v1/qbit/collaboration/presence', area: 'collaboration', background: true }],
['[API] Request failed:', { context: 'mutation', status: 503, code: 'ERR_BAD_REQUEST', name: 'AxiosError', request: 'POST /qqq/v1/qbit/collaboration/recents', area: undefined, background: true }],
])
})
it('still shows the banner for the same failure of a request the person started', async () => {
const recovering = { status: 503, data: { error: 'Presence is recovering; active viewers are rejoining. Please retry.' } }
await failQuery(axiosError({ method: 'get', url: '/qbit/collaboration/presence?table=order' }, recovering), queryKeys.collaborationResource('order', '', 'presence'))
expect(banners()).toEqual([['Server error — retrying…', 'GET /qqq/v1/qbit/collaboration/presence (HTTP 503)']])
})
it('logs the technical detail once per failure, without message, body, headers or query string', async () => {
await failQuery(axiosError(QUERY, { status: 409, data: { error: 'Private Person is locked', record: { name: 'Private Person' } } }))
await failQuery(axiosError(QUERY))
+36 -5
View File
@@ -113,11 +113,14 @@ function failureMessage(error: unknown, status: number | undefined, context: 'qu
* 401 responses are silently ignored — the axios interceptor already redirects
* to login, so surfacing a toast would be redundant and confusing.
*
* A background request (see {@link BACKGROUND_REQUEST}) is logged the same way and shows no banner.
*
* @param error - The unknown error thrown by the query or mutation.
* @param context - `'query'` or `'mutation'` — selects message wording.
* @param queryKey - The failed query's key; only its namespace (a word from the code) is read.
* @param background - True for a request the page made on its own; it is logged, never shown.
*/
function handleQueryError(error: unknown, context: 'query' | 'mutation', queryKey?: readonly unknown[]): void {
function handleQueryError(error: unknown, context: 'query' | 'mutation', queryKey?: readonly unknown[], background = false): void {
// A cancelled request (an axios cancel, an aborted `fetch`, or a response discarded because
// the session ended at logout) has no result to report.
if (isCancel(error) || (error as { name?: unknown } | null)?.name === 'AbortError') return
@@ -148,7 +151,10 @@ function handleQueryError(error: unknown, context: 'query' | 'mutation', queryKe
name: error instanceof Error ? error.name : undefined,
request,
area,
...(background ? { background } : {}),
})
// Nothing the person did failed, and the page works without it: no banner.
if (background) return
const sameForEveryRequest = status === undefined && gotNoResponse(error)
toast.error(message, { id: `request-failed:${message}:${sameForEveryRequest ? '' : (description ?? '')}`, description })
@@ -191,7 +197,8 @@ function exponentialBackoff(attemptIndex: number): number {
* - 10-minute GC time keeps recently visited pages snappy when navigating back.
* - Smart query retry: never retries 4xx errors; retries server errors up to 3 times. Mutations are not retried.
* - Global `QueryCache.onError` and `MutationCache.onError` surface toast notifications
* for all unhandled API errors without requiring per-call error handling.
* for all unhandled API errors without requiring per-call error handling, except for
* background requests ({@link BACKGROUND_REQUEST}), which are only logged.
* - Pending queries are included in dehydration so SSR can pass them to the client shell.
*/
/**
@@ -212,16 +219,40 @@ function handlesOwnErrors(meta: Record<string, unknown> | undefined): boolean {
return meta?.handlesOwnErrors === true
}
/**
* Meta flag for a request the page makes on its own, for something the page works without: a
* poll that keeps an indicator fresh (presence, the notification bell, the jobs tray, the
* assistant's unread count) or a write nobody asked for (noting a recently viewed record).
*
* The rule: a background request never raises the global error banner. The person did nothing
* that failed and can do nothing about it, and a poll would raise the banner again on every
* attempt. The failure is still logged to the console, and the indicator it feeds shows its own
* quiet state or nothing until a later attempt succeeds. A request the person started (opening a
* page, saving, running something) is never a background request.
*/
export const BACKGROUND_REQUEST = { backgroundRequest: true } as const
/**
* Whether a query or mutation is a background request.
*
* @param meta - The query or mutation `meta` object.
* @returns `true` when `meta.backgroundRequest` is set.
*/
function isBackgroundRequest(meta: Record<string, unknown> | undefined): boolean {
return meta?.backgroundRequest === true
}
export const queryClient = new QueryClient({
queryCache: new QueryCache({
// Queries that render their own error state (records, widgets) opt out with HANDLES_OWN_ERRORS.
// Queries that render their own error state (records, widgets) opt out with HANDLES_OWN_ERRORS;
// background requests (polls for an indicator) are logged without a banner (BACKGROUND_REQUEST).
onError: (error, query) => {
if (!handlesOwnErrors(query.meta)) handleQueryError(error, 'query', query.queryKey)
if (!handlesOwnErrors(query.meta)) handleQueryError(error, 'query', query.queryKey, isBackgroundRequest(query.meta))
},
}),
mutationCache: new MutationCache({
onError: (error, _variables, _context, mutation) => {
if (!handlesOwnErrors(mutation.meta)) handleQueryError(error, 'mutation')
if (!handlesOwnErrors(mutation.meta)) handleQueryError(error, 'mutation', undefined, isBackgroundRequest(mutation.meta))
},
}),
defaultOptions: {
+47
View File
@@ -0,0 +1,47 @@
/*
* 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.
*/
import { describe, expect, it } from 'vitest'
import { backoffDelay } from './backoff'
const limits = { baseMs: 5_000, maxMs: 60_000 }
describe('backoffDelay', () => {
it('doubles its ceiling per failure, up to the maximum', () => {
const ceilings = [1, 2, 3, 4, 5, 6, 50].map((failures) => backoffDelay(failures, { ...limits, random: () => 1 }))
expect(ceilings).toEqual([5_000, 10_000, 20_000, 40_000, 60_000, 60_000, 60_000])
})
it('waits between half the ceiling and the ceiling', () => {
expect(backoffDelay(3, { ...limits, random: () => 0 })).toBe(10_000)
expect(backoffDelay(3, { ...limits, random: () => 0.5 })).toBe(15_000)
expect(backoffDelay(3, { ...limits, random: () => 0.999 })).toBeLessThanOrEqual(20_000)
})
it('spreads clients that failed at the same moment', () => {
const waits = new Set(Array.from({ length: 50 }, () => backoffDelay(4, limits)))
expect(waits.size).toBeGreaterThan(10)
for (const wait of waits) {
expect(wait).toBeGreaterThanOrEqual(20_000)
expect(wait).toBeLessThanOrEqual(40_000)
}
})
it('treats no failure yet like the first', () => {
expect(backoffDelay(0, { ...limits, random: () => 1 })).toBe(5_000)
})
})
+44
View File
@@ -0,0 +1,44 @@
/*
* 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 backoff — how long a background request waits before it tries again after failing.
*/
/** Limits of a backoff. */
export interface BackoffOptions {
/** Ceiling of the wait after the first failure, in milliseconds. */
baseMs: number
/** Ceiling of any wait, in milliseconds. */
maxMs: number
/** Source of randomness in `[0, 1)`; `Math.random` unless a test fixes it. */
random?: () => number
}
/**
* The wait before the next attempt, after `failures` consecutive failures: a ceiling that doubles
* per failure from `baseMs` up to `maxMs`, of which half is fixed and half is random ("equal
* jitter"). The random half spreads out clients that all failed at the same moment (a server
* restart), so they do not all return at the same moment.
*
* @param failures - Consecutive failures so far (1 after the first).
* @param options - See {@link BackoffOptions}.
* @returns Milliseconds, between half the ceiling and the ceiling.
*/
export function backoffDelay(failures: number, { baseMs, maxMs, random = Math.random }: BackoffOptions): number {
const ceiling = Math.min(maxMs, baseMs * 2 ** Math.max(0, Math.min(failures, 31) - 1))
return Math.round(ceiling / 2 + random() * (ceiling / 2))
}
+53
View File
@@ -0,0 +1,53 @@
/*
* 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.
*/
import { describe, expect, it } from 'vitest'
import { EXPLORE_VIEWS } from './data-analysis-explore'
import { listSearch, TABLE_SUB_VIEWS, tableSubView } from './table-sub-views'
describe('table sub-views', () => {
it('registers every explore view, and the saved analysis viewer', () => {
expect(Object.keys(TABLE_SUB_VIEWS).sort()).toEqual([...EXPLORE_VIEWS, 'saved'].sort())
})
it.each(Object.values(TABLE_SUB_VIEWS))('$name has a label, a back control and its own parameters', (view) => {
expect(TABLE_SUB_VIEWS[view.name]).toBe(view)
expect(view.label.trim()).not.toBe('')
expect(view.backId).toMatch(/-back$/)
expect(view.params.length).toBeGreaterThan(0)
expect(tableSubView(`?view=${view.name}`)).toBe(view)
})
it('opens no sub-view for the list, an unknown view or an inherited property name', () => {
expect(tableSubView('')).toBeUndefined()
expect(tableSubView(null)).toBeUndefined()
expect(tableSubView('?view=tabs')).toBeUndefined()
expect(tableSubView('?view=constructor')).toBeUndefined()
expect(tableSubView(new URLSearchParams({ filter: 'abc' }))).toBeUndefined()
})
it.each(Object.values(TABLE_SUB_VIEWS))('the list behind $name keeps filter, sort, page and search', (view) => {
const params = new URLSearchParams({ page: '3', pageSize: '50', filter: 'abc', q: 'smith', from: '/app/home', view: view.name })
for (const name of view.params) params.set(name, 'layout')
expect(listSearch(params)).toBe('?page=3&pageSize=50&filter=abc&q=smith&from=%2Fapp%2Fhome')
expect(listSearch(`?${params}`)).toBe('?page=3&pageSize=50&filter=abc&q=smith&from=%2Fapp%2Fhome')
})
it('leaves nothing of one view behind when another view was in the address', () => {
expect(listSearch('?view=pivot&pivot=a&correlation=b&saved=7')).toBe('')
})
})
+87
View File
@@ -0,0 +1,87 @@
/*
* 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 table-sub-views — the views of a table's record list that are selected by the query
* string (`?view=pivot`, `?view=correlation`, `?view=saved&saved=7`) instead of a path.
*
* A sub-view replaces the list on the same route, so nothing in the path says it is open. This
* registry is the one place that does: the record list opens a view only through it, the
* breadcrumb reads it to show the view as the current page and the table as a link back, and the
* tests walk it, so a view cannot be added without a label and a way back.
*/
import { EXPLORE_LABELS, EXPLORE_VIEWS } from './data-analysis-explore'
/** The query parameter that names the open sub-view. */
export const TABLE_SUB_VIEW_PARAM = 'view'
/** Name of a sub-view: every explore view, and the saved analysis viewer. */
export type TableSubViewName = (typeof EXPLORE_VIEWS)[number] | 'saved'
/** One sub-view of a table's record list. */
export interface TableSubView {
/** Value of the `view` parameter. */
name: TableSubViewName
/** The breadcrumb's label for the view. */
label: string
/** Query parameters that belong to the view (its layout or id), dropped with it on the way back. */
params: readonly string[]
/** `data-qqq-id` of the control inside the view that returns to the list. */
backId: string
}
/**
* Every sub-view, by name. The key type makes a new explore view a compile error until it is
* registered here.
*/
export const TABLE_SUB_VIEWS: Record<TableSubViewName, TableSubView> = {
pivot: { name: 'pivot', label: EXPLORE_LABELS.pivot, params: ['pivot'], backId: 'pivot-back' },
compare: { name: 'compare', label: EXPLORE_LABELS.compare, params: ['compare'], backId: 'explore-back' },
correlation: { name: 'correlation', label: EXPLORE_LABELS.correlation, params: ['correlation'], backId: 'explore-back' },
crosstab: { name: 'crosstab', label: EXPLORE_LABELS.crosstab, params: ['crosstab'], backId: 'explore-back' },
shift: { name: 'shift', label: EXPLORE_LABELS.shift, params: ['shift'], backId: 'explore-back' },
saved: { name: 'saved', label: 'Saved analysis', params: ['saved'], backId: 'saved-back' },
}
/** Every parameter a sub-view can own, including `view` itself. */
const SUB_VIEW_PARAMS = [TABLE_SUB_VIEW_PARAM, ...new Set(Object.values(TABLE_SUB_VIEWS).flatMap((view) => view.params))]
/**
* The sub-view a query string opens, if any. An unknown `view` value opens none (a record page
* uses `view=tabs` for its own layout).
*
* @param search - The query string or its parameters.
* @returns The sub-view, or undefined when the list itself is shown.
*/
export function tableSubView(search: URLSearchParams | string | null | undefined): TableSubView | undefined {
const name = new URLSearchParams(search ?? '').get(TABLE_SUB_VIEW_PARAM)
return name !== null && Object.prototype.hasOwnProperty.call(TABLE_SUB_VIEWS, name) ? TABLE_SUB_VIEWS[name as TableSubViewName] : undefined
}
/**
* The query string of the list behind a sub-view: the same parameters (filter, sort, page, page
* size, quick search and anything else) without the view's own.
*
* @param search - The current query string or its parameters.
* @returns The list's query string, with a leading `?` unless it is empty.
*/
export function listSearch(search: URLSearchParams | string | null | undefined): string {
const params = new URLSearchParams(search ?? '')
for (const name of SUB_VIEW_PARAMS) params.delete(name)
const rest = params.toString()
return rest ? `?${rest}` : ''
}
+38
View File
@@ -170,17 +170,43 @@ export interface AssistantHistoryRender {
entries: AssistantHistoryEntry[]
}
/** One record of the set a card acts on: its name and, when it has one, its link into the application. */
export interface AssistantPendingActionRecord {
id: string | number
/** The record's name; its id when it has no other. */
label: string
/** An `/app` link to the record; absent when the card names no table. */
href?: string
}
/** A write the assistant proposed; nothing changes until the user confirms it. */
export interface AssistantPendingActionRender {
type: 'pending_action'
actionId: number
toolName: 'create_record' | 'update_record' | 'delete_record'
/**
* What is proposed: `record_create`, `record_update`, `record_delete`, `process_run`, or the
* proposing tool's name. A process run arrives with `toolName: 'update_record'` and its real
* kind here. Absent from an older server.
*/
actionKind?: string
/** A process run: the process, and its label. */
processName?: string
processLabel?: string
tableName: string
tableLabel: string
recordId?: string | null
summary: string
changes: Array<{ field: string; label: string; value: string | null }>
href?: string
/** A run over a set of records: how many records it acts on. */
recordCount?: number
/**
* A run over a set of records: every record of the set (the server allows at most 500), in the
* order the card's own lines name the first few. Absent or empty for a change to one record and
* from an older server.
*/
records?: AssistantPendingActionRecord[]
}
/** A pending action's state on the server. */
@@ -198,6 +224,18 @@ export interface AssistantPendingAction {
outcome?: string
message?: string
href?: string
/** A run over a set of records: how many, and every record of the set (as on the render). */
recordCount?: number | null
records?: AssistantPendingActionRecord[] | null
/**
* A run over a set of records: what was kept of them as they were when the run was proposed
* (a capped sample of their values, as the user may see them).
*/
recordsBefore?: {
count: number
sampleCap: number
sample: Array<{ id: string | number; label: string; values: Record<string, unknown> }>
} | null
}
/**
+130
View File
@@ -0,0 +1,130 @@
/*
* 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
*/
// The record audit dialog with a 64 character record identifier: every control stays inside the
// dialog's card at phone to desktop widths in both themes, an empty history is one block, and
// opening and re-sorting ask the server once.
import AxeBuilder from '@axe-core/playwright'
import { expect, test, type Page } from '@playwright/test'
import { METADATA, setupApiMocks } from './api-mocks'
const LONG_ID = 'a3f9c2e17b5d4086a3f9c2e17b5d4086a3f9c2e17b5d4086a3f9c2e17b5d4086'
const DIALOG = '[data-qqq-id="audit-history-dialog"]'
const CONTROLS = ['button-audit-copy-record', 'button-audit-sort-ascending', 'button-audit-sort-descending', 'button-close-audit-history']
const audit = (id: number, day: number, detail: number) => ({
tableName: 'audit',
values: {
id, recordId: 1, message: 'Record was Edited', timestamp: `2026-01-${String(day).padStart(2, '0')}T10:00:00Z`, auditUserId: 3,
'auditDetail.id': detail, 'auditDetail.fieldName': 'email', 'auditDetail.message': `Changed Email from "a${detail}@example.com" to "b${detail}@example.com"`,
},
displayValues: { auditUserId: 'Alice (sample)', auditTableId: 'People' },
})
/**
* Serves the record with a long label and the audit process with the given rows.
*
* @param page - The page.
* @param audits - Rows the process answers with (newest first).
* @returns The audit requests made so far.
*/
async function mockAudits(page: Page, audits: unknown[]) {
await setupApiMocks(page)
const auditProcess = { ...METADATA.processes.importData, name: 'GetAuditsForRecord', label: 'Audits', isHidden: true, frontendSteps: [] }
await page.route((url) => url.pathname === '/qqq/v1/metaData', (route) =>
route.fulfill({ json: { ...METADATA, processes: { ...METADATA.processes, GetAuditsForRecord: auditProcess } } })
)
await page.route(/\/qqq\/v1\/table\/person\/1(\?|$)/, async (route) => {
if (route.request().method() !== 'GET') return route.fallback()
const response = await route.fetch().catch(() => null)
const body = response ? await response.json().catch(() => null) : null
const record = body?.record ?? { tableName: 'person', values: { id: 1 } }
return route.fulfill({ json: { record: { ...record, recordLabel: LONG_ID } } })
})
const requests: Record<string, unknown>[] = []
await page.route('**/qqq/v1/processes/GetAuditsForRecord/init**', (route) => {
const values = /name="values"\r?\n\r?\n([^\r\n]+)/.exec(route.request().postData() ?? '')?.[1]
const stepTimeoutMillis = /name="stepTimeoutMillis"\r?\n\r?\n([^\r\n]+)/.exec(route.request().postData() ?? '')?.[1]
const sent = { ...(values ? JSON.parse(values) : {}), stepTimeoutMillis }
requests.push(sent)
return route.fulfill({ json: { type: 'COMPLETE', values: { audits: sent.isSortAscending ? [...audits].reverse() : audits } } })
})
return requests
}
/**
* Whether every box lies inside the outer one.
*
* @param page - The page.
* @returns Names of the controls that leave the dialog's card.
*/
async function controlsOutside(page: Page): Promise<string[]> {
const card = (await page.locator(DIALOG).boundingBox())!
const outside: string[] = []
for (const id of [...CONTROLS, 'audit-history-title', 'audit-history-status']) {
const box = (await page.locator(`${DIALOG} [data-qqq-id="${id}"]`).boundingBox())!
const inside = box.x >= card.x - 0.5 && box.y >= card.y - 0.5 && box.x + box.width <= card.x + card.width + 0.5 && box.y + box.height <= card.y + card.height + 0.5
if (!inside) outside.push(id)
}
return outside
}
for (const width of [320, 390, 768, 1440])
test(`audit dialog keeps a 64 character identifier and its controls inside the card at ${width}px, light and dark`, async ({ page }) => {
await page.setViewportSize({ width, height: 800 })
await mockAudits(page, [])
await page.goto('/app/person/1')
await page.locator('[data-qqq-id="button-audit"]').click()
const dialog = page.locator(DIALOG)
await expect(dialog).toBeVisible()
await expect(dialog.getByRole('heading', { level: 2 })).toHaveAttribute('title', `Audit for People: ${LONG_ID}`)
const status = dialog.locator('[data-qqq-id="audit-history-status"]')
await expect(status).toHaveText('No audits were found for this record.')
for (const dark of [false, true]) {
await page.evaluate((value) => document.documentElement.classList.toggle('dark', value), dark)
expect(await controlsOutside(page)).toEqual([])
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)
// the dialog does not scroll sideways, and its heading is not wider than the card
expect(await dialog.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true)
// The empty state is one block: the icon sits inside the status, above its sentence, and
// nothing follows it in the card
const icon = (await status.locator('svg').boundingBox())!
const block = (await status.boundingBox())!
expect(icon.y).toBeGreaterThanOrEqual(block.y)
expect(icon.y + icon.height).toBeLessThanOrEqual(block.y + block.height)
expect(icon.height).toBeLessThanOrEqual(28)
expect(await dialog.evaluate((element) => element.lastElementChild?.getAttribute('data-qqq-id'))).toBe('audit-history-status')
expect(await dialog.locator('svg').count()).toBe(CONTROLS.length + 1)
expect((await new AxeBuilder({ page }).include(DIALOG).withTags(['wcag2a', 'wcag2aa', 'wcag21aa']).analyze()).violations).toEqual([])
}
})
test('audit dialog asks the server once to open and not again to re-sort a complete history', async ({ page }) => {
const rows = [audit(3, 5, 31), audit(3, 5, 32), audit(2, 4, 21), audit(1, 3, 11)]
const requests = await mockAudits(page, rows)
await page.goto('/app/person/1')
await page.locator('[data-qqq-id="button-audit"]').click()
const dialog = page.locator(DIALOG)
await expect(dialog.locator('[data-qqq-id="audit-history-status"]')).toHaveText('Showing all 3 audits for this record')
const order = () => dialog.locator('[data-qqq-id^="audit-entry-"][data-qqq-id$="1"], [data-qqq-id^="audit-entry-"][data-qqq-id$="2"], [data-qqq-id^="audit-entry-"][data-qqq-id$="3"]')
.evaluateAll((entries) => entries.map((entry) => entry.getAttribute('data-qqq-id')).filter((id) => /^audit-entry-\d+$/.test(id ?? '')))
expect(await order()).toEqual(['audit-entry-3', 'audit-entry-2', 'audit-entry-1'])
expect(requests).toHaveLength(1)
expect(requests[0]).toMatchObject({ tableName: 'person', recordId: '1', isSortAscending: false, limit: 1000 })
expect(Number(requests[0].stepTimeoutMillis)).toBeGreaterThan(3000)
await dialog.getByRole('button', { name: 'Sort by time ascending (oldest to newest)' }).click()
await expect.poll(order).toEqual(['audit-entry-1', 'audit-entry-2', 'audit-entry-3'])
await dialog.getByRole('button', { name: 'Sort by time descending (newest to oldest)' }).click()
await expect.poll(order).toEqual(['audit-entry-3', 'audit-entry-2', 'audit-entry-1'])
await page.waitForTimeout(300)
expect(requests).toHaveLength(1)
expect(await controlsOutside(page)).toEqual([])
})
@@ -37,7 +37,7 @@ async function openRecord(page: Page) {
})
await expect(page.locator('[data-qqq-id="record-view-title-person"]')).toHaveText('Alice Johnson')
await expect(page.locator('[data-qqq-id="presence-sam"]')).toBeVisible()
await expect(page.getByText('Presence temporarily unavailable', { exact: true })).toHaveCount(0)
await expect(page.locator('[data-qqq-id="presence-reconnecting"]')).toHaveCount(0)
}
async function concurrentEdit(page: Page) {
await page.evaluate(async () => {
+64
View File
@@ -262,3 +262,67 @@ test('Explore is absent without the capability', async ({ page }) => {
await expect(page.getByRole('button', { name: 'Toggle advanced filter panel' })).toBeVisible()
await expect(page.getByRole('button', { name: 'Explore', exact: true })).toHaveCount(0)
})
// Every relationship view leaves three ways back to the list it was opened from: the browser's
// Back button, its own "Back to records" button and the table's breadcrumb. Each returns the list
// with its filter and page as they were.
const VIEW_LABELS = {
compare: 'Compare',
correlation: 'Correlation',
crosstab: 'Crosstab',
shift: 'Shift over time',
} as const
for (const view of ['compare', 'correlation', 'crosstab', 'shift'] as const)
test(`${view} leaves a way back: browser Back, Back to records and the breadcrumb`, async ({
page,
}) => {
await mockRelationships(page)
const filter = Buffer.from(JSON.stringify(baseFilter)).toString('base64')
await page.goto(`/app/person?${new URLSearchParams({ filter, page: '2' })}`)
const crumbs = page.getByRole('navigation', { name: 'Breadcrumb', exact: true })
const current = crumbs.locator('[aria-current="page"]')
const list = page.locator('[data-qqq-id="record-query-person"]')
const explorer = page.locator(`[data-qqq-id="${view}-explorer"]`)
const address = () => {
const params = new URL(page.url()).searchParams
const encoded = params.get('filter')
return {
view: params.get('view'),
layout: params.has(view),
page: params.get('page'),
criteria: encoded ? JSON.parse(Buffer.from(encoded, 'base64').toString()).criteria : null,
}
}
const asLeft = { view: null, layout: false, page: '2', criteria: baseFilter.criteria }
const backAtList = async () => {
await expect(explorer).toHaveCount(0)
await expect(list).toBeVisible()
await expect(current).toHaveText('People')
await expect.poll(address).toEqual(asLeft)
}
await expect(list).toBeVisible()
await backAtList()
// The breadcrumb follows the view; the table becomes a link
await build(page, view)
await expect(current).toHaveText(VIEW_LABELS[view])
await expect(crumbs.getByRole('link', { name: 'People', exact: true })).toBeVisible()
expect(address()).toMatchObject({ view, layout: true, page: '2' })
// Browser Back, after the view ran
await page.goBack()
await backAtList()
// The view's own button is one step back too, so the view stays one Forward away
await page.goForward()
await expect(explorer).toBeVisible()
await explorer.getByRole('button', { name: 'Back to records' }).click()
await backAtList()
await page.goForward()
await expect(explorer).toBeVisible()
await expect(current).toHaveText(VIEW_LABELS[view])
// The table's breadcrumb
await crumbs.getByRole('link', { name: 'People', exact: true }).click()
await backAtList()
})
+47
View File
@@ -118,6 +118,53 @@ test('browser Back returns to the grid and Forward restores the layout', async (
await expect(page.locator(EXPLORER).getByRole('link', { name: '14', exact: true })).toBeVisible()
})
test('pivot leaves a way back: browser Back, Back to records and the breadcrumb', async ({
page,
}) => {
await mockPivot(page)
const filter = Buffer.from(JSON.stringify(baseFilter)).toString('base64')
await page.goto(`/app/person?${new URLSearchParams({ filter, page: '2' })}`)
const crumbs = page.getByRole('navigation', { name: 'Breadcrumb', exact: true })
const current = crumbs.locator('[aria-current="page"]')
const explorer = page.locator(EXPLORER)
const address = () => {
const params = new URL(page.url()).searchParams
const encoded = params.get('filter')
return {
view: params.get('view'),
layout: params.has('pivot'),
page: params.get('page'),
criteria: encoded ? JSON.parse(Buffer.from(encoded, 'base64').toString()).criteria : null,
}
}
const backAtList = async () => {
await expect(explorer).toHaveCount(0)
await expect(page.locator('[data-qqq-id="record-query-person"]')).toBeVisible()
await expect(current).toHaveText('People')
await expect
.poll(address)
.toEqual({ view: null, layout: false, page: '2', criteria: baseFilter.criteria })
}
await backAtList()
await buildPivot(page)
await expect(current).toHaveText('Pivot')
await expect(crumbs.getByRole('link', { name: 'People', exact: true })).toBeVisible()
await page.goBack()
await backAtList()
// The pivot's own button is one step back too, so the pivot stays one Forward away
await page.goForward()
await expect(explorer).toBeVisible()
await explorer.getByRole('button', { name: 'Back to records' }).click()
await backAtList()
await page.goForward()
await expect(explorer).toBeVisible()
await crumbs.getByRole('link', { name: 'People', exact: true }).click()
await backAtList()
})
for (const width of [390, 768, 1440]) {
test(`pivot stays within ${width}px and passes axe in both themes`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 })
+89
View File
@@ -0,0 +1,89 @@
/*
* 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 history-navigation — a `next/navigation` stand-in for unit tests whose hooks follow the
* address, as the App Router's do: `usePathname` and `useSearchParams` re-render after
* `history.pushState`, `history.replaceState` and a Back or Forward step, and nothing is
* remounted. Use it for components whose state lives in the query string:
*
* ```ts
* vi.mock('next/navigation', async () => (await import('../../../tests/helpers/history-navigation')).historyNavigation)
* ```
*/
import { useMemo, useSyncExternalStore } from 'react'
const listeners = new Set<() => void>()
const notify = () => listeners.forEach((listener) => listener())
let installed = false
/** Makes every write to the history, and every traversal, tell the hooks. Idempotent. */
function install(): void {
if (installed) return
installed = true
for (const method of ['pushState', 'replaceState'] as const) {
const original = window.history[method].bind(window.history)
window.history[method] = (...args: Parameters<History['pushState']>) => {
original(...args)
notify()
}
}
window.addEventListener('popstate', notify)
}
/**
* Subscribes a hook to address changes.
*
* @param listener - Called after every change.
* @returns The unsubscribe function.
*/
function subscribe(listener: () => void): () => void {
install()
listeners.add(listener)
return () => listeners.delete(listener)
}
/**
* Moves to an address as a router navigation would: a new history entry, and the hooks follow.
*
* @param href - Path and query string.
*/
function push(href: string): void {
install()
window.history.pushState(null, '', href)
}
/**
* Replaces the current address as a router navigation would.
*
* @param href - Path and query string.
*/
function replace(href: string): void {
install()
window.history.replaceState(null, '', href)
}
/** The module to return from `vi.mock('next/navigation', ...)`. */
export const historyNavigation = {
useRouter: () => ({ push, replace, back: () => window.history.back(), forward: () => window.history.forward(), refresh: () => undefined, prefetch: () => undefined }),
usePathname: () => useSyncExternalStore(subscribe, () => window.location.pathname),
useSearchParams: () => {
const search = useSyncExternalStore(subscribe, () => window.location.search)
return useMemo(() => new URLSearchParams(search), [search])
},
redirect: (href: string) => replace(href),
}