Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5694671227
|
||
|
|
787a227602
|
||
|
|
30f4f9d586
|
||
|
|
24bbe4a038
|
||
|
|
8903f272c4
|
||
|
|
2345039911
|
||
|
|
4347924658
|
||
|
|
523f59cf38
|
||
|
|
fefd5be0d4
|
||
|
|
c0e5b285db
|
||
|
|
42b509f35c
|
||
|
|
37c4234324
|
||
|
|
412d884402
|
||
|
|
27e8754f32
|
||
|
|
00c00b0e71
|
||
|
|
3a72c8b88a
|
||
|
|
46e9f1212c | ||
|
|
bfcc008ca2 | ||
|
|
fdf12d3c40 | ||
|
|
04ab9ad6c9 | ||
|
|
70618bd143 | ||
|
|
aaa77d7e6e | ||
|
|
73b1ea16d7 | ||
|
|
94726bb52c | ||
|
|
56ab7fe21c | ||
|
|
0f2eb173c1 | ||
|
|
22f5749e36 | ||
|
|
090f5febea
|
||
|
|
afb9d75c75
|
||
|
|
119f1211d0
|
||
|
|
aba43263b2 | ||
|
|
ddc7de731b | ||
|
|
3d162dce74
|
||
|
|
d186ad7086 | ||
|
|
2186561950 | ||
|
|
40ee257847 | ||
|
|
b67fb5fd20 | ||
|
|
d04cfa4b58
|
||
|
|
94424b3f46
|
||
|
|
e31716aa52 | ||
|
|
9756b9d93b | ||
|
|
f205992878 | ||
|
|
5f503fa7e9 | ||
|
|
09828ab1cc | ||
|
|
c39748b1a0 | ||
|
|
829ef6b384 | ||
|
|
a94e1e39c8 | ||
|
|
9bea8cc63f | ||
|
|
ada9946eea | ||
|
|
fa960580f6
|
||
|
|
596bee88cc | ||
|
|
df764362b8 | ||
|
|
07b4a973de
|
||
|
|
e36afde222 | ||
|
|
69836fc62f
|
||
|
|
3cb3659a41 | ||
|
|
b30ff4e916
|
||
|
|
d558c1378d
|
||
|
|
f1c5f09b4a | ||
|
|
c9a56b0d9f
|
||
|
|
3bab5596ab
|
||
|
|
ae2498868d
|
||
|
|
ea21505e96
|
||
|
|
1b37e5efa9 | ||
|
|
ba20307fa0
|
||
|
|
81a03eab2d | ||
|
|
ab9cf837df
|
||
|
|
5c9307015c
|
||
|
|
55c150136b | ||
|
|
d644995c85
|
||
|
|
6f95554362
|
||
|
|
ba38367244 | ||
|
|
c623b3bc87
|
||
|
|
17f605261a | ||
|
|
0db8ab0bfa
|
||
|
|
68a2b9de0c | ||
|
|
af42c7613f
|
||
|
|
f5170ed130
|
||
|
|
77fc832f9e
|
||
|
|
627ad7ae34
|
||
|
|
03f67def30
|
||
|
|
cc64297d83
|
||
|
|
1d7c1a5ebf
|
||
|
|
960538ebc0 | ||
|
|
67eca54900
|
||
|
|
b4b59cee6e | ||
|
|
28fdb2a781 | ||
|
|
524adff0d5
|
||
|
|
893bbf26df
|
||
|
|
1df522097f
|
||
|
|
f5a56eaf7e
|
||
|
|
9b475797a0
|
||
|
|
5283503e89
|
||
|
|
bb9e083539
|
||
|
|
d5003ebdd5
|
||
|
|
9a63173efe | ||
|
|
93e0fd7303
|
||
|
|
b24b74e30d | ||
|
|
ea028dc86f
|
||
|
|
3e5b097667
|
||
|
|
98229202f3
|
||
|
|
9df3324687
|
||
|
|
ae6649f8e1 | ||
|
|
a504a21718
|
||
|
|
9aff198a60 | ||
|
|
2d125e4f90
|
||
|
|
ec974fa121
|
||
|
|
4f1641cb72
|
||
|
|
154be4f827
|
||
|
|
04fc4d7692
|
||
|
|
81fa126305
|
||
|
|
1fc984a3c6
|
||
|
|
a5fb8dd8d5
|
||
|
|
692d0cb166 | ||
|
|
e9208fc34c | ||
|
|
2cbfb6d962 | ||
|
|
b2a41b3eb9
|
||
|
|
35d937ed30 | ||
|
|
a00473c305
|
||
|
|
e76f0325a5
|
||
|
|
de1d4a5295
|
||
|
|
42ee6b87ce
|
||
|
|
a73e4e245c
|
||
|
|
e0ca5b1bb4
|
||
|
|
c9773cf45f
|
||
|
|
15cdffe7f3
|
||
|
|
41462cc4f6
|
||
|
|
039fa56a0b
|
||
|
|
f93a1d3c8f
|
||
|
|
600af361f4
|
||
|
|
0969231c95
|
||
|
|
99170dbff8
|
||
|
|
74cf6e88d7
|
||
|
|
0f6c37c998 | ||
|
|
4306da9cdd
|
||
|
|
abfbbb2e55 | ||
|
|
4139316789
|
||
|
|
aa0bc65774
|
||
|
|
86b54181f7 | ||
|
|
b32141cf65
|
||
|
|
16699aedfa | ||
|
|
e0ff899cb6
|
||
|
|
e807d30209
|
||
|
|
11d0f34639
|
||
|
|
45928e8abf
|
||
|
|
1a381c2a68
|
||
|
|
ee3682e859 | ||
|
|
62ec386035
|
||
|
|
427a037d53 | ||
|
|
2381579a52
|
||
|
|
112bbc557a | ||
|
|
463e9cc8e9
|
||
|
|
20fd1fa3d3 | ||
|
|
4f685d200b
|
||
|
|
9fc9cab48f
|
||
|
|
aafeabfb33
|
||
|
|
b19d4c09b4
|
||
|
|
e434716cbd
|
||
|
|
4bd2c95d01
|
||
|
|
34efebb434
|
||
|
|
439c4b00e4
|
||
|
|
f95baaf8c7
|
||
|
|
9d2ece4228
|
||
|
|
46436866be
|
No files matched your search
@@ -1,80 +1,14 @@
|
||||
version: 2.1
|
||||
|
||||
setup: true
|
||||
orbs:
|
||||
qqq-orb: kingsrook/qqq-orb@0.6
|
||||
|
||||
# ─── Jobs ────────────────────────────────────────────────────────────────────
|
||||
# The dashboard jar (static export under next-dashboard/) is published to Maven
|
||||
# Central on release tags, with the same orb commands and credentials as the
|
||||
# Material Dashboard. QApplicationJavalinServer serves it at / when it is present.
|
||||
|
||||
commands:
|
||||
configure-package-install:
|
||||
steps:
|
||||
- run:
|
||||
name: Keep package installation unattended
|
||||
command: |
|
||||
# These build machines are discarded after the job; avoid the interactive needrestart prompt.
|
||||
sudo sed -i 's|http://security.ubuntu.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' /etc/apt/sources.list
|
||||
sudo install -d /etc/needrestart/conf.d
|
||||
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
|
||||
|
||||
jobs:
|
||||
publish_dashboard_jar:
|
||||
executor: qqq-orb/java
|
||||
steps:
|
||||
- configure-package-install
|
||||
- checkout
|
||||
- qqq-orb/install_java:
|
||||
install_node: true
|
||||
node_version: "22"
|
||||
- run:
|
||||
name: Verify the immutable release version
|
||||
command: |
|
||||
release_version="${CIRCLE_TAG#v}"
|
||||
frontend_version=$(node -p "require('./package.json').version")
|
||||
maven_version=$(mvn -B -q help:evaluate -Dexpression=project.version -DforceStdout)
|
||||
test "$frontend_version" = "$release_version"
|
||||
test "$maven_version" = "$release_version"
|
||||
- run:
|
||||
name: Build the static export
|
||||
command: |
|
||||
corepack enable
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test
|
||||
pnpm build:export
|
||||
- qqq-orb/mvn_jar_deploy
|
||||
|
||||
# ─── Workflows ───────────────────────────────────────────────────────────────
|
||||
# Trunk-based: main is the only long-lived branch (see CONTRIBUTING.md).
|
||||
# test_only → every branch except main (the PR check ci/circleci: qqq-orb/node_app_test_only)
|
||||
# publish_release → main builds; v* version tags publish the dashboard jar
|
||||
|
||||
qqq-orb: kingsrook/qqq-orb@0.8
|
||||
workflows:
|
||||
|
||||
test_only:
|
||||
setup:
|
||||
jobs:
|
||||
- qqq-orb/node_app_test_only:
|
||||
filters:
|
||||
branches:
|
||||
ignore: main
|
||||
tags:
|
||||
only: []
|
||||
|
||||
publish_release:
|
||||
jobs:
|
||||
- qqq-orb/node_app_build:
|
||||
filters:
|
||||
branches:
|
||||
only: [ main ]
|
||||
tags:
|
||||
only: [ /v.*/ ]
|
||||
- publish_dashboard_jar:
|
||||
context: [qqq-maven-registry-credentials]
|
||||
filters:
|
||||
branches:
|
||||
ignore: /.*/
|
||||
tags:
|
||||
only: /^v[0-9]+\.[0-9]+\.[0-9]+(-RC\.[0-9]+)?$/
|
||||
- qqq-orb/generate_pipeline:
|
||||
orb_version: '0.8'
|
||||
filters:
|
||||
branches:
|
||||
ignore: /.*/
|
||||
tags:
|
||||
only: /.*/
|
||||
@@ -6,3 +6,5 @@ playwright-report
|
||||
coverage
|
||||
.env*
|
||||
*.log
|
||||
|
||||
.pnpm-store
|
||||
@@ -0,0 +1 @@
|
||||
dynamic-components/** -text
|
||||
@@ -0,0 +1,13 @@
|
||||
# Copyright 2026 QRun.IO, Inc.
|
||||
# Licensed under the Apache License, Version 2.0.
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
jobs:
|
||||
maven:
|
||||
uses: self:KofTwentyTwo/ci-workflows/.gitea/workflows/maven.yaml@v1
|
||||
secrets: inherit
|
||||
with:
|
||||
node-version: '22.20.0'
|
||||
prebuild: corepack enable && pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint && pnpm test && pnpm build:export
|
||||
@@ -1,281 +0,0 @@
|
||||
name: Real-backend acceptance
|
||||
|
||||
# One production build feeds independent, serial-worker backends. Require "acceptance gate".
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled, unlabeled]
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
qqq_ref:
|
||||
description: QRun-IO/qqq branch or tag to build the sample backend from
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: acceptance-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
QQQ_REF: ${{ inputs.qqq_ref || vars.QQQ_ACCEPTANCE_REF || 'develop' }}
|
||||
NEXT_TELEMETRY_DISABLED: '1'
|
||||
MAVEN_ARGS: -Dmaven.wagon.http.retryHandler.count=5 -Daether.transport.http.retryHandler.count=5 -Daether.connector.http.retryHandler.count=5
|
||||
|
||||
jobs:
|
||||
plan:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
mode: ${{ steps.select.outputs.mode }}
|
||||
matrix: ${{ steps.select.outputs.matrix }}
|
||||
specs: ${{ steps.select.outputs.specs }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Select projects, shards and changed areas
|
||||
id: select
|
||||
run: node scripts/acceptance-select.mjs
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: QRun-IO/qqq
|
||||
ref: ${{ env.QQQ_REF }}
|
||||
path: qqq-backend
|
||||
- name: Resolve QQQ source revision
|
||||
id: qqq
|
||||
run: echo "sha=$(git -C qqq-backend rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
cache: maven
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
id: qqq-cache
|
||||
with:
|
||||
path: ~/.m2/repository/com/kingsrook
|
||||
key: qqq-source-${{ runner.os }}-java21-v1-${{ steps.qqq.outputs.sha }}
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Bundled UI API document matches the server's (src/lib/api/openapi/qqq-v1.json)
|
||||
run: node scripts/check-ui-api-spec.mjs --server-spec qqq-backend/qqq-middleware-javalin/src/main/resources/openapi/v1/openapi.yaml
|
||||
- name: Build QQQ from source
|
||||
if: steps.qqq-cache.outputs.cache-hit != 'true'
|
||||
run: bash scripts/ci/retry.sh 4 mvn -B -q -f qqq-backend/pom.xml install -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true
|
||||
- name: Build and install the dashboard jar (static export)
|
||||
run: |
|
||||
# Equivalent to build:jar, with retries around its Maven invocation too.
|
||||
pnpm build:export
|
||||
bash scripts/ci/retry.sh 4 mvn -B -q clean package
|
||||
bash scripts/ci/retry.sh 4 mvn -B -q install
|
||||
# Failed-attempt Maven stdout must not become part of the version value.
|
||||
bash scripts/ci/retry.sh 4 mvn -B -q help:evaluate -Dexpression=project.version -Doutput="$RUNNER_TEMP/acceptance-next-version"
|
||||
next_version=$(cat "$RUNNER_TEMP/acceptance-next-version")
|
||||
echo "NEXT_JAR_VERSION=$next_version" >> "$GITHUB_ENV"
|
||||
- name: Build the sample application jar
|
||||
working-directory: qqq-backend
|
||||
run: |
|
||||
# QQQ checkstyle/pmd paths are relative to this checkout.
|
||||
bash "$GITHUB_WORKSPACE/scripts/ci/retry.sh" 4 mvn -B -q -f qqq-sample-project/pom.xml package -DskipTests -Djacoco.skip=true \
|
||||
-Dqqq.frontend.next.version="$NEXT_JAR_VERSION"
|
||||
- name: Stage runtime artifacts
|
||||
run: |
|
||||
sample_jars=(qqq-backend/qqq-sample-project/target/*-jar-with-dependencies.jar)
|
||||
test "${#sample_jars[@]}" -eq 1
|
||||
sample_version="${sample_jars[0]##*/}"
|
||||
sample_version="${sample_version#qqq-sample-project-}"
|
||||
sample_version="${sample_version%-jar-with-dependencies.jar}"
|
||||
mkdir -p test-results/acceptance-jars
|
||||
cp "${sample_jars[0]}" test-results/acceptance-jars/
|
||||
# javac and the security fixture need the API JAR in addition to the fat sample JAR.
|
||||
cp "$HOME/.m2/repository/com/kingsrook/qqq/qqq-middleware-api/$sample_version/qqq-middleware-api-$sample_version.jar" \
|
||||
test-results/acceptance-jars/qqq-middleware-api.jar
|
||||
tar -cf test-results/acceptance-build.tar out test-results/acceptance-jars
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: acceptance-build
|
||||
path: test-results/acceptance-build.tar
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
shards:
|
||||
name: acceptance ${{ matrix.project }} ${{ matrix.shard }}/${{ matrix.total }}
|
||||
needs: [plan, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
cache: maven
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Installed Playwright version
|
||||
id: playwright
|
||||
run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
id: browser-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-${{ matrix.browser }}
|
||||
- run: pnpm exec playwright install-deps ${{ matrix.browser }}
|
||||
- if: steps.browser-cache.outputs.cache-hit != 'true'
|
||||
run: pnpm exec playwright install ${{ matrix.browser }}
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: acceptance-build
|
||||
path: test-results
|
||||
- name: Restore runtime artifacts
|
||||
run: |
|
||||
tar -xf test-results/acceptance-build.tar
|
||||
echo "QQQ_SAMPLE_JAR=$(ls "$PWD"/test-results/acceptance-jars/*-jar-with-dependencies.jar)" >> "$GITHUB_ENV"
|
||||
echo "QQQ_MIDDLEWARE_API_JAR=$PWD/test-results/acceptance-jars/qqq-middleware-api.jar" >> "$GITHUB_ENV"
|
||||
- name: Run shard
|
||||
env:
|
||||
QQQ_ACCEPTANCE_BROWSERS: ${{ matrix.project }}
|
||||
QQQ_ACCEPTANCE_SPEC_PATHS: ${{ needs.plan.outputs.specs }}
|
||||
QQQ_ACCEPTANCE_BLOB: '1'
|
||||
# Environment-selected projects must not produce colliding default blob names.
|
||||
QQQ_ACCEPTANCE_BLOB_NAME: report-${{ matrix.project }}-${{ matrix.shard }}.zip
|
||||
QQQ_ACCEPTANCE_TRANSPORT_TRACE: '1'
|
||||
QQQ_ACCEPTANCE_BROWSER_TRACE: ${{ (matrix.project == 'webkit' || matrix.project == 'mobile' || matrix.project == 'tablet') && 'navigation' || '0' }}
|
||||
DEBUG: pw:browser
|
||||
run: node scripts/acceptance.mjs --skip-build --shard=${{ matrix.shard }}/${{ matrix.total }}
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: acceptance-blob-${{ matrix.project }}-${{ matrix.shard }}
|
||||
path: test-results/acceptance/blob-report/
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
gate:
|
||||
name: acceptance gate
|
||||
if: always()
|
||||
needs: [plan, build, shards]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
pattern: acceptance-blob-*
|
||||
path: test-results/acceptance/blobs
|
||||
merge-multiple: true
|
||||
- name: Merge shard reports
|
||||
env:
|
||||
PLAYWRIGHT_JSON_OUTPUT_NAME: test-results/acceptance/report.json
|
||||
PLAYWRIGHT_HTML_OUTPUT_DIR: test-results/acceptance/html
|
||||
PLAYWRIGHT_HTML_OPEN: never
|
||||
run: npx playwright merge-reports --reporter=json,html test-results/acceptance/blobs
|
||||
- name: Evaluate acceptance matrix
|
||||
if: always()
|
||||
env:
|
||||
ACCEPTANCE_MODE: ${{ needs.plan.outputs.mode }}
|
||||
run: |
|
||||
args=()
|
||||
if [[ "$ACCEPTANCE_MODE" == pr ]]; then args+=(--partial); fi
|
||||
node scripts/acceptance-gate.mjs "${args[@]}"
|
||||
- name: Require every planned shard and successful build
|
||||
if: always()
|
||||
env:
|
||||
PLAN_RESULT: ${{ needs.plan.result }}
|
||||
BUILD_RESULT: ${{ needs.build.result }}
|
||||
SHARDS_RESULT: ${{ needs.shards.result }}
|
||||
PLANNED_MATRIX: ${{ needs.plan.outputs.matrix }}
|
||||
run: |
|
||||
test "$PLAN_RESULT" = success
|
||||
test "$BUILD_RESULT" = success
|
||||
test "$SHARDS_RESULT" = success
|
||||
node --input-type=module -e 'import { existsSync } from "node:fs"; for (const { project, shard } of JSON.parse(process.env.PLANNED_MATRIX).include) { const file = "test-results/acceptance/blobs/report-" + project + "-" + shard + ".zip"; if (!existsSync(file)) throw new Error("Missing shard report: " + file); }'
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: acceptance
|
||||
path: test-results/acceptance/
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
quarantine:
|
||||
name: acceptance quarantine (chromium)
|
||||
needs: [plan, build]
|
||||
if: needs.plan.outputs.mode == 'full'
|
||||
continue-on-error: true
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
cache: maven
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Installed Playwright version
|
||||
id: playwright
|
||||
run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
id: browser-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-chromium
|
||||
- run: pnpm exec playwright install-deps chromium
|
||||
- if: steps.browser-cache.outputs.cache-hit != 'true'
|
||||
run: pnpm exec playwright install chromium
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: acceptance-build
|
||||
path: test-results
|
||||
- name: Restore runtime artifacts
|
||||
run: |
|
||||
tar -xf test-results/acceptance-build.tar
|
||||
echo "QQQ_SAMPLE_JAR=$(ls "$PWD"/test-results/acceptance-jars/*-jar-with-dependencies.jar)" >> "$GITHUB_ENV"
|
||||
echo "QQQ_MIDDLEWARE_API_JAR=$PWD/test-results/acceptance-jars/qqq-middleware-api.jar" >> "$GITHUB_ENV"
|
||||
- name: Run quarantined scenarios
|
||||
env:
|
||||
QQQ_ACCEPTANCE_BROWSERS: chromium
|
||||
QQQ_ACCEPTANCE_QUARANTINE: only
|
||||
QQQ_ACCEPTANCE_TRANSPORT_TRACE: '1'
|
||||
QQQ_ACCEPTANCE_BROWSER_TRACE: '0'
|
||||
DEBUG: pw:browser
|
||||
run: node scripts/acceptance.mjs --skip-build
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: acceptance-quarantine
|
||||
path: test-results/acceptance/
|
||||
retention-days: 30
|
||||
@@ -1,158 +1,41 @@
|
||||
name: CI
|
||||
|
||||
# Fast PR checks (QRun-IO/qqq#709, bundle budget #710). The real-backend gate, including the
|
||||
# runtime performance budgets (specs/performance), runs in acceptance.yml.
|
||||
# Each job installs on its own so they run in parallel; none needs a backend.
|
||||
|
||||
on:
|
||||
name: Next centralized CI
|
||||
'on':
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
- labeled
|
||||
- unlabeled
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- v*
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
qqq_ref:
|
||||
description: QQQ source ref for acceptance
|
||||
type: string
|
||||
required: false
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
NEXT_TELEMETRY_DISABLED: '1'
|
||||
STORYBOOK_DISABLE_TELEMETRY: '1'
|
||||
|
||||
jobs:
|
||||
unit:
|
||||
name: Typecheck, lint, unit tests and coverage
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
- name: Unit tests with src/lib coverage thresholds (vitest.config.ts)
|
||||
run: pnpm test:coverage
|
||||
|
||||
e2e:
|
||||
name: Mocked e2e (Playwright, chromium)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- name: Installed Playwright version
|
||||
id: playwright
|
||||
run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
id: browser-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-chromium
|
||||
- run: pnpm exec playwright install-deps chromium
|
||||
- if: steps.browser-cache.outputs.cache-hit != 'true'
|
||||
run: pnpm exec playwright install chromium
|
||||
- name: Production build
|
||||
run: pnpm build
|
||||
- name: Mocked e2e suite
|
||||
env:
|
||||
QQQ_E2E_SERVER: production
|
||||
run: pnpm test:e2e
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: failure()
|
||||
with:
|
||||
name: e2e-report
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
retention-days: 14
|
||||
|
||||
collaboration-e2e:
|
||||
name: Collaboration e2e (MSW; chromium, firefox, webkit, mobile, tablet)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- name: Installed Playwright version
|
||||
id: playwright
|
||||
run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
id: browser-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-all
|
||||
- run: pnpm exec playwright install-deps chromium firefox webkit
|
||||
- if: steps.browser-cache.outputs.cache-hit != 'true'
|
||||
run: pnpm exec playwright install chromium firefox webkit
|
||||
- name: Collaboration suite (mock API, every browser project)
|
||||
run: pnpm exec playwright test --config playwright.collaboration.config.ts
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: collaboration-e2e
|
||||
path: |
|
||||
test-results/collaboration/
|
||||
test-results/collab-shots/
|
||||
retention-days: 14
|
||||
|
||||
storybook:
|
||||
name: Storybook build
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- run: pnpm build-storybook --quiet
|
||||
|
||||
performance:
|
||||
name: Bundle budget (static export)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- run: corepack enable
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- name: Static export
|
||||
run: pnpm build:export
|
||||
- name: First-load JS per route, total JS and largest chunk against perf-budget.json
|
||||
run: pnpm perf:budget
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: bundle-budget
|
||||
path: test-results/performance/bundle.json
|
||||
retention-days: 30
|
||||
ci:
|
||||
if: (github.event_name == 'pull_request' && !contains(fromJSON('["labeled","unlabeled"]'),
|
||||
github.event.action)) || (github.event_name == 'push' && github.ref == 'refs/heads/main')
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-ci.yml@0f33ddadf88b9a1b940b8883782fe2000ee1d2bd
|
||||
acceptance:
|
||||
if: github.event_name != 'pull_request' || !contains(fromJSON('["labeled","unlabeled"]'),
|
||||
github.event.action) || github.event.label.name == 'full-acceptance'
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-acceptance.yml@0f33ddadf88b9a1b940b8883782fe2000ee1d2bd
|
||||
with:
|
||||
qqq_ref: ${{ inputs.qqq_ref || '' }}
|
||||
dashboard-image:
|
||||
if: (github.event_name == 'pull_request' && !contains(fromJSON('["labeled","unlabeled"]'),
|
||||
github.event.action)) || (github.event_name == 'push' && startsWith(github.ref,
|
||||
'refs/tags/v'))
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/next-dashboard-image.yml@0f33ddadf88b9a1b940b8883782fe2000ee1d2bd
|
||||
@@ -1,75 +0,0 @@
|
||||
name: Dashboard image
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
IMAGE: ghcr.io/qrun-io/qqq-frontend-next
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
runner: ubuntu-24.04
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
if: github.event_name == 'push'
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/quickstart/Dockerfile
|
||||
platforms: linux/${{ matrix.arch }}
|
||||
push: ${{ github.event_name == 'push' }}
|
||||
load: ${{ github.event_name == 'pull_request' }}
|
||||
tags: ${{ env.IMAGE }}:${{ github.sha }}-${{ matrix.arch }}
|
||||
cache-from: type=gha,scope=dashboard-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=dashboard-${{ matrix.arch }}
|
||||
- name: Verify runnable dashboard
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
TAG: ${{ env.IMAGE }}:${{ github.sha }}-${{ matrix.arch }}
|
||||
run: |
|
||||
container=$(docker run -d --rm -p 127.0.0.1:3000:3000 "$TAG")
|
||||
trap 'docker rm -f "$container"' EXIT
|
||||
curl -fsS --max-time 3 --retry 30 --retry-delay 1 --retry-all-errors \
|
||||
--retry-max-time 90 http://127.0.0.1:3000/app/person >/dev/null \
|
||||
|| { docker logs "$container"; exit 1; }
|
||||
|
||||
publish:
|
||||
if: github.event_name == 'push'
|
||||
needs: build
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
packages: write
|
||||
steps:
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Publish versioned multi-architecture image
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
--tag "$IMAGE:${GITHUB_REF_NAME#v}" \
|
||||
"$IMAGE:$GITHUB_SHA-amd64" "$IMAGE:$GITHUB_SHA-arm64"
|
||||
@@ -10,6 +10,8 @@
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/.next-collaboration/
|
||||
/.next-presence-live/
|
||||
/out/
|
||||
|
||||
# production
|
||||
@@ -41,3 +43,6 @@ target/
|
||||
/log/
|
||||
/.playwright-mcp/
|
||||
/storybook-static/
|
||||
/public/scripting-generated/
|
||||
/public/pdf-generated/
|
||||
/public/dynamic-qfmd-components/
|
||||
@@ -0,0 +1,5 @@
|
||||
|
||||
|
||||
# Reviewed findings committed before the Gitea migration; exact historical fingerprints only.
|
||||
0969231c95f876bb0a41529e8c6c4621a0257aee:src/lib/qa-capture/sanitizers.test.ts:jwt:33
|
||||
23a855297de0f84b564b20d782e01180a68b5257:tests/acceptance/specs/security/restrictions.spec.ts:generic-api-key:248
|
||||
@@ -0,0 +1,3 @@
|
||||
profile: frontend-next
|
||||
orb_version: '0.8'
|
||||
default_branch: main
|
||||
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -1,8 +1,11 @@
|
||||
# QQQ Frontend Next
|
||||
|
||||
> **QBit integration branch (2026-11-04).** File delivery/preview, TypeScript editing and generic process controls use the QQQ UIUX APIs. See [current verification and dependency setup](docs/QBIT-RELEASE-STATUS.md) and [remaining release requirements](docs/QBIT-KNOWN-ISSUES.md). These changes are source/local snapshots, not part of the published RC.36 baseline described below.
|
||||
|
||||
|
||||
A metadata-driven admin UI for the QQQ low-code application framework, rewritten from React + Material UI to Next.js 16 + Tailwind CSS + shadcn/ui. The UI renders entirely from backend metadata — no table names, field lists, or navigation items are hardcoded in the frontend.
|
||||
|
||||
**This checkout targets Next UI 1.0.0-RC.26**, which adds tables that open with a short default column set instead of every field to RC25. Confirm availability in the [RC26 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.26) before installing; see the [RC26 notes](docs/releases/1.0.0-RC.26.md) for the preparation checkpoint and verification scope. [RC25](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.25) was the previously verified public candidate at that checkpoint and remains immutable. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
**Published baseline: Next UI 1.0.0-RC.36**, which adds accessibility fixes: readable link text, 24px clear targets, h2 widget titles and skip-link focus to RC35. Confirm availability in the [RC36 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.36) before installing; see the [RC36 notes](docs/releases/1.0.0-RC.36.md) for the preparation checkpoint and verification scope. [RC35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35) was the previously verified public candidate at that checkpoint and remains immutable. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
**Current roadmap and known issues:** [Next UI 1.0 tracker](https://github.com/QRun-IO/qqq/issues/713). GitHub issues are the source of truth for status and remaining work; see [issue tracking](docs/ISSUE-TRACKING.md).
|
||||
|
||||
@@ -14,11 +17,11 @@ The dashboard is the default admin UI for QQQ 4.1+. Add the jar (managed by `qqq
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-frontend-next</artifactId>
|
||||
<version>1.0.0-RC.26</version>
|
||||
<version>1.0.0-RC.36</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
The explicit version overrides an older BOM-managed frontend. RC26 requires a published QQQ 4.1 candidate: 4.1.0-RC.1 or later; 4.1.0-RC.2 or later for standalone branding images (QQQ #1009); and **4.1.0-RC.3 or later** for FILE_PREVIEW thumbnails (QQQ #1056) and the instance home app (QQQ #1059); **4.1.0-RC.4 or later** for record developer panels (QQQ #1076); **4.1.0-RC.5 or later** for the record picker (QQQ #1099), form validation limits (QQQ #1100) and date filter presets (QQQ #1115). The Alerts bell appears only with qbit-alerts (0.1.0-RC.1 or later); the notification center needs qbit-alerts 0.1.0-RC.2 or later. The assistant panel appears only with the qbit-assistant backend (0.1.0-RC.3 or later). The SQL Workbench needs the qbit-sql-workbench QBit (1.0.0-RC.1 or later); see the release notes for the verified backend. Select Next explicitly with `-Dqqq.javalin.frontend=next`. This does not release QQQ 4.1.
|
||||
The explicit version overrides an older BOM-managed frontend. RC36 requires a published QQQ 4.1 candidate: 4.1.0-RC.1 or later; 4.1.0-RC.2 or later for standalone branding images (QQQ #1009); and **4.1.0-RC.3 or later** for FILE_PREVIEW thumbnails (QQQ #1056) and the instance home app (QQQ #1059); **4.1.0-RC.4 or later** for record developer panels (QQQ #1076); **4.1.0-RC.5 or later** for the record picker (QQQ #1099), form validation limits (QQQ #1100) and date filter presets (QQQ #1115). The Alerts bell appears only with qbit-alerts (0.1.0-RC.1 or later); the notification center needs qbit-alerts 0.1.0-RC.2 or later. The assistant panel appears only with the qbit-assistant backend (0.1.0-RC.3 or later). The SQL Workbench needs the qbit-sql-workbench QBit (1.0.0-RC.1 or later); QA capture appears only with qbit-qa-capture (the `qa-capture` UI API extension); see the release notes for the verified backend. Select Next explicitly with `-Dqqq.javalin.frontend=next`. This does not release QQQ 4.1.
|
||||
|
||||
The jar holds the static export (`pnpm build:export`) under `next-dashboard/`. Deep links such as `/app/person/1` are served from placeholder pages and read their route from the browser path, so no Node.js server is involved. The Material Dashboard remains available: select it with `withServeFrontendMaterialDashboard(true)` or `-Dqqq.javalin.frontend=material`. Material routes are `/<app>/<table>/<id>`; Next routes are `/app/<table>/<id>`.
|
||||
|
||||
@@ -222,3 +225,38 @@ Saved views and legacy stored visibility (including `{}`, meaning all base colum
|
||||
are preserved. New View and Reset All Changes on an unsaved view restore these
|
||||
metadata defaults. Quick search searches only visible string fields. Responsive
|
||||
card/grid behavior is unchanged.
|
||||
## Default sort
|
||||
|
||||
A record list opens sorted by primary key, descending. An application can declare another
|
||||
sort for a table (newest first by a date field, for example) in the same hint object:
|
||||
|
||||
```json
|
||||
{
|
||||
"supplementalMetaData": {
|
||||
"nextUi": {
|
||||
"defaultSort": [
|
||||
{ "fieldName": "receivedAt", "isAscending": false }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`defaultSort` is an array of order-bys in the shape a query filter uses (`QFilterOrderBy`):
|
||||
`fieldName` is a field of the table, or of an exposed join as `joinTable.fieldName`, and
|
||||
`isAscending` is a boolean (ascending when absent). Several entries sort by the first, then
|
||||
the next. The legacy `supplementalTableMetaData.nextUi.defaultSort` path is also accepted.
|
||||
|
||||
The declared sort is the table's default, not a setting that overrides people: a sort in the
|
||||
address, the sort of a saved view, and the sort the browser remembers for the table from an
|
||||
earlier visit are each used instead. New View and Reset All Changes return to the declared
|
||||
sort, and it is not counted as an unsaved change. An entry that names an unknown field, a
|
||||
field the user may not sort by, or carries a non-boolean `isAscending` is ignored; when no
|
||||
entry is usable, or the hint is malformed, the list sorts by primary key, descending, as
|
||||
before.
|
||||
|
||||
QQQ has no table-level default sort of its own (as of 4.1.0-RC.32), so the application supplies
|
||||
the hint: a `QSupplementalTableMetaData` subclass whose `getType()` is `nextUi`, that returns
|
||||
`true` from `includeInFullFrontendMetaData()` and exposes `getDefaultSort()` as a list of
|
||||
`QFilterOrderBy` (and `getDefaultColumns()` for the hint above), attached to the table with
|
||||
`withSupplementalMetaData(...)`. The table metadata response publishes it as shown.
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM registry-1.docker.io/library/node:22-bookworm-slim AS frontend
|
||||
FROM registry-1.docker.io/library/node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS frontend
|
||||
WORKDIR /app
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
RUN corepack enable && corepack prepare pnpm@9.15.9 --activate
|
||||
@@ -9,8 +9,12 @@ ENV QQQ_BACKEND_URL=http://host.docker.internal:8000
|
||||
ENV NEXT_PUBLIC_MOCK_API=false
|
||||
RUN pnpm build
|
||||
|
||||
FROM registry-1.docker.io/library/node:22-bookworm-slim AS runtime
|
||||
FROM registry-1.docker.io/library/node:22-alpine@sha256:fe4f6d74e20370acb04ad889077d14d0f64a9c8ea6a42bc60cddf1e844699914 AS runtime
|
||||
LABEL org.opencontainers.image.source="https://github.com/QRun-IO/qqq-frontend-next"
|
||||
# Standalone production starts node directly; package managers are build-only.
|
||||
RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/corepack /opt/yarn-* \
|
||||
&& rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \
|
||||
/usr/local/bin/pnpm /usr/local/bin/pnpx /usr/local/bin/yarn /usr/local/bin/yarnpkg
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 HOSTNAME=0.0.0.0 PORT=3000
|
||||
COPY --from=frontend --chown=node:node /app/.next/standalone ./
|
||||
|
||||
@@ -23,10 +23,12 @@ Axios interceptor
|
||||
▼
|
||||
TanStack Query cache (onError)
|
||||
│ 401 → silently ignored (already handled)
|
||||
│ 403 → toast "Permission denied" / "You do not have permission…"
|
||||
│ 403 → toast the server's message, or "Permission denied"
|
||||
│ 404 → toast "Resource not found"
|
||||
│ 5xx → toast "Server error — retrying…" / "Server error — please try again"
|
||||
│ network → toast "Something went wrong"
|
||||
│ other status → toast the server's message, or "Request failed (HTTP 409)"
|
||||
│ no response → toast "No response from the server" / "The server took too long to respond"
|
||||
│ every toast names the request, and a repeat of the same failure updates it
|
||||
▼
|
||||
Component (optional per-query onError)
|
||||
│ Only needed when generic toast is wrong for the specific UX
|
||||
@@ -66,52 +68,38 @@ The `unauthorizedCallback` is wired to the auth provider's logout/redirect funct
|
||||
|
||||
**Location:** `src/lib/query-client.ts` — `handleQueryError` function
|
||||
|
||||
```typescript
|
||||
function handleQueryError(error: unknown, context: 'query' | 'mutation'): void {
|
||||
const status = getErrorStatusCode(error)
|
||||
It is registered on both `QueryCache.onError` and `MutationCache.onError`. A query or mutation whose
|
||||
component renders its own error opts out with `meta: HANDLES_OWN_ERRORS`.
|
||||
|
||||
if (status === 401) return // handled by axios interceptor
|
||||
| Failure | Banner text |
|
||||
|---|---|
|
||||
| Cancelled request (an axios cancel or an aborted `fetch`), 401 | none |
|
||||
| 403 | the server's message (of a JSON body), or `Permission denied` |
|
||||
| 404 | `Resource not found` |
|
||||
| 5xx | `Server error — retrying…` (query), `Server error — please try again` (mutation) |
|
||||
| Any other status (400, 409, 422, …) | the server's message (`userFacingError`, `error` or `message` of a JSON body), or `Request failed (HTTP 409)` |
|
||||
| No response (connection failed) | `No response from the server` |
|
||||
| No response (the 30 s timeout) | `The server took too long to respond` |
|
||||
| An error the application raised (`throw new Error('Invalid audit response')`) | that sentence |
|
||||
| A runtime error (`TypeError`, a schema error, …) | `The page hit an unexpected error (TypeError)` |
|
||||
|
||||
if (status === 403) {
|
||||
toast.error(
|
||||
context === 'mutation'
|
||||
? 'You do not have permission to perform this action'
|
||||
: 'Permission denied'
|
||||
)
|
||||
return
|
||||
}
|
||||
Under the text, every banner names what failed: the request as `POST /qqq/v1/table/order/query (HTTP 409)`,
|
||||
or `While loading records` (the query key's namespace in plain words: `possibleValues` reads
|
||||
`possible values`) for a query that failed outside a request. The
|
||||
request is written without its query string, and every path segment that is not a plain word (a record
|
||||
id, a UUID, an encoded value) is shown as `{id}`. Nothing else of the request or response is shown.
|
||||
|
||||
if (status === 404) {
|
||||
toast.error('Resource not found')
|
||||
return
|
||||
}
|
||||
**One banner per failure.** The banner's sonner `id` is its text plus the request, so a failure that
|
||||
repeats (a polling query that fails on every attempt) updates the banner already on screen instead of
|
||||
adding one. A different failure gets its own banner. A lost connection is one cause whichever request
|
||||
met it, so it has a single banner, which names the request that failed most recently. Without the id
|
||||
every failed poll added a banner, and sonner pauses a toast's timer while the tab is hidden or the
|
||||
pointer rests on the stack, so the banners could pile up.
|
||||
|
||||
if (status !== undefined && status >= 500) {
|
||||
toast.error(
|
||||
context === 'mutation'
|
||||
? 'Server error — please try again'
|
||||
: 'Server error — retrying…'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Network failure or unexpected status
|
||||
toast.error('Something went wrong')
|
||||
}
|
||||
```
|
||||
|
||||
This handler is registered on both `QueryCache` and `MutationCache`:
|
||||
|
||||
```typescript
|
||||
export const queryClient = new QueryClient({
|
||||
queryCache: new QueryCache({
|
||||
onError: (error) => handleQueryError(error, 'query'),
|
||||
}),
|
||||
mutationCache: new MutationCache({
|
||||
onError: (error) => handleQueryError(error, 'mutation'),
|
||||
}),
|
||||
})
|
||||
```
|
||||
**Console.** Each banner is also logged once with `console.warn('[API] Request failed:', { context,
|
||||
status, code, name, request, area })`: the HTTP status, the axios error code (`ERR_NETWORK`,
|
||||
`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.
|
||||
|
||||
**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.
|
||||
|
||||
@@ -139,7 +127,7 @@ Returns `undefined` for anything else (non-object errors, null, network failures
|
||||
|
||||
### 400 — Validation Error
|
||||
|
||||
The global handler does NOT toast on 400 because 400s typically carry field-level validation messages that must be mapped back to individual form fields. Handle 400 explicitly wherever you submit a form.
|
||||
The global handler toasts the server's message for a 400 (or `Request failed (HTTP 400)` when it sent none). 400s typically carry field-level validation messages that belong beside individual form fields, so a form handles 400 explicitly, and sets `meta: HANDLES_OWN_ERRORS` on the mutation when the toast would repeat what the form shows.
|
||||
|
||||
```typescript
|
||||
import { getErrorStatusCode } from '@/lib/utils/error-utils'
|
||||
@@ -207,7 +195,7 @@ No additional per-component handling is needed for 5xx unless you want a custom
|
||||
|
||||
### Network Failure (no response)
|
||||
|
||||
Treated as non-4xx by the retry logic — queries retry up to 3 times. The global handler toasts "Something went wrong" after all retries are exhausted. No per-component handling needed for the common case.
|
||||
Treated as non-4xx by the retry logic — queries retry up to 3 times. After all retries are exhausted the global handler toasts "No response from the server" (or "The server took too long to respond" for the 30 s timeout) with the request that failed. No per-component handling needed for the common case.
|
||||
|
||||
---
|
||||
|
||||
@@ -274,8 +262,8 @@ export function EditOrderForm({ orderId, schema, defaultValues }: Props) {
|
||||
onError: (error) => {
|
||||
if (getErrorStatusCode(error) === 400) {
|
||||
// Map field errors from the server response body to form fields.
|
||||
// The global handler does NOT toast on 400, so we must do it here or
|
||||
// rely on inline field error messages in the form UI.
|
||||
// The global handler toasts the server's message for a 400; the form
|
||||
// places each field's message beside it.
|
||||
const body = (error as AxiosError<{ errors: Record<string, string> }>).response?.data
|
||||
if (body?.errors) {
|
||||
for (const [field, message] of Object.entries(body.errors)) {
|
||||
@@ -305,6 +293,6 @@ export function EditOrderForm({ orderId, schema, defaultValues }: Props) {
|
||||
| Layer | File | Handles |
|
||||
|---|---|---|
|
||||
| Axios interceptor | `src/lib/api/client.ts` | 401 → redirect to login |
|
||||
| Global query handler | `src/lib/query-client.ts` | 403, 404, 5xx, network → toast |
|
||||
| Global query handler | `src/lib/query-client.ts` | Every status but 401, no response, page errors → one toast per failure, naming the request |
|
||||
| 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 |
|
||||
@@ -28,6 +28,7 @@ The ID may be on a layout-neutral wrapper around a native button or menu item. S
|
||||
- Record view: `.recordView`, `record-sidebar`, `record-view-header-{table}`, `record-view-title-{table}`, `record-view-button-bar-{table}`, `record-view-actions-menu`, and `delete-confirmation-*` with `button-delete-yes`/`button-delete-no`.
|
||||
- File previews: a `FILE_PREVIEW` value keeps its cell or value ID (`grid-cell-{field}`, `field-value-{field}`) on the thumbnail button with `data-preview-kind`; the box is `{id}-thumbnail`. The dialog uses `file-preview-dialog`, `file-preview-image`/`-pdf`/`-video`/`-audio`/`-unavailable`, `file-preview-details`, and `file-preview-{previous,next,zoom-in,zoom-out,zoom-fit,open,download,close}`.
|
||||
- Forms: `.entityForm`, `record-create-{table}`/`record-edit-{table}`, `form-section-{section}`, `.field-wrapper.is-visible`, and `.stickyBottomButtonBar`. Default action buttons expose `data-button-variant` values such as `gradient`, `contained`, and `outlined`.
|
||||
- Jobs: `button-jobs`, `jobs-active-badge`, `jobs-popover`, `link-job-{jobId}`, `link-all-jobs`, `jobs-page`, `tab-jobs-{active,recent,all}`, `job-progress-view`, `job-status`, `job-phases`, `job-progress-bar`, `job-progress-stats`, `job-progress-message`, `job-log-panel`, `job-log-scroll`, `button-job-log-{toggle,copy,latest}`, `job-background-countdown`, `button-job-{stay,background,cancel,retry,done}`, and `link-job-record`. Jobs motion is confined to `.qqq-job-{fill,shimmer,pulse,ring}` and is static under reduced motion.
|
||||
|
||||
The record view has a phone accordion and action sheet, a tablet tab list without the large-screen sidebar, and a large-screen tab list with the sidebar. A selector can be present in the DOM while its control is hidden at a narrower width. Test custom CSS at all three widths, including focus and contrast, before shipping it.
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Isolated scripting editor
|
||||
|
||||
ScriptViewer routes explicit server-controlled ISOLATED projects before legacy hooks mount. Unknown nonempty modes fail closed. The native scripting extension must be advertised; otherwise isolated source stays unavailable. Developer page provides semantic project creation and opens the same IDE; project names never imply execution mode or actor identity.
|
||||
|
||||
The isolated CodeMirror editor supports multi-file TypeScript, immutable source history, explicit save/build/test/publish, server compiler diagnostics, scoped API declarations, JSON context tests and exact-commit GitHub imports with retained provenance. Edits invalidate build/test evidence. Saves and imports carry the observed latest revision. No browser credential fields or background repository synchronization.
|
||||
|
||||
## Semantic language service
|
||||
|
||||
Pinned editor-only typescript-editor alias6.0.3 powers a same-origin classic worker. It receives a bounded virtual filesystem and host-generated SDK declarations, with57 trusted ES2022 standard-library files bundled at build time. Diagnostics, completion, hover, go-to-definition(F12), formatting(Ctrl+Shift+F), file navigation and compiler diagnostic selection operate on the same workspace. Text remains ordinary undoable editor state. Tab moves focus.
|
||||
|
||||
There is no source execution, compiler emit, runtime fetch, arbitrary package loading, filesystem, DOM/Node declarations or user npm hooks. Browser analysis is advisory; authoritative strict builds still use the qualified isolated server. Worker cold deadline10s/warm3s terminates it on timeout; bounded request/result sizes, four pending calls, idle30s termination and recycling after200 requests limit work. The next explicit request may start a new worker; no hidden retry of timed-out source analysis. A browser worker supplies termination responsiveness, not an OS-enforced memory sandbox. Debugging and automatic imports are not implemented.
|
||||
|
||||
scripts/build-scripting-worker.mjs assembles only trusted package/compiler and our own session source into public/scripting-generated/typescript-6.0.3.worker.js, with license/notices. Generated9.6MB artifact is ignored and built before dev/build/build:export. Runtime worker requests no other resource. Exact compiler and library dependencies remain independent from server runtime qualification.
|
||||
|
||||
The alias package also exports tsc and would shadow the existing compiler under pnpm exec tsc. Use **pnpm typecheck** or **pnpm tsc**: both explicitly call node_modules/typescript/bin/tsc (the existing5.9 build compiler). Existing CI typecheck scripts follow that path. Do not replace frontend build TypeScript with the editor compiler. Compatible CodeMirror versions are pinned through pnpm overrides to avoid duplicate nominal EditorView/state classes.
|
||||
|
||||
## Authorization and uncertainty
|
||||
|
||||
Server permissions and worker availability control lifecycle actions, with backend checks authoritative. Use the matching Core `4.1.0-SNAPSHOT` dependency set described in [current integration status](QBIT-RELEASE-STATUS.md); the old mixed private-artifact/RC20 setup is superseded. Project creation and publication use typed core authority; isolated revision/file content and ownership are immutable. Real native HTTP lifecycle succeeds with protocol-only fixture worker; no production provider is implied.
|
||||
|
||||
Stop waiting or network timeout makes mutation outcome uncertain and prevents another mutation. History refresh does not prove completion; inspect history/reopen. Creation uncertainty directs the user to Scripts before retrying. Abort does not undo committed work. GitHub import needs a server-installed managed access provider and full immutable commit.
|
||||
|
||||
## Verification
|
||||
|
||||
2026-10-30: **114 focused tests across12 files**, existing build-compiler typecheck and changed-file ESLint passed. Real Playwright Chromium worker check exercises strict diagnostics, multi-file completion/hover/definition/format, rejects remote types and proves source does not execute or fetch. Final optimized production build with typecheck, static generation and standalone packaging passed at 21:36, including the creation panel (parent run20209, editor-build-verification.log). Native server tests separately cover create/save/build/context-test/publish and permission/association/legacy denials. No live browser-to-deployed-worker end-to-end or production sandbox qualification claim.
|
||||
|
||||
Run pnpm scripting:worker:check after generating the worker; this environment uses PLAYWRIGHT_BROWSERS_PATH=C:/Users/james/AppData/Local/ms-playwright. The harness serves only a local trusted page/worker with connect-src none and closes browser/server on completion.
|
||||
|
||||
Current integration verification (2026-11-04): the real Chromium offline-worker check passes strict diagnostics, multi-file completion/hover/definition and formatting, with no source execution or external requests. Typecheck, lint and production worker packaging pass on the canonical integration branch. See [current status](QBIT-RELEASE-STATUS.md) for the final full-suite evidence. This frontend result does not qualify the server's untrusted-code runtime.
|
||||
@@ -0,0 +1,47 @@
|
||||
# PDF preview boundary
|
||||
|
||||
The generic file lightbox uses pinned Mozilla `pdfjs-dist` **6.4.299**, loaded only for
|
||||
PDFs, and a locally packaged worker. It no longer embeds uploaded PDF responses in an
|
||||
application-origin iframe or offers a PDF "Open original" navigation. Downloads retain
|
||||
the existing owner authorization callback.
|
||||
|
||||
Retained attachment previews reach it only after the tracked-download helper verifies
|
||||
server receipt, byte length and SHA-256, and assigns `application/pdf` from the fixed
|
||||
PDF signature. The generic renderer accepts local same-origin blob URLs or native
|
||||
file endpoints at the exact configured API origin and base path. Both dashboard hosts must permit `blob:` in CSP `connect-src` so the verified local bytes can be read; the current Javalin and standalone defaults include it. It never forwards API
|
||||
credentials to arbitrary external URLs. Uploaded MIME labels alone are insufficient.
|
||||
|
||||
The renderer supplies bytes (not a document URL) to an explicitly created parser
|
||||
Worker, preventing the library's fake-worker fallback. It creates a canvas and an
|
||||
optional plain-text view only: no PDF annotation/action, form, XFA, scripting or HTML
|
||||
viewer layer. Auxiliary resource requests are rejected, worker fetching and WASM are
|
||||
disabled, and no document-selected external URL is followed. Missing auxiliary fonts
|
||||
or unsupported resources can limit fidelity; the retained original is downloadable.
|
||||
|
||||
Limits: 20 MiB input, 1000 pages, one visible page at a time, 8 million canvas pixels,
|
||||
8192 pixels per edge, 30 seconds to load/parse, 15 seconds per page render/text read.
|
||||
Text is streamed and stopped at 10,000 items or 100,000 characters, slicing each
|
||||
string before aggregation. The stream is cancelled on page change, close or timeout;
|
||||
page controls remain busy through text completion.
|
||||
Closing the dialog aborts input loading, cancels rendering, destroys the loading task
|
||||
and terminates the worker. These are application limits, not a browser-process memory
|
||||
quota: compressed PDF complexity can allocate parser memory before page checks.
|
||||
Canvas rendering and a Web Worker do **not** constitute a full hostile-parser security
|
||||
sandbox. Browser/library patching, CSP and deployment qualification remain necessary.
|
||||
|
||||
Primary references checked on 2026-10-30:
|
||||
|
||||
- [Mozilla release 6.4.299](https://github.com/mozilla/pdf.js/releases/tag/v6.4.299)
|
||||
- [Mozilla PDF.js API](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html)
|
||||
- [Mozilla prior arbitrary-JavaScript advisory](https://github.com/mozilla/pdf.js/security/advisories/GHSA-wgrm-67xf-hhpq)
|
||||
|
||||
The prior advisory affected versions through 4.1.392 and was fixed in 4.2.67. The current
|
||||
6.4.299 API no longer exposes the old `isEvalSupported` option; this integration does
|
||||
not pretend an obsolete option supplies isolation. It uses the pinned current release,
|
||||
no PDF scripting manager, and the application's restrictive script CSP.
|
||||
|
||||
## Current verification (2026-11-04)
|
||||
|
||||
The production export and local Maven JAR include the pinned worker. Twelve Chromium browser scenarios pass against that packaged UI, including actual PDF worker/canvas pixels, page navigation, no executed PDF OpenAction, separate retained preview/download receipts, refusal of incomplete receipts, and ordered-file submission. Real Core/Collaboration API sessions separately pass ordinary signed-PDF canvas preview, page controls and PDF download.
|
||||
|
||||
Signed attachment PDFs are read with credentials omitted and redirects refused, bounded to 20 MiB and 30 seconds, and checked by byte signature before a local preview URL is exposed. Their storage origin needs host CSP/CORS configuration. Tracked deliveries retain the receipt/hash path. Cancellation and streaming-limit tests cover both paths. See [current status](QBIT-RELEASE-STATUS.md) for the full suite and [release requirements](QBIT-KNOWN-ISSUES.md) for remaining deployment qualifications.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Metadata-driven process result fields
|
||||
|
||||
`ViewFormComponent` delegates adorned result fields to the shared `FieldValue` component. Hidden fields remain in the result value map so native metadata can supply display companions; they are not rendered as separate controls. Ordinary process values and validation errors keep their existing behavior.
|
||||
|
||||
`LINK` supports either `toRecordFromTable` (a static table name) or `toRecordFromTableField` (the name of another result field containing the table name). The field value is the record identity. Navigation uses the native encoded table/record route. A missing companion table produces no link. Possible-value sources that identify a known instance table also retain native record navigation.
|
||||
|
||||
`FILE_DOWNLOAD` can specify `fileNameField` and `deliveryModeField`. If the latter is present, its companion value must be `SIGNED_URL` or `AUTHENTICATED_FETCH`; missing or unknown modes render no access action. Older fields without that metadata retain their existing behavior.
|
||||
|
||||
For `AUTHENTICATED_FETCH`, the issued URL is never placed in an `href`, image source or iframe. Download uses the shared authenticated transfer helper, which checks the configured origin, response bounds, exact digest/length and completed durable receipt. An additional `FILE_PREVIEW` adornment enables an explicit preview action. Only verified PDF/raster blobs reach the shared preview component; component-owned blob URLs are revoked when closed or unmounted. Unsupported content and transfer/audit errors remain visible and never fall back to direct access.
|
||||
|
||||
`CODE_EDITOR` result fields use the shared read-only source display, including renderer-supplied plain catalog help and HTML/JSON examples. No template or script evaluation occurs in a process result.
|
||||
|
||||
Verification for this increment: 178 focused tests across 18 files, owned ESLint and the explicit build-compiler typecheck passed. Each actual transfer creates a fresh correlation UUID only after validating the configured endpoint, preserving the immutable file coordinate and using that same fresh attempt for its receipt. Source changes and unmount abort active body/receipt work. Final integrated production-build/browser acceptance remains pending. These generic components do not embed a QBit name or depend on its backend implementation.
|
||||
@@ -0,0 +1,106 @@
|
||||
# QA capture (Jam)
|
||||
|
||||
Optional QA bug capture for the Next UI. The backend is the `qbit-qa-capture` QBit, which publishes the `qa-capture` UI API extension (1.0.0). [Jam](https://jam.dev) is the first provider. The UI calls only the two operations in [`src/lib/api/openapi/extensions/qa-capture.json`](../src/lib/api/openapi/extensions/qa-capture.json):
|
||||
|
||||
| Operation | Call | Used for |
|
||||
|---|---|---|
|
||||
| `qaCaptureCapability` | `GET /qqq/v1/qbit/qa-capture/capability` | Whether capture is on for the signed-in user, and the Jam team, sanitizer rules, blur selectors and backend context |
|
||||
| `qaCaptureReportCreate` | `POST /qqq/v1/qbit/qa-capture/report` | "Report a bug": creates a report and returns the Recording Link `jam-*` parameters |
|
||||
|
||||
The vendored document is hand-written from the shared contract until the QBit publishes its generated `openapi/qqq-v1/qa-capture.yaml`. Re-vendor it from the QBit before release.
|
||||
|
||||
## When anything loads
|
||||
|
||||
Capture is off unless all of the following hold. When it is off, the UI loads no Jam chunk, adds no Jam meta tags and makes no Jam request:
|
||||
|
||||
1. `GET /qqq/v1/version` lists the `qa-capture` extension. Otherwise the capability is never requested.
|
||||
2. The user is signed in. `QaCaptureLoader` in the root providers then requests the capability once (TanStack Query, `['qqq', 'qa-capture', 'capability']`).
|
||||
3. The capability has `enabled: true`, provider `jam`, a team id and sanitizer rules. Anything else counts as disabled.
|
||||
|
||||
When capture is enabled, `src/lib/qa-capture/jam-loader.ts` (the only module that imports Jam, and only through `import()`) does the following:
|
||||
|
||||
- adds `<meta name="jam:team">` and `<meta name="jam:blur">` (the server's `blurSelectors` plus `[data-qqq-secure]`);
|
||||
- dynamic-imports `@jam.dev/recording-links/sdk` (0.4.0) and `@jam.dev/sdk` (1.0.1);
|
||||
- calls `jam.initialize({ teamId, blurSelectors, network, console })` once, with the sanitizers;
|
||||
- registers `jam.metadata(...)`.
|
||||
|
||||
A Vitest check fails if any other file imports Jam at runtime.
|
||||
|
||||
What the SDKs fetch was checked in their published source. `initialize` loads `https://js.jam.dev/recorder.js` only in two cases: the page URL has `jam-recording` (checked on load and on every `pushState`, `replaceState` or `popstate`), or `loadRecorder()` is called. It loads `https://js.jam.dev/capture.js` only while some tab has an active recorder, which it tracks with the `jam:numRecorders` localStorage counter. `jam.metadata` only stores a callback on `window.__jam__`.
|
||||
|
||||
The browser cannot undo the Jam SDK, so turning capture off for a user (QA mode off) takes effect on the next page load. Request-id collection stops immediately.
|
||||
|
||||
## QA mode
|
||||
|
||||
When `capability.qaMode.preferenceSection` is set, the Preferences page renders that section like any other. Saving it refetches the capability, so turning QA mode on loads Jam without a reload. While `reason` is `QA_MODE`, the header shows a "QA mode on" badge that links to the section.
|
||||
|
||||
## Report a bug
|
||||
|
||||
The user menu shows **Report a bug** when `canReport` is true, and **QA reports** when `reportsHref` is an in-app path. The UI follows that link as given and never builds table paths itself. The Next UI has no help menu (the header help button opens the keyboard shortcuts), so both entries are in the user menu only.
|
||||
|
||||
Report a bug sends `POST /report` with:
|
||||
|
||||
- the page URL, with the sanitizer `queryParamNames`, the OAuth `code`, `state` and token parameters, and every `jam-*` parameter removed;
|
||||
- the title `Bug: <page title>`;
|
||||
- the app, table, record id or process, resolved from `/app/<slug>[/<id>[/<process>]]` against the instance metadata;
|
||||
- the last request ids;
|
||||
- the frontend version, user agent and viewport.
|
||||
|
||||
When the response has `recordingParams`, the UI opens the recorder with `await jam.loadRecorder({ openImmediately: false })` and then `Recorder.open(params['jam-recording'], { jamParams: { 'jam-title', 'jam-reference', ... } })`. The SDK puts those parameters on the URL while recording and removes them when the recorder closes, which lets the QBit's `jam.created` webhook match the capture to the report by `jam-reference`.
|
||||
|
||||
Without `recordingParams`, a toast explains that an administrator must set the Recording Link in the QA capture settings. It includes a QA reports action when `reportsHref` is present.
|
||||
|
||||
## Sanitizers
|
||||
|
||||
`src/lib/qa-capture/sanitizers.ts` builds the four Jam sanitizers from `capability.sanitizer`. They are pure, synchronous and deterministic, and they never log or fetch. The server's rules always get a baseline added: the `authorization`, `proxy-authorization`, `cookie` and `set-cookie` headers; the `password`, `sessionUUID`, `accessToken`, `refreshToken`, `idToken`, `clientSecret` and `code_verifier` fields; the `code`, `state`, `access_token` and `id_token` parameters; and JWTs.
|
||||
|
||||
| Data | Rule |
|
||||
|---|---|
|
||||
| Request and response headers | `headerNames` (lowercase) are deleted |
|
||||
| JSON bodies | values of `bodyFieldNames` keys are replaced at any depth (case-insensitive); `valuePatterns` are applied to every string; the body stays valid JSON |
|
||||
| Form-encoded bodies | the same, field by field |
|
||||
| Other text bodies, WebSocket data | `valuePatterns` |
|
||||
| Request URLs | `queryParamNames` values are redacted; `valuePatterns` are applied |
|
||||
| Same-origin paths under `dropPathPrefixes` | request and response bodies are dropped |
|
||||
| Console arguments | object keys and string patterns as for JSON |
|
||||
|
||||
A `valuePatterns` entry that is not a valid RegExp makes the affected sanitizers throw. Jam then redacts that data instead of sending it (fail closed).
|
||||
|
||||
## Secure fields
|
||||
|
||||
The UI knows a value is secure from its field metadata:
|
||||
|
||||
- the field type is `PASSWORD`;
|
||||
- the field has the `REVEAL` adornment;
|
||||
- secured data restricts the field (`accessTier` is `MASKED` or `REVEALABLE`).
|
||||
|
||||
Elements that show or edit such a value carry `data-jam-blur` and `data-qqq-secure`. This covers `MaskedValue`, a revealed restricted value, grid password and reveal cells, record view reveal and password values, password inputs (including while shown as text) and secure text inputs. The attributes are always present and have no effect when capture is off.
|
||||
|
||||
## Request ids
|
||||
|
||||
While capture is enabled, an axios interceptor keeps the last 50 `{ id, method, path, status, at }` entries from the response header named by `capability.requestIdHeader` (default `X-Request-Id`). The path is stored without its query string. They go into the Jam metadata and the report. Disabling capture clears the buffer.
|
||||
|
||||
## Jam metadata
|
||||
|
||||
At capture time Jam receives the following, kept under 10 KB by dropping the oldest request ids first:
|
||||
|
||||
- the app, table, record id and process;
|
||||
- the frontend version (`NEXT_PUBLIC_APP_VERSION`);
|
||||
- the backend `environment`, `backendVersion` and `node` from the capability;
|
||||
- the request ids;
|
||||
- the report reference;
|
||||
- the page path, filtered as above.
|
||||
|
||||
## Recording Links and sign-in
|
||||
|
||||
A Recording Link can open a protected page as `?jam-recording=...&jam-title=...`. The login redirect, the OIDC/OAuth2 callback and the 401 redirect already carry the query in `returnTo`. Every page load also stashes the `jam-*` parameters in sessionStorage. After sign-in they are put back on the URL with `history.replaceState`, unless the page already has a `jam-recording`. The stash expires after 30 minutes. The Jam SDK watches `replaceState`, so the recorder then opens.
|
||||
|
||||
The public `/qa/recorder` page for Jam domain verification is served by the QBit, not by Next. The standalone server forwards `/qa/*` to the backend.
|
||||
|
||||
## Content-Security-Policy
|
||||
|
||||
Next adds no CSP of its own. In a jar deployment the dashboard CSP comes from the QQQ server (`NextDashboardSecurityHeaders`), and the QBit or application must add the Jam origins listed in `capability.cspOrigins`. The standalone container server (`standalone/qqq-server.mjs`) adds them only when `QQQ_QA_CAPTURE_CSP=true`:
|
||||
|
||||
- `script-src https://js.jam.dev`
|
||||
- `frame-src https://*.jam.dev`
|
||||
- `connect-src https://*.jam.dev`
|
||||
@@ -0,0 +1,11 @@
|
||||
# QBit integration known issues and release requirements
|
||||
|
||||
Updated: 2026-11-05.
|
||||
|
||||
- The Core, Collaboration and Next UI changes are verified source branches and local snapshots, not a published dependency set. Public Core RC.21 / Collaboration RC.6 lack the required retention contracts. Merge and publication through the existing release process remain separate from local verification.
|
||||
- The frontend checks include real Core/Collaboration sessions and file storage, plus browser protocol fixtures for retained receipts. They do not establish end-to-end document generation/printing or deployed untrusted-script execution. Those QBits and workers retain their own qualification requirements.
|
||||
- External signed PDF storage needs CORS for the dashboard origin and its origin in CSP `connect-src`. Application credentials are never sent to those URLs. Hosts replacing dashboard CSP must retain `blob:` in `connect-src` for verified local previews.
|
||||
- Lint reports six existing warnings in unchanged files. The unit suite has one existing skipped test. Canonical Next 16.4.1 and Zod 3 are preserved; dependency patch upgrades remain a separate release review.
|
||||
- The local artifact is `qqq-frontend-next:1.0.0-SNAPSHOT`, built with an explicit Maven revision override. It includes generated PDF and TypeScript workers. The prepared release-managed version is `1.0.0-RC.38`; RC.36 and RC.37 already exist in Central and must never be overwritten.
|
||||
- Next publisher support and the shared producer are merged (Praetor PR238, platform-ci PR67); the local caller pins327e9b3a9d45a08665fa9468f0f9741e972d8e3e. Runtime qualification passed736 Linux tests and its vulnerability scan. GitOps PR269 deployed the qualified runtime and exact workflow/GAV enrollment; ArgoCD adoption and the scheduled publisher startup are verified. The signed application tag and resulting Central artifact still remain. The existing tag, package.json and POM version agreement, typecheck/lint/tests/static export and signed Central delivery are preserved. Neither the local JAR nor source merge proves publication.
|
||||
- The full application acceptance matrix across all browsers and deployment-specific storage/printer/scanner behavior is not claimed by the scoped QBit integration checks.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Next UI QBit integration status
|
||||
|
||||
Updated: 2026-11-05. Source integration is prepared; no published release or deployment is claimed.
|
||||
|
||||
Current main `090f5febeaacf3f9c39a22952e5c93c859cdbeb7` (permission editor and companion Tools workspace) is integrated. The latest merge passed all 110 affected Authentik/widget/process tests, typecheck and the copyright-header gate. Both branches supplied the same worker limit; the merged configuration retains one setting. Prior focused Tools/UI-API checks covered 61 cases. These are integration checks, not completed release CI.
|
||||
|
||||
Core PR1343 merged as7825261ab after full CI4482 passed; promotion PR1345 merged as1bef44cf and immutable publication4629 is running. Collaboration must consume the resulting published version. Next publisher support merged in Praetor PR238 and platform-ci PR67. GitOps PR269 merged as883e1ce3; ArgoCD adopted the exact configuration and a scheduled publisher is running image sha256:ea068b2a02147280cacedd095fbc55114daa9e3db72f1b0ca8511bc43bfd12c7 with the exact Next enrollment. Its 736 Linux tests and vulnerability scan passed. The dashboard candidate version is 1.0.0-RC.38; this source preparation is not a published release.
|
||||
|
||||
Candidate CI4602 passed 3,800 tests but hit the unchanged five-second timeout in two `RecordQuery` filter tests. These also timed out on an earlier baseline; the newer main baseline's Node job passed. Profiling the focused cases identified repeated whole-page accessibility lookups. Scoping those lookups to the existing filter controls and confirmation dialog reduced their sampled CPU cost from 387 to 261 samples; the same assertions, interactions and timeouts are preserved. All 17 tests in the affected file and focused lint pass after the change. Release CI for this correction remains required; these focused results do not replace it.
|
||||
|
||||
## Changes
|
||||
|
||||
The canonical Next UI integration renders file preview/download adornments, retained-transfer receipts, isolated TypeScript editing and generic process results through QQQ metadata and UIUX APIs. It adds no table-specific application routes. The completion pass fixes Windows static-export execution, local PDF reads under dashboard CSP, and ordinary signed-storage PDF previews. Signed storage reads omit credentials, refuse redirects and enforce byte/time limits before canvas rendering. Retained transfers preserve their receipt/hash checks. Tests now use four workers by default to avoid high-core host contention; no timeout or coverage threshold was relaxed.
|
||||
|
||||
## Verified dependencies
|
||||
|
||||
- Core `feat/standalone-scripting-api`, code commit `d384d1c753cb0ac2ee4d0f6ccd564a3e47488a1c`, locally installed as `4.1.0-SNAPSHOT`.
|
||||
- Collaboration `feat/record-files-standalone`, `53bd8f00d8a180b0fa4eb6cd029dc31044b6d4b3`, locally installed as `0.1.0-SNAPSHOT`.
|
||||
- Next UI retains canonical Next 16.4.1, Zod 3 and existing dependencies. Local packaging explicitly overrides Maven revision to `1.0.0-SNAPSHOT`; it does not replace public RC.36.
|
||||
|
||||
## Completed verification
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Full `pnpm test:coverage` | 359 files; **3,784 passed**, 1 existing skip; all coverage gates passed |
|
||||
| Coverage | 93.14% statements, 87.00% branches, 94.57% functions, 94.95% lines; API/utility sub-gates also passed |
|
||||
| Lint and license headers | Zero errors, six existing warnings in unchanged files; Apache headers passed |
|
||||
| Typecheck | Passed |
|
||||
| Offline TypeScript worker in Chromium | Strict diagnostics, multi-file completion/hover/definition and formatting passed; no source execution or external fetch |
|
||||
| Windows production static export | Passed using `pnpm build:export` |
|
||||
| Local Maven snapshot JAR | Built successfully with PDF/TypeScript workers included |
|
||||
| Browser file/process regressions | **12 passed** against the packaged production UI; API fixtures exercise PDF canvas, separate audit receipts, incomplete-receipt refusal and keyboard ordering |
|
||||
| Live Core + Collaboration file workflow | Upload, thumbnail, preview, open, exact-byte download, rename/describe, reload and delete passed with synthetic data |
|
||||
| Live PDF and authorization | Signed PDF canvas/page controls and download passed; another session was denied access to the parent record |
|
||||
| Live UI API specification check | Bundled 1.8.0 compatible with running Core 1.10.0 |
|
||||
|
||||
The live tests used the existing disposable `CollaborationDevServer`, synthetic Alice/Bob sessions and the current UI JAR on loopback. No API mocks were used for those file/permission checks. The separate 12-case browser suite uses its existing API fixtures, not a deployed Record Files or scripting worker. Test-owned services and browsers were stopped after verification.
|
||||
|
||||
## Reproduce
|
||||
|
||||
```shell
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm test:coverage
|
||||
pnpm lint
|
||||
pnpm typecheck
|
||||
pnpm scripting:worker:check
|
||||
pnpm build:export
|
||||
mvn -B -Drevision=1.0.0-SNAPSHOT package
|
||||
pnpm ui-api:check --server-url http://localhost:18098
|
||||
```
|
||||
|
||||
Start the matching Collaboration demo using its README and place the resulting UI JAR first on its classpath. The live check used port 18098. The standard `pnpm test:e2e` owns its frontend fixture for the browser scenarios. Maven was invoked through the sibling Collaboration wrapper during this Windows run.
|
||||
|
||||
Local JAR SHA-256: `0626B33DF49569476E17FA080E2777A7AD9C7AF717CB75DFABF9EB40BE0A46A8`.
|
||||
|
||||
## Release boundary
|
||||
|
||||
See [known issues and release requirements](QBIT-KNOWN-ISSUES.md). Compatible public artifact publication, the complete application acceptance matrix and deployed document/script worker qualification are not implied by these source and local integration results.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Record Files client integration
|
||||
|
||||
Updated: 2026-11-04. Current canonical integration branch: `feat/standalone-qbits-ui`. See [verification and dependencies](QBIT-RELEASE-STATUS.md).
|
||||
|
||||
## Standard controls and APIs
|
||||
|
||||
The Files tab uses standard themed buttons for Preview, Open, Download and Rename / describe. Navigation uses Next links with keyboard focus. Attachment metadata supplies independent `canEdit` and `canDelete` permissions; an explicitly denied edit capability never falls back to deletion permission. The server remains authoritative.
|
||||
|
||||
Every download requests a fresh owner-issued descriptor. `AUTHENTICATED_FETCH` deliveries use the configured native Record Files route, a new correlation identifier, and a separately verified completion receipt, byte count and SHA-256. Preview and save are separate attempts. A failed receipt never becomes a direct link or a successful save. Generic `FILE_DOWNLOAD` and `FILE_PREVIEW` adornments use the same controls; they do not require table-specific pages.
|
||||
|
||||
Tracked raster/PDF previews expose a local object URL only after verification. Ordinary signed PDF previews read bounded bytes with credentials omitted, redirects refused and a 30-second deadline. Both use the same canvas PDF renderer; uploaded PDFs are never framed. Closing the preview aborts work and revokes local URLs. Hosts serving signed files from another origin must allow that storage origin in CSP `connect-src` and configure storage CORS for the dashboard origin. This never forwards QQQ credentials to storage.
|
||||
|
||||
Open previews supported media; unsupported types use the authorized download action. The UI does not claim that a browser saved bytes or that a printer physically printed them. Retention, upload sessions, collections and durable audits belong to their server QBits.
|
||||
|
||||
## Dependency order
|
||||
|
||||
Install matching Core, then Collaboration, then Record Files and other feature QBits before the matching frontend. Public Core RC.21 and Collaboration RC.6 do not contain the new retention contracts. Local verification uses Core `4.1.0-SNAPSHOT` and Collaboration `0.1.0-SNAPSHOT`; see their branch status files for exact source commits. Core's dashboard CSP must include `blob:` in `connect-src` for local PDF-byte reads.
|
||||
|
||||
## Verification scope
|
||||
|
||||
The full component/API suite and coverage gates, production export, browser PDF/receipt/ordering scenarios and live Collaboration file workflow are recorded in [current status](QBIT-RELEASE-STATUS.md). Live tests use disposable synthetic data and real Core/Collaboration APIs. Browser mocks of the retained-transfer protocol do not establish production storage or worker qualification.
|
||||
@@ -0,0 +1,17 @@
|
||||
# UI API 1.6 adoption
|
||||
|
||||
Adopts QQQ UI API 1.6.0 (QQQ 4.1.0-RC.15): table clientCapabilities, field validation, BasicErrorResponseV1, /qqq/v1/branding.
|
||||
|
||||
- Vendors the supplied core, api-aware, ESB, alerts, collaboration, data-analysis and EDI documents; regenerates EDI types. Assistant, quick-search, secured-data and sql-workbench documents are unchanged.
|
||||
- Saved views, audits, sharing and bulk actions use per-user table capabilities. Legacy discovery is used only when `clientCapabilities` is absent; a missing or unavailable feature in a present capability object does not enable legacy access.
|
||||
- Forms use `field.validation` for required values, length policies, inclusive/exclusive bounds and whole-value patterns. Existing record-write error mapping remains intact.
|
||||
- Errors prefer `message` over legacy error fields. Global error toasts and process error details expose the trace identifier. Session-expiration handling remains in place.
|
||||
- Standalone branding aliases call `/qqq/v1/branding/{role}` and retry the old public route only after a 404. Instance consumers prefer `supplementalInstanceMetaData.uiSettings`, with deprecated settings as a fallback.
|
||||
|
||||
The app version is unchanged. No commit, push, PR or deployment was made.
|
||||
|
||||
## Verification
|
||||
|
||||
The supplied server specification comparison passes at 1.6.0. `OFF_SPEC_CALLS` remains empty and `OFF_SPEC_CEILING` remains 0.
|
||||
|
||||
Vitest startup is blocked by this session's Windows sandbox (`spawn EPERM` launching esbuild), so no Vitest pass count is claimed. The production bundle compiles, but `pnpm build` stops at its TypeScript child-process launch with `spawn EPERM`; no completed build or bundle-budget delta is available. Standalone `pnpm typecheck` passes. `pnpm lint` passes with six pre-existing warnings. Twelve direct Node smoke checks pass: seven lossless JSON vendoring comparisons and five branding status/fallback cases. The focused contract/extension Vitest invocation and full `pnpm test` both stop before running tests.
|
||||
@@ -91,7 +91,7 @@ The additional ESB integration scenarios and their focused three-browser results
|
||||
| PRC-016 | Back to the backend back step with entered values | Back restarts at the back step with values (possible-value label shown); resubmitting saves again | no Back without a backend backStep | prcComponents review, prcWizard longDetails, greetInteractive | pass (chromium) | [#655](https://github.com/QRun-IO/qqq/issues/655) [#667](https://github.com/QRun-IO/qqq/issues/667) |
|
||||
| PRC-017 | Dynamic step list from processMetaDataAdjustment.updatedFrontendStepList | short route drops a screen from the stepper; values logged (SQL) | | prcWizard | pass (chromium) | [#662](https://github.com/QRun-IO/qqq/issues/662) |
|
||||
| PRC-018 | Updated field metadata from processMetaDataAdjustment.updatedFields | field relabelled and required on the later screen | empty relabelled required field blocks | prcWizard long route | pass (chromium) | [#662](https://github.com/QRun-IO/qqq/issues/662) |
|
||||
| PRC-019 | Async job progress (message, N of M, progress bar, updated time) then continue | RUNNING progress shown while polling; finished screen and SQL log | | prcProgress | pass (chromium) | [#657](https://github.com/QRun-IO/qqq/issues/657) |
|
||||
| PRC-019 | Async job progress in the live job view (message, N / M, determinate progress bar, elapsed) then continue | RUNNING progress shown while polling; finished screen and SQL log | | prcProgress | pass (chromium) | [#657](https://github.com/QRun-IO/qqq/issues/657) |
|
||||
| PRC-020 | Cancel from a screen and mid-job runs the cancel step and leaves | confirm dialog; cancel step row (SQL) from a screen and while working | Stay on Page keeps the run | prcProgress cancelStep | pass (chromium) | |
|
||||
| PRC-021 | Step errors: user-facing messages directly, internal errors behind a detail toggle, Close | user-facing message; internal detail toggle; expanded details meet contrast requirements in light, dark and application themes; simpleThrow "I always throw."; Close returns to the app | | prcFailures, prcComponents, sample simpleThrow | pass (chromium) | |
|
||||
| PRC-022 | Retry after an error restarts with the original record selection | retry loads the selected records 2 and 4 | | prcFlaky (fails once) | pass (chromium) | [#658](https://github.com/QRun-IO/qqq/issues/658) |
|
||||
@@ -348,6 +348,7 @@ The additional ESB integration scenarios and their focused three-browser results
|
||||
| INT-012 | Stale state: changes and deletions made elsewhere are shown after refresh/navigation, not stale cache | record edited through the API shows the new value on revisit | record deleted through the API shows not found | qqq-sample-project (stock sample, mock auth, sharing demo) | pass (chromium) | [#683](https://github.com/QRun-IO/qqq/issues/683) |
|
||||
| INT-013 | Empty state: a query with no results explains it and offers the create action | no-match filter shows the empty message and Create | | qqq-sample-project (stock sample, mock auth, sharing demo) | pass (chromium) | |
|
||||
| INT-014 | Backend unavailable at sign-in: the login page explains the failure and recovers with Try again | Try again after recovery signs in | network failure shows "Sign-in failed" | qqq-sample-project (stock sample, mock auth, sharing demo) | pass (chromium) | [#669](https://github.com/QRun-IO/qqq/issues/669) |
|
||||
| SEC-050 | Optional QA capture (Jam, qbit-qa-capture qa-capture extension): Jam loads only for enabled users; Report a bug opens the recorder; secure values blurred; captures sanitized | extension absent or capability disabled: no Jam chunk, meta or request; enabled: jam:team meta, one initialize with sanitizers, jam.metadata; Report a bug: POST report then Recorder.open with jam-title and jam-reference; Recording Link jam-* parameters survive the OIDC sign-in; QA mode preference refetches the capability | no Recording Link configured: toast, no recorder; Authorization/Cookie headers, secure body fields and JWTs redacted | qbit-qa-capture (not yet released); Vitest: src/lib/qa-capture/*.test.ts, src/components/qa-capture/QaCapture.test.tsx | excluded (Pending: not yet approved by the owner. No real-backend fixture until qbit-qa-capture is released; the row is covered by Vitest until then (QA capture PR, 2026-10-15).) | |
|
||||
|
||||
## Dashboards, widgets, reports, saved and scheduled reports, and sharing
|
||||
|
||||
@@ -455,3 +456,11 @@ The additional ESB integration scenarios and their focused three-browser results
|
||||
| HLP-006 | Help author affordance | key and specific role URL presets; standard create form; read-only users cannot author | Strict diagnostics; no off-spec API calls | HelpFixtures.java | not run | |
|
||||
|
||||
The help rows above have not been executed locally; historical results above predate this change.
|
||||
|
||||
## Release notes UI API extension
|
||||
|
||||
`release-notes` 1.0.0 (qbit-release-notes 0.1.0-RC.1+) provides What's new at
|
||||
`/app/whats-new`: category groups, new badges, append paging, safe links/screenshots,
|
||||
release deep links, seen tracking and the user-menu unread count. Extension discovery
|
||||
hides the menu and prevents requests on unsupported servers. Covered by the release-notes
|
||||
client/page and Sidebar Vitest suites; real-backend acceptance remains pending.
|
||||
@@ -545,7 +545,7 @@ Process and report launch, the step lifecycle, process form fields, step compone
|
||||
| Load instance/process/table metadata, with load-error messages | `material:src/qqq/pages/processes/ProcessRun.tsx:1858-1897` | `src/app/(dashboard)/app/[slug]/page.tsx` ("Failed to load process metadata.") | none | Done |
|
||||
| Init, then handle JobComplete / Started / Running / Error | `material:src/qqq/pages/processes/ProcessRun.tsx:1595-1740` | `src/lib/hooks/use-process.ts:handle` | PRC-001, PRC-019 | Done |
|
||||
| Async polling: 1.5 s, ×1.5 backoff to 12 s on 5xx, then "Could not connect to server" | `material:src/qqq/pages/processes/ProcessRun.tsx:98-100, 1745-1795` | `src/lib/hooks/use-process.ts` pollRef / POLL_* | PRC-019 | Done |
|
||||
| Working screen: spinner, message, "N of M", progress bar, "Updated at" | `material:src/qqq/pages/processes/ProcessRun.tsx:631-670` | `src/components/process/ProcessRun.tsx` working block | PRC-019 | Done |
|
||||
| Working screen: spinner, message, "N of M", progress bar, "Updated at" | `material:src/qqq/pages/processes/ProcessRun.tsx:631-670` | `src/components/jobs/InlineJobProgress.tsx` (live job view: phases, message, N / M, eased bar, ETA, elapsed and live log in place of "Updated at") | PRC-019 | Done |
|
||||
| Loading shown before the first step | `material:src/qqq/pages/processes/ProcessRun.tsx:631, 2079` | `src/components/process/ProcessRun.tsx` (phase ≠ step) | PRC-040 | Done |
|
||||
| userFacingError vs internal error | `material:src/qqq/pages/processes/ProcessRun.tsx:1720-1734` | `src/lib/hooks/use-process.ts` ERROR case | PRC-021 | Done |
|
||||
| Error screen: "An error occurred…", show/hide detail toggle, Close/Cancel | `material:src/qqq/pages/processes/ProcessRun.tsx:589-629` | `src/components/process/ProcessErrorState.tsx` | PRC-021, PRC-022 | Done: Next adds Retry |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Next UI agent guide
|
||||
|
||||
> **This checkout targets RC26.** Confirm availability in the [RC26 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.26) before installing. [RC26 notes](../releases/1.0.0-RC.26.md) record the preparation checkpoint and verification scope; RC25 was the previously verified public candidate at that checkpoint. Earlier versioned receipts remain historical evidence; final 1.0 remains held.
|
||||
> **This checkout targets RC36.** Confirm availability in the [RC36 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.36) before installing. [RC36 notes](../releases/1.0.0-RC.36.md) record the preparation checkpoint and verification scope; RC35 was the previously verified public candidate at that checkpoint. Earlier versioned receipts remain historical evidence; final 1.0 remains held.
|
||||
|
||||
> **Live roadmap and known issues:** [QRun-IO/qqq#713](https://github.com/QRun-IO/qqq/issues/713). GitHub issues own current status and remaining work. Follow the [issue-tracking policy](../ISSUE-TRACKING.md) when reporting or resolving findings; keep this guide focused on usage and evidence.
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Next UI developer guide
|
||||
|
||||
> **This checkout targets RC26.** Confirm availability in the [RC26 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.26) before installing. [RC26 notes](../releases/1.0.0-RC.26.md) record the preparation checkpoint and verification scope; RC25 was the previously verified public candidate at that checkpoint. Earlier versioned receipts remain historical evidence; final 1.0 remains held.
|
||||
> **This checkout targets RC36.** Confirm availability in the [RC36 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.36) before installing. [RC36 notes](../releases/1.0.0-RC.36.md) record the preparation checkpoint and verification scope; RC35 was the previously verified public candidate at that checkpoint. Earlier versioned receipts remain historical evidence; final 1.0 remains held.
|
||||
|
||||
> **RC9:** application code is unchanged from RC8. See [RC9 notes](../releases/1.0.0-RC.9.md) and [published releases](https://github.com/QRun-IO/qqq-frontend-next/releases) for versioned verification and public delivery status. Earlier RC8 receipts below remain historical evidence.
|
||||
|
||||
> **Live roadmap and known issues:** [QRun-IO/qqq#713](https://github.com/QRun-IO/qqq/issues/713). GitHub issues own current status and remaining work. Follow the [issue-tracking policy](../ISSUE-TRACKING.md) when reporting or resolving findings; keep this guide focused on usage and evidence.
|
||||
|
||||
This guide describes the `feature/next-1.0` release worktree as of 2026-10-01. It explains the current frontend and backend metadata contract. The previously verified public candidate at the RC26 preparation checkpoint was [1.0.0-RC.25](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.25) (commit `5f3b7c6`); final `1.0.0` remains on hold. Later branch changes are not retroactive changes to that immutable release. For behavior proven against a real server use the [feature matrix](../acceptance/feature-matrix.md); for the full Material inventory use the [parity ledger](../acceptance/material-parity.md). Some ledger rows predate recent work, so verify an individual status against current source and acceptance results before making a release claim.
|
||||
This guide describes the `feature/next-1.0` release worktree as of 2026-10-01. It explains the current frontend and backend metadata contract. The previously verified public candidate at the RC36 preparation checkpoint was [1.0.0-RC.35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35) (commit `55c1501`); final `1.0.0` remains on hold. Later branch changes are not retroactive changes to that immutable release. For behavior proven against a real server use the [feature matrix](../acceptance/feature-matrix.md); for the full Material inventory use the [parity ledger](../acceptance/material-parity.md). Some ledger rows predate recent work, so verify an individual status against current source and acceptance results before making a release claim.
|
||||
|
||||
The visual baseline is the September 25 Next UI design (`e42ad2b2`). Material remains the reference for backend contracts and functional behavior. The layout defaults below describe current source; they do not certify a completed visual review.
|
||||
|
||||
@@ -35,7 +35,7 @@ The preferred QQQ-hosted distribution is the `com.kingsrook.qqq:qqq-frontend-nex
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-frontend-next</artifactId>
|
||||
<version>1.0.0-RC.26</version>
|
||||
<version>1.0.0-RC.36</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ RC1 remains immutable: [v1.0.0-RC.1](https://github.com/QRun-IO/qqq-frontend-nex
|
||||
|
||||
The owner authorizes publishing new RCs at verified stability or daily milestones. Each RC gets a new immutable version and notes describing its fixes, backend prerequisites, verification, and known gaps. RC publication does not authorize final 1.0.
|
||||
|
||||
Previously verified public candidate at the RC26 preparation checkpoint: **[1.0.0-RC.25](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.25)**. Its public release entry records exact artifact verification, backend requirements and known limits. RC1 through RC20 and RC22 through RC25 remain available and unchanged (RC21 was never published).
|
||||
Previously verified public candidate at the RC36 preparation checkpoint: **[1.0.0-RC.35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35)**. Its public release entry records exact artifact verification, backend requirements and known limits. RC1 through RC20 and RC22 through RC35 remain available and unchanged (RC21 was never published).
|
||||
|
||||
## Fixes during testing
|
||||
|
||||
This checkout targets [RC26](1.0.0-RC.26.md); confirm availability in the [RC26 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.26) before installing. RC26 adds tables that open with a short default column set instead of every field ([PR142](https://github.com/QRun-IO/qqq-frontend-next/pull/142) (tables open with a short default column set)). RC25 added an assistant panel that never blocks asking, re-attaches after refresh, shows live progress and can always Stop ([PR151](https://github.com/QRun-IO/qqq-frontend-next/pull/151) (assistant: never block asking, re-attach after refresh, live progress and Stop)). RC24 added the tablet record-tab fix, empty tables that explain themselves, a Full access checkbox in the policy editor and homes without duplicate card grids ([PR149](https://github.com/QRun-IO/qqq-frontend-next/pull/149) (record section tabs wrap instead of folding into More; tablet regression from PR144), [PR150](https://github.com/QRun-IO/qqq-frontend-next/pull/150) (empty tables explain what they are for and how rows get created), [PR148](https://github.com/QRun-IO/qqq-frontend-next/pull/148) (Full access checkbox in the authentik policy editor), [PR145](https://github.com/QRun-IO/qqq-frontend-next/pull/145) (no automatic card grids on homes that declare widgets)). RC23 added help everywhere, the Preferences page, contingent possible values in forms, search typeahead and System/Light/Dark theming ([PR127](https://github.com/QRun-IO/qqq-frontend-next/pull/127) (help everywhere: help icons, long-help panel, help search, author links), [PR121](https://github.com/QRun-IO/qqq-frontend-next/pull/121) (Preferences page, notification settings drawer and section actions), [PR120](https://github.com/QRun-IO/qqq-frontend-next/pull/120) (contingent possible values across forms, bulk edit, processes and filters), [PR143](https://github.com/QRun-IO/qqq-frontend-next/pull/143) (typeahead suggestions from qbit-quick-search in the global search box), [PR140](https://github.com/QRun-IO/qqq-frontend-next/pull/140) (authentik policy editor feature permissions and member preview), [PR138](https://github.com/QRun-IO/qqq-frontend-next/pull/138) (theme defaults to the OS color scheme), [PR144](https://github.com/QRun-IO/qqq-frontend-next/pull/144) (record section tabs fold into a More menu), [PR139](https://github.com/QRun-IO/qqq-frontend-next/pull/139) (breadcrumb without inner horizontal scroll), [PR146](https://github.com/QRun-IO/qqq-frontend-next/pull/146) (app-nested URLs redirect to their canonical path), [PR137](https://github.com/QRun-IO/qqq-frontend-next/pull/137) (realtime client isolated between tests), [PR68](https://github.com/QRun-IO/qqq-frontend-next/pull/68) (rapidoc 10.1.0), [PR99](https://github.com/QRun-IO/qqq-frontend-next/pull/99) (GitHub Actions updates)). RC22 added the collaboration UI, the full data-analysis UI, background process runs and assistant file attach ([PR113](https://github.com/QRun-IO/qqq-frontend-next/pull/113) (collaboration record panel: comments, files, activity, tags and follow), [PR128](https://github.com/QRun-IO/qqq-frontend-next/pull/128) (collaboration: realtime presence, conflict review, sharing, tasks and My work), [PR106](https://github.com/QRun-IO/qqq-frontend-next/pull/106) (data-analysis pivot / group-by explorer), [PR118](https://github.com/QRun-IO/qqq-frontend-next/pull/118) (data-analysis compare, correlation, crosstab and shift explorers), [PR123](https://github.com/QRun-IO/qqq-frontend-next/pull/123) (data-analysis save, share, star, export and watch), [PR126](https://github.com/QRun-IO/qqq-frontend-next/pull/126) (run processes in background, background-job banner, widget refresh), [PR125](https://github.com/QRun-IO/qqq-frontend-next/pull/125) (attach a file in the assistant panel for bulk load), [PR132](https://github.com/QRun-IO/qqq-frontend-next/pull/132) (vendored alerts and sql-workbench extension documents, off-spec 46 to 21), [PR131](https://github.com/QRun-IO/qqq-frontend-next/pull/131) (off-spec ceiling for POST /uploads), [PR129](https://github.com/QRun-IO/qqq-frontend-next/pull/129) (chart data table overflow and doubled widget section headings)). RC21 was tagged but never published: its tag build failed the off-spec ceiling test and publishing was cancelled. RC20 added readable assistant answers (GFM and presentation blocks), data-analysis profile panels, and favorites and recents ([PR92](https://github.com/QRun-IO/qqq-frontend-next/pull/92) (UI API version contract), [PR104](https://github.com/QRun-IO/qqq-frontend-next/pull/104) (UI API contract picker paths), [PR109](https://github.com/QRun-IO/qqq-frontend-next/pull/109) (acceptance ESB extension fix), [PR103](https://github.com/QRun-IO/qqq-frontend-next/pull/103) (data-analysis column and table profile panels), [PR105](https://github.com/QRun-IO/qqq-frontend-next/pull/105) (favorites, server recents and command-palette favorites), [PR111](https://github.com/QRun-IOLine truncated
|
||||
This checkout targets [RC36](1.0.0-RC.36.md); confirm availability in the [RC36 GitHub release](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.36) before installing. RC36 adds accessibility fixes: readable link text, 24px clear targets, h2 widget titles and skip-link focus ([PR175](https://github.com/QRun-IO/qqq-frontend-next/pull/175) (a11y: readable link text, 24px clear target, h2 widget titles, skip link focus)). RC35 added a profile photo uploader and avatars everywhere (UI API 1.8.0) ([PR164](https://github.com/QRun-IO/qqq-frontend-next/pull/164) (profile photo uploader and avatars everywhere, UI API 1.8.0)). RC34 added fail-soft error handling: layered error boundaries, validated assistant payloads and streams that can no longer lock the panel ([PR172](https://github.com/QRun-IO/qqq-frontend-next/pull/172) (layered error boundaries, zod payload repair, streaming can no longer lock the assistant panel)). RC33 added the new navigation (sidebar sections and favorites, one search, a new header, single-key shortcuts) and an assistant crash fix ([PR168](https://github.com/QRun-IO/qqq-frontend-next/pull/168) (sidebar sections and favorites, one search, new header, single-key shortcut switch), [PR170](https://github.com/QRun-IO/qqq-frontend-next/pull/170) (empty assistant query results no longer crash the page)). RC32 added a What's new page and user-menu entry for release notes ([PR165](https://github.com/QRun-IO/qqq-frontend-next/pull/165) (What's new page and user-menu entry, release-notes UI API 1.0.0)). RC31 added UI API 1.6.0 adoption: client capabilities, field validation, one error schema and v1 branding ([PR162](https://github.com/QRun-IO/qqq-frontend-next/pull/162) (adopt QQQ UI API 1.6.0: clientCapabilities, field validation, error schema, v1 branding)). RC30 added optional Jam QA capture on the qbit-qa-capture UI API extension ([PR160](https://github.com/QRun-IO/qqq-frontend-next/pull/160) (optional Jam QA capture on the qbit-qa-capture qa-capture extension)). RC29 added the EDI mapper page on the qbit-edi UI API extension ([PR136](https://github.com/QRun-IO/qqq-frontend-next/pull/136) (EDI mapper page on the qbit-edi edi extension, all calls on spec)). RC28 added zero off-spec UI API calls, so every backend call is a /qqq/v1 operation in the spec (minimum UI API 1.4.0) ([PR141](https://github.com/QRun-IO/qqq-frontend-next/pull/141) (zero off-spec UI API calls; OFF_SPEC_CEILING 0; minimum UI API 1.4.0)). RC27 added the secured-data UI (masked values, reveal, restricted filters, break-glass banner) and the live job view with a header Jobs tray and Jobs page ([PR124](https://github.com/QRun-IO/qqq-frontend-next/pull/124) (secured-data UI: masked values, reveal, restricted filters, break-glass banner), [PR155](https://github.com/QRun-IO/qqq-frontend-next/pull/155) (live job view, header Jobs tray and Jobs page), [PR156](https://github.com/QRun-IO/qqq-frontend-next/pull/156) (large-table acceptance fixture declares its default columns)). RC26 added tables that open with a short default column set instead of every field ([PR142](https://github.com/QRun-IO/qqq-frontend-next/pull/142) (tables open with a short default column set)). RC25 added an assistant panel that never blocks asking, re-attaches after refresh, shows live progress and can always Stop ([PR151](https://github.com/QRun-IO/qqq-frontend-next/pull/151) (assistant: never block asking, re-attach after refresh, live progress and Stop)). RC24 added the tablet record-tab fix, empty tables that explain themselves, a Full access checkbox in the policy editor and homes without duplicate card grids ([PR149](https://github.com/QRun-IO/qqq-frontend-next/pull/149) (record section tabs wrap instead of folding into More; tablet regression from PR144), [PR150](https://github.com/QRun-IO/qqq-frontend-next/pull/150) (empty tables explain what they are for and how rows get created), [PR148](https://github.com/QRun-IO/qqq-frontend-next/pull/148) (Full access checkbox in the authentik policy editor), [PR145](https://github.com/QRun-IO/qqq-frontend-next/pull/145) (no automatic card grids on homes that declare widgets)). RC23 added help everywhere, the Preferences page, contingent possible values in forms, search typeahead and System/Light/Dark theming ([PR127](https://github.com/QRun-IO/qqq-frontend-next/pull/127) (help everywhere: help icons, long-help panel, help search, author links), [PR121](https://github.com/QRun-IO/qqq-frontend-next/pull/121) (Preferences page, notification settings drawer and section actions), [PR120](https://github.com/QRun-IO/qqq-frontend-next/pull/120) (contingent possible values across forms, bulk edit, processes and filters), [PR143](https://github.com/QRun-IO/qqq-frontend-next/pull/143) (typeahead suggestions from qbit-quick-search in the global search box), [PR140](https://github.com/QRun-IO/qqq-frontend-next/pull/140) (authentik policy editor feature permissions and member preview), [PR138](https://github.cLine truncated
|
||||
|
||||
RC9's immutable-tag acceptance run completed with known Firefox and tablet failures; its release notes preserve the exact results. Follow [qqq#985](https://github.com/QRun-IO/qqq/issues/985) for browser investigations and [qqq#713](https://github.com/QRun-IO/qqq/issues/713) for the complete backlog. The [original Next visual review](../acceptance/next-ui-visual-review.md) and owner approval remain separate requirements.
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Next UI 1.0.0-RC.27 — preparation
|
||||
|
||||
At this preparation checkpoint RC27 **is not yet published**. [RC26](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.26) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.27` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.27`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `427a037` (merge of [PR155](https://github.com/QRun-IO/qqq-frontend-next/pull/155)). Merged since RC26: [PR124](https://github.com/QRun-IO/qqq-frontend-next/pull/124) (secured-data UI: masked values, reveal, restricted filters, break-glass banner), [PR155](https://github.com/QRun-IO/qqq-frontend-next/pull/155) (live job view, header Jobs tray and Jobs page), [PR156](https://github.com/QRun-IO/qqq-frontend-next/pull/156) (large-table acceptance fixture declares its default columns).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Unchanged from RC26 for existing screens. The Jobs tray and live job view need QQQ **4.1.0-RC.8** (jobs UI API, UI API 1.4.0); against older cores the Jobs button stays hidden. The secured-data UI renders what QQQ **4.1.0-RC.7** field access tiers enforce and needs qbit-secured-data **0.1.0-RC.1** for reveal and break-glass. RC27 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **Secured-data UI** ([PR124](https://github.com/QRun-IO/qqq-frontend-next/pull/124)): masked values shown with a lock chip, reveal with reason, restricted filters, and a break-glass banner. The server masks values; the client never receives the real value.
|
||||
- **Jobs** ([PR155](https://github.com/QRun-IO/qqq-frontend-next/pull/155)): a header Jobs button next to alerts, a live job view with progress, phases and log, the ability to leave a job running, and a Jobs page.
|
||||
- Acceptance: the large-table fixture declares its 40 default columns after PR142 ([PR156](https://github.com/QRun-IO/qqq-frontend-next/pull/156)).
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC27 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC27 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC26 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.28 — preparation
|
||||
|
||||
At this preparation checkpoint RC28 **is not yet published**. [RC27](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.27) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.28` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.28`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `16699ae` (merge of [PR141](https://github.com/QRun-IO/qqq-frontend-next/pull/141)). Merged since RC27: [PR141](https://github.com/QRun-IO/qqq-frontend-next/pull/141) (zero off-spec UI API calls; OFF_SPEC_CEILING 0; minimum UI API 1.4.0).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
**Requires QQQ 4.1.0-RC.9 or later** (UI API 1.4.0 operations; RC.8's `GET /table/{t}/apis` was shadowed by the record route, fixed in qqq#1216). RC28 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **Zero off-spec calls** ([PR141](https://github.com/QRun-IO/qqq-frontend-next/pull/141)): the form adjuster, table API discovery, table API documents and the remaining legacy routes now use spec'd `/qqq/v1` operations. `OFF_SPEC_CEILING` is 0.
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC28 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC28 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC27 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.29 — preparation
|
||||
|
||||
At this preparation checkpoint RC29 **is not yet published**. [RC28](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.28) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.29` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.29`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `abfbbb2` (merge of [PR136](https://github.com/QRun-IO/qqq-frontend-next/pull/136)). Merged since RC28: [PR136](https://github.com/QRun-IO/qqq-frontend-next/pull/136) (EDI mapper page on the qbit-edi edi extension, all calls on spec).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Requires QQQ **4.1.0-RC.9** or later (as RC28). The EDI mapper needs qbit-edi with the `edi` UI API extension (qbit-edi#15); without it the Open Mapper action stays hidden. RC29 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **EDI mapper** ([PR136](https://github.com/QRun-IO/qqq-frontend-next/pull/136)): an Open Mapper action on `edi_map` records opens a mapper page built on the vendored qbit-edi `edi` UI API extension, with generated types and an API client. Every call is on spec.
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC29 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC29 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC28 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,34 @@
|
||||
# Next UI 1.0.0-RC.30 — preparation
|
||||
|
||||
At this preparation checkpoint RC30 **is not yet published**. [RC29](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.29) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.30` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.30`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main after [PR160](https://github.com/QRun-IO/qqq-frontend-next/pull/160), which this preparation depends on. Merged since RC29: [PR160](https://github.com/QRun-IO/qqq-frontend-next/pull/160) (optional Jam QA capture on the qbit-qa-capture `qa-capture` extension, all calls on spec).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
RC30 needs QQQ **4.1.0-RC.9** or later, the same as RC29. QA capture also needs qbit-qa-capture with the `qa-capture` 1.0.0 UI API extension. Without it the UI makes no QA capture call and loads no Jam code. The vendored `qa-capture.json` must match the published QBit fragment before tagging. RC30 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **QA capture (Jam)** ([PR160](https://github.com/QRun-IO/qqq-frontend-next/pull/160)), shown only to users the QBit enables:
|
||||
- Jam's Recording Links SDK is loaded on demand and initialized with sanitizers built from the server's rules (headers, JSON and form fields, query parameters, value patterns, dropped paths, fail closed).
|
||||
- Jam receives metadata with the page context and the last request ids.
|
||||
- "Report a bug" and "QA reports" are in the user menu, and a "QA mode on" badge appears in the header.
|
||||
- Password, reveal and secured-data values are blurred in recordings.
|
||||
- Recording Link `jam-*` parameters are kept through sign-in.
|
||||
- The standalone image adds the Jam CSP origins when `QQQ_QA_CAPTURE_CSP=true`.
|
||||
- Dependencies: `@jam.dev/recording-links` 0.4.0 and `@jam.dev/sdk` 1.0.1, pinned. See [QA capture](../QA-CAPTURE.md).
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13). PR160 measured +3.4 to +4.2 KB gzip first-load JS per route and +9.2 KB gzip total JS. The Jam chunks load only for enabled users.
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC30 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC30 GitHub release after delivery. Acceptance row SEC-050 (QA capture) is excluded pending owner approval until qbit-qa-capture has a real-backend fixture; Vitest covers it meanwhile.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC29 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.31 — preparation
|
||||
|
||||
At this preparation checkpoint RC31 **is not yet published**. [RC30](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.30) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.31` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.31`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `9aff198` (merge of [PR162](https://github.com/QRun-IO/qqq-frontend-next/pull/162)). Merged since RC30: [PR162](https://github.com/QRun-IO/qqq-frontend-next/pull/162) (adopt QQQ UI API 1.6.0: clientCapabilities, field validation, error schema, v1 branding).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
**Requires QQQ 4.1.0-RC.15 or later** (UI API 1.6.0). RC31 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **UI API 1.6.0** ([PR162](https://github.com/QRun-IO/qqq-frontend-next/pull/162)): vendors the core 1.6.0 and API-aware documents and the updated qbit extensions (alerts 1.2.0, assistant 1.3.0, collaboration 1.1.0, data-analysis 1.5.0, edi 1.1.0, esb 1.1.0, quick-search 1.1.0, secured-data 1.1.0, sql-workbench 1.1.0); uses table client capabilities, server field validation, the single error schema and v1 branding. The off-spec ceiling stays 0.
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC31 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC31 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC30 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.32 — preparation
|
||||
|
||||
At this preparation checkpoint RC32 **is not yet published**. [RC31](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.31) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.32` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.32`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `b24b74e` (merge of [PR165](https://github.com/QRun-IO/qqq-frontend-next/pull/165)). Merged since RC31: [PR165](https://github.com/QRun-IO/qqq-frontend-next/pull/165) (What's new page and user-menu entry, release-notes UI API 1.0.0).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Requires QQQ **4.1.0-RC.15** or later for the UI API 1.6.0 features (as RC31). What's new needs qbit-release-notes **0.1.0-RC.1** (release-notes UI API extension 1.0.0); without it the feature hides itself. RC32 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **What's new** ([PR165](https://github.com/QRun-IO/qqq-frontend-next/pull/165)): an `/app/whats-new` page and a user-menu entry with an unread count, on the release-notes UI API extension 1.0.0 (vendored). The page is a separate lazy route; off-spec calls stay at 0.
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC32 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC32 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC31 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,31 @@
|
||||
# Next UI 1.0.0-RC.33 — preparation
|
||||
|
||||
At this preparation checkpoint RC33 **is not yet published**. [RC32](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.32) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.33` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.33`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `b4b59ce` (merge of [PR170](https://github.com/QRun-IO/qqq-frontend-next/pull/170)). Merged since RC32: [PR168](https://github.com/QRun-IO/qqq-frontend-next/pull/168) (sidebar sections and favorites, one search, new header, single-key shortcut switch), [PR170](https://github.com/QRun-IO/qqq-frontend-next/pull/170) (empty assistant query results no longer crash the page).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Requires QQQ **4.1.0-RC.15** or later for the UI API 1.6.0 features (as RC32). The navigation works against any 1.x server (it infers section roles when absent); QQQ **4.1.0-RC.16** (UI API 1.7.0) adds the server-declared section roles, section apps and search keywords. RC33 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **Navigation** ([PR168](https://github.com/QRun-IO/qqq-frontend-next/pull/168)): sidebar sections and favorites, one search, a header with Search, Ask, Jobs, Notifications, Help and Account, a single-key shortcut switch and Shift+D.
|
||||
|
||||
## Product fixes
|
||||
|
||||
- Empty assistant query results no longer crash the page ([PR170](https://github.com/QRun-IO/qqq-frontend-next/pull/170)).
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC33 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC33 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC32 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.34 — preparation
|
||||
|
||||
At this preparation checkpoint RC34 **is not yet published**. [RC33](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.33) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.34` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.34`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `68a2b9d` (merge of [PR172](https://github.com/QRun-IO/qqq-frontend-next/pull/172)). Merged since RC33: [PR172](https://github.com/QRun-IO/qqq-frontend-next/pull/172) (layered error boundaries, zod payload repair, streaming can no longer lock the assistant panel).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Requires QQQ **4.1.0-RC.15** or later for the UI API 1.6.0 features (as RC33). The navigation works against any 1.x server (it infers section roles when absent); QQQ **4.1.0-RC.16** (UI API 1.7.0) adds the server-declared section roles, section apps and search keywords. RC34 does not publish QQQ 4.1.
|
||||
|
||||
## Product fixes
|
||||
|
||||
- **Fail soft** ([PR172](https://github.com/QRun-IO/qqq-frontend-next/pull/172)): layered error boundaries keep a failing widget, section or panel from taking down the page; assistant payloads are validated and repaired with zod; a stream can no longer lock the assistant panel. Pairs with qbit-assistant 0.1.0-RC.22 (fail-soft server, extension 1.5.0).
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC34 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC34 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC33 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.35 — preparation
|
||||
|
||||
At this preparation checkpoint RC35 **is not yet published**. [RC34](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.34) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.35` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.35`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `ba38367` (merge of [PR164](https://github.com/QRun-IO/qqq-frontend-next/pull/164)). Merged since RC34: [PR164](https://github.com/QRun-IO/qqq-frontend-next/pull/164) (profile photo uploader and avatars everywhere, UI API 1.8.0).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Requires QQQ **4.1.0-RC.15** or later for the UI API 1.6.0 features (as RC34). Profiles and avatars need QQQ **4.1.0-RC.17** (UI API 1.8.0). RC35 does not publish QQQ 4.1.
|
||||
|
||||
## Features
|
||||
|
||||
- **Profiles and avatars** ([PR164](https://github.com/QRun-IO/qqq-frontend-next/pull/164)): a profile photo uploader on the Profile section and user avatars shown throughout the UI.
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC35 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC35 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC34 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,27 @@
|
||||
# Next UI 1.0.0-RC.36 — preparation
|
||||
|
||||
At this preparation checkpoint RC36 **is not yet published**. [RC35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35) remains the latest public candidate and is immutable. Planned artifacts are `com.kingsrook.qqq:qqq-frontend-next:1.0.0-RC.36` and `ghcr.io/qrun-io/qqq-frontend-next:1.0.0-RC.36`. Public hashes, signatures and image digests will be recorded after delivery verification. Final 1.0 remains held for application soak and explicit owner approval.
|
||||
|
||||
## Source
|
||||
|
||||
Main at `81a03ea` (merge of [PR175](https://github.com/QRun-IO/qqq-frontend-next/pull/175)). Merged since RC35: [PR175](https://github.com/QRun-IO/qqq-frontend-next/pull/175) (a11y: readable link text, 24px clear target, h2 widget titles, skip link focus).
|
||||
|
||||
## Backend requirements
|
||||
|
||||
Requires QQQ **4.1.0-RC.15** or later for the UI API 1.6.0 features (as RC35). Profiles and avatars need QQQ **4.1.0-RC.17** (UI API 1.8.0); against older servers avatars fall back to initials and the uploader stays hidden. RC36 does not publish QQQ 4.1.
|
||||
|
||||
## Product fixes
|
||||
|
||||
- **Accessibility** ([PR175](https://github.com/QRun-IO/qqq-frontend-next/pull/175)): link text meets 4.5:1 contrast through a new derived link color, clear buttons have 24px targets, widget titles are h2 headings, and the skip link takes focus correctly.
|
||||
|
||||
## Bundle budget
|
||||
|
||||
Report-only (owner decision 2026-10-13).
|
||||
|
||||
## Verification checkpoint
|
||||
|
||||
PR checks on the RC36 preparation source are recorded on the preparation PR; tag acceptance and public-artifact verification are recorded in the RC36 GitHub release after delivery.
|
||||
|
||||
## Remaining RC limits
|
||||
|
||||
The RC35 limits carry forward unchanged; see [#713](https://github.com/QRun-IO/qqq/issues/713), [#711](https://github.com/QRun-IO/qqq/issues/711), [#712](https://github.com/QRun-IO/qqq/issues/712) and [#904](https://github.com/QRun-IO/qqq/issues/904).
|
||||
@@ -0,0 +1,11 @@
|
||||
# 1.0.0-RC.38 — prepared candidate
|
||||
|
||||
This candidate is not yet released. Merge and publication follow the compatible Core and Collaboration releases.
|
||||
|
||||
- Record file controls support previews, opening and downloading through the documented delivery APIs, including PDF previews.
|
||||
- Script authoring includes the isolated TypeScript editor, server lifecycle actions and record hook controls.
|
||||
- Process results support file delivery, PDF preview and ordered record lists through standard metadata.
|
||||
- Record queries respect authorization-filtered pagination; record layouts preserve section metadata.
|
||||
- The current permission editor and companion Tools workspace remain integrated.
|
||||
|
||||
The release uses the standard UI API and extension documents. Worker execution, storage configuration and printer/scanner qualification remain responsibilities of the respective QBits and host application. See [verification and release status](../QBIT-RELEASE-STATUS.md) and [known requirements](../QBIT-KNOWN-ISSUES.md).
|
||||
@@ -1,14 +1,31 @@
|
||||
# Next UI — unreleased
|
||||
|
||||
[RC26 preparation](1.0.0-RC.26.md) collects every change merged since [RC25](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.25). RC25 is published and immutable. Changes merged after the RC26 preparation commit are listed below. Central tracking: [qqq#713](https://github.com/QRun-IO/qqq/issues/713), [browser investigations #985](https://github.com/QRun-IO/qqq/issues/985), and [QQQ Roadmap Project 12](https://github.com/orgs/QRun-IO/projects/12).
|
||||
[RC36 preparation](1.0.0-RC.36.md) collects every change merged since [RC35](https://github.com/QRun-IO/qqq-frontend-next/releases/tag/v1.0.0-RC.35). RC35 is published and immutable. Changes merged after the RC36 preparation commit are listed below. Central tracking: [qqq#713](https://github.com/QRun-IO/qqq/issues/713), [browser investigations #985](https://github.com/QRun-IO/qqq/issues/985), and [QQQ Roadmap Project 12](https://github.com/orgs/QRun-IO/projects/12).
|
||||
|
||||
## Features
|
||||
|
||||
None yet.
|
||||
- **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.
|
||||
|
||||
- **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`):
|
||||
- The core **Profile** preferences section renders generically. Its photo is a `FILE_UPLOAD` field with `valueIsUploadRef`, so you can drag and drop or choose a picture, crop it square (drag, arrow keys or the zoom slider), preview it and remove it. The cropped PNG goes to `POST /uploads`, and the ref saves with the form.
|
||||
- One `UserAvatar` (photo via one batched `POST /avatars/lookup` and `GET /avatars/{avatarId}`, otherwise initials) shows people in the user menu, presence, comments, mention candidates, the people picker, activity and your own assistant messages. A missing avatar is remembered for the session, so it isn't requested again.
|
||||
- **Privacy:** branding `gravatarDefault` no longer sends your email hash to Gravatar. A Gravatar appears only if you turn it on in your Profile, and the server serves it.
|
||||
- Image fields take a full form row at every width. e2e coverage is `tests/e2e/profile-avatars.spec.ts`, including the 6-width light/dark screenshot matrix.
|
||||
- **A table can declare the sort its record list opens with.** The list's initial sort was fixed at primary key descending and read nothing from the table's metadata, so an application could not make a list open newest first by a date field. A table's Next UI hint now takes `defaultSort` beside `defaultColumns`: `supplementalMetaData.nextUi.defaultSort`, an array of `{ "fieldName", "isAscending" }` in the shape of a query filter's order-bys. The list opens with it when the address carries no sort, no saved view is open and the browser remembers no sort for the table; each of those wins when present. New View and Reset All Changes return to it, and it is not counted as an unsaved change. Unknown or unsortable fields are ignored, and a table without a usable hint sorts by primary key descending as before. QQQ itself has no table-level default sort (as of 4.1.0-RC.32), so the application supplies the hint through a supplemental table metadata object of type `nextUi`; see the README, [Default sort](../../README.md#default-sort).
|
||||
|
||||
## Product fixes
|
||||
|
||||
None yet.
|
||||
- **A preference action that connects another service takes you there.** A provider that starts an OAuth connection (Connect Slack, for example) answers with the address of the service's consent page in the action result's `message`, since the UI API has no redirect field. That address was shown as the text of a success toast: long, not clickable and gone in seconds. A message that is nothing but one absolute `https:` address is now where the browser goes, in the same tab, and is never shown. A message that only mentions an address is still a message. Plain `http:`, addresses with credentials and every other scheme are not followed.
|
||||
- **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.
|
||||
|
||||
- **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.
|
||||
|
||||
- **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 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.
|
||||
|
||||
## Browser testing and infrastructure
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Jobs screenshots
|
||||
|
||||
The mocked browser spec is `tests/e2e/jobs-tray.spec.ts`. Capture the actual UI with:
|
||||
|
||||
```powershell
|
||||
$env:QQQ_E2E_SERVER='production'
|
||||
$env:QQQ_JOBS_SCREENSHOTS='docs/screenshots/jobs-tray'
|
||||
$env:QQQ_E2E_PORT='3117'
|
||||
pnpm exec playwright test tests/e2e/jobs-tray.spec.ts --workers=1 --reporter=list
|
||||
```
|
||||
|
||||
Captured 2026-10-14 from the production build (`QQQ_E2E_SERVER=production`), 1000 px tall:
|
||||
|
||||
| View | 390 light | 390 dark | 1440 light | 1440 dark |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Live job |  |  |  |  |
|
||||
| Open tray |  |  |  |  |
|
||||
| Jobs page |  |  |  |  |
|
||||
|
||||
The spec also checks horizontal overflow, popover bounds, keyboard focus restoration, axe at 1440
|
||||
light, and reduced motion; its lifecycle case runs an inline process, detaches it, watches it
|
||||
finish in the tray and reopens the finished view.
|
||||
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"q-sequential-workflow.bundle.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAI,IAAI,SAAI;AAC5B;AACA,iDAAiD,OAAO;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD;AAClD;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,0CAA0C;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,0BAA0B;AACtD;AACA;AACA;AACA;AACA;AACA,4BAA4B,4BAA4B;AACxD;AACA;AACA;AACA;AACA;AACA,CAAC;AACkB;AACnB,mC;;;;;;;;;;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,yCAAyC,iBAAiB;AAC1D;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAI,IAAI,SAAI;AAC5B;AACA,iDAAiD,OAAO;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,SAAI,IAAI,SAAI;AACjC,6EAA6E,OAAO;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACmD;AACE;AACH;AACJ;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,8BAA8B;AAC1D,yCAAyC,2DAAc;AACvD;AACA;AACA;AACA;AACA,4BAA4B,yGAAyG;AACrI,wDAAwD,2DAAc;AACtE;AACA;AACA,4BAA4B,uDAAY;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,6DAAY;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,4BAA4B;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,gBAAgB;AAClF;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,gBAAgB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,gBAAgB;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,2DAA2D,WAAW,iJAAiJ;AACvN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAI,IAAI,SAAI;AAC5B;AACA,iDAAiD,OAAO;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yBAAyB;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yBAAyB;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,wBAAwB;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,gDAAgD;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACuB;AACxB,wC;;;;;;;;;;;;;;AC3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,8CAA8C;AAC/C,6C;;;;;;;;;;;;;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,SAAI,IAAI,SAAI;AACjC,6EAA6E,OAAO;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAC0B;AAC3B,2C;;;;;;;;;;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACyB;AAC1B,0C;;;;;;;;;;;;;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACoD;AACF;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,6EAA6E;AACrG;AACA,8BAA8B,6DAAe;AAC7C;AACA,wBAAwB,6EAA6E;AACrG;AACA,8BAA8B,2DAAc;AAC5C;AACA,wBAAwB,+EAA+E;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,gBAAgB;AACjE;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,gBAAgB;AACjE;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,gBAAgB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACuB;AACxB,wC;;;;;;;;;;;;;;;;;;ACjHA;AACgG;AACjB;AAC/E,8BAA8B,sEAA2B,CAAC,+EAAqC;AAC/F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACALine truncated
|
||||
@@ -20,6 +20,8 @@ const BACKEND_PREFIXES: string[] = backendPrefixes
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
reactStrictMode: true,
|
||||
// Allow acceptance servers to run without sharing the developer server's lock/cache.
|
||||
distDir: process.env.QQQ_NEXT_DIST_DIR || '.next',
|
||||
// Reported to the backend as frontendVersion and shown on the developer page.
|
||||
env: { NEXT_PUBLIC_APP_VERSION: process.env.NEXT_PUBLIC_APP_VERSION || packageJson.version },
|
||||
...(exportBuild
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
{
|
||||
"name": "qqq-frontend-next",
|
||||
"version": "1.0.0-RC.26",
|
||||
"version": "1.0.0-RC.38",
|
||||
"private": true,
|
||||
"packageManager": "pnpm@9.15.9",
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
"build": "next build",
|
||||
"build:export": "QQQ_NEXT_OUTPUT=export NEXT_PUBLIC_MOCK_API=false next build",
|
||||
"scripting:worker": "node scripts/build-scripting-worker.mjs",
|
||||
"scripting:worker:check": "node scripts/build-scripting-worker.mjs && node scripts/check-scripting-worker.mjs",
|
||||
"dev": "node scripts/build-scripting-worker.mjs && node scripts/build-pdf-worker.mjs && node scripts/stage-dynamic-components.mjs && next dev --turbopack",
|
||||
"build": "node scripts/build-scripting-worker.mjs && node scripts/build-pdf-worker.mjs && node scripts/stage-dynamic-components.mjs && next build",
|
||||
"build:export": "node scripts/build-scripting-worker.mjs && node scripts/build-pdf-worker.mjs && node scripts/stage-dynamic-components.mjs && node scripts/build-export.mjs",
|
||||
"workflow:bundle": "node scripts/stage-dynamic-components.mjs",
|
||||
"build:jar": "pnpm build:export && mvn -B -q clean package",
|
||||
"start": "next start",
|
||||
"lint": "eslint src && node scripts/check-license-headers.mjs",
|
||||
@@ -22,20 +25,25 @@
|
||||
"test:acceptance": "node scripts/acceptance.mjs",
|
||||
"perf:budget": "node scripts/perf-budget.mjs",
|
||||
"ui-api:check": "node scripts/check-ui-api-spec.mjs",
|
||||
"tsc": "tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"tsc": "node node_modules/typescript/bin/tsc",
|
||||
"typecheck": "node node_modules/typescript/bin/tsc --noEmit",
|
||||
"prepare": "git config core.hooksPath .githooks || true",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build"
|
||||
"build-storybook": "storybook build",
|
||||
"pdf:worker": "node scripts/build-pdf-worker.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "6.18.6",
|
||||
"@codemirror/commands": "6.8.1",
|
||||
"@codemirror/lang-javascript": "6.2.5",
|
||||
"@codemirror/lang-sql": "6.9.0",
|
||||
"@codemirror/language": "6.11.2",
|
||||
"@codemirror/lint": "6.8.5",
|
||||
"@codemirror/state": "6.5.2",
|
||||
"@codemirror/view": "6.38.1",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@jam.dev/recording-links": "0.4.0",
|
||||
"@jam.dev/sdk": "1.0.1",
|
||||
"@lezer/highlight": "1.2.1",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
@@ -52,10 +60,11 @@
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.4.16",
|
||||
"dompurify": "^3.4.17",
|
||||
"lodash": "^4.18.1",
|
||||
"lucide-react": "^0.485.0",
|
||||
"next": "16.3.8",
|
||||
"next": "16.4.3",
|
||||
"pdfjs-dist": "6.4.299",
|
||||
"rapidoc": "10.1.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
@@ -68,15 +77,16 @@
|
||||
"sonner": "^2.0.7",
|
||||
"sql-formatter": "15.6.6",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"zod": "^3.25.76"
|
||||
"typescript-editor": "npm:typescript@6.0.3",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.11.1",
|
||||
"@eslint/eslintrc": "^3.3.4",
|
||||
"@playwright/test": "1.64.0-alpha-2026-10-01",
|
||||
"@storybook/addon-docs": "10.6.0",
|
||||
"@storybook/nextjs-vite": "10.6.0",
|
||||
"@storybook/react": "10.6.0",
|
||||
"@storybook/addon-docs": "10.6.2",
|
||||
"@storybook/nextjs-vite": "10.6.2",
|
||||
"@storybook/react": "10.6.2",
|
||||
"@tailwindcss/postcss": "^4.2.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
@@ -87,11 +97,11 @@
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.11",
|
||||
"@vitest/ui": "^4.1.11",
|
||||
"@vitest/coverage-v8": "^4.1.12",
|
||||
"@vitest/ui": "^4.1.12",
|
||||
"autoprefixer": "^10.4.27",
|
||||
"eslint": "^9.39.3",
|
||||
"eslint-config-next": "16.3.6",
|
||||
"eslint-config-next": "16.4.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-jsdoc": "^62.7.1",
|
||||
"jest-axe": "^10.0.0",
|
||||
@@ -99,10 +109,11 @@
|
||||
"msw": "^2.12.10",
|
||||
"postcss": "^8.5.28",
|
||||
"prettier": "^3.8.1",
|
||||
"storybook": "10.6.0",
|
||||
"storybook": "10.6.2",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.11"
|
||||
"vite": "7.3.7",
|
||||
"vitest": "^4.1.12"
|
||||
},
|
||||
"msw": {
|
||||
"workerDirectory": [
|
||||
@@ -111,9 +122,22 @@
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"@codemirror/autocomplete": "6.18.6",
|
||||
"@codemirror/commands": "6.8.1",
|
||||
"@codemirror/language": "6.11.2",
|
||||
"@codemirror/lint": "6.8.5",
|
||||
"@codemirror/state": "6.5.2",
|
||||
"@codemirror/view": "6.38.1",
|
||||
"serialize-javascript": ">=7.0.3",
|
||||
"@humanfs/node": ">=0.16.8",
|
||||
"@babel/core": ">=7.29.6 <8"
|
||||
}
|
||||
"@babel/core": ">=7.29.6 <8",
|
||||
"source-map-js": ">=1.2.2",
|
||||
"follow-redirects": ">=1.16.2",
|
||||
"undici@>=7 <8": ">=7.30.1 <8",
|
||||
"fast-uri@>=3 <4": ">=3.1.9 <4"
|
||||
},
|
||||
"ignoredOptionalDependencies": [
|
||||
"electron"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -53,11 +53,6 @@
|
||||
"marker": "search-result-card",
|
||||
"gzipKB": 14.5
|
||||
},
|
||||
"quickSearchPanel": {
|
||||
"$comment": "The quick search results panel of the header box and the '/' dialog (groups, highlights, completions, failure and fallback notices), loaded when the panel first opens: import() in GlobalSearch and SearchDialog. Measured 9.4 KB gzip at introduction (#59); budget about 8% above.",
|
||||
"marker": "search-results-status",
|
||||
"gzipKB": 10.2
|
||||
},
|
||||
"commandRecordResults": {
|
||||
"$comment": "The command palette's record groups, loaded when the palette searches records: import() in CommandMenu. Measured 7.5 KB gzip at introduction (#59); budget about 8% above.",
|
||||
"marker": "command-menu-searching",
|
||||
|
||||
@@ -34,7 +34,7 @@ export default defineConfig({
|
||||
webServer: {
|
||||
command: `pnpm dev --port ${port}`,
|
||||
url: baseURL,
|
||||
env: { NEXT_PUBLIC_MOCK_API: 'true' },
|
||||
env: { NEXT_PUBLIC_MOCK_API: 'true', QQQ_NEXT_DIST_DIR: '.next-collaboration' },
|
||||
reuseExistingServer: false,
|
||||
timeout: 120_000,
|
||||
},
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
</developers>
|
||||
|
||||
<properties>
|
||||
<revision>1.0.0-RC.26</revision>
|
||||
<revision>1.0.0-RC.38</revision>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.build.outputTimestamp>2026-09-24T00:00:00Z</project.build.outputTimestamp>
|
||||
</properties>
|
||||
@@ -89,8 +89,10 @@
|
||||
<files>
|
||||
<file>${project.basedir}/out/index.html</file>
|
||||
<file>${project.basedir}/out/app/_/_/index.html</file>
|
||||
<file>${project.basedir}/out/dynamic-qfmd-components/q-sequential-workflow.bundle.js</file>
|
||||
<file>${project.basedir}/out/dynamic-qfmd-components/q-sequential-workflow.bundle.js.map</file>
|
||||
</files>
|
||||
<message>Run "QQQ_NEXT_OUTPUT=export pnpm build" (or pnpm build:jar) before packaging.</message>
|
||||
<message>Run pnpm build:export (or pnpm build:jar) before packaging; the export must contain the QSequentialWorkflow editor bundle staged from dynamic-components/.</message>
|
||||
</requireFilesExist>
|
||||
</rules>
|
||||
</configuration>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
|
||||
// Pass build settings through the child environment on Windows and POSIX alike.
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const result = spawnSync(process.execPath, [require.resolve('next/dist/bin/next'), 'build'], {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, QQQ_NEXT_OUTPUT: 'export', NEXT_PUBLIC_MOCK_API: 'false' },
|
||||
})
|
||||
if (result.error) console.error(result.error.message)
|
||||
process.exit(result.status ?? 1)
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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 Copy the pinned trusted PDF worker; never copy uploaded files. */
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFile, mkdir, copyFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
const require = createRequire(import.meta.url)
|
||||
const entry = require.resolve('pdfjs-dist/package.json')
|
||||
const root = path.dirname(entry)
|
||||
const pkg = JSON.parse(await readFile(entry, 'utf8'))
|
||||
if (pkg.version !== '6.4.299') throw new Error('Pinned PDF.js 6.4.299 is required')
|
||||
const output = new URL('../public/pdf-generated/', import.meta.url)
|
||||
await mkdir(output, { recursive: true })
|
||||
await copyFile(path.join(root, 'build/pdf.worker.min.mjs'), new URL('pdf-6.4.299.worker.js', output))
|
||||
await copyFile(path.join(root, 'LICENSE'), new URL('LICENSE', output))
|
||||
console.log('Prepared pinned PDF.js 6.4.299 worker and Apache-2.0 license')
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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 Build the offline editor worker from pinned trusted dependencies; never reads a script project. */
|
||||
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const ts = require('typescript-editor')
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
if (ts.version !== '6.0.3') throw new Error('Pinned editor TypeScript 6.0.3 is required')
|
||||
const libraryDirectory = path.dirname(require.resolve('typescript-editor'))
|
||||
const libraries = Object.create(null)
|
||||
|
||||
/** Include only the standard ES2022 library closure, never DOM, Node or project packages. */
|
||||
async function includeLibrary(name) {
|
||||
if (!/^lib\.[a-z0-9.]+\.d\.ts$/.test(name)) throw new Error('Invalid shipped library name')
|
||||
if (libraries['/lib/' + name] !== undefined) return
|
||||
const source = await readFile(path.join(libraryDirectory, name), 'utf8')
|
||||
libraries['/lib/' + name] = source
|
||||
for (const reference of source.matchAll(/<reference lib="([a-z0-9.]+)"\s*\/>/g)) await includeLibrary('lib.' + reference[1] + '.d.ts')
|
||||
}
|
||||
await includeLibrary('lib.es2022.d.ts')
|
||||
const compiler = (await readFile(require.resolve('typescript-editor'), 'utf8')).replace(/\/\/# sourceMappingURL=.*$/gm, '')
|
||||
const source = await readFile(path.join(root, 'src/lib/scripting/typescript-session.ts'), 'utf8')
|
||||
const engine = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||
if (/require\s*\(/.test(engine)) throw new Error('Editor engine must have no runtime module imports')
|
||||
const worker = compiler + '\n;(() => {\nconst exports = {};\n' + engine + '\n' +
|
||||
'const session = new exports.TypeScriptSession(ts, ' + JSON.stringify(libraries) + ');\n' +
|
||||
`self.onmessage = (event) => {
|
||||
const id = event.data?.id;
|
||||
try {
|
||||
const result = session.run(event.data);
|
||||
if (new TextEncoder().encode(JSON.stringify(result)).length > 262144) throw new Error("Result limit");
|
||||
self.postMessage({ protocol: "qqq-typescript-ide/1", id, version: "6.0.3", result });
|
||||
} catch {
|
||||
self.postMessage({ protocol: "qqq-typescript-ide/1", id, version: "6.0.3", error: "Editor analysis could not be completed" });
|
||||
}
|
||||
};\n})();\n`
|
||||
const destination = path.join(root, 'public/scripting-generated')
|
||||
await mkdir(destination, { recursive: true })
|
||||
await writeFile(path.join(destination, 'typescript-6.0.3.worker.js'), worker)
|
||||
await writeFile(path.join(destination, 'LICENSE.txt'), await readFile(path.join(libraryDirectory, '../LICENSE.txt'), 'utf8'))
|
||||
await writeFile(path.join(destination, 'ThirdPartyNoticeText.txt'), await readFile(path.join(libraryDirectory, '../ThirdPartyNoticeText.txt'), 'utf8'))
|
||||
console.log('Generated offline TypeScript 6.0.3 worker (' + Buffer.byteLength(worker) + ' bytes, ' + Object.keys(libraries).length + ' standard libraries)')
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* 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 Real Chromium smoke test for the generated offline worker, served only on loopback. */
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import http from 'node:http'
|
||||
import { chromium } from '@playwright/test'
|
||||
|
||||
const workerBytes = await readFile(new URL('../public/scripting-generated/typescript-6.0.3.worker.js', import.meta.url))
|
||||
const server = http.createServer((request, response) => {
|
||||
if (request.url === '/worker.js') {
|
||||
response.writeHead(200, { 'Content-Type': 'text/javascript', 'Cache-Control': 'no-store' }); response.end(workerBytes)
|
||||
} else if (request.url === '/') {
|
||||
response.writeHead(200, { 'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; worker-src 'self'; connect-src 'none'" })
|
||||
response.end('<!doctype html><title>Offline TypeScript fixture</title>')
|
||||
} else { response.writeHead(404); response.end() }
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
let browser
|
||||
try {
|
||||
browser = await chromium.launch({ headless: true })
|
||||
const page = await browser.newPage()
|
||||
const requested = []
|
||||
page.on('request', (request) => requested.push(new URL(request.url()).pathname))
|
||||
await page.goto('http://127.0.0.1:' + server.address().port)
|
||||
const result = await page.evaluate(async () => {
|
||||
const worker = new Worker('/worker.js')
|
||||
let id = 0
|
||||
const request = (operation, files, position = 0) => new Promise((resolve, reject) => {
|
||||
const requestId = ++id
|
||||
const timer = setTimeout(() => { worker.terminate(); reject(new Error('Worker deadline exceeded')) }, 10_000)
|
||||
worker.onmessage = (event) => { clearTimeout(timer); if (event.data.id !== requestId || event.data.error) reject(new Error('Worker protocol failed')); else resolve(event.data.result) }
|
||||
worker.onerror = () => { clearTimeout(timer); reject(new Error('Worker failed')) }
|
||||
worker.postMessage({ id: requestId, operation, files, file: 'src/main.ts', position, declarations: '' })
|
||||
})
|
||||
try {
|
||||
const diagnostics = await request('diagnostics', [{ path: 'src/main.ts', content: 'export const count: number = "wrong";' }])
|
||||
const source = 'import { order } from "./order.js";\norder.status;\norder.'
|
||||
const files = [{ path: 'src/main.ts', content: source }, { path: 'src/order.ts', content: 'export const order = { status: "READY" };' }]
|
||||
const completion = await request('completion', files, source.length)
|
||||
const hover = await request('hover', files, source.indexOf('status') + 1)
|
||||
const definition = await request('definition', files, source.indexOf('order.status') + 1)
|
||||
const formatting = await request('format', [{ path: 'src/main.ts', content: 'export const value={a:1,b:2};' }])
|
||||
await request('diagnostics', [{ path: 'src/main.ts', content: 'fetch("https://example.invalid/leak"); globalThis.__qqqNeverExecute = true;' }])
|
||||
return { diagnostics, completion, hover, definition, formatting, executed: globalThis.__qqqNeverExecute === true }
|
||||
} finally { worker.terminate() }
|
||||
})
|
||||
assert(result.diagnostics.diagnostics.some((item) => item.code === 2322))
|
||||
assert(result.completion.completions.some((item) => item.label === 'status'))
|
||||
assert.match(result.hover.hover.text, /string/)
|
||||
assert.equal(result.definition.definitions[0].file, 'src/order.ts')
|
||||
assert(result.formatting.edits.length > 0)
|
||||
assert.equal(result.executed, false)
|
||||
assert.deepEqual(requested.sort(), ['/', '/worker.js'])
|
||||
console.log('PASS real Chromium: strict diagnostics, multi-file completion/hover/definition, formatting, no source execution or external requests')
|
||||
} finally {
|
||||
await browser?.close()
|
||||
await new Promise((resolve) => server.close(resolve))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"component": {
|
||||
"repository": "QRun-IO/qqq-frontend-component-sequential-workflow",
|
||||
"sourceCommit": "e6036d2a474a90d80c72bc4c5f242e666b3415f6",
|
||||
"sourceTree": "9efc09210a81dc4121aa53e156443b7f4fcb6dd7",
|
||||
"mainCommit": "ede4eba875ca17c5921ad4caf61a08bdff6f794d",
|
||||
"build": {
|
||||
"node": "v22.20.0",
|
||||
"npm": "10.9.3",
|
||||
"image": "node@sha256:b21fe589dfbe5cc39365d0544b9be3f1f33f55f3c86c87a76ff65a02f8f5848e",
|
||||
"commands": [
|
||||
"npm ci --ignore-scripts",
|
||||
"npm test (existing 3 suites, 62 tests)",
|
||||
"npx webpack"
|
||||
],
|
||||
"packageLockSha256": "737cc1a3e416d942c050076dfae36345e9ba3f62d679dec71f04c2a2382b1a21",
|
||||
"qualifiedUtc": "2026-11-05T12:31Z"
|
||||
},
|
||||
"mainTree": "9efc09210a81dc4121aa53e156443b7f4fcb6dd7",
|
||||
"mainMerge": "normal merge of PR 5 (parents a32a7b4d437f09c09b03eb8828fccfd7de4eae7a, e6036d2a474a90d80c72bc4c5f242e666b3415f6); its tree equals the qualified source tree, so the qualified assets are the canonical main build output"
|
||||
},
|
||||
"assetDirectory": "dynamic-components/q-sequential-workflow",
|
||||
"files": {
|
||||
"q-sequential-workflow.bundle.js": "9f8358b105d0c157cb32a476313a7750281549f8e9423dd7d125ceaaafe8f32d",
|
||||
"q-sequential-workflow.bundle.js.map": "776c716690a357213e00d109652ab7eb9c9025073b362c995564e11ca5c5ee92"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
|
||||
// Vendor the qbit YAML as lossless JSON, like the other extension documents, then run
|
||||
// node scripts/generate-edi-types.mjs. No runtime schema or generator dependency ships.
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
|
||||
const document = JSON.parse(readFileSync(new URL('../src/lib/api/openapi/extensions/edi.json', import.meta.url), 'utf8'))
|
||||
const header = readFileSync(new URL('../src/lib/api/tables.ts', import.meta.url), 'utf8').split('/**')[0]
|
||||
function typeOf(schema) {
|
||||
let type = schema.$ref ? schema.$ref.split('/').at(-1)
|
||||
: schema.enum ? schema.enum.map(JSON.stringify).join(' | ')
|
||||
: schema.type === 'array' ? `Array<${typeOf(schema.items)}>`
|
||||
: schema.type === 'object' ? schema.properties
|
||||
? `{\n${Object.entries(schema.properties).map(([name, value]) => ` ${name}${schema.required?.includes(name) ? '' : '?'}: ${typeOf(value)}`).join('\n')}\n}`
|
||||
: `Record<string, ${typeof schema.additionalProperties === 'object' ? typeOf(schema.additionalProperties) : 'unknown'}>`
|
||||
: ['integer', 'number'].includes(schema.type) ? 'number'
|
||||
: ['string', 'boolean'].includes(schema.type) ? schema.type : 'unknown'
|
||||
return type + (schema.nullable && type !== 'unknown' ? ' | null' : '')
|
||||
}
|
||||
writeFileSync(new URL('../src/types/edi.ts', import.meta.url), header + '/** @file Generated from the vendored edi.json. Run scripts/generate-edi-types.mjs; do not edit. */\n\n' + Object.entries(document.components.schemas).map(([name, schema]) => `/** ${schema.description ?? name} */\nexport type ${name} = ${typeOf(schema)}\n`).join('\n'))
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file Stage the versioned, precompiled QSequentialWorkflow editor bundle (the qbit-workflows `QSequentialWorkflow` editor)
|
||||
* under `public/dynamic-qfmd-components/`, which is where qbit-workflows' widget metadata points
|
||||
* (`/dynamic-qfmd-components/q-sequential-workflow.bundle.js`) and where the single-origin host serves the UI from.
|
||||
* The bundle and its map are tracked library assets in `dynamic-components/q-sequential-workflow/`, compiled from the
|
||||
* canonical component repository (source commit and toolchain recorded in `dynamic-components.lock.json`). Nothing is
|
||||
* downloaded or built here, and a file is refused unless its sha256 matches the lock. A missing or altered bundle fails the
|
||||
* build, so a release can never silently omit the workflow editor.
|
||||
*/
|
||||
import { createHash } from 'node:crypto'
|
||||
import { copyFile, mkdir, readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')
|
||||
|
||||
/** Copies every locked file from `assetDir` to `outDir`; throws on a missing file or a hash mismatch. */
|
||||
export async function stageDynamicComponents({ assetDir, lock, outDir }) {
|
||||
await mkdir(outDir, { recursive: true })
|
||||
const staged = []
|
||||
for (const [name, expected] of Object.entries(lock.files)) {
|
||||
if (path.basename(name) !== name) throw new Error(`Locked file name must be a plain file name: ${name}`)
|
||||
if (!/^[0-9a-f]{64}$/.test(expected ?? '')) throw new Error(`${name} has no sha256 in the dynamic component lock`)
|
||||
const source = path.join(assetDir, name)
|
||||
const actual = sha256(await readFile(source).catch(() => { throw new Error(`Missing ${name} in ${assetDir}`) }))
|
||||
if (actual !== expected) throw new Error(`${name} sha256 ${actual} does not match the lock ${expected}`)
|
||||
await copyFile(source, path.join(outDir, name))
|
||||
staged.push(name)
|
||||
}
|
||||
return staged
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const lock = JSON.parse(await readFile(path.join(here, 'dynamic-components.lock.json'), 'utf8'))
|
||||
const staged = await stageDynamicComponents({ assetDir: path.join(here, '..', lock.assetDirectory), lock, outDir: path.join(here, '../public/dynamic-qfmd-components') })
|
||||
console.log(`Staged dynamic components compiled from ${lock.component.repository}@${lock.component.sourceCommit.slice(0, 8)}: ${staged.join(', ')}`)
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import { useRouteParams } from '@/lib/hooks/use-route-params'
|
||||
@@ -32,6 +33,10 @@ import { launchTableName } from '@/lib/utils/process-utils'
|
||||
import { NotFoundState } from '@/components/layout/NotFoundState'
|
||||
import { RouteRedirect } from '@/components/layout/RouteRedirect'
|
||||
|
||||
const EdiMapperPage = dynamic(() => import('@/components/edi-mapper/EdiMapperPage'), {
|
||||
loading: () => <p role="status">Loading mapper…</p>,
|
||||
})
|
||||
|
||||
/**
|
||||
* Opens the named process for the record, returning to the record afterwards, or shows the
|
||||
* in-shell not-found state when the segment is not one of the table's processes.
|
||||
@@ -42,6 +47,8 @@ export default function RecordProcessPage() {
|
||||
const { slug, recordId, action } = useRouteParams<{ slug: string; recordId: string; action: string }>()
|
||||
const { data: metaData, isError } = useQuery({ queryKey: queryKeys.metadataAll(), queryFn: loadMetaData, staleTime: 1000 * 60 * 30 })
|
||||
|
||||
if (slug === 'edi_map' && action === 'mapper') return <EdiMapperPage key={recordId} mapId={Number(recordId)} />
|
||||
|
||||
if (isError) {
|
||||
return <div role="alert" className="py-12 text-center text-destructive">Failed to load application metadata.</div>
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { QInstance } from '@/types'
|
||||
import { QContextProvider, useQContext } from '@/lib/context/q-context'
|
||||
@@ -55,7 +55,7 @@ vi.mock('@/lib/api/developer', () => ({
|
||||
getTableApis: vi.fn(async () => []),
|
||||
getApiVersions: vi.fn(),
|
||||
getApiTableSpec: vi.fn(),
|
||||
apiTableSpecUrl: () => '/api/v1/person/openapi.json',
|
||||
apiTableSpecUrl: () => '/qqq/v1/table/person/apis/siteApi/v1/openapi',
|
||||
apiMiddlewareBaseURL: () => '',
|
||||
}))
|
||||
|
||||
@@ -113,6 +113,9 @@ function renderPage() {
|
||||
}
|
||||
|
||||
describe('RecordDeveloperViewPage', () => {
|
||||
// The page lazy-loads this view; transforming its module graph cold must not count against the first test's waits
|
||||
beforeAll(async () => { await import('@/components/developer/RecordDeveloperView') }, 120_000)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getRecord).mockResolvedValue(record)
|
||||
vi.mocked(getRecordDeveloperData).mockResolvedValue({
|
||||
@@ -140,7 +143,7 @@ describe('RecordDeveloperViewPage', () => {
|
||||
expect(within(card).getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['Code', 'Logs', 'Test', 'Docs'])
|
||||
expect(screen.getByTestId('page-header')).toHaveTextContent('Ada Lovelace Developer Mode')
|
||||
expect(getRecordDeveloperData).toHaveBeenCalledWith('person', '1')
|
||||
})
|
||||
}, 15_000) // three waits of up to 5 s each: the 5 s default could expire before they do
|
||||
|
||||
it('shows the raw values of the developer-mode record, not a separate record read (Material getRecordDeveloperMode)', async () => {
|
||||
serveInstance([])
|
||||
|
||||
@@ -59,7 +59,7 @@ const RecordView = lazy(() => import('@/components/records/RecordView').then((mo
|
||||
*
|
||||
* Loads the base record and optional whole-association expansion independently. Once
|
||||
* the record loads it is registered in the recently-viewed history (via
|
||||
* `addRecentRecord`) so it surfaces in the GlobalSearch and SearchDialog.
|
||||
* `addRecentRecord`) so it surfaces in the search box (recently viewed records).
|
||||
* The page header in QContext is updated to the record label.
|
||||
*
|
||||
* @returns A composed view that assembles:
|
||||
@@ -218,7 +218,7 @@ export default function RecordViewPage() {
|
||||
allTables={metaData?.tables}
|
||||
widgetMetaDataMap={metaData?.widgets}
|
||||
associationTables={associationTables}
|
||||
auditSource={auditSource(metaData)}
|
||||
auditSource={auditSource(metaData, tableMetaData.clientCapabilities)}
|
||||
/></Suspense>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -88,7 +88,7 @@ describe('TableDeveloperViewPage API Docs & Playground', () => {
|
||||
window.localStorage.clear()
|
||||
getTableApisMock.mockReset()
|
||||
getApiVersionsMock.mockReset()
|
||||
getApiVersionsMock.mockImplementation(async (path: string) => versions[path])
|
||||
getApiVersionsMock.mockImplementation((api) => versions[api.path])
|
||||
})
|
||||
|
||||
it('selects the first API and its current version and embeds RapiDoc for the table spec', async () => {
|
||||
@@ -108,7 +108,7 @@ describe('TableDeveloperViewPage API Docs & Playground', () => {
|
||||
|
||||
await waitFor(() => expect(container.querySelector('rapi-doc')).not.toBeNull())
|
||||
const rapiDoc = container.querySelector('[data-qqq-id="table-dev-api-reference"] rapi-doc')!
|
||||
expect(rapiDoc).toHaveAttribute('spec-url', '/person-api/2026.Q2/person/openapi.json')
|
||||
expect(rapiDoc).toHaveAttribute('spec-url', '/qqq/v1/table/person/apis/person-api/2026.Q2/openapi?format=json')
|
||||
expect(rapiDoc).toHaveAttribute('primary-color', '#6366f1')
|
||||
expect(rapiDoc).toHaveAttribute('show-header', 'false')
|
||||
expect(rapiDoc).toHaveAttribute('render-style', 'view')
|
||||
@@ -128,7 +128,7 @@ describe('TableDeveloperViewPage API Docs & Playground', () => {
|
||||
|
||||
expect(await screen.findByLabelText('API')).toHaveValue('admin-api')
|
||||
expect(await screen.findByLabelText('Version')).toHaveValue('v2')
|
||||
await waitFor(() => expect(container.querySelector('rapi-doc')).toHaveAttribute('spec-url', '/admin-api/v2/person/openapi.json'))
|
||||
await waitFor(() => expect(container.querySelector('rapi-doc')).toHaveAttribute('spec-url', '/qqq/v1/table/person/apis/admin-api/v2/openapi?format=json'))
|
||||
})
|
||||
|
||||
it('falls back to the first API and the current version when the remembered ones are gone', async () => {
|
||||
@@ -151,7 +151,7 @@ describe('TableDeveloperViewPage API Docs & Playground', () => {
|
||||
expect(await screen.findByLabelText('Version')).toHaveValue('v1')
|
||||
await user.selectOptions(screen.getByLabelText('Version'), 'v2')
|
||||
|
||||
await waitFor(() => expect(container.querySelector('rapi-doc')).toHaveAttribute('spec-url', '/admin-api/v2/person/openapi.json'))
|
||||
await waitFor(() => expect(container.querySelector('rapi-doc')).toHaveAttribute('spec-url', '/qqq/v1/table/person/apis/admin-api/v2/openapi?format=json'))
|
||||
expect(window.localStorage.getItem('qqq.tableDeveloperView.lastApiName')).toBe('admin-api')
|
||||
expect(window.localStorage.getItem('qqq.tableDeveloperView.lastApiVersion')).toBe('v2')
|
||||
})
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import apiClient from '@/lib/api/client'
|
||||
import { QContextProvider } from '@/lib/context/q-context'
|
||||
@@ -54,6 +54,8 @@ function renderPage(page: React.ReactNode) {
|
||||
}
|
||||
|
||||
describe('Create and base edit use full metadata and actual write contracts', () => {
|
||||
// The pages lazy-load the form; transforming its module graph cold must not count against the first test's waits
|
||||
beforeAll(async () => { await import('@/components/forms/EntityForm') }, 120_000)
|
||||
beforeEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); localStorage.clear(); fixture() })
|
||||
|
||||
it('edits the base without requesting denied children or replacing associations', async () => {
|
||||
|
||||
@@ -43,6 +43,7 @@ import { loadMetaData } from '@/lib/api/metadata'
|
||||
import apiClient from '@/lib/api/client'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { CreateIsolatedScript } from '@/components/scripts/CreateIsolatedScript'
|
||||
|
||||
/** Duration in milliseconds before the "copied!" feedback resets to the copy icon. */
|
||||
const COPY_RESET_MS = 2000
|
||||
@@ -252,6 +253,8 @@ export default function DeveloperPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CreateIsolatedScript />
|
||||
|
||||
{/* Session Info */}
|
||||
<SectionCard
|
||||
title="Session Info"
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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 Static export placeholder for job detail routes. */
|
||||
import type { ReactNode } from 'react'
|
||||
import { EXPORT_PLACEHOLDER } from '@/lib/utils/export-placeholder'
|
||||
|
||||
/** Generates the export placeholder.
|
||||
* @returns One job path.
|
||||
*/
|
||||
export function generateStaticParams() { return [{ jobId: EXPORT_PLACEHOLDER }] }
|
||||
|
||||
/** Pass-through layout.
|
||||
* @param props - Children.
|
||||
* @returns Children unchanged.
|
||||
*/
|
||||
export default function Layout({ children }: { children: ReactNode }) { return children }
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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 Live job route, separate from metadata table records. */
|
||||
'use client'
|
||||
import { useRouteParams } from '@/lib/hooks/use-route-params'
|
||||
import { JobDetailView } from '@/components/jobs/JobDetailView'
|
||||
|
||||
/** Renders a job by id.
|
||||
* @returns Job view or invalid-id message.
|
||||
*/
|
||||
export default function JobRoute() {
|
||||
const { jobId } = useRouteParams<{ jobId: string }>()
|
||||
const id = Number(jobId)
|
||||
if (!Number.isSafeInteger(id) || id <= 0) return <p role="alert">Invalid job identifier.</p>
|
||||
return <div className="w-full min-w-0 rounded-xl border border-border bg-card"><JobDetailView key={id} jobId={id} /></div>
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* 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 Static Jobs page, taking precedence over the metadata slug route. */
|
||||
'use client'
|
||||
import dynamic from 'next/dynamic'
|
||||
const JobsPage = dynamic(() => import('@/components/jobs/JobsPage').then((module) => module.JobsPage))
|
||||
|
||||
/** Renders the Jobs page.
|
||||
* @returns Page content.
|
||||
*/
|
||||
export default function JobsRoute() { return <JobsPage /> }
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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 What's new route, split from the dashboard's first load. */
|
||||
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
/** The page loads on demand, so its code stays out of every route's first load. */
|
||||
const WhatsNewPage = dynamic(() => import('@/components/release-notes/WhatsNewPage').then((module) => module.WhatsNewPage), {
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<p className="flex items-center gap-2 p-6 text-sm text-muted-foreground" role="status" data-qqq-id="whats-new-page-loading">
|
||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
|
||||
Loading release notes...
|
||||
</p>
|
||||
),
|
||||
})
|
||||
|
||||
/**
|
||||
* Renders the whats-new page at `/app/whats-new`.
|
||||
*
|
||||
* @returns The page.
|
||||
*/
|
||||
export default function WhatsNewRoute() {
|
||||
return <WhatsNewPage />
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* 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 React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
|
||||
import { resetClientErrorsForTesting, setClientErrorSink } from '@/lib/errors/client-errors'
|
||||
import PageError from './error'
|
||||
|
||||
describe('page error boundary', () => {
|
||||
afterEach(() => {
|
||||
resetClientErrorsForTesting()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('reports the failure and offers Try again inside the shell', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const sink = vi.fn().mockResolvedValue(undefined)
|
||||
setClientErrorSink(sink)
|
||||
const reset = vi.fn()
|
||||
render(<PageError error={new Error("Cannot read properties of undefined (reading 'length')")} reset={reset} />)
|
||||
expect(screen.getByText('This page hit a problem')).toBeVisible()
|
||||
expect(sink).toHaveBeenCalledWith(expect.objectContaining({ scope: 'page' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Try again' }))
|
||||
expect(reset).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -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 Page error boundary — a page that throws is replaced inside the app shell, so the
|
||||
* navigation, header and assistant keep working.
|
||||
*/
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { AlertCircle, RefreshCw } from 'lucide-react'
|
||||
|
||||
import { clientErrorDetails, reportClientError, type ClientErrorReport } from '@/lib/errors/client-errors'
|
||||
|
||||
/**
|
||||
* Whether the error means the session ended (the root boundary sends the user to log in).
|
||||
*
|
||||
* @param error - The thrown error.
|
||||
* @returns True for 401 / unauthorized / session expired.
|
||||
*/
|
||||
function isSessionError(error: Error): boolean {
|
||||
const message = error.message?.toLowerCase() ?? ''
|
||||
return message.includes('401') || message.includes('unauthorized') || message.includes('session expired')
|
||||
}
|
||||
|
||||
/**
|
||||
* The page-level fallback, rendered by Next.js inside the dashboard layout.
|
||||
*
|
||||
* @param props - The Next.js error boundary props.
|
||||
* @param props.error - The thrown error.
|
||||
* @param props.reset - Renders the page again.
|
||||
* @returns A card with Try again, Go home and the error's details.
|
||||
*/
|
||||
export default function PageError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
|
||||
const [report, setReport] = useState<ClientErrorReport | null>(null)
|
||||
const sessionExpired = isSessionError(error)
|
||||
useEffect(() => {
|
||||
if (!sessionExpired) setReport(reportClientError(error, { scope: 'page' }))
|
||||
}, [error, sessionExpired])
|
||||
// the root boundary owns the "Session Expired" screen
|
||||
if (sessionExpired) throw error
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-lg rounded-xl border border-border bg-card p-6 text-center shadow-sm" role="alert" data-qqq-id="page-error">
|
||||
<AlertCircle className="mx-auto mb-3 h-10 w-10 text-destructive" aria-hidden="true" />
|
||||
<h1 className="text-lg font-semibold text-foreground">This page hit a problem</h1>
|
||||
<p className="mt-1 text-sm text-muted-foreground">The rest of the app still works. Try again, or go to another page.</p>
|
||||
<div className="mt-4 flex flex-wrap justify-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11"
|
||||
data-qqq-id="button-page-try-again"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" aria-hidden="true" />
|
||||
Try again
|
||||
</button>
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center gap-2 rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11"
|
||||
data-qqq-id="link-page-go-home"
|
||||
>
|
||||
Go home
|
||||
</Link>
|
||||
</div>
|
||||
{report && (
|
||||
<details className="mt-4 text-left text-xs text-muted-foreground">
|
||||
<summary className="cursor-pointer select-none">Details</summary>
|
||||
<pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-2 font-mono" data-qqq-id="page-error-details">{clientErrorDetails(report)}</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -22,7 +22,8 @@
|
||||
|
||||
/** Dashboard layout — authenticated route group shell providing sidebar, header, banners, command palette, and global keyboard shortcuts. */
|
||||
|
||||
import React, { useEffect, useState, useCallback, useMemo, useRef } from 'react'
|
||||
import { SecuredDataProvider, SecuredDataBannerSlot } from '@/components/secured-data/SecuredDataProvider'
|
||||
import React, { useEffect, useLayoutEffect, useState, useCallback, useMemo, useRef } from 'react'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
@@ -32,15 +33,16 @@ import { useQContext, QContextProvider } from '@/lib/context/q-context'
|
||||
import { useAppTreeRoutes } from '@/lib/hooks/use-routes'
|
||||
import { useDocumentTitle } from '@/lib/hooks/use-document-title'
|
||||
import { loadMetaData } from '@/lib/api/metadata'
|
||||
import { ApplicationLoading } from '@/components/layout/ApplicationLoading'
|
||||
import { applyBrandingTheme } from '@/lib/theme/apply-branding'
|
||||
import { skipToFirstZone } from '@/lib/utils/skip-link'
|
||||
import { readMaterialTheme } from '@/lib/theme/material-theme'
|
||||
import { useTheme } from '@/lib/theme/theme-provider'
|
||||
import { recordAnalytics } from '@/lib/analytics'
|
||||
import { useAnalytics } from '@/lib/analytics/use-analytics'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import { searchableTables } from '@/lib/utils/record-search'
|
||||
import { scrollPageToTop } from '@/lib/utils/scroll-to-top'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
|
||||
import Sidebar from '@/components/layout/Sidebar'
|
||||
import Header from '@/components/layout/Header'
|
||||
@@ -49,8 +51,12 @@ import BrandedHeaderBar from '@/components/layout/BrandedHeaderBar'
|
||||
import CompanyFooter from '@/components/layout/CompanyFooter'
|
||||
import { buildBreadcrumbs, buildDocumentTitle } from '@/components/layout/Breadcrumbs'
|
||||
import { CommandMenu } from '@/components/feedback/CommandMenu'
|
||||
import { SearchDialog } from '@/components/feedback/SearchDialog'
|
||||
import { KeyboardShortcutsDialog } from '@/components/feedback/KeyboardShortcutsDialog'
|
||||
import { AccountMenu } from '@/components/layout/AccountMenu'
|
||||
import { HelpMenu, HelpMenuItems } from '@/components/layout/HelpMenu'
|
||||
import { HEADER_MENU_ITEM_CLASS } from '@/components/layout/HeaderMenu'
|
||||
import { singleKeyShortcutsEnabled } from '@/lib/keyboard/single-key-shortcuts'
|
||||
import { useSingleKeyShortcutsSync } from '@/lib/keyboard/use-single-key-shortcuts-sync'
|
||||
import { HelpPanelProvider } from '@/components/help/HelpPanelProvider'
|
||||
import { AssistantProvider, useAssistantController } from '@/components/assistant/AssistantProvider'
|
||||
import { AssistantHeaderButton } from '@/components/assistant/AssistantHeaderButton'
|
||||
@@ -58,10 +64,6 @@ import { AssistantMount } from '@/components/assistant/AssistantMount'
|
||||
import { AlertsBell, useAlertsInstalled } from '@/components/alerts/AlertsBell'
|
||||
import { NotificationBannerSlot } from '@/components/alerts/NotificationBannerSlot'
|
||||
|
||||
// The favorites menu checks for collaboration and loads after hydration, so neither it nor the
|
||||
// collaboration hooks are in the dashboard's first load (the slot stays empty until then).
|
||||
const LazyFavoritesMenu = dynamic(() => import('@/components/collaboration/FavoritesMenuSlot').then((module) => module.LazyFavoritesMenu), { ssr: false })
|
||||
|
||||
/**
|
||||
* Inner layout that renders the full dashboard chrome.
|
||||
*
|
||||
@@ -73,7 +75,8 @@ const LazyFavoritesMenu = dynamic(() => import('@/components/collaboration/Favor
|
||||
* - Applies the application theme (tokens, rules, customCss) and the branded header bar.
|
||||
* - Configures analytics and records a page view per screen.
|
||||
* - Redirects unauthenticated users to `/login`.
|
||||
* - Registers global keyboard shortcuts: Cmd+K (command palette), `/` (search), `?` (help).
|
||||
* - Registers global keyboard shortcuts: Cmd+K and `/` (search), `?` (keyboard shortcuts); the
|
||||
* single-key ones only while the user has not turned single-key shortcuts off (WCAG 2.1.4).
|
||||
* - Renders the desktop sidebar, mobile sidebar drawer, banners, header, and main content slot.
|
||||
*
|
||||
* @param children - The authenticated page content to render in the main slot.
|
||||
@@ -88,15 +91,17 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
// Mobile sidebar drawer state
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false)
|
||||
const menuButtonRef = useRef<HTMLButtonElement>(null)
|
||||
const helpButtonRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
// Command palette state
|
||||
// The one search box (pages, records, actions, help, Ask): Cmd/Ctrl+K, `/`, the header field
|
||||
const [commandOpen, setCommandOpen] = useState(false)
|
||||
// opened from Help > Search help: scoped to help articles
|
||||
const [commandHelpOnly, setCommandHelpOnly] = useState(false)
|
||||
const openSearch = useCallback((helpOnly = false) => {
|
||||
setCommandHelpOnly(helpOnly)
|
||||
setCommandOpen(true)
|
||||
}, [])
|
||||
|
||||
// Search dialog state (/ key)
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
|
||||
// Keyboard shortcuts help dialog state
|
||||
// Keyboard shortcuts sheet (`?`, or Help > Keyboard shortcuts)
|
||||
const [helpOpen, setHelpOpen] = useState(false)
|
||||
|
||||
// Load full application metadata
|
||||
@@ -104,6 +109,7 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
data: metaData,
|
||||
isLoading: metaLoading,
|
||||
error: metaError,
|
||||
refetch: reloadMetaData,
|
||||
} = useQuery({
|
||||
queryKey: queryKeys.metadataAll(),
|
||||
queryFn: loadMetaData,
|
||||
@@ -116,16 +122,24 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
const assistant = useAssistantController(metaData, isAuthenticated)
|
||||
const { enabled: assistantEnabled, toggle: toggleAssistant } = assistant
|
||||
|
||||
// The user's single-key shortcut setting (server Keyboard section, or this browser's choice)
|
||||
useSingleKeyShortcutsSync(isAuthenticated)
|
||||
|
||||
// Generate sidebar routes and path map from app tree
|
||||
const { sidebarRoutes, pathToLabelMap, ancestorAppMap, navTargets, homePath } = useAppTreeRoutes(metaData)
|
||||
const { sidebarRoutes, pathToLabelMap, ancestorAppMap, navTargets, homePath, sectionRedirects } = useAppTreeRoutes(metaData)
|
||||
|
||||
// A section heading is not a page: its name as a path (an old link to a group that used to be an
|
||||
// app) goes to the app that heads it, at the section
|
||||
useEffect(() => {
|
||||
const target = sectionRedirects[(pathname ?? '').replace(/\/+$/, '')]
|
||||
if (target) router.replace(target)
|
||||
}, [pathname, sectionRedirects, router])
|
||||
|
||||
// Every route change starts at the top of the page (Material App scrolls to 0 on each pathname)
|
||||
useEffect(() => {
|
||||
scrollPageToTop()
|
||||
}, [pathname])
|
||||
|
||||
// Tables the backend record search covers for this user (none: search stays local)
|
||||
const searchTables = useMemo(() => searchableTables(metaData), [metaData])
|
||||
|
||||
// Sync pathToLabelMap to QContext
|
||||
useEffect(() => {
|
||||
@@ -134,8 +148,8 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}, [pathToLabelMap, setPathToLabelMap])
|
||||
|
||||
// Sync branding to QContext and inject theme
|
||||
useEffect(() => {
|
||||
// Install branding before the first branded shell is painted.
|
||||
useLayoutEffect(() => {
|
||||
if (metaData?.branding) {
|
||||
setBranding(metaData.branding)
|
||||
// accent colors (validated, MED-3) and the favicon
|
||||
@@ -158,7 +172,7 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
// customCss; removed again when the dashboard unmounts (sign-out)
|
||||
const { theme, setTheme } = useTheme()
|
||||
const applicationTheme = useMemo(() => readMaterialTheme(metaData), [metaData])
|
||||
useEffect(() => { setTheme(applicationTheme) }, [applicationTheme, setTheme])
|
||||
useLayoutEffect(() => { setTheme(applicationTheme) }, [applicationTheme, setTheme])
|
||||
useEffect(() => () => setTheme(null), [setTheme])
|
||||
|
||||
// Analytics (QRun-IO/qqq#730): off unless configured; one page view per screen
|
||||
@@ -166,10 +180,8 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
|
||||
// Sync user ID to QContext
|
||||
useEffect(() => {
|
||||
if (user?.email) {
|
||||
setUserId(user.email)
|
||||
}
|
||||
}, [user?.email, setUserId])
|
||||
setUserId(user?.id ?? user?.email)
|
||||
}, [user?.id, user?.email, setUserId])
|
||||
|
||||
// Redirect to login if not authenticated
|
||||
useEffect(() => {
|
||||
@@ -197,18 +209,19 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
/**
|
||||
* Global `keydown` handler that drives the application-level keyboard shortcuts.
|
||||
*
|
||||
* - Cmd+K / Ctrl+K — toggles the command palette.
|
||||
* - Cmd+K / Ctrl+K — toggles the search box.
|
||||
* - Cmd+J / Ctrl+J — toggles the assistant panel (when available; works in text fields too).
|
||||
* - Escape — closes all overlays (command palette, search dialog, help dialog, mobile sidebar).
|
||||
* - `.` — opens the command palette (only when not in a text field).
|
||||
* - `/` — opens the search dialog (only when not in a text field).
|
||||
* - `?` — opens the keyboard shortcuts dialog (only when not in a text field).
|
||||
* - Escape — closes all overlays (search box, shortcuts sheet, mobile sidebar).
|
||||
* - `/` — opens the search box (not in a text field; off with single-key shortcuts).
|
||||
* - `.` — the same, kept quietly for Material habits (off with single-key shortcuts).
|
||||
* - `?` — opens the keyboard shortcuts sheet (not in a text field; off with single-key shortcuts).
|
||||
*
|
||||
* @param e - The native DOM keyboard event.
|
||||
*/
|
||||
const handleGlobalKeyDown = useCallback((e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
||||
e.preventDefault()
|
||||
setCommandHelpOnly(false)
|
||||
setCommandOpen((prev) => !prev)
|
||||
}
|
||||
if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'j' && assistantEnabled) {
|
||||
@@ -218,46 +231,35 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
setCommandOpen(false)
|
||||
setSearchOpen(false)
|
||||
setHelpOpen(false)
|
||||
// The navigation drawer is a modal dialog and handles its own Escape
|
||||
}
|
||||
|
||||
// Single-key shortcuts — only when not focused in a text field
|
||||
if (!isInputFocused() && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||
// Single-key shortcuts — only when not focused in a text field, and not turned off (WCAG 2.1.4)
|
||||
if (!isInputFocused() && !e.metaKey && !e.ctrlKey && !e.altKey && singleKeyShortcutsEnabled()) {
|
||||
if (e.key === '.') {
|
||||
e.preventDefault()
|
||||
recordAnalytics({ category: 'globalEvents', action: 'dotMenuKeyboardShortcut' })
|
||||
setCommandOpen(true)
|
||||
openSearch()
|
||||
}
|
||||
if (e.key === '/') {
|
||||
e.preventDefault()
|
||||
setSearchOpen(true)
|
||||
openSearch()
|
||||
}
|
||||
if (e.key === '?') {
|
||||
e.preventDefault()
|
||||
setHelpOpen(true)
|
||||
}
|
||||
}
|
||||
}, [isInputFocused, assistantEnabled, toggleAssistant])
|
||||
}, [isInputFocused, assistantEnabled, toggleAssistant, openSearch])
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('keydown', handleGlobalKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleGlobalKeyDown)
|
||||
}, [handleGlobalKeyDown])
|
||||
|
||||
// Show loading state while auth initializes
|
||||
if (authLoading) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div
|
||||
className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"
|
||||
role="status"
|
||||
aria-label="Loading"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
// Use the same neutral screen through authentication and metadata loading.
|
||||
if (authLoading) return <ApplicationLoading />
|
||||
|
||||
// Auth loaded but not authenticated — redirect handled above
|
||||
if (!isAuthenticated) {
|
||||
@@ -269,15 +271,18 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-destructive">Failed to load application metadata.</p>
|
||||
<p role="alert" className="text-destructive">Unable to load your workspace.</p>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
{metaError instanceof Error ? metaError.message : 'Unknown error'}
|
||||
</p>
|
||||
<button type="button" className="mt-4 rounded-md border px-4 py-2" onClick={() => { void reloadMetaData() }}>Try again</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!metaData) return <ApplicationLoading />
|
||||
|
||||
// One scroll container: the shell is exactly the viewport and only <main> scrolls. Both are
|
||||
// positioned (`relative`) so they contain absolutely positioned descendants (`sr-only` text,
|
||||
// tooltips): otherwise such an element's containing block is the viewport, `overflow-hidden`
|
||||
@@ -285,8 +290,9 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
// tab") makes the document taller than the window, a second scrollbar beside main's.
|
||||
return (
|
||||
<HelpPanelProvider instance={metaData}>
|
||||
<AssistantProvider value={assistant}>
|
||||
<SecuredDataProvider enabled={isAuthenticated}><AssistantProvider value={assistant}>
|
||||
<div className="relative flex h-screen flex-col overflow-hidden bg-background" data-qqq-id="app-shell">
|
||||
<SecuredDataBannerSlot />
|
||||
{/* Top-of-site banner spans the whole window, above the sidebar */}
|
||||
<BannerComponent banners={metaData?.branding?.banners} slot="QFMD_TOP_OF_SITE" className="border-x-0 border-t-0" />
|
||||
<BrandedHeaderBar theme={theme} />
|
||||
@@ -296,6 +302,7 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
href="#main-content"
|
||||
className="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-[9999] focus:inline-flex focus:items-center pointer-coarse:focus:min-h-11 focus:rounded-md focus:bg-primary focus:px-4 focus:py-2 focus:text-sm focus:font-medium focus:text-primary-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||
data-qqq-id="skip-to-content"
|
||||
onClick={(event) => { if (skipToFirstZone()) event.preventDefault() }}
|
||||
>
|
||||
Skip to main content
|
||||
</a>
|
||||
@@ -305,9 +312,7 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
routes={sidebarRoutes}
|
||||
branding={metaData?.branding}
|
||||
homePath={homePath}
|
||||
logout={logout}
|
||||
userName={user?.name}
|
||||
userEmail={user?.email}
|
||||
showFavorites={isAuthenticated}
|
||||
data-qqq-id="sidebar-container"
|
||||
/>
|
||||
|
||||
@@ -316,9 +321,8 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
routes={sidebarRoutes}
|
||||
branding={metaData?.branding}
|
||||
homePath={homePath}
|
||||
logout={logout}
|
||||
userName={user?.name}
|
||||
userEmail={user?.email}
|
||||
showFavorites={isAuthenticated}
|
||||
onSearchOpen={() => openSearch()}
|
||||
open={sidebarOpen}
|
||||
onClose={() => setSidebarOpen(false)}
|
||||
returnFocusRef={menuButtonRef}
|
||||
@@ -333,22 +337,37 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
onMenuOpen={() => setSidebarOpen(true)}
|
||||
menuOpen={sidebarOpen}
|
||||
menuButtonRef={menuButtonRef}
|
||||
onSearchOpen={() => setSearchOpen(true)}
|
||||
onCommandOpen={() => setCommandOpen(true)}
|
||||
onHelpOpen={() => setHelpOpen(true)}
|
||||
helpButtonRef={helpButtonRef}
|
||||
onSearchOpen={() => openSearch()}
|
||||
pathToLabelMap={pathToLabelMap}
|
||||
ancestorAppMap={ancestorAppMap}
|
||||
homePath={homePath}
|
||||
navTargets={navTargets}
|
||||
searchTables={searchTables}
|
||||
assistantButton={<AssistantHeaderButton />}
|
||||
favoritesButton={isAuthenticated ? <LazyFavoritesMenu /> : null}
|
||||
notificationsButton={isAuthenticated && alertsInstalled ? <AlertsBell metaData={metaData} /> : null}
|
||||
helpMenu={<HelpMenu onSearchHelp={() => openSearch(true)} onShortcuts={() => setHelpOpen(true)} />}
|
||||
accountMenu={(
|
||||
<AccountMenu
|
||||
userName={user?.name}
|
||||
userEmail={user?.email}
|
||||
logout={logout}
|
||||
compactItems={(close) => (
|
||||
<>
|
||||
{/* the compact header has no room for Help and Ask: they lead this menu (help stays in one place) */}
|
||||
<HelpMenuItems close={close} onSearchHelp={() => openSearch(true)} onShortcuts={() => setHelpOpen(true)} />
|
||||
{assistantEnabled && (
|
||||
<button type="button" role="menuitem" className={HEADER_MENU_ITEM_CLASS} data-qqq-id="menu-item-ask"
|
||||
onClick={() => close(toggleAssistant)}>
|
||||
<Sparkles className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
|
||||
Ask the assistant
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Page content */}
|
||||
<main className="relative flex-1 overflow-y-auto p-6" id="main-content" data-qqq-id="main-content">
|
||||
<main className="relative flex-1 overflow-y-auto p-6 focus:outline-none" id="main-content" tabIndex={-1} data-qqq-id="main-content">
|
||||
{metaLoading ? (
|
||||
<div
|
||||
className="flex items-center justify-center py-12"
|
||||
@@ -379,16 +398,14 @@ function DashboardLayoutContent({ children }: { children: React.ReactNode }) {
|
||||
onClose={() => setCommandOpen(false)}
|
||||
navTargets={navTargets}
|
||||
metaData={metaData}
|
||||
helpOnly={commandHelpOnly}
|
||||
onAskAssistant={assistantEnabled ? (text) => assistant.openWith(text) : undefined}
|
||||
/>
|
||||
|
||||
{/* Search Dialog */}
|
||||
<SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} navTargets={navTargets} searchTables={searchTables} />
|
||||
|
||||
{/* Keyboard Shortcuts Help Dialog */}
|
||||
<KeyboardShortcutsDialog open={helpOpen} onClose={() => setHelpOpen(false)} returnFocusRef={helpButtonRef} assistantEnabled={assistantEnabled} />
|
||||
{/* Keyboard Shortcuts Sheet */}
|
||||
<KeyboardShortcutsDialog open={helpOpen} onClose={() => setHelpOpen(false)} assistantEnabled={assistantEnabled} />
|
||||
</div>
|
||||
</AssistantProvider>
|
||||
</AssistantProvider></SecuredDataProvider>
|
||||
</HelpPanelProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ import { AuthProvider } from '@/lib/auth/auth-provider'
|
||||
import { ThemeProvider } from '@/lib/theme/theme-provider'
|
||||
import { injectThemeTokens } from '@/lib/theme/tokens'
|
||||
import { AppToaster } from '@/components/feedback/Toast'
|
||||
import { QaCaptureLoader } from '@/components/qa-capture/QaCaptureLoader'
|
||||
|
||||
// Inject default theme tokens on first render
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -79,7 +80,11 @@ export default function Providers({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
<AuthProvider>
|
||||
{/* QA capture (qa-capture extension): nothing is loaded unless the server enables it for this user */}
|
||||
<QaCaptureLoader />
|
||||
{children}
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
<AppToaster />
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -35,6 +35,7 @@ import { getAlertsInboxSummary } from '@/lib/api/alerts'
|
||||
import { 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'
|
||||
|
||||
const AlertsBellPopover = lazy(() => import('./AlertsBellPopover'))
|
||||
|
||||
@@ -115,30 +116,34 @@ export function AlertsBell(_props: { metaData: QInstance | undefined }) {
|
||||
if (!data) return null
|
||||
|
||||
const unread = data.unreadCount
|
||||
const label = unread > 0 ? `Notifications, ${unread} unread` : 'Notifications, none unread'
|
||||
const critical = data.highestUnreadSeverity === 'CRITICAL'
|
||||
// severity is in the name, not only in the badge's color
|
||||
const label = unread > 0 ? `Notifications, ${unread} unread${critical ? ', critical' : ''}` : 'Notifications, none unread'
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
className="relative flex items-center justify-center rounded-lg p-2 hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className={HEADER_BUTTON_CLASS}
|
||||
aria-label={label}
|
||||
title="Notifications"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
data-qqq-id="button-notifications"
|
||||
>
|
||||
<Bell className="h-5 w-5 text-foreground/60" aria-hidden="true" />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
className={`absolute right-0.5 top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none ${critical ? 'bg-destructive text-white' : 'bg-primary text-primary-foreground'}`}
|
||||
aria-hidden="true"
|
||||
data-qqq-id="alerts-unread-badge"
|
||||
>
|
||||
{unread > 99 ? '99+' : unread}
|
||||
</span>
|
||||
)}
|
||||
<HeaderIconAnchor>
|
||||
<Bell className="h-5 w-5" aria-hidden="true" />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
className={`${HEADER_BADGE_CLASS} ${critical ? 'bg-destructive text-white' : 'bg-primary text-primary-foreground'}`}
|
||||
aria-hidden="true"
|
||||
data-qqq-id="alerts-unread-badge"
|
||||
>
|
||||
{unread > 99 ? '99+' : unread}
|
||||
</span>
|
||||
)}
|
||||
</HeaderIconAnchor>
|
||||
</button>
|
||||
<span className="sr-only" aria-live="polite" data-qqq-id="alerts-unread-announcer">{label}</span>
|
||||
{open && (
|
||||
|
||||
@@ -148,7 +148,7 @@ describe('AlertsBell', () => {
|
||||
return HttpResponse.json({ ...SUMMARY, pollSeconds: 0.05 })
|
||||
}))
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
expect(await screen.findByRole('button', { name: 'Notifications, 2 unread' })).toBeInTheDocument()
|
||||
expect(await screen.findByRole('button', { name: /^Notifications, 2 unread/ })).toBeInTheDocument()
|
||||
await waitFor(() => expect(calls).toBeGreaterThanOrEqual(3))
|
||||
})
|
||||
|
||||
@@ -159,7 +159,7 @@ describe('AlertsBell', () => {
|
||||
return HttpResponse.json({ ...SUMMARY, pollSeconds: 0.05 })
|
||||
}))
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await screen.findByRole('button', { name: 'Notifications, 2 unread' })
|
||||
await screen.findByRole('button', { name: /^Notifications, 2 unread/ })
|
||||
act(() => focusManager.setFocused(false))
|
||||
await sleep(100)
|
||||
const hidden = calls
|
||||
@@ -194,15 +194,22 @@ describe('AlertsBell', () => {
|
||||
it('shows the unread count, red for critical, capped at 99+, with an accessible label', async () => {
|
||||
server.use(http.get('/qqq/v1/alerts/inbox/summary', () => HttpResponse.json(SUMMARY)))
|
||||
const first = renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
const bell = await screen.findByRole('button', { name: 'Notifications, 2 unread' })
|
||||
const bell = await screen.findByRole('button', { name: /^Notifications, 2 unread/ })
|
||||
expect(bell).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.getByText('2', { selector: '[data-qqq-id="alerts-unread-badge"]' })).toHaveClass('bg-destructive')
|
||||
// severity is in the name, not only in the badge color
|
||||
expect(bell).toHaveAccessibleName('Notifications, 2 unread, critical')
|
||||
const badge = screen.getByText('2', { selector: '[data-qqq-id="alerts-unread-badge"]' })
|
||||
expect(badge).toHaveClass('bg-destructive')
|
||||
// the badge is positioned against the icon (the header's shared anchor), inside the button
|
||||
expect(badge.parentElement).toHaveAttribute('data-qqq-id', 'header-icon-anchor')
|
||||
expect(badge.parentElement).toHaveClass('relative')
|
||||
expect(badge.parentElement?.parentElement).toBe(bell)
|
||||
expect(document.querySelector('[data-qqq-id="alerts-unread-announcer"]')).toHaveAttribute('aria-live', 'polite')
|
||||
first.unmount()
|
||||
|
||||
server.use(http.get('/qqq/v1/alerts/inbox/summary', () => HttpResponse.json({ ...SUMMARY, unreadCount: 140, highestUnreadSeverity: 'WARNING' })))
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await screen.findByRole('button', { name: 'Notifications, 140 unread' })
|
||||
await screen.findByRole('button', { name: /^Notifications, 140 unread/ })
|
||||
expect(screen.getByText('99+', { selector: '[data-qqq-id="alerts-unread-badge"]' })).toHaveClass('bg-primary')
|
||||
})
|
||||
|
||||
@@ -211,7 +218,7 @@ describe('AlertsBell', () => {
|
||||
const reads = captureAction('read')
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
const bell = await screen.findByRole('button', { name: 'Notifications, 2 unread' })
|
||||
const bell = await screen.findByRole('button', { name: /^Notifications, 2 unread/ })
|
||||
await user.click(bell)
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Notifications' })
|
||||
expect(await axe(dialog)).toHaveNoViolations()
|
||||
@@ -241,7 +248,7 @@ describe('AlertsBell', () => {
|
||||
server.use(http.get('/qqq/v1/alerts/inbox/summary', () => HttpResponse.json(SUMMARY)))
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Notifications, 2 unread' }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Notifications, 2 unread/ }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Notifications' })
|
||||
const first = within(dialog).getAllByRole('link')[0]
|
||||
await waitFor(() => expect(first).toHaveFocus())
|
||||
@@ -258,7 +265,7 @@ describe('AlertsBell', () => {
|
||||
const dismissals = captureAction('dismiss')
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Notifications, 2 unread' }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Notifications, 2 unread/ }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Notifications' })
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Mark read: Nightly backup did not run' }))
|
||||
@@ -283,11 +290,11 @@ describe('AlertsBell', () => {
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Notifications, 2 unread' }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Notifications, 2 unread/ }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Notifications' })
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Dismiss: Nightly backup did not run' }))
|
||||
expect(within(dialog).queryByText('Nightly backup did not run')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Notifications, 1 unread' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /^Notifications, 1 unread/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('rolls back when an action fails', async () => {
|
||||
@@ -297,9 +304,9 @@ describe('AlertsBell', () => {
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Notifications, 2 unread' }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Notifications, 2 unread/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Mark all read' }))
|
||||
expect(await screen.findByRole('button', { name: 'Notifications, 2 unread' })).toBeInTheDocument()
|
||||
expect(await screen.findByRole('button', { name: /^Notifications, 2 unread/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('marks all read and opens the notifications page', async () => {
|
||||
@@ -307,7 +314,7 @@ describe('AlertsBell', () => {
|
||||
const reads = captureAction('read')
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Notifications, 2 unread' }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Notifications, 2 unread/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Mark all read' }))
|
||||
await waitFor(() => expect(reads).toEqual([{ all: true }]))
|
||||
await user.click(screen.getByRole('link', { name: 'View all' }))
|
||||
@@ -319,7 +326,7 @@ describe('AlertsBell', () => {
|
||||
const reads = captureAction('read')
|
||||
const user = userEvent.setup()
|
||||
renderWithClient(<AlertsBell metaData={WITH_ALERTS} />)
|
||||
await user.click(await screen.findByRole('button', { name: 'Notifications, 1 unread' }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Notifications, 1 unread/ }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Notifications' })
|
||||
expect(dialog).toHaveTextContent('CDN · 20 min ago')
|
||||
expect(within(dialog).queryByRole('button', { name: /Dismiss/ })).not.toBeInTheDocument()
|
||||
|
||||
@@ -20,6 +20,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { axe } from 'jest-axe'
|
||||
|
||||
import { attachmentPolicy, ATTACHMENTS_ACCEPT, BULK_LOAD_ACCEPT } from '@/lib/utils/assistant-attachments'
|
||||
import { AssistantComposer } from './AssistantComposer'
|
||||
|
||||
/** Composer props with no page context. */
|
||||
@@ -66,4 +67,40 @@ describe('AssistantComposer attachments', () => {
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Uploading')
|
||||
expect(screen.getByRole('button', { name: 'Attach a file' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('offers CSV or Excel for a bulk load by default', () => {
|
||||
const { container } = render(<AssistantComposer {...BASE} onAttach={() => {}} />)
|
||||
expect(screen.getByRole('button', { name: 'Attach a file' })).toHaveAttribute('title', 'Attach a file (CSV or Excel) for a bulk load')
|
||||
expect((container.querySelector('[data-qqq-id="assistant-attach-input"]') as HTMLInputElement).accept).toBe(BULK_LOAD_ACCEPT)
|
||||
})
|
||||
|
||||
it('offers any readable file when the server reads attachments, and describes the limits', () => {
|
||||
const policy = attachmentPolicy({ enabled: true, features: { attachments: true }, limits: { maxAttachmentBytes: 10 * 1024 * 1024, attachmentTypes: ['Text', 'PDF', 'Images'] } }, false)
|
||||
const { container } = render(<AssistantComposer {...BASE} onAttach={() => {}} attachPolicy={policy} />)
|
||||
const button = screen.getByRole('button', { name: 'Attach a file' })
|
||||
expect(button).toHaveAttribute('title', 'Attach a file')
|
||||
expect(button).toHaveAccessibleDescription('Reads Text, PDF, Images, up to 10 MB per file')
|
||||
expect((container.querySelector('[data-qqq-id="assistant-attach-input"]') as HTMLInputElement).accept).toBe(ATTACHMENTS_ACCEPT)
|
||||
})
|
||||
|
||||
it('shows each chip with its name, size and type, and an attach problem inline; passes axe', async () => {
|
||||
const onDismiss = vi.fn()
|
||||
const { container } = render(
|
||||
<AssistantComposer {...BASE} onAttach={() => {}} onRemoveAttachment={() => {}} onDismissAttachError={onDismiss}
|
||||
attachError="scan.pdf is 12 MB. The assistant reads files up to 10 MB."
|
||||
attachments={[
|
||||
{ uploadRef: 'up_1', fileName: 'notes.txt', sizeBytes: 524_288, contentType: 'text/plain' },
|
||||
{ uploadRef: 'up_2', fileName: 'screenshot.png', sizeBytes: 1_572_864, contentType: 'image/png' },
|
||||
{ uploadRef: 'up_3', fileName: 'rows.xlsx', sizeBytes: 2048 },
|
||||
]} />
|
||||
)
|
||||
const chips = container.querySelectorAll('[data-qqq-id="assistant-attachment-chip"]')
|
||||
expect(Array.from(chips).map((chip) => chip.getAttribute('data-kind'))).toEqual(['text', 'image', 'spreadsheet'])
|
||||
expect(chips[0]).toHaveTextContent('notes.txt, text file512 KB')
|
||||
expect(chips[1]).toHaveTextContent('1.5 MB')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('scan.pdf is 12 MB. The assistant reads files up to 10 MB.')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
|
||||
expect(onDismiss).toHaveBeenCalled()
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
})
|
||||
})
|
||||
@@ -22,10 +22,11 @@
|
||||
'use client'
|
||||
|
||||
import React, { forwardRef, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { FileText, Loader2, MapPin, Paperclip, SendHorizontal, Square, X } from 'lucide-react'
|
||||
import { AlertTriangle, File as FileIcon, FileImage, FileJson, FileSpreadsheet, FileText, Loader2, MapPin, Paperclip, SendHorizontal, Square, X } from 'lucide-react'
|
||||
|
||||
import type { AssistantAttachment } from '@/types/assistant'
|
||||
import type { AssistantPageInfo } from '@/lib/utils/assistant-links'
|
||||
import { attachmentKind, BULK_LOAD_ACCEPT, formatBytes, type AttachmentKind } from '@/lib/utils/assistant-attachments'
|
||||
|
||||
/** Props of {@link AssistantComposer}. */
|
||||
interface AssistantComposerProps {
|
||||
@@ -69,10 +70,31 @@ interface AssistantComposerProps {
|
||||
onRemoveAttachment?: (uploadRef: string) => void
|
||||
/** Whether an upload is in progress. */
|
||||
attaching?: boolean
|
||||
/** The file picker hint, tooltip and limits (defaults: CSV or Excel for a bulk load). */
|
||||
attachPolicy?: { accept: string; title: string; maxBytes?: number; types?: string[] }
|
||||
/** A problem with the last file (too large, upload failed), shown inline. */
|
||||
attachError?: string | null
|
||||
/** Clears {@link AssistantComposerProps.attachError}. */
|
||||
onDismissAttachError?: () => void
|
||||
}
|
||||
|
||||
/** File types the attach button offers (bulk load files). */
|
||||
const ATTACH_ACCEPT = '.csv,.tsv,.txt,.xlsx'
|
||||
/** Chip icon per attachment kind. */
|
||||
const KIND_ICON: Record<AttachmentKind, typeof FileText> = {
|
||||
image: FileImage,
|
||||
spreadsheet: FileSpreadsheet,
|
||||
json: FileJson,
|
||||
pdf: FileText,
|
||||
text: FileText,
|
||||
file: FileIcon,
|
||||
}
|
||||
|
||||
/** What a chip says about its type, for screen readers. */
|
||||
const KIND_LABEL: Record<AttachmentKind, string> = {
|
||||
image: 'image', spreadsheet: 'data file', json: 'JSON file', pdf: 'PDF', text: 'text file', file: 'file',
|
||||
}
|
||||
|
||||
/** Default attach policy: the bulk-load files of servers that do not read attachments. */
|
||||
const BULK_LOAD_POLICY = { accept: BULK_LOAD_ACCEPT, title: 'Attach a file (CSV or Excel) for a bulk load' }
|
||||
|
||||
/** Tallest the textarea grows before it scrolls, in pixels. */
|
||||
const MAX_TEXTAREA_HEIGHT = 160
|
||||
@@ -85,7 +107,7 @@ const MAX_TEXTAREA_HEIGHT = 160
|
||||
* @returns The composer form.
|
||||
*/
|
||||
function AssistantComposerInner(
|
||||
{ pageInfo, contextDismissed, onDismissContext, onRefreshContext, streaming, stopping, concurrency = 'supersede', onSend, onStop, prefill, attachments = [], onAttach, onRemoveAttachment, attaching = false }: AssistantComposerProps,
|
||||
{ pageInfo, contextDismissed, onDismissContext, onRefreshContext, streaming, stopping, concurrency = 'supersede', onSend, onStop, prefill, attachments = [], onAttach, onRemoveAttachment, attaching = false, attachPolicy = BULK_LOAD_POLICY, attachError = null, onDismissAttachError }: AssistantComposerProps,
|
||||
ref: React.ForwardedRef<HTMLTextAreaElement>
|
||||
) {
|
||||
const [text, setText] = useState('')
|
||||
@@ -93,6 +115,11 @@ function AssistantComposerInner(
|
||||
const hintId = useId()
|
||||
const localRef = useRef<HTMLTextAreaElement | null>(null)
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
const attachHintId = useId()
|
||||
const attachHint = [
|
||||
attachPolicy.types?.length ? `Reads ${attachPolicy.types.join(', ')}` : '',
|
||||
attachPolicy.maxBytes ? `up to ${formatBytes(attachPolicy.maxBytes)} per file` : '',
|
||||
].filter(Boolean).join(', ')
|
||||
|
||||
// A deep link pre-fills the box; the user reviews and sends it
|
||||
useEffect(() => {
|
||||
@@ -149,23 +176,30 @@ function AssistantComposerInner(
|
||||
)}
|
||||
{(attachments.length > 0 || attaching) && (
|
||||
<ul className="mb-2 flex min-w-0 flex-wrap gap-1.5" aria-label="Attached files" data-qqq-id="assistant-attachments">
|
||||
{attachments.map((attachment) => (
|
||||
<li key={attachment.uploadRef} className="inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border border-border bg-muted py-0.5 pl-2 pr-0.5 text-xs text-muted-foreground" data-qqq-id="assistant-attachment-chip">
|
||||
<FileText className="h-3 w-3 shrink-0" aria-hidden="true" />
|
||||
<span className="truncate">{attachment.fileName ?? 'Attached file'}</span>
|
||||
{onRemoveAttachment && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveAttachment(attachment.uploadRef)}
|
||||
className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full hover:bg-accent hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:h-8 pointer-coarse:w-8"
|
||||
aria-label={`Remove ${attachment.fileName ?? 'the attached file'}`}
|
||||
data-qqq-id="assistant-attachment-remove"
|
||||
>
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
{attachments.map((attachment) => {
|
||||
const kind = attachmentKind(attachment.fileName, attachment.contentType)
|
||||
const Icon = KIND_ICON[kind]
|
||||
const size = typeof attachment.sizeBytes === 'number' ? formatBytes(attachment.sizeBytes) : ''
|
||||
return (
|
||||
<li key={attachment.uploadRef} className="inline-flex min-w-0 max-w-full items-center gap-1 rounded-full border border-border bg-muted py-0.5 pl-2 pr-0.5 text-xs text-muted-foreground" data-qqq-id="assistant-attachment-chip" data-kind={kind}>
|
||||
<Icon className="h-3 w-3 shrink-0" aria-hidden="true" />
|
||||
<span className="truncate text-foreground">{attachment.fileName || 'Attached file'}</span>
|
||||
<span className="sr-only">, {KIND_LABEL[kind]}</span>
|
||||
{size && <span className="shrink-0 tabular-nums" data-qqq-id="assistant-attachment-size">{size}</span>}
|
||||
{onRemoveAttachment && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveAttachment(attachment.uploadRef)}
|
||||
className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full hover:bg-accent hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:h-8 pointer-coarse:w-8"
|
||||
aria-label={`Remove ${attachment.fileName || 'the attached file'}`}
|
||||
data-qqq-id="assistant-attachment-remove"
|
||||
>
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
{attaching && (
|
||||
<li className="inline-flex items-center gap-1 rounded-full border border-border py-0.5 pl-2 pr-2 text-xs text-muted-foreground" role="status" data-qqq-id="assistant-attaching">
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
|
||||
@@ -174,13 +208,30 @@ function AssistantComposerInner(
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
{attachError && (
|
||||
<div className="mb-2 flex min-w-0 items-start gap-1.5 rounded-md border border-destructive/40 px-2 py-1.5 text-xs text-destructive" role="alert" data-qqq-id="assistant-attach-error">
|
||||
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1 break-words">{attachError}</span>
|
||||
{onDismissAttachError && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDismissAttachError}
|
||||
className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:h-8 pointer-coarse:w-8"
|
||||
aria-label="Dismiss"
|
||||
data-qqq-id="assistant-attach-error-dismiss"
|
||||
>
|
||||
<X className="h-3 w-3" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-end gap-2 rounded-lg border border-input bg-background px-2 py-1.5 focus-within:ring-2 focus-within:ring-ring">
|
||||
{onAttach && (
|
||||
<>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept={ATTACH_ACCEPT}
|
||||
accept={attachPolicy.accept}
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
aria-hidden="true"
|
||||
@@ -197,11 +248,13 @@ function AssistantComposerInner(
|
||||
disabled={attaching}
|
||||
className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 pointer-coarse:h-11 pointer-coarse:w-11"
|
||||
aria-label="Attach a file"
|
||||
title="Attach a file (CSV or Excel) for a bulk load"
|
||||
aria-describedby={attachHint ? attachHintId : undefined}
|
||||
title={attachPolicy.title}
|
||||
data-qqq-id="assistant-attach"
|
||||
>
|
||||
<Paperclip className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
{attachHint && <span id={attachHintId} className="sr-only">{attachHint}</span>}
|
||||
</>
|
||||
)}
|
||||
<label htmlFor={inputId} className="sr-only">Message the assistant</label>
|
||||
@@ -231,9 +284,8 @@ function AssistantComposerInner(
|
||||
<button
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
disabled={stopping}
|
||||
className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border text-foreground hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 pointer-coarse:h-11 pointer-coarse:w-11"
|
||||
aria-label={stopping ? 'Stopping' : 'Stop the reply'}
|
||||
aria-label={stopping ? 'Stopping - select to stop now' : 'Stop the reply'}
|
||||
data-qqq-id="assistant-stop"
|
||||
>
|
||||
<Square className="h-3.5 w-3.5 fill-current" aria-hidden="true" />
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
/*
|
||||
* Copyright 2026 QRun.IO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// Tests for the conversation list: row actions (archive, restore, delete with confirmation and
|
||||
// rollback), the manage link, running and unread indicators, and marking read when a reply ends
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { toast } from 'sonner'
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { axe } from 'jest-axe'
|
||||
|
||||
import type { QInstance } from '@/types'
|
||||
import type { AssistantConversation } from '@/types/assistant'
|
||||
import { server } from '@/mocks/node'
|
||||
import { uiApiVersionHandler } from '@/mocks/ui-api-version'
|
||||
import { AssistantProvider, useAssistantController } from './AssistantProvider'
|
||||
import { AssistantHeaderButton } from './AssistantHeaderButton'
|
||||
import { AssistantMount } from './AssistantMount'
|
||||
import { ConversationRail } from './ConversationRail'
|
||||
|
||||
const router = vi.hoisted(() => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn(), forward: vi.fn(), refresh: vi.fn(), prefetch: vi.fn() }))
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => router,
|
||||
usePathname: () => window.location.pathname,
|
||||
useSearchParams: () => new URLSearchParams(window.location.search),
|
||||
}))
|
||||
|
||||
const BASE = '/qqq/v1/assistant'
|
||||
const META = {
|
||||
tables: { person: { name: 'person', label: 'People' }, assistantConversation: { name: 'assistantConversation', label: 'Conversations' } },
|
||||
supplementalInstanceMetaData: { assistant: {} },
|
||||
} as unknown as QInstance
|
||||
|
||||
/**
|
||||
* Builds a conversation.
|
||||
*
|
||||
* @param id - The id.
|
||||
* @param title - The title.
|
||||
* @param extra - Other fields.
|
||||
* @returns The conversation.
|
||||
*/
|
||||
function conversation(id: number, title: string, extra: Partial<AssistantConversation> = {}): AssistantConversation {
|
||||
return { id, title, status: 'ACTIVE', pinned: false, lastMessageAt: null, unreadCount: 0, createDate: '2026-10-12T00:00:00Z', ...extra }
|
||||
}
|
||||
|
||||
/** The accessible name of the unread row (the spacing around the screen-reader text varies by engine). */
|
||||
const UNREAD_ROW = /^Open invoices\s*,\s*unread$/
|
||||
|
||||
const LIST = [
|
||||
conversation(1, 'Sales report', { running: true }),
|
||||
conversation(2, 'Open invoices', { unreadCount: 2 }),
|
||||
conversation(3, 'Weekly summary', { pinned: true }),
|
||||
conversation(4, 'Quiet one'),
|
||||
]
|
||||
|
||||
/**
|
||||
* Props of the rail, with spies.
|
||||
*
|
||||
* @param overrides - Props to change.
|
||||
* @returns The props.
|
||||
*/
|
||||
function railProps(overrides: Partial<React.ComponentProps<typeof ConversationRail>> = {}): React.ComponentProps<typeof ConversationRail> {
|
||||
return {
|
||||
conversations: LIST, loading: false, activeId: null, status: 'ACTIVE',
|
||||
onStatusChange: vi.fn(), onSelect: vi.fn(), onArchive: vi.fn(), onDelete: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('ConversationRail', () => {
|
||||
it('has Archive and Delete on every row, and Restore in the archived list', async () => {
|
||||
const props = railProps()
|
||||
const user = userEvent.setup()
|
||||
const { rerender } = render(<ConversationRail {...props} />)
|
||||
for (const item of LIST) {
|
||||
expect(screen.getByRole('button', { name: `Archive ${item.title}` })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: `Delete ${item.title}` })).toBeInTheDocument()
|
||||
}
|
||||
await user.click(screen.getByRole('button', { name: 'Archive Quiet one' }))
|
||||
expect(props.onArchive).toHaveBeenCalledWith(LIST[3])
|
||||
await user.click(screen.getByRole('button', { name: 'Delete Open invoices' }))
|
||||
expect(props.onDelete).toHaveBeenCalledWith(LIST[1])
|
||||
|
||||
const archived = LIST.map((item) => ({ ...item, status: 'ARCHIVED' as const }))
|
||||
rerender(<ConversationRail {...props} conversations={archived} status="ARCHIVED" />)
|
||||
expect(screen.getByRole('button', { name: 'Restore Quiet one' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /^Archive / })).toBeNull()
|
||||
})
|
||||
|
||||
it('moves between rows with the arrow keys and reaches a row\'s actions with Right', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<ConversationRail {...railProps()} />)
|
||||
// pinned first, then recent in order
|
||||
const names: Array<string | RegExp> = ['Weekly summary', 'Working: Sales report', UNREAD_ROW, 'Quiet one']
|
||||
const mains = names.map((name) => screen.getByRole('button', { name }))
|
||||
mains[0].focus()
|
||||
await user.keyboard('{ArrowDown}')
|
||||
expect(mains[1]).toHaveFocus()
|
||||
await user.keyboard('{End}')
|
||||
expect(mains[3]).toHaveFocus()
|
||||
await user.keyboard('{Home}')
|
||||
expect(mains[0]).toHaveFocus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
expect(screen.getByRole('button', { name: 'Archive Weekly summary' })).toHaveFocus()
|
||||
await user.keyboard('{ArrowRight}')
|
||||
expect(screen.getByRole('button', { name: 'Delete Weekly summary' })).toHaveFocus()
|
||||
await user.keyboard('{ArrowLeft}{ArrowLeft}')
|
||||
expect(mains[0]).toHaveFocus()
|
||||
// one tab stop per list: only the current row's buttons are tabbable
|
||||
expect(mains[1]).toHaveAttribute('tabindex', '-1')
|
||||
expect(screen.getByRole('button', { name: 'Delete Quiet one' })).toHaveAttribute('tabindex', '-1')
|
||||
})
|
||||
|
||||
it('marks running conversations with a spinner and unread ones with a dot and a bold title', () => {
|
||||
const { container } = render(<ConversationRail {...railProps()} />)
|
||||
const running = screen.getByRole('button', { name: 'Working: Sales report' })
|
||||
expect(running.querySelector('[data-qqq-id="assistant-conversation-running"]')).not.toBeNull()
|
||||
expect(running.querySelector('.motion-safe\\:animate-spin')).not.toBeNull()
|
||||
const unread = screen.getByRole('button', { name: UNREAD_ROW })
|
||||
expect(unread.querySelector('[data-qqq-id="assistant-conversation-unread"]')).not.toBeNull()
|
||||
expect(unread.querySelector('.font-semibold')).toHaveTextContent('Open invoices')
|
||||
expect(container.querySelectorAll('[data-qqq-id="assistant-conversation-running"]')).toHaveLength(1)
|
||||
expect(container.querySelectorAll('[data-qqq-id="assistant-conversation-unread"]')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('shows both indicators on a conversation that is running and unread', () => {
|
||||
render(<ConversationRail {...railProps({ conversations: [conversation(7, 'Busy', { running: true, unreadCount: 1 })] })} />)
|
||||
const row = screen.getByRole('button', { name: /^Working: Busy/ })
|
||||
expect(row.querySelector('[data-qqq-id="assistant-conversation-running"]')).not.toBeNull()
|
||||
expect(row.querySelector('[data-qqq-id="assistant-conversation-unread"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('shows the manage link only with a path', () => {
|
||||
const { rerender } = render(<ConversationRail {...railProps({ manageHref: '/app/assistantConversation' })} />)
|
||||
expect(screen.getByRole('link', { name: 'Manage all conversations' })).toHaveAttribute('href', '/app/assistantConversation')
|
||||
rerender(<ConversationRail {...railProps({ manageHref: null })} />)
|
||||
expect(screen.queryByRole('link', { name: 'Manage all conversations' })).toBeNull()
|
||||
})
|
||||
|
||||
it.each(['ACTIVE', 'ARCHIVED'] as const)('passes axe with running and unread rows (%s)', async (status) => {
|
||||
const conversations = LIST.map((item) => ({ ...item, status }))
|
||||
const { container } = render(<ConversationRail {...railProps({ conversations, status, activeId: 4, manageHref: '/app/assistantConversation' })} />)
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Inside the panel ────────────────────────────────────────────────────────
|
||||
|
||||
/** Records the traffic of one test. */
|
||||
const traffic: { patches: Array<{ id: string; body: unknown }>; deletes: string[] } = { patches: [], deletes: [] }
|
||||
|
||||
/**
|
||||
* Harness: the dashboard's assistant wiring.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.metaData - Instance metadata.
|
||||
* @returns The shell.
|
||||
*/
|
||||
function Shell({ metaData }: { metaData: QInstance }) {
|
||||
const assistant = useAssistantController(metaData, true)
|
||||
return (
|
||||
<AssistantProvider value={assistant}>
|
||||
<header><AssistantHeaderButton /></header>
|
||||
<main>page</main>
|
||||
<AssistantMount />
|
||||
</AssistantProvider>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the shell.
|
||||
*
|
||||
* @param metaData - Instance metadata.
|
||||
* @returns The render result.
|
||||
*/
|
||||
function renderShell(metaData: QInstance = META) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(<QueryClientProvider client={client}><Shell metaData={metaData} /></QueryClientProvider>)
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the assistant routes with a mutable conversation list.
|
||||
*
|
||||
* @param options - `config` extra probe fields; `list` the conversations; `archived` the archived ones.
|
||||
* @param options.config - Extra probe fields.
|
||||
* @param options.list - The active conversations.
|
||||
* @param options.archived - The archived conversations.
|
||||
*/
|
||||
function mockAssistant(options: { config?: Record<string, unknown>; list?: AssistantConversation[]; archived?: AssistantConversation[] } = {}) {
|
||||
let list = options.list ?? LIST
|
||||
let archived = options.archived ?? []
|
||||
traffic.patches = []
|
||||
traffic.deletes = []
|
||||
server.use(
|
||||
uiApiVersionHandler('assistant'),
|
||||
http.get(`${BASE}/turns/active`, () => HttpResponse.json({ error: 'Not found' }, { status: 404 })),
|
||||
http.get(`${BASE}/config`, () => HttpResponse.json({ enabled: true, ...options.config })),
|
||||
http.get(`${BASE}/conversations`, ({ request }) =>
|
||||
HttpResponse.json({ conversations: new URL(request.url).searchParams.get('status') === 'ARCHIVED' ? archived : list })),
|
||||
http.patch(`${BASE}/conversations/:id`, async ({ params, request }) => {
|
||||
const body = await request.json() as { status?: 'ACTIVE' | 'ARCHIVED'; read?: boolean }
|
||||
traffic.patches.push({ id: String(params.id), body })
|
||||
const id = Number(params.id)
|
||||
if (body.read) list = list.map((item) => (item.id === id ? { ...item, unreadCount: 0 } : item))
|
||||
if (body.status === 'ARCHIVED') { archived = [...archived, ...list.filter((item) => item.id === id).map((item) => ({ ...item, status: 'ARCHIVED' as const }))]; list = list.filter((item) => item.id !== id) }
|
||||
if (body.status === 'ACTIVE') { list = [...list, ...archived.filter((item) => item.id === id).map((item) => ({ ...item, status: 'ACTIVE' as const }))]; archived = archived.filter((item) => item.id !== id) }
|
||||
return HttpResponse.json(conversation(id, 'x'))
|
||||
}),
|
||||
http.delete(`${BASE}/conversations/:id`, ({ params }) => {
|
||||
traffic.deletes.push(String(params.id))
|
||||
list = list.filter((item) => item.id !== Number(params.id))
|
||||
return new HttpResponse(null, { status: 204 })
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the panel and its conversation list.
|
||||
*
|
||||
* @param user - The user.
|
||||
*/
|
||||
async function openRail(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Show conversations' }))
|
||||
await screen.findByRole('button', { name: UNREAD_ROW })
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
await import('./AssistantPanel')
|
||||
}, 30_000)
|
||||
|
||||
beforeEach(() => {
|
||||
router.push.mockReset()
|
||||
window.history.replaceState(null, '', '/app/person')
|
||||
window.localStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
window.history.replaceState(null, '', '/')
|
||||
})
|
||||
|
||||
describe('conversation list in the panel', () => {
|
||||
it('archives a row at once and asks the server', async () => {
|
||||
mockAssistant()
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
await user.click(screen.getByRole('button', { name: 'Archive Quiet one' }))
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: 'Quiet one' })).toBeNull())
|
||||
expect(traffic.patches).toContainEqual({ id: '4', body: { status: 'ARCHIVED' } })
|
||||
await user.click(screen.getByRole('button', { name: 'Archived' }))
|
||||
expect(await screen.findByRole('button', { name: 'Restore Quiet one' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('confirms a delete naming the conversation; Cancel keeps it, Delete removes it', async () => {
|
||||
mockAssistant()
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
await user.click(screen.getByRole('button', { name: 'Delete Quiet one' }))
|
||||
const dialog = await screen.findByRole('alertdialog')
|
||||
expect(within(dialog).getByText(/Quiet one and its messages are deleted/)).toBeInTheDocument()
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }))
|
||||
expect(traffic.deletes).toEqual([])
|
||||
expect(screen.getByRole('button', { name: 'Quiet one' })).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete Quiet one' }))
|
||||
await user.click(within(await screen.findByRole('alertdialog')).getByRole('button', { name: 'Delete' }))
|
||||
await waitFor(() => expect(traffic.deletes).toEqual(['4']))
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: 'Quiet one' })).toBeNull())
|
||||
})
|
||||
|
||||
it('puts the row back and shows a toast when the server refuses', async () => {
|
||||
mockAssistant()
|
||||
server.use(http.patch(`${BASE}/conversations/:id`, () => HttpResponse.json({ error: 'nope' }, { status: 500 })))
|
||||
const error = vi.spyOn(toast, 'error')
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
await user.click(screen.getByRole('button', { name: 'Archive Quiet one' }))
|
||||
await waitFor(() => expect(error).toHaveBeenCalled())
|
||||
expect(error.mock.calls[0][0]).toContain('Quiet one')
|
||||
expect(await screen.findByRole('button', { name: 'Quiet one' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('rolls a failed delete back too', async () => {
|
||||
mockAssistant()
|
||||
server.use(http.delete(`${BASE}/conversations/:id`, () => HttpResponse.json({ error: 'nope' }, { status: 500 })))
|
||||
const error = vi.spyOn(toast, 'error')
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
await user.click(screen.getByRole('button', { name: 'Delete Quiet one' }))
|
||||
await user.click(within(await screen.findByRole('alertdialog')).getByRole('button', { name: 'Delete' }))
|
||||
await waitFor(() => expect(error).toHaveBeenCalled())
|
||||
expect(await screen.findByRole('button', { name: 'Quiet one' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('links to the conversations table only when the server names one that is in the metadata', async () => {
|
||||
mockAssistant({ config: { conversationsTable: 'assistantConversation' } })
|
||||
const user = userEvent.setup()
|
||||
const first = renderShell()
|
||||
await openRail(user)
|
||||
expect(await screen.findByRole('link', { name: 'Manage all conversations' })).toHaveAttribute('href', '/app/assistantConversation')
|
||||
first.unmount()
|
||||
|
||||
mockAssistant({ config: { conversationsTable: 'notInMetadata' } })
|
||||
const second = renderShell()
|
||||
await openRail(user)
|
||||
expect(screen.queryByRole('link', { name: 'Manage all conversations' })).toBeNull()
|
||||
second.unmount()
|
||||
|
||||
mockAssistant()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
expect(screen.queryByRole('link', { name: 'Manage all conversations' })).toBeNull()
|
||||
})
|
||||
|
||||
it('works with an old server that reports neither running nor a table', async () => {
|
||||
mockAssistant({ list: [{ ...conversation(2, 'Open invoices'), unreadCount: 1 }] })
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
expect(document.querySelector('[data-qqq-id="assistant-conversation-running"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('dots the History toggle while another conversation is working or unread, with an accessible label', async () => {
|
||||
mockAssistant()
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const toggle = await screen.findByRole('button', { name: 'Show conversations' })
|
||||
await waitFor(() => expect(toggle.querySelector('[data-qqq-id="assistant-rail-toggle-dot"]')).not.toBeNull())
|
||||
expect(toggle).toHaveAccessibleDescription('Other conversations are working or have unread replies')
|
||||
})
|
||||
|
||||
it('does not dot the History toggle when nothing else is working or unread', async () => {
|
||||
mockAssistant({ list: [conversation(4, 'Quiet one')] })
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const toggle = await screen.findByRole('button', { name: 'Show conversations' })
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
expect(toggle.querySelector('[data-qqq-id="assistant-rail-toggle-dot"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('passes axe with the rail open (Recent and Archived)', async () => {
|
||||
mockAssistant({ config: { conversationsTable: 'assistantConversation' }, archived: [conversation(9, 'Old thread', { status: 'ARCHIVED', unreadCount: 1 })] })
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await openRail(user)
|
||||
const panel = screen.getByRole('dialog')
|
||||
expect(await axe(panel)).toHaveNoViolations()
|
||||
await user.click(screen.getByRole('button', { name: 'Archived' }))
|
||||
await screen.findByRole('button', { name: 'Restore Old thread' })
|
||||
expect(await axe(panel)).toHaveNoViolations()
|
||||
})
|
||||
})
|
||||
|
||||
describe('unread correctness', () => {
|
||||
/**
|
||||
* A reply that streams to its end in the open conversation, the server counting it unread.
|
||||
*/
|
||||
it('marks the open conversation read when its reply finishes, so it never counts as unread', async () => {
|
||||
const open = conversation(4, 'Quiet one')
|
||||
mockAssistant({ list: [open] })
|
||||
let unread = 0
|
||||
server.use(
|
||||
http.get(`${BASE}/conversations`, () => HttpResponse.json({ conversations: [{ ...open, unreadCount: unread }] })),
|
||||
http.get(`${BASE}/conversations/4`, () => HttpResponse.json({ conversation: open, messages: [] })),
|
||||
http.post(`${BASE}/conversations/4/turns`, () => {
|
||||
unread = 1 // the server counts the reply as unread until it is marked read
|
||||
const frames = [
|
||||
['message.start', { seq: 1, turnId: 9, conversationId: 4, userMessageId: 10, messageId: 11 }],
|
||||
['text.delta', { seq: 2, messageId: 11, text: 'Done.' }],
|
||||
['message.end', { seq: 3, messageId: 11, status: 'COMPLETE' }],
|
||||
] as Array<[string, Record<string, unknown>]>
|
||||
return new HttpResponse(frames.map(([type, data]) => `id: ${data.seq}\nevent: ${type}\ndata: ${JSON.stringify(data)}\n\n`).join(''), { headers: { 'Content-Type': 'text/event-stream' } })
|
||||
}),
|
||||
http.patch(`${BASE}/conversations/4`, async ({ request }) => {
|
||||
traffic.patches.push({ id: '4', body: await request.json() })
|
||||
unread = 0
|
||||
return HttpResponse.json(open)
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Show conversations' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Quiet one' }))
|
||||
const composer = await screen.findByRole('textbox', { name: 'Message the assistant' })
|
||||
await user.type(composer, 'Hello{Enter}')
|
||||
await waitFor(() => expect(traffic.patches).toContainEqual({ id: '4', body: { read: true } }))
|
||||
// the header badge never shows the reply the user was watching
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
expect(document.querySelector('[data-qqq-id="assistant-unread-badge"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('opening a conversation with unread replies marks it read on the server', async () => {
|
||||
mockAssistant({ list: [conversation(2, 'Open invoices', { unreadCount: 2 })] })
|
||||
server.use(http.get(`${BASE}/conversations/2`, () => HttpResponse.json({ conversation: conversation(2, 'Open invoices'), messages: [] })))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant, 2 unread/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Show conversations' }))
|
||||
await user.click(await screen.findByRole('button', { name: UNREAD_ROW }))
|
||||
await waitFor(() => expect(traffic.patches).toContainEqual({ id: '2', body: { read: true } }))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// The header's Ask button: its busy dot and unread badge stay on the sparkles icon in every state.
|
||||
// jsdom has no layout, so these tests assert what decides the layout: which element is each
|
||||
// indicator's containing block, what gives that element its size, and the indicator's offsets.
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HEADER_ICON_ANCHOR_CLASS, HEADER_STATUS_DOT_CLASS } from '@/components/layout/HeaderMenu'
|
||||
import { assistantKeys, type AssistantController } from './assistant-context'
|
||||
import { AssistantHeaderButton } from './AssistantHeaderButton'
|
||||
import { AssistantProvider } from './AssistantProvider'
|
||||
|
||||
const ANCHOR = '[data-qqq-id="header-icon-anchor"]'
|
||||
const BUSY = '[data-qqq-id="assistant-busy"]'
|
||||
const UNREAD = '[data-qqq-id="assistant-unread-badge"]'
|
||||
|
||||
/**
|
||||
* The class tokens of an element (an SVG element's `className` is not a string).
|
||||
*
|
||||
* @param element - The element.
|
||||
* @returns Its classes.
|
||||
*/
|
||||
function classes(element: Element): string[] {
|
||||
return (element.getAttribute('class') ?? '').split(/\s+/).filter(Boolean)
|
||||
}
|
||||
|
||||
/**
|
||||
* The containing block of an absolutely positioned element: its nearest positioned ancestor.
|
||||
*
|
||||
* @param element - The absolutely positioned element.
|
||||
* @returns The ancestor its offsets are measured from, or null (the viewport).
|
||||
*/
|
||||
function containingBlock(element: Element): Element | null {
|
||||
for (let parent = element.parentElement; parent; parent = parent.parentElement) {
|
||||
if (classes(parent).some((name) => ['relative', 'absolute', 'fixed', 'sticky'].includes(name))) return parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The children that give an element its size: every child that is not absolutely positioned.
|
||||
*
|
||||
* @param element - The element.
|
||||
* @returns Its in-flow children.
|
||||
*/
|
||||
function inFlowChildren(element: Element): Element[] {
|
||||
return Array.from(element.children).filter((child) => !classes(child).includes('absolute'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the button in a given state.
|
||||
*
|
||||
* @param state - The state.
|
||||
* @param state.busy - Whether a reply is being written.
|
||||
* @param state.unreadCount - Unread replies.
|
||||
* @param state.open - Whether the panel is open.
|
||||
* @param state.enabled - Whether the assistant is available.
|
||||
* @returns The button, or null when it renders nothing.
|
||||
*/
|
||||
function renderButton({ busy = false, unreadCount = 0, open = false, enabled = true }: { busy?: boolean; unreadCount?: number; open?: boolean; enabled?: boolean }): HTMLElement | null {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
client.setQueryData(assistantKeys.busy(), busy)
|
||||
const controller: AssistantController = {
|
||||
config: null,
|
||||
enabled,
|
||||
open,
|
||||
setOpen: vi.fn(),
|
||||
toggle: vi.fn(),
|
||||
activeConversationId: null,
|
||||
setActiveConversationId: vi.fn(),
|
||||
unreadCount,
|
||||
openWith: vi.fn(),
|
||||
pendingRequest: null,
|
||||
consumeRequest: vi.fn(),
|
||||
triggerRef: React.createRef<HTMLButtonElement>(),
|
||||
}
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AssistantProvider value={controller}>
|
||||
<header><AssistantHeaderButton /></header>
|
||||
</AssistantProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return screen.queryByRole('button', { name: /^Ask the assistant/ })
|
||||
}
|
||||
|
||||
describe('AssistantHeaderButton', () => {
|
||||
it('renders nothing when the assistant is unavailable', () => {
|
||||
expect(renderButton({ enabled: false, busy: true, unreadCount: 2 })).toBeNull()
|
||||
})
|
||||
|
||||
it('idle: the icon anchor holds only the icon, and the label sits beside it', () => {
|
||||
const button = renderButton({})!
|
||||
const anchor = button.querySelector(ANCHOR)!
|
||||
expect(anchor.parentElement).toBe(button)
|
||||
expect(Array.from(anchor.children).map((child) => child.tagName.toLowerCase())).toEqual(['svg'])
|
||||
expect(button.querySelector(BUSY)).toBeNull()
|
||||
expect(button.querySelector(UNREAD)).toBeNull()
|
||||
const label = screen.getByText('Ask')
|
||||
expect(label.parentElement).toBe(button)
|
||||
expect(anchor.contains(label)).toBe(false)
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false')
|
||||
})
|
||||
|
||||
const states = [
|
||||
{ name: 'a reply being written', busy: true, unreadCount: 0 },
|
||||
{ name: 'unread replies', busy: false, unreadCount: 3 },
|
||||
{ name: 'a reply being written and unread replies', busy: true, unreadCount: 12 },
|
||||
]
|
||||
const cases = states.flatMap((state) => [{ ...state, open: false, panel: 'closed' }, { ...state, open: true, panel: 'open' }])
|
||||
|
||||
it.each(cases)('$name, panel $panel: every indicator is positioned against the icon, never the button', ({ busy, unreadCount, open }) => {
|
||||
const button = renderButton({ busy, unreadCount, open })!
|
||||
expect(button).toHaveAttribute('aria-pressed', String(open))
|
||||
const anchor = button.querySelector(ANCHOR)!
|
||||
const indicators = Array.from(button.querySelectorAll(`${BUSY}, ${UNREAD}`))
|
||||
expect(indicators).toHaveLength((busy ? 1 : 0) + (unreadCount > 0 ? 1 : 0))
|
||||
for (const indicator of indicators) {
|
||||
expect(classes(indicator)).toContain('absolute')
|
||||
// the button is positioned too (its focus ring and the Jobs ring need that), so only an
|
||||
// indicator inside the anchor is measured from the icon
|
||||
expect(containingBlock(indicator)).toBe(anchor)
|
||||
expect(containingBlock(indicator)).not.toBe(button)
|
||||
}
|
||||
// the anchor is exactly the icon: nothing else in flow, so the label and the button's
|
||||
// padding cannot move an indicator
|
||||
expect(classes(anchor)).toContain('relative')
|
||||
expect(inFlowChildren(anchor).map((child) => child.tagName.toLowerCase())).toEqual(['svg'])
|
||||
expect(anchor.contains(screen.getByText('Ask'))).toBe(false)
|
||||
})
|
||||
|
||||
it('places the dot on the icon\'s bottom-right corner and the badge over its top-right corner', () => {
|
||||
const button = renderButton({ busy: true, unreadCount: 3 })!
|
||||
const dot = screen.getByRole('status', { name: 'Assistant is answering' })
|
||||
expect(dot).toBe(button.querySelector(BUSY))
|
||||
expect(classes(dot)).toEqual(expect.arrayContaining(['-bottom-0.5', '-right-0.5', 'h-2', 'w-2', 'rounded-full']))
|
||||
const badge = button.querySelector(UNREAD)!
|
||||
expect(badge).toHaveTextContent('3')
|
||||
expect(classes(badge)).toEqual(expect.arrayContaining(['-right-2', '-top-2', 'h-4', 'min-w-4']))
|
||||
// the offsets of the button's own corner (the defect: past the label, under its baseline)
|
||||
for (const indicator of [dot, badge]) {
|
||||
for (const offset of ['bottom-0', 'right-0', 'right-0.5', 'top-0.5']) expect(classes(indicator)).not.toContain(offset)
|
||||
}
|
||||
})
|
||||
|
||||
it('caps the badge at 9+ and names the unread count', () => {
|
||||
const button = renderButton({ unreadCount: 12 })!
|
||||
expect(button.querySelector(UNREAD)).toHaveTextContent('9+')
|
||||
expect(button).toHaveAccessibleName('Ask the assistant, 12 unread (Ctrl+J or ⌘J)')
|
||||
})
|
||||
|
||||
it('shares one anchor and one badge geometry with the bell and Jobs', () => {
|
||||
expect(HEADER_ICON_ANCHOR_CLASS.split(' ')).toEqual(expect.arrayContaining(['relative', 'shrink-0']))
|
||||
expect(HEADER_BADGE_CLASS.split(' ')).toEqual(expect.arrayContaining(['absolute', '-right-2', '-top-2']))
|
||||
expect(HEADER_STATUS_DOT_CLASS.split(' ')).toEqual(expect.arrayContaining(['absolute', '-bottom-0.5', '-right-0.5']))
|
||||
// an 8 px offset from a 20 px icon stays inside the 10 px padding of the 40 px button
|
||||
expect(HEADER_BUTTON_CLASS.split(' ')).toEqual(expect.arrayContaining(['h-10', 'min-w-10', 'px-2.5']))
|
||||
})
|
||||
})
|
||||
@@ -25,10 +25,14 @@ import React from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Sparkles } from 'lucide-react'
|
||||
|
||||
import { HEADER_BADGE_CLASS, HEADER_BUTTON_CLASS, HEADER_STATUS_DOT_CLASS, HeaderIconAnchor } from '@/components/layout/HeaderMenu'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { assistantKeys, useAssistant } from './assistant-context'
|
||||
|
||||
/**
|
||||
* Toggles the assistant panel; the badge counts unread replies.
|
||||
* Toggles the assistant panel ("Ask"); the badge counts unread replies and the dot shows a reply
|
||||
* being written. The sparkles icon alone is ambiguous, so from 1440 px it carries the text label
|
||||
* "Ask" (its tooltip says so below that).
|
||||
*
|
||||
* @returns The button, or null when the assistant is unavailable.
|
||||
*/
|
||||
@@ -37,7 +41,7 @@ export function AssistantHeaderButton() {
|
||||
const { data: busy = false } = useQuery({ queryKey: assistantKeys.busy(), queryFn: () => false, enabled: false })
|
||||
if (!assistant?.enabled) return null
|
||||
const { open, unreadCount, toggle, triggerRef } = assistant
|
||||
const label = unreadCount > 0 ? `Assistant, ${unreadCount} unread (Ctrl+J or ⌘J)` : 'Assistant (Ctrl+J or ⌘J)'
|
||||
const label = unreadCount > 0 ? `Ask the assistant, ${unreadCount} unread (Ctrl+J or ⌘J)` : 'Ask the assistant (Ctrl+J or ⌘J)'
|
||||
return (
|
||||
<button
|
||||
ref={triggerRef}
|
||||
@@ -47,22 +51,23 @@ export function AssistantHeaderButton() {
|
||||
event.currentTarget.focus({ preventScroll: true })
|
||||
toggle()
|
||||
}}
|
||||
className="relative flex items-center justify-center rounded-lg p-2 hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className={cn(HEADER_BUTTON_CLASS, 'gap-2')}
|
||||
aria-label={label}
|
||||
title="Ask the assistant (Ctrl+J or ⌘J)"
|
||||
aria-pressed={open}
|
||||
data-qqq-id="button-assistant"
|
||||
>
|
||||
<Sparkles className="h-5 w-5 text-foreground/60" aria-hidden="true" />
|
||||
{busy && <span className="absolute bottom-0 right-0 h-2 w-2 rounded-full bg-primary motion-safe:animate-pulse" role="status" aria-label="Assistant is answering" data-qqq-id="assistant-busy" />}
|
||||
{unreadCount > 0 && (
|
||||
<span
|
||||
className="absolute right-0.5 top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold leading-none text-primary-foreground"
|
||||
aria-hidden="true"
|
||||
data-qqq-id="assistant-unread-badge"
|
||||
>
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
{/* the indicators sit on the icon: the button's corner is past the label from 1440 px */}
|
||||
<HeaderIconAnchor>
|
||||
<Sparkles className="h-5 w-5" aria-hidden="true" />
|
||||
{busy && <span className={cn(HEADER_STATUS_DOT_CLASS, 'bg-primary motion-safe:animate-pulse')} role="status" aria-label="Assistant is answering" data-qqq-id="assistant-busy" />}
|
||||
{unreadCount > 0 && (
|
||||
<span className={cn(HEADER_BADGE_CLASS, 'bg-primary text-primary-foreground')} aria-hidden="true" data-qqq-id="assistant-unread-badge">
|
||||
{unreadCount > 9 ? '9+' : unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</HeaderIconAnchor>
|
||||
<span className="hidden text-sm font-medium min-[1440px]:inline" aria-hidden="true">Ask</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// Fail-soft rendering of assistant replies: a failed bulk-load tool step, malformed parts and a
|
||||
// renderer that throws all stay local to their part; the rest of the reply keeps rendering.
|
||||
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { AssistantMessage, AssistantPart, AssistantStreamEvent } from '@/types/assistant'
|
||||
import { toAssistantEvent } from '@/lib/api/assistant'
|
||||
import { resetClientErrorsForTesting, setClientErrorSink } from '@/lib/errors/client-errors'
|
||||
import { AssistantMessageView, PART_RENDERERS } from './AssistantMessageView'
|
||||
import { optimisticTurnMessages, reduceStreamEvent, type TurnMessageIds } from './message-reducer'
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), prefetch: vi.fn() }), usePathname: () => '/app/home' }))
|
||||
|
||||
/**
|
||||
* Parses SSE frames the way the stream client does.
|
||||
*
|
||||
* @param frames - `[type, data]` pairs, as the server writes them.
|
||||
* @returns The typed events.
|
||||
*/
|
||||
function events(...frames: Array<[string, Record<string, unknown>]>): AssistantStreamEvent[] {
|
||||
return frames.flatMap(([type, data]) => {
|
||||
const { event } = toAssistantEvent({ id: String(data.seq), event: type, data: JSON.stringify(data) })
|
||||
return event ? [event] : []
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders messages like the panel does.
|
||||
*
|
||||
* @param messages - The messages.
|
||||
* @returns The render result.
|
||||
*/
|
||||
function show(messages: AssistantMessage[]) {
|
||||
const client = new QueryClient()
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
{messages.map((message) => <AssistantMessageView key={message.id} message={message} onSend={() => undefined} />)}
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// What qbit-assistant streams when a bulk-load tool rejects an attached file: a tool.result with
|
||||
// INVALID_INPUT, the server's message as the summary and no render (BulkLoadTools.fail).
|
||||
const BULK_LOAD_FAILURE: Array<[string, Record<string, unknown>]> = [
|
||||
['message.start', { seq: 1, turnId: 9, conversationId: 4, userMessageId: 10, messageId: 11, startedAt: '2026-10-16T19:50:00Z' }],
|
||||
['turn.phase', { seq: 2, phase: 'thinking', label: 'thinking' }],
|
||||
['tool.start', { seq: 3, messageId: 11, toolCallId: 'toolu_1', name: 'describe_table', summary: 'Describing a table' }],
|
||||
['tool.result', { seq: 4, messageId: 11, toolCallId: 'toolu_1', name: 'describe_table', outcome: 'OK', summary: 'Described Blog Posts' }],
|
||||
['tool.start', { seq: 5, messageId: 11, toolCallId: 'toolu_2', name: 'bulk_load_attach', summary: 'Reading the file' }],
|
||||
['tool.result', { seq: 6, messageId: 11, toolCallId: 'toolu_2', name: 'bulk_load_attach', outcome: 'INVALID_INPUT', summary: 'Unrecognized file extension - expecting .csv or .xlsx' }],
|
||||
['turn.phase', { seq: 7, phase: 'writing', label: 'writing' }],
|
||||
['text.delta', { seq: 8, messageId: 11, text: 'I could not read that file.' }],
|
||||
['usage', { seq: 9, turnId: 9, inputTokens: 10, outputTokens: 5 }],
|
||||
['message.end', { seq: 10, messageId: 11, status: 'COMPLETE', stopReason: 'end_turn' }],
|
||||
]
|
||||
|
||||
describe('assistant replies fail soft', () => {
|
||||
afterEach(() => {
|
||||
resetClientErrorsForTesting()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('shows a failed bulk-load step from the live stream as a failed step, not a crash', () => {
|
||||
const ids: TurnMessageIds = { userId: -1, assistantId: -2 }
|
||||
let messages = optimisticTurnMessages('can we post this as a blog?', { userId: -1, assistantId: -2 }, '2026-10-16T19:50:00Z')
|
||||
const live = events(...BULK_LOAD_FAILURE)
|
||||
for (const [index, event] of live.entries()) {
|
||||
messages = reduceStreamEvent(messages, event, ids)
|
||||
// every intermediate state renders (the panel renders after each event)
|
||||
if (index < live.length - 1) show(messages).unmount()
|
||||
}
|
||||
show(messages)
|
||||
expect(screen.getByText('Described Blog Posts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Unrecognized file extension - expecting .csv or .xlsx')).toBeInTheDocument()
|
||||
expect(screen.getAllByText(', Invalid request')).toHaveLength(1)
|
||||
expect(screen.getByText('I could not read that file.')).toBeInTheDocument()
|
||||
expect(screen.queryByText(/could not be shown/)).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps a renderer that throws inside its part; the reply keeps rendering', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const sink = vi.fn().mockResolvedValue(true)
|
||||
setClientErrorSink(sink)
|
||||
const original = PART_RENDERERS.navigate
|
||||
PART_RENDERERS.navigate = () => {
|
||||
throw new TypeError("Cannot read properties of undefined (reading 'length')")
|
||||
}
|
||||
try {
|
||||
show([{ id: 11, role: 'ASSISTANT', status: 'COMPLETE', turnId: 9, createDate: '', parts: [
|
||||
{ type: 'navigate', href: '/app/person' },
|
||||
{ type: 'text', text: 'Still here.' },
|
||||
] }])
|
||||
} finally {
|
||||
PART_RENDERERS.navigate = original
|
||||
}
|
||||
expect(screen.getByText('This part could not be shown.')).toBeInTheDocument()
|
||||
expect(screen.getByText('Still here.')).toBeInTheDocument()
|
||||
expect(sink).toHaveBeenCalledWith(expect.objectContaining({ scope: 'assistant-part', partType: 'navigate', messageId: 11 }))
|
||||
// the report names the part type and the error, never the reply's content
|
||||
expect(JSON.stringify(sink.mock.calls)).not.toContain('Still here')
|
||||
})
|
||||
|
||||
it('degrades malformed parts and a message without parts locally', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const malformed = [null, 42, { text: 'no type' }, { type: 'text', text: 'Readable part.' }] as unknown as AssistantPart[]
|
||||
show([
|
||||
{ id: 11, role: 'ASSISTANT', status: 'COMPLETE', turnId: 9, createDate: '', parts: malformed },
|
||||
{ id: 12, role: 'ASSISTANT', status: 'COMPLETE', turnId: 9, createDate: '', parts: undefined as unknown as AssistantPart[] },
|
||||
{ id: 13, role: 'USER', status: 'COMPLETE', turnId: 9, createDate: '', parts: [null, { type: 'text', text: 'My question' }] as unknown as AssistantPart[] },
|
||||
])
|
||||
expect(screen.getAllByText('This part could not be shown.')).toHaveLength(2)
|
||||
expect(screen.getByText('Readable part.')).toBeInTheDocument()
|
||||
expect(screen.getByText('My question')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('applies events to a malformed message instead of throwing', () => {
|
||||
const ids: TurnMessageIds = { userId: null, assistantId: 11 }
|
||||
const broken = [{ id: 11, role: 'ASSISTANT', status: 'STREAMING', turnId: 9, createDate: '' }] as unknown as AssistantMessage[]
|
||||
const [text] = events(['text.delta', { seq: 2, messageId: 11, text: 'Hello' }])
|
||||
const next = reduceStreamEvent(broken, text, ids)
|
||||
expect(next[0].parts).toEqual([{ type: 'text', text: 'Hello' }])
|
||||
const [presentation] = events(['presentation', { seq: 3, messageId: 11, part: 'not a part' }])
|
||||
expect(presentation).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -23,7 +23,7 @@
|
||||
'use client'
|
||||
|
||||
import React, { useId, useState } from 'react'
|
||||
import { AlertTriangle, Check, ChevronRight, CircleX, Info, Loader2, Navigation, ThumbsDown, ThumbsUp } from 'lucide-react'
|
||||
import { AlertTriangle, Check, ChevronRight, CircleX, Info, Loader2, Navigation, RefreshCw, Square, ThumbsDown, ThumbsUp } from 'lucide-react'
|
||||
|
||||
import type {
|
||||
AssistantMessage,
|
||||
@@ -34,18 +34,25 @@ import type {
|
||||
AssistantTextPart,
|
||||
AssistantToolOutcome,
|
||||
AssistantToolPart,
|
||||
AssistantUnknownPart,
|
||||
} from '@/types/assistant'
|
||||
import { sendAssistantFeedback } from '@/lib/api/assistant'
|
||||
import { internalAppHref } from '@/lib/utils/assistant-links'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import { MyAvatar } from '@/components/ui/UserAvatar'
|
||||
import { AssistantRunStatus } from './AssistantRunStatus'
|
||||
import { partsOf } from './message-reducer'
|
||||
import type { AssistantRun } from './use-assistant-engine'
|
||||
import { AssistantMarkdown } from './AssistantMarkdown'
|
||||
import { AssistantPresentation, type AssistantPresentationActions } from './AssistantPresentation'
|
||||
import { AssistantRenderView, RecordChips } from './AssistantRenders'
|
||||
import { AssistantRenderView, RawJsonView, RecordChips } from './AssistantRenders'
|
||||
import { ErrorBoundary } from '@/components/feedback/ErrorBoundary'
|
||||
import { InlineFailure } from '@/components/feedback/InlineFailure'
|
||||
import Link from 'next/link'
|
||||
|
||||
/** Plain-language outcome of a tool call. */
|
||||
const INLINE_ACTION = 'inline-flex items-center gap-1 rounded px-1 text-xs font-medium text-primary hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 pointer-coarse:min-h-11'
|
||||
|
||||
const OUTCOME_LABEL: Record<AssistantToolOutcome, string> = {
|
||||
OK: 'Done',
|
||||
DENIED: 'Not permitted',
|
||||
@@ -95,7 +102,16 @@ function ToolStep({ part, finished = false }: { part: AssistantToolPart; finishe
|
||||
<dt>Result</dt>
|
||||
<dd>{running ? 'Running' : outcome}</dd>
|
||||
</dl>
|
||||
{part.render && <AssistantRenderView render={part.render} />}
|
||||
{part.render && (
|
||||
<ErrorBoundary
|
||||
scope="assistant-render"
|
||||
reportContext={{ renderType: part.render.type === 'unknown' ? part.render.originalType : part.render.type }}
|
||||
resetKeys={[part.render]}
|
||||
fallbackRender={({ report, error, reset }) => <InlineFailure message="This result could not be shown." report={report} error={error} onRetry={reset} qqqId="assistant-render-error" />}
|
||||
>
|
||||
<AssistantRenderView render={part.render} />
|
||||
</ErrorBoundary>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -157,6 +173,7 @@ export const PART_RENDERERS: { [K in AssistantPart['type']]: PartRenderer<Extrac
|
||||
record_refs: ({ part }: { part: AssistantRecordRefsPart }) => <RecordChips refs={part.refs} />,
|
||||
navigate: ({ part }: { part: AssistantNavigatePart }) => <NavigateView part={part} />,
|
||||
notice: ({ part }: { part: AssistantNoticePart }) => <NoticeView part={part} />,
|
||||
unknown: ({ part }: { part: AssistantUnknownPart }) => <RawJsonView label={part.originalType ? `Unsupported content (${part.originalType})` : 'Unsupported content'} value={part.raw} />,
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -164,11 +181,38 @@ export const PART_RENDERERS: { [K in AssistantPart['type']]: PartRenderer<Extrac
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.part - Any part, including types this version does not know.
|
||||
* @param props.messageId - The message's id, for the failure report.
|
||||
* @returns The rendered part, or null.
|
||||
*/
|
||||
function PartView({ part, onSend, sending, finished }: { part: AssistantPart; finished?: boolean } & AssistantPresentationActions) {
|
||||
const render = (PART_RENDERERS as Record<string, PartRenderer<AssistantPart> | undefined>)[part.type]
|
||||
return render ? <>{render({ part, onSend, sending, finished })}</> : null
|
||||
function PartView({ part, onSend, sending, finished, messageId }: { part: AssistantPart; finished?: boolean; messageId?: number } & AssistantPresentationActions) {
|
||||
if (!part || typeof part !== 'object') return <InlineFailure message="This part could not be shown." qqqId="assistant-part-error" />
|
||||
const render = typeof part.type === 'string' ? (PART_RENDERERS as Record<string, PartRenderer<AssistantPart> | undefined>)[part.type] : undefined
|
||||
if (!render) return null
|
||||
// One part that fails to render (for example, a malformed tool payload) must
|
||||
// not take down the reply - or the page - around it. A new payload (streaming) renders again.
|
||||
// The renderer runs inside the boundary (as a component), so an error in it stays here too.
|
||||
return (
|
||||
<ErrorBoundary
|
||||
scope="assistant-part"
|
||||
reportContext={{ messageId, partType: part.type }}
|
||||
resetKeys={[part]}
|
||||
fallbackRender={({ report, error }) => <InlineFailure message="This part could not be shown." report={report} error={error} qqqId="assistant-part-error" />}
|
||||
>
|
||||
<RenderPart render={render} part={part} onSend={onSend} sending={sending} finished={finished} />
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a part renderer during its own render, inside the part's error boundary.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.render - The renderer.
|
||||
* @param props.part - The part.
|
||||
* @returns What the renderer returns.
|
||||
*/
|
||||
function RenderPart({ render, part, onSend, sending, finished }: { render: PartRenderer<AssistantPart>; part: AssistantPart; finished?: boolean } & AssistantPresentationActions) {
|
||||
return <>{render({ part, onSend, sending, finished })}</>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -239,42 +283,65 @@ function FeedbackButtons({ messageId }: { messageId: number }) {
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.message - The message.
|
||||
* @param props.onRetry - Asks the question again (offered when the reply failed).
|
||||
* @param props.onStop - Stops the reply (offered while it is running, and for a reply left running).
|
||||
* @returns The message article.
|
||||
*/
|
||||
export function AssistantMessageView({ message, onSend, sending, run }: { message: AssistantMessage; run?: AssistantRun } & AssistantPresentationActions) {
|
||||
export function AssistantMessageView({ message, onSend, sending, run, onRetry, onStop }: { message: AssistantMessage; run?: AssistantRun; onRetry?: () => void; onStop?: () => void } & AssistantPresentationActions) {
|
||||
if (message.role === 'USER') {
|
||||
const text = message.parts.map((part) => (part.type === 'text' ? part.text : '')).join('')
|
||||
const text = partsOf(message).map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : '')).join('')
|
||||
return (
|
||||
<article className="flex justify-end" aria-label="You" data-qqq-id="assistant-message" data-role="user">
|
||||
<article className="flex items-end justify-end gap-2" aria-label="You" data-qqq-id="assistant-message" data-role="user">
|
||||
<p className="max-w-[85%] whitespace-pre-wrap break-words rounded-2xl rounded-br-sm bg-muted px-3 py-2 text-sm text-foreground">{text}</p>
|
||||
<MyAvatar size={28} data-qqq-id="assistant-user-avatar" />
|
||||
</article>
|
||||
)
|
||||
}
|
||||
if (message.role === 'SYSTEM_NOTICE') {
|
||||
return (
|
||||
<article className="space-y-1" aria-label="Notice" data-qqq-id="assistant-message" data-role="notice">
|
||||
{message.parts.map((part, index) => <PartView key={index} part={part} />)}
|
||||
{partsOf(message).map((part, index) => <PartView key={index} part={part} messageId={message.id} />)}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
const streaming = message.status === 'STREAMING'
|
||||
const parts = partsOf(message)
|
||||
return (
|
||||
<article className="min-w-0 space-y-2" aria-label="Assistant" data-qqq-id="assistant-message" data-role="assistant" data-status={message.status}>
|
||||
{message.parts.length > 0 && (
|
||||
{parts.length > 0 && (
|
||||
<div className="space-y-2" aria-busy={streaming}>
|
||||
{message.parts.map((part, index) => <PartView key={part.type === 'tool' ? part.toolCallId : index} part={part} onSend={onSend} sending={sending || streaming} finished={!streaming} />)}
|
||||
{parts.map((part, index) => <PartView key={part?.type === 'tool' && part.toolCallId ? part.toolCallId : index} part={part} messageId={message.id} onSend={onSend} sending={sending || streaming} finished={!streaming} />)}
|
||||
</div>
|
||||
)}
|
||||
{run && <AssistantRunStatus run={run} />}
|
||||
{streaming && !run && message.parts.length === 0 && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground" data-qqq-id="assistant-thinking">
|
||||
<Loader2 className="h-3.5 w-3.5 motion-safe:animate-spin" aria-hidden="true" />
|
||||
Working on it...
|
||||
</p>
|
||||
{(run || streaming) && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{run ? <AssistantRunStatus run={run} /> : parts.length === 0 && (
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground" data-qqq-id="assistant-thinking">
|
||||
<Loader2 className="h-3.5 w-3.5 motion-safe:animate-spin" aria-hidden="true" />
|
||||
Working on it...
|
||||
</p>
|
||||
)}
|
||||
{onStop && (
|
||||
<button type="button" onClick={onStop} className={INLINE_ACTION} data-qqq-id="assistant-message-stop">
|
||||
<Square className="h-3 w-3 fill-current" aria-hidden="true" />
|
||||
{run?.status === 'cancelling' ? 'Stop now' : 'Stop'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{message.status === 'CANCELLED' && <p className="text-xs text-muted-foreground">Stopped.</p>}
|
||||
{message.status === 'ERROR' && !message.parts.some((part) => part.type === 'notice' && part.level === 'error') && (
|
||||
<p className="text-xs text-destructive" role="alert">The reply did not finish.</p>
|
||||
{message.status === 'ERROR' && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1" data-qqq-id="assistant-reply-failed">
|
||||
{!parts.some((part) => part?.type === 'notice' && part.level === 'error') && (
|
||||
<p className="text-xs text-destructive" role="alert">The reply did not finish.</p>
|
||||
)}
|
||||
{onRetry && (
|
||||
<button type="button" onClick={onRetry} disabled={sending} className={INLINE_ACTION} data-qqq-id="assistant-message-retry">
|
||||
<RefreshCw className="h-3 w-3" aria-hidden="true" />
|
||||
Retry
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{message.status === 'COMPLETE' && message.id > 0 && <FeedbackButtons messageId={message.id} />}
|
||||
</article>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* 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 crashing assistant panel is replaced by a small card; the page around it keeps working
|
||||
|
||||
import React from 'react'
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { resetClientErrorsForTesting, setClientErrorSink } from '@/lib/errors/client-errors'
|
||||
import { AssistantContext, assistantKeys, type AssistantController } from './assistant-context'
|
||||
import { AssistantMount, setAssistantPanelLoaderForTesting } from './AssistantMount'
|
||||
|
||||
const panel = vi.hoisted(() => ({ broken: true }))
|
||||
vi.mock('./AssistantPanel', () => ({
|
||||
default: function AssistantPanel() {
|
||||
if (panel.broken) throw new TypeError("Cannot read properties of undefined (reading 'length')")
|
||||
return <aside data-qqq-id="assistant-panel">panel</aside>
|
||||
},
|
||||
}))
|
||||
|
||||
function renderMount(setOpen = vi.fn(), client = new QueryClient()) {
|
||||
const controller = { enabled: true, open: true, setOpen, activeConversationId: 4 } as unknown as AssistantController
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AssistantContext.Provider value={controller}>
|
||||
<main><button type="button">page action</button></main>
|
||||
<AssistantMount />
|
||||
</AssistantContext.Provider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('AssistantMount', () => {
|
||||
afterEach(() => {
|
||||
resetClientErrorsForTesting()
|
||||
setAssistantPanelLoaderForTesting(null)
|
||||
vi.restoreAllMocks()
|
||||
panel.broken = true
|
||||
})
|
||||
|
||||
it('replaces a crashed panel with Retry, Copy details and Close, and reports it', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const sink = vi.fn().mockResolvedValue(true)
|
||||
setClientErrorSink(sink)
|
||||
const setOpen = vi.fn()
|
||||
renderMount(setOpen)
|
||||
expect(await screen.findByText('The assistant hit a problem')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'page action' })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: 'Copy details' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Report a bug' })).not.toBeInTheDocument() // QA capture off
|
||||
expect(sink).toHaveBeenCalledWith(expect.objectContaining({ scope: 'assistant-panel', conversationId: 4 }))
|
||||
|
||||
panel.broken = false
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(await screen.findByText('panel')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes from the failure card', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const setOpen = vi.fn()
|
||||
renderMount(setOpen)
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Close assistant' }))
|
||||
expect(setOpen).toHaveBeenCalledWith(false)
|
||||
})
|
||||
|
||||
it('loads the panel again on Retry after its code failed to load (a chunk missing after a deploy)', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
panel.broken = false
|
||||
const real = () => import('./AssistantPanel')
|
||||
let attempts = 0
|
||||
setAssistantPanelLoaderForTesting(() => {
|
||||
attempts++
|
||||
return attempts === 1 ? Promise.reject(new Error('Failed to fetch dynamically imported module')) : real()
|
||||
})
|
||||
renderMount()
|
||||
expect(await screen.findByText('The assistant hit a problem')).toBeInTheDocument()
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(await screen.findByText('panel')).toBeInTheDocument()
|
||||
expect(attempts).toBe(2)
|
||||
})
|
||||
|
||||
it('recovers by itself once an assistant request succeeds again', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const client = new QueryClient()
|
||||
const list = vi.fn().mockResolvedValue([])
|
||||
// the header badge's list query, as the shell registers it
|
||||
await client.prefetchQuery({ queryKey: assistantKeys.conversations(), queryFn: list })
|
||||
renderMount(vi.fn(), client)
|
||||
expect(await screen.findByText('The assistant hit a problem')).toBeInTheDocument()
|
||||
|
||||
// the next poll succeeds (the mount's own backoff check, a focus refetch or the badge)
|
||||
panel.broken = false
|
||||
await act(async () => {
|
||||
await client.refetchQueries({ queryKey: assistantKeys.conversations(), type: 'all' })
|
||||
})
|
||||
expect(await screen.findByText('panel')).toBeInTheDocument()
|
||||
expect(screen.queryByText('The assistant hit a problem')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -22,23 +22,141 @@
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { Suspense, lazy } from 'react'
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
|
||||
import { useAssistant } from './assistant-context'
|
||||
import { ErrorBoundary } from '@/components/feedback/ErrorBoundary'
|
||||
import { assistantKeys, useAssistant } from './assistant-context'
|
||||
import { AssistantPanelFailure } from './AssistantPanelFailure'
|
||||
|
||||
const AssistantPanel = lazy(() => import('./AssistantPanel'))
|
||||
/** The panel module. */
|
||||
type PanelModule = { default: React.ComponentType }
|
||||
|
||||
/** First wait before a crashed panel is tried again on its own; doubles up to the cap. */
|
||||
export const RECOVERY_FIRST_DELAY_MS = 5_000
|
||||
/** Longest wait between two recovery checks. */
|
||||
export const RECOVERY_MAX_DELAY_MS = 60_000
|
||||
|
||||
const importPanel = (): Promise<PanelModule> => import('./AssistantPanel')
|
||||
let panelLoader: () => Promise<PanelModule> = importPanel
|
||||
let loadedPanel: Promise<PanelModule> | null = null
|
||||
let panelModule: PanelModule | null = null
|
||||
|
||||
/**
|
||||
* Mounts the lazily loaded assistant panel when the assistant is available.
|
||||
* Loads the panel code once; a failed load (a chunk missing after a deploy, a network error) is
|
||||
* forgotten so the next attempt fetches it again.
|
||||
*
|
||||
* @returns The panel module.
|
||||
*/
|
||||
function loadPanel(): Promise<PanelModule> {
|
||||
if (!loadedPanel) {
|
||||
loadedPanel = panelLoader().then((module) => {
|
||||
panelModule = module
|
||||
return module
|
||||
}, (error: unknown) => {
|
||||
loadedPanel = null
|
||||
throw error
|
||||
})
|
||||
}
|
||||
return loadedPanel
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces how the panel code is loaded (tests: a chunk that fails to load).
|
||||
*
|
||||
* @param loader - The loader, or null for the real import.
|
||||
*/
|
||||
export function setAssistantPanelLoaderForTesting(loader: (() => Promise<PanelModule>) | null): void {
|
||||
panelLoader = loader ?? importPanel
|
||||
loadedPanel = null
|
||||
panelModule = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts the lazily loaded assistant panel when the assistant is available. The panel sits
|
||||
* behind its own error boundary: if it (or its code chunk) fails, a small card offers Retry,
|
||||
* Copy details and Report a bug, and the page keeps working. The panel comes back on Retry, on
|
||||
* reopening, and by itself once an assistant request succeeds again (checked with a backoff).
|
||||
*
|
||||
* @returns The panel, or null until the assistant is available.
|
||||
*/
|
||||
export function AssistantMount() {
|
||||
const assistant = useAssistant()
|
||||
const queryClient = useQueryClient()
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [recovery, setRecovery] = useState(0)
|
||||
const onError = useCallback(() => setFailed(true), [])
|
||||
const onLoaded = useCallback(() => setFailed(false), [])
|
||||
|
||||
// While crashed: try the assistant again with a backoff; the panel renders again as soon as an
|
||||
// assistant request (this check, a focus refetch, the badge) succeeds.
|
||||
useEffect(() => {
|
||||
if (!failed) return
|
||||
const cache = queryClient.getQueryCache()
|
||||
const root = assistantKeys.all()
|
||||
const unsubscribe = cache.subscribe((event) => {
|
||||
if (event.type !== 'updated' || event.action.type !== 'success') return
|
||||
const key = event.query.queryKey
|
||||
if (root.every((part, index) => key[index] === part)) setRecovery((value) => value + 1)
|
||||
})
|
||||
let delay = RECOVERY_FIRST_DELAY_MS
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const check = () => {
|
||||
void queryClient.refetchQueries({ queryKey: assistantKeys.conversations(), type: 'all' }).catch(() => undefined)
|
||||
delay = Math.min(delay * 2, RECOVERY_MAX_DELAY_MS)
|
||||
timer = setTimeout(check, delay)
|
||||
}
|
||||
timer = setTimeout(check, delay)
|
||||
return () => {
|
||||
unsubscribe()
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [failed, queryClient])
|
||||
|
||||
if (!assistant?.enabled) return null
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<AssistantPanel />
|
||||
</Suspense>
|
||||
<ErrorBoundary
|
||||
scope="assistant-panel"
|
||||
reportContext={{ conversationId: assistant.activeConversationId }}
|
||||
resetKeys={[assistant.open, recovery]}
|
||||
onError={onError}
|
||||
onReset={() => setFailed(false)}
|
||||
fallbackRender={({ report, error, reset }) => <AssistantPanelFailure report={report} error={error} onRetry={reset} />}
|
||||
>
|
||||
<PanelLoader onLoaded={failed ? onLoaded : undefined} />
|
||||
</ErrorBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the panel code and renders the panel. Unlike React.lazy, which keeps a failed load
|
||||
* forever, a remount (Retry, reopening, recovery) loads it again. A load failure is thrown to
|
||||
* the panel's error boundary like a render error.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @param props.onLoaded - Called once the panel rendered, when set (the mount was showing a failure).
|
||||
* @returns The panel, or nothing while its code loads.
|
||||
*/
|
||||
function PanelLoader({ onLoaded }: { onLoaded?: () => void }) {
|
||||
const [module, setModule] = useState<PanelModule | null>(panelModule)
|
||||
const [error, setError] = useState<unknown>(null)
|
||||
useEffect(() => {
|
||||
if (module) return
|
||||
let active = true
|
||||
loadPanel().then((loaded) => {
|
||||
if (active) setModule(loaded)
|
||||
}, (failure: unknown) => {
|
||||
if (active) setError(failure ?? new Error('The assistant could not be loaded.'))
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [module])
|
||||
useEffect(() => {
|
||||
if (module) onLoaded?.()
|
||||
}, [module, onLoaded])
|
||||
if (error) throw error
|
||||
if (!module) return null
|
||||
const Panel = module.default
|
||||
return <Panel />
|
||||
}
|
||||
@@ -187,7 +187,7 @@ describe('assistant gating', () => {
|
||||
mockAssistant()
|
||||
server.use(http.get(`${BASE}/conversations`, () => HttpResponse.json({ conversations: [{ ...CONVERSATION, unreadCount: 2 }, { ...CONVERSATION, id: 5, unreadCount: 1 }] })))
|
||||
renderShell()
|
||||
expect(await screen.findByRole('button', { name: 'Assistant, 3 unread (Ctrl+J or ⌘J)' })).toBeInTheDocument()
|
||||
expect(await screen.findByRole('button', { name: 'Ask the assistant, 3 unread (Ctrl+J or ⌘J)' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -204,7 +204,7 @@ describe('asking a question', () => {
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const composer = await screen.findByRole('textbox', { name: 'Message the assistant' })
|
||||
await user.type(composer, 'Count images{Enter}')
|
||||
const action = await screen.findByRole('button', { name: 'Show PNG' })
|
||||
@@ -223,7 +223,7 @@ describe('asking a question', () => {
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
const composer = within(panel).getByRole('textbox', { name: 'Message the assistant' })
|
||||
expect(within(panel).getByText('On: People')).toBeInTheDocument()
|
||||
@@ -274,7 +274,7 @@ describe('asking a question', () => {
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
expect(within(panel).getAllByText('Ada').length).toBeGreaterThan(0)
|
||||
expect(within(panel).getByText('Hi, I am Ada.')).toBeInTheDocument()
|
||||
@@ -298,7 +298,7 @@ describe('asking a question', () => {
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'hi{Enter}')
|
||||
act(() => stream.close())
|
||||
@@ -325,7 +325,7 @@ describe('asking a question', () => {
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Count people{Enter}')
|
||||
act(() => stream.write(sse(START, ['text.delta', { seq: 2, messageId: 11, text: 'Counting' }])))
|
||||
@@ -335,12 +335,67 @@ describe('asking a question', () => {
|
||||
expect(await within(panel).findByText('Stopped.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('still stops when the stop request fails, and the composer stays usable', async () => {
|
||||
mockAssistant()
|
||||
const stream = controllableStream()
|
||||
server.use(
|
||||
http.post(`${BASE}/conversations/4/turns`, () => stream.response()),
|
||||
http.post(`${BASE}/turns/9/cancel`, () => HttpResponse.json({ error: 'Gateway down' }, { status: 502 })),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Count people{Enter}')
|
||||
act(() => stream.write(sse(START, ['text.delta', { seq: 2, messageId: 11, text: 'Counting' }])))
|
||||
await within(panel).findByText('Counting')
|
||||
await user.click(within(panel).getByRole('button', { name: 'Stop the reply' }))
|
||||
expect(await within(panel).findByText('Stopped.')).toBeInTheDocument()
|
||||
expect(within(panel).queryByRole('button', { name: /^Stop/ })).not.toBeInTheDocument()
|
||||
expect(within(panel).getByRole('textbox', { name: 'Message the assistant' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('stops at once on a second Stop while the server is still stopping', async () => {
|
||||
mockAssistant()
|
||||
const stream = controllableStream()
|
||||
server.use(
|
||||
http.post(`${BASE}/conversations/4/turns`, () => stream.response()),
|
||||
http.post(`${BASE}/turns/9/cancel`, () => HttpResponse.json({ status: 'CANCELLING' }, { status: 202 })),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Count people{Enter}')
|
||||
act(() => stream.write(sse(START)))
|
||||
await user.click(await within(panel).findByRole('button', { name: 'Stop the reply' }))
|
||||
await user.click(await within(panel).findByRole('button', { name: 'Stop now' }))
|
||||
expect(await within(panel).findByText('Stopped.', { selector: MESSAGE_TEXT })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('offers Retry on a failed reply, which asks the question again', async () => {
|
||||
mockAssistant()
|
||||
let posts = 0
|
||||
server.use(http.post(`${BASE}/conversations/4/turns`, () => {
|
||||
posts++
|
||||
return HttpResponse.json({ error: 'Provider unavailable' }, { status: 503 })
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Hi{Enter}')
|
||||
expect(await within(panel).findByText('Provider unavailable')).toBeInTheDocument()
|
||||
await user.click(within(panel).getByRole('button', { name: 'Retry' }))
|
||||
await waitFor(() => expect(posts).toBe(2))
|
||||
})
|
||||
|
||||
it('shows a refused turn as an error in the reply', async () => {
|
||||
mockAssistant()
|
||||
server.use(http.post(`${BASE}/conversations/4/turns`, () => HttpResponse.json({ error: 'Daily budget reached' }, { status: 429 })))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Hi{Enter}')
|
||||
expect(await within(panel).findByText('Daily budget reached')).toBeInTheDocument()
|
||||
@@ -358,7 +413,7 @@ describe('asking a question', () => {
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.click(within(panel).getByRole('button', { name: "Don't send page context (People)" }))
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Hi{Enter}')
|
||||
@@ -383,7 +438,7 @@ describe('markdown safety', () => {
|
||||
}))
|
||||
const user = userEvent.setup()
|
||||
renderShell()
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
const panel = await screen.findByRole('dialog', {}, { timeout: 10_000 })
|
||||
await user.type(within(panel).getByRole('textbox', { name: 'Message the assistant' }), 'Links?{Enter}')
|
||||
const internal = await within(panel).findByRole('link', { name: 'the record' })
|
||||
@@ -434,7 +489,7 @@ function activeTurn() {
|
||||
|
||||
/** Opens the panel and returns its composer. */
|
||||
async function openComposer(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.click(await screen.findByRole('button', { name: /^Assistant/ }))
|
||||
await user.click(await screen.findByRole('button', { name: /^Ask the assistant/ }))
|
||||
return screen.findByRole('textbox', { name: 'Message the assistant' })
|
||||
}
|
||||
|
||||
@@ -596,7 +651,7 @@ describe('answer lifecycle and recovery', () => {
|
||||
renderShell()
|
||||
await openComposer(user)
|
||||
await user.click(screen.getByRole('button', { name: 'Show conversations' }))
|
||||
await user.click(await screen.findByRole('option', { name: /Saved conversation/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Saved conversation' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Stop the reply' }))
|
||||
expect(await screen.findByText('Finished on another pod', { selector: MESSAGE_TEXT })).toBeInTheDocument()
|
||||
await waitFor(() => expect(screen.queryByRole('button', { name: 'Stop the reply' })).not.toBeInTheDocument())
|
||||
|
||||
@@ -32,8 +32,7 @@ import { Archive, ArchiveRestore, Check, Eye, MoreHorizontal, PanelLeft, Pencil,
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import type { QInstance } from '@/types'
|
||||
import type { AssistantAttachment, AssistantConcurrency, AssistantConversation, AssistantConversationDetail, AssistantConversationStatus, AssistantConversationUpdate } from '@/types/assistant'
|
||||
import { uploadFile } from '@/lib/api/uploads'
|
||||
import type { AssistantConcurrency, AssistantConversation, AssistantConversationDetail, AssistantConversationStatus, AssistantConversationUpdate, AssistantMessage } from '@/types/assistant'
|
||||
import {
|
||||
deleteAssistantConversation,
|
||||
getAssistantConversation,
|
||||
@@ -51,8 +50,13 @@ import { AssistantElapsed } from './AssistantRunStatus'
|
||||
import { AssistantComposer } from './AssistantComposer'
|
||||
import { AssistantMessageView } from './AssistantMessageView'
|
||||
import { ConversationRail, conversationTitle } from './ConversationRail'
|
||||
import { markConversationRead } from './mark-read'
|
||||
import { useRailActions } from './use-rail-actions'
|
||||
import { useAssistantEngine, type AssistantEngine } from './use-assistant-engine'
|
||||
import { useAssistantAttachments } from './use-assistant-attachments'
|
||||
import { useStreamAnnouncer } from './use-stream-announcer'
|
||||
import { ErrorBoundary } from '@/components/feedback/ErrorBoundary'
|
||||
import { InlineFailure } from '@/components/feedback/InlineFailure'
|
||||
|
||||
/** Docked width limits, in pixels. */
|
||||
export const PANEL_MIN_WIDTH = 360
|
||||
@@ -160,33 +164,14 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
const [railStatus, setRailStatus] = useState<AssistantConversationStatus>('ACTIVE')
|
||||
const [renaming, setRenaming] = useState(false)
|
||||
const [confirmDelete, setConfirmDelete] = useState(false)
|
||||
/** The rail row whose delete is being confirmed; the open conversation when null. */
|
||||
const [rowDelete, setRowDelete] = useState<AssistantConversation | null>(null)
|
||||
const [dismissedRoute, setDismissedRoute] = useState<string | null>(null)
|
||||
const [pageInfo, setPageInfo] = useState(() => readPageInfo(metaData))
|
||||
const [prefill, setPrefill] = useState<{ id: number; text: string } | null>(null)
|
||||
const [attachments, setAttachments] = useState<AssistantAttachment[]>([])
|
||||
const [attaching, setAttaching] = useState(false)
|
||||
// attaching is offered where saved bulk load profiles are (the bulk-load tools use the files)
|
||||
const canAttach = Boolean(metaData?.processes?.storeSavedBulkLoadProfile)
|
||||
|
||||
// attachments belong to one conversation
|
||||
useEffect(() => setAttachments([]), [activeConversationId])
|
||||
|
||||
/**
|
||||
* Uploads a picked file (POST /uploads, as the user) and attaches its ref.
|
||||
*
|
||||
* @param file - The file.
|
||||
*/
|
||||
const attach = async (file: File) => {
|
||||
setAttaching(true)
|
||||
try {
|
||||
const uploaded = await uploadFile(file)
|
||||
setAttachments((current) => [...current.filter((a) => a.uploadRef !== uploaded.ref), { uploadRef: uploaded.ref, fileName: uploaded.fileName }].slice(-5))
|
||||
} catch (error) {
|
||||
toast.error(`Could not attach ${file.name}: ${getErrorMessage(error)}`)
|
||||
} finally {
|
||||
setAttaching(false)
|
||||
}
|
||||
}
|
||||
// attaching is offered when the server reads attachments, else where saved bulk load profiles are
|
||||
const files = useAssistantAttachments(assistant.config, Boolean(metaData?.processes?.storeSavedBulkLoadProfile), activeConversationId)
|
||||
const clearAttachments = files.clear
|
||||
const listId = useId()
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const stickToBottom = useRef(true)
|
||||
@@ -212,13 +197,29 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
?? conversationsQuery.data?.find((item) => item.id === activeConversationId)
|
||||
const announcement = useStreamAnnouncer(messages)
|
||||
|
||||
// Opening a conversation reads it: the badge drops its unread replies
|
||||
// Opening a conversation reads it: the badge drops its unread replies, here and on the server
|
||||
useEffect(() => {
|
||||
if (activeConversationId === null || !assistant.open) return
|
||||
queryClient.setQueryData<AssistantConversation[]>(assistantKeys.conversations(), (list) =>
|
||||
list?.map((item) => (item.id === activeConversationId && item.unreadCount ? { ...item, unreadCount: 0 } : item)))
|
||||
const unread = queryClient.getQueriesData<AssistantConversation[]>({ queryKey: [...assistantKeys.all(), 'conversations'] })
|
||||
.some(([, list]) => list?.some((item) => item.id === activeConversationId && item.unreadCount > 0))
|
||||
if (unread) markConversationRead(queryClient, activeConversationId)
|
||||
}, [activeConversationId, assistant.open, queryClient, messages.length])
|
||||
|
||||
// Anything else working or unread in the active list, for the History toggle's dot
|
||||
const activeList = useQuery({
|
||||
queryKey: assistantKeys.conversations(),
|
||||
queryFn: () => listAssistantConversations(),
|
||||
staleTime: 1000 * 60,
|
||||
}).data
|
||||
const othersBusy = (activeList ?? []).some((item) => item.id !== activeConversationId && (item.running === true || item.unreadCount > 0))
|
||||
|| Object.keys(engine.runs).some((id) => Number(id) !== activeConversationId)
|
||||
const railConversations = useMemo(() => conversationsQuery.data?.map((item) => (
|
||||
item.running || !engine.runs[item.id] ? item : { ...item, running: true }
|
||||
)), [conversationsQuery.data, engine.runs])
|
||||
const railActions = useRailActions({ activeConversationId, setActiveConversationId })
|
||||
const manageTable = assistant.config?.conversationsTable
|
||||
const manageHref = manageTable && metaData?.tables?.[manageTable] ? `/app/${encodeURIComponent(manageTable)}` : null
|
||||
|
||||
// A reply still streaming on the server (another tab, a reload): follow it
|
||||
useEffect(() => {
|
||||
if (activeConversationId === null) return
|
||||
@@ -230,6 +231,7 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
useEffect(() => {
|
||||
if (!pendingRequest) return
|
||||
consumeRequest(pendingRequest.id)
|
||||
clearAttachments()
|
||||
setActiveConversationId(null)
|
||||
setRailOpen(false)
|
||||
if (pendingRequest.mode === 'prefill') {
|
||||
@@ -238,7 +240,7 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
}
|
||||
const context = pendingRequest.context === undefined ? readPageInfo(metaData)?.context ?? null : pendingRequest.context
|
||||
void engine.send(pendingRequest.prompt, null, context, concurrency)
|
||||
}, [pendingRequest, consumeRequest, setActiveConversationId, metaData, engine, concurrency])
|
||||
}, [pendingRequest, consumeRequest, setActiveConversationId, metaData, engine, concurrency, clearAttachments])
|
||||
|
||||
// Keep the newest message in view while the user has not scrolled up
|
||||
useLayoutEffect(() => {
|
||||
@@ -251,6 +253,19 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
|
||||
const contextDismissed = pageInfo !== null && dismissedRoute === pageInfo.context.route
|
||||
|
||||
/**
|
||||
* Retry for a failed reply: asks the question before it again.
|
||||
*
|
||||
* @param list - The conversation's messages.
|
||||
* @param index - The failed reply's index.
|
||||
* @returns The retry action, or undefined when no question precedes it.
|
||||
*/
|
||||
const retryFor = (list: AssistantMessage[], index: number): (() => void) | undefined => {
|
||||
const question = list.slice(0, index).reverse().find((item) => item.role === 'USER')
|
||||
const text = question?.parts.map((part) => (part.type === 'text' ? part.text : '')).join('').trim()
|
||||
return text ? () => send(text) : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends from the composer, with the page context unless dismissed.
|
||||
*
|
||||
@@ -259,7 +274,8 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
const send = (text: string) => {
|
||||
const info = readPageInfo(metaData)
|
||||
const pageContext = info && dismissedRoute !== info.context.route ? info.context : null
|
||||
const context = attachments.length ? { ...(pageContext ?? {}), attachments } : pageContext
|
||||
const attachments = files.forTurn()
|
||||
const context = attachments ? { ...(pageContext ?? {}), attachments } : pageContext
|
||||
stickToBottom.current = true
|
||||
void engine.send(text, activeConversationId, context, concurrency)
|
||||
}
|
||||
@@ -281,18 +297,11 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes the active conversation. */
|
||||
/** Deletes the conversation being confirmed (a rail row, or the open one). */
|
||||
const deleteConversation = async () => {
|
||||
if (activeConversationId === null) return
|
||||
const id = activeConversationId
|
||||
try {
|
||||
await deleteAssistantConversation(id)
|
||||
setActiveConversationId(null)
|
||||
queryClient.removeQueries({ queryKey: assistantKeys.conversation(id) })
|
||||
await queryClient.invalidateQueries({ queryKey: [...assistantKeys.all(), 'conversations'] })
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error, 'Could not delete the conversation.'))
|
||||
}
|
||||
const target = rowDelete ?? conversation
|
||||
if (!target) return
|
||||
await railActions.remove(target)
|
||||
}
|
||||
|
||||
const showMessages = wide || !railOpen
|
||||
@@ -308,14 +317,21 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
<div className="flex shrink-0 items-center gap-1 border-b border-border px-2" style={{ minHeight: 'var(--qqq-header-height)' }}>
|
||||
<button
|
||||
type="button"
|
||||
className={iconButton}
|
||||
className={cn(iconButton, 'relative')}
|
||||
onClick={() => setRailOpen((value) => !value)}
|
||||
aria-expanded={railOpen}
|
||||
aria-controls={listId}
|
||||
aria-label={railOpen ? 'Hide conversations' : 'Show conversations'}
|
||||
aria-describedby={othersBusy ? `${listId}-busy` : undefined}
|
||||
data-qqq-id="assistant-rail-toggle"
|
||||
>
|
||||
<PanelLeft className="h-4 w-4" aria-hidden="true" />
|
||||
{othersBusy && (
|
||||
<>
|
||||
<span className="absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-primary" aria-hidden="true" data-qqq-id="assistant-rail-toggle-dot" />
|
||||
<span id={`${listId}-busy`} className="sr-only">Other conversations are working or have unread replies</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{renaming && conversation ? (
|
||||
<form
|
||||
@@ -408,6 +424,7 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
type="button"
|
||||
className={iconButton}
|
||||
onClick={() => {
|
||||
clearAttachments()
|
||||
setActiveConversationId(null)
|
||||
setRailOpen(false)
|
||||
requestAnimationFrame(() => composerRef.current?.focus())
|
||||
@@ -427,7 +444,7 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
return (
|
||||
<div key={id} className="flex items-center gap-2 border-b border-border px-3 py-2 text-xs" data-qqq-id="assistant-background-run">
|
||||
<span className="min-w-0 flex-1">Answering in {conversationTitle(other)} - <AssistantElapsed startedAt={runs[0].startedAt} /></span>
|
||||
<button type="button" className={textButton} onClick={() => { setActiveConversationId(Number(id)); setRailOpen(false) }} data-qqq-id="assistant-background-open">Open</button>
|
||||
<button type="button" className={textButton} onClick={() => { clearAttachments(); setActiveConversationId(Number(id)); setRailOpen(false) }} data-qqq-id="assistant-background-open">Open</button>
|
||||
<button type="button" className={textButton} onClick={() => engine.cancel(Number(id))} data-qqq-id="assistant-background-stop">Stop</button>
|
||||
</div>
|
||||
)
|
||||
@@ -438,12 +455,17 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
<div id={listId} className={cn('flex min-h-0', wide ? 'w-52 shrink-0 border-r border-border' : 'min-w-0 flex-1')}>
|
||||
<ConversationRail
|
||||
className="min-w-0 flex-1"
|
||||
conversations={conversationsQuery.data}
|
||||
conversations={railConversations}
|
||||
loading={conversationsQuery.isLoading}
|
||||
activeId={activeConversationId}
|
||||
status={railStatus}
|
||||
onStatusChange={setRailStatus}
|
||||
onArchive={(item) => void railActions.archive(item)}
|
||||
onDelete={(item) => { setRowDelete(item); setConfirmDelete(true) }}
|
||||
manageHref={manageHref}
|
||||
onManage={() => { if (!wide) assistant.setOpen(false) }}
|
||||
onSelect={(id) => {
|
||||
if (id !== activeConversationId) clearAttachments()
|
||||
setActiveConversationId(id)
|
||||
if (!engine.runs[id]) void queryClient.invalidateQueries({ queryKey: assistantKeys.conversation(id) })
|
||||
if (!wide) setRailOpen(false)
|
||||
@@ -491,36 +513,61 @@ function PanelBody({ assistant, engine, wide, titleId, composerRef }: PanelBodyP
|
||||
{activeConversationId !== null && detailQuery.isError && (
|
||||
<p className="text-xs text-destructive" role="alert">{getErrorMessage(detailQuery.error, 'Could not load the conversation.')}</p>
|
||||
)}
|
||||
{messages.map((message) => <AssistantMessageView key={message.id} message={message} onSend={send} run={activeConversationId === null ? undefined : engine.runs[activeConversationId]?.find((entry) => entry.assistantMessageId === message.id)} />)}
|
||||
{messages.map((message, index) => (
|
||||
<ErrorBoundary
|
||||
key={message.id}
|
||||
scope="assistant-message"
|
||||
reportContext={{ conversationId: activeConversationId, messageId: message.id, turnId: message.turnId }}
|
||||
resetKeys={[message]}
|
||||
fallbackRender={({ report, error }) => <InlineFailure message="This message could not be shown." report={report} error={error} qqqId="assistant-message-error" />}
|
||||
>
|
||||
<AssistantMessageView
|
||||
message={message}
|
||||
onSend={send}
|
||||
run={activeConversationId === null ? undefined : engine.runs[activeConversationId]?.find((entry) => entry.assistantMessageId === message.id)}
|
||||
onRetry={message.status === 'ERROR' ? retryFor(messages, index) : undefined}
|
||||
onStop={message.status === 'STREAMING' && activeConversationId !== null ? () => engine.stopMessage(activeConversationId, message) : undefined}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
))}
|
||||
</div>
|
||||
<AssistantComposer
|
||||
ref={composerRef}
|
||||
pageInfo={pageInfo}
|
||||
contextDismissed={contextDismissed}
|
||||
onDismissContext={() => setDismissedRoute(pageInfo?.context.route ?? null)}
|
||||
onRefreshContext={() => setPageInfo(readPageInfo(metaData))}
|
||||
concurrency={concurrency}
|
||||
streaming={Boolean(run)}
|
||||
stopping={Boolean(run) && engine.runs[activeConversationId as number]?.every((entry) => entry.status === 'cancelling')}
|
||||
onSend={send}
|
||||
onStop={() => activeConversationId !== null && engine.cancel(activeConversationId)}
|
||||
prefill={prefill}
|
||||
attachments={attachments}
|
||||
onAttach={canAttach ? (file) => void attach(file) : undefined}
|
||||
onRemoveAttachment={(uploadRef) => setAttachments((current) => current.filter((a) => a.uploadRef !== uploadRef))}
|
||||
attaching={attaching}
|
||||
/>
|
||||
<ErrorBoundary
|
||||
scope="assistant-composer"
|
||||
reportContext={{ conversationId: activeConversationId }}
|
||||
fallbackRender={({ report, error, reset }) => <InlineFailure message="The message box could not be shown." report={report} error={error} onRetry={reset} qqqId="assistant-composer-error" className="m-3" />}
|
||||
>
|
||||
<AssistantComposer
|
||||
ref={composerRef}
|
||||
pageInfo={pageInfo}
|
||||
contextDismissed={contextDismissed}
|
||||
onDismissContext={() => setDismissedRoute(pageInfo?.context.route ?? null)}
|
||||
onRefreshContext={() => setPageInfo(readPageInfo(metaData))}
|
||||
concurrency={concurrency}
|
||||
streaming={Boolean(run)}
|
||||
stopping={Boolean(run) && engine.runs[activeConversationId as number]?.every((entry) => entry.status === 'cancelling')}
|
||||
onSend={send}
|
||||
onStop={() => activeConversationId !== null && engine.cancel(activeConversationId)}
|
||||
prefill={prefill}
|
||||
attachments={files.attachments}
|
||||
onAttach={files.policy.enabled ? (file) => void files.attach(file) : undefined}
|
||||
onRemoveAttachment={files.remove}
|
||||
attaching={files.attaching}
|
||||
attachPolicy={files.policy}
|
||||
attachError={files.error}
|
||||
onDismissAttachError={files.dismissError}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="sr-only" aria-live="polite" aria-atomic="true" data-qqq-id="assistant-announcer">{announcement}</div>
|
||||
|
||||
<AlertDialog.Root open={confirmDelete} onOpenChange={setConfirmDelete}>
|
||||
<AlertDialog.Root open={confirmDelete} onOpenChange={(open) => { setConfirmDelete(open); if (!open) setRowDelete(null) }}>
|
||||
<AlertDialog.Portal>
|
||||
<AlertDialog.Overlay className="fixed inset-0 z-[2200] bg-black/40" />
|
||||
<AlertDialog.Content className="fixed left-1/2 top-1/2 z-[2201] w-[calc(100%-2rem)] max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-card p-5 shadow-lg focus:outline-none" data-qqq-id="assistant-delete-dialog">
|
||||
<AlertDialog.Title className="text-base font-semibold text-foreground">Delete this conversation?</AlertDialog.Title>
|
||||
<AlertDialog.Description className="mt-1 text-sm text-muted-foreground">{conversationTitle(conversation)} and its messages are deleted. This cannot be undone.</AlertDialog.Description>
|
||||
<AlertDialog.Description className="mt-1 text-sm text-muted-foreground">{conversationTitle(rowDelete ?? conversation)} and its messages are deleted. This cannot be undone.</AlertDialog.Description>
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<AlertDialog.Cancel className="rounded-md border border-border px-3 py-1.5 text-sm hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11">Cancel</AlertDialog.Cancel>
|
||||
<AlertDialog.Action
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* 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 AssistantPanelFailure — what the assistant panel shows when it crashes: the page keeps
|
||||
* working, and the user can retry, copy the details or report a bug.
|
||||
*/
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { AlertTriangle, Bug, Copy, RefreshCw, X } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { clientErrorDetails, type ClientErrorReport } from '@/lib/errors/client-errors'
|
||||
import { useQaCaptureCapability } from '@/lib/hooks/use-qa-capture'
|
||||
import type { RouteMetaData } from '@/lib/qa-capture/route-context'
|
||||
import { queryKeys } from '@/lib/query-client'
|
||||
import { useAssistant } from './assistant-context'
|
||||
|
||||
const BUTTON = 'inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 pointer-coarse:min-h-11'
|
||||
|
||||
/**
|
||||
* Starts a QA capture bug report, when QA capture is enabled for this user.
|
||||
*
|
||||
* @returns The action, or null when reporting is unavailable.
|
||||
*/
|
||||
function useReportBug(): { busy: boolean; report: () => Promise<void> } | null {
|
||||
const capability = useQaCaptureCapability()
|
||||
const client = useQueryClient()
|
||||
const [busy, setBusy] = useState(false)
|
||||
if (!capability?.enabled || !capability.canReport) return null
|
||||
return {
|
||||
busy,
|
||||
report: async () => {
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
// loaded on demand: this card ships with the app shell
|
||||
const { startBugReport } = await import('@/lib/qa-capture/report')
|
||||
await startBugReport({ capability, metaData: client.getQueryData<RouteMetaData>(queryKeys.metadataAll()) })
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error && error.message ? `Could not start the bug report: ${error.message}` : 'Could not start the bug report.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The crashed panel's replacement: a small card with Retry, Copy details, Report a bug and Close.
|
||||
* Shown only while the panel is open; the page around it is untouched.
|
||||
*
|
||||
* @param props - The failure.
|
||||
* @param props.report - The report built for the crash (null until it is built).
|
||||
* @param props.error - The error.
|
||||
* @param props.onRetry - Mounts the panel again.
|
||||
* @returns The card, or null when the panel is closed.
|
||||
*/
|
||||
export function AssistantPanelFailure({ report, error, onRetry }: { report: ClientErrorReport | null; error: Error; onRetry: () => void }) {
|
||||
const assistant = useAssistant()
|
||||
const bug = useReportBug()
|
||||
if (!assistant?.open) return null
|
||||
const details = report ? clientErrorDetails(report) : `${error.name}: ${error.message}`
|
||||
|
||||
/** Copies the details for a bug report. */
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(details)
|
||||
toast.success('Details copied')
|
||||
} catch {
|
||||
toast.error('Could not copy the details.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="fixed bottom-4 right-4 z-[var(--qqq-z-modal,1000)] w-[min(24rem,calc(100vw-2rem))] rounded-xl border border-border bg-card p-4 shadow-lg"
|
||||
role="alert"
|
||||
aria-label="Assistant"
|
||||
data-qqq-id="assistant-panel-error"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" aria-hidden="true" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-semibold text-foreground">The assistant hit a problem</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">The rest of the page still works. Retry to reopen the assistant; your conversations are kept.</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => assistant.setOpen(false)}
|
||||
className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:h-11 pointer-coarse:w-11"
|
||||
aria-label="Close assistant"
|
||||
data-qqq-id="assistant-panel-error-close"
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" onClick={onRetry} className={BUTTON} data-qqq-id="assistant-panel-error-retry">
|
||||
<RefreshCw className="h-3.5 w-3.5" aria-hidden="true" />Retry
|
||||
</button>
|
||||
<button type="button" onClick={() => void copy()} className={BUTTON} data-qqq-id="assistant-panel-error-copy">
|
||||
<Copy className="h-3.5 w-3.5" aria-hidden="true" />Copy details
|
||||
</button>
|
||||
{bug && (
|
||||
<button type="button" onClick={() => void bug.report()} disabled={bug.busy} className={BUTTON} data-qqq-id="assistant-panel-error-report">
|
||||
<Bug className="h-3.5 w-3.5" aria-hidden="true" />{bug.busy ? 'Starting...' : 'Report a bug'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<details className="mt-2 text-xs text-muted-foreground">
|
||||
<summary className="cursor-pointer select-none">Details</summary>
|
||||
<pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-muted p-1.5 font-mono text-[11px]" data-qqq-id="assistant-panel-error-details">{details}</pre>
|
||||
</details>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -27,7 +27,8 @@ import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import type { QInstance } from '@/types'
|
||||
import type { AssistantPageContext } from '@/types/assistant'
|
||||
import { getAssistantConfig, listAssistantConversations } from '@/lib/api/assistant-probe'
|
||||
import { getAssistantConfig, listAssistantConversations, reportAssistantClientError, supportsAssistantClientErrors } from '@/lib/api/assistant-probe'
|
||||
import { setClientErrorSink } from '@/lib/errors/client-errors'
|
||||
import { readAssistantDeepLink } from '@/lib/utils/assistant-deep-link'
|
||||
import { ASSISTANT_DOCKED_MEDIA_QUERY, AssistantContext, assistantKeys, type AssistantController, type AssistantRequest } from './assistant-context'
|
||||
|
||||
@@ -97,11 +98,28 @@ export function useAssistantController(metaData: QInstance | undefined, isAuthen
|
||||
})
|
||||
const enabled = installed && Boolean(config?.enabled)
|
||||
|
||||
// UI failures (error boundaries, stream errors) go to Admin through the assistant's
|
||||
// client-error operation when the server has it; otherwise they are only logged.
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
let active = true
|
||||
void supportsAssistantClientErrors().then((supported) => {
|
||||
if (active && supported) setClientErrorSink(reportAssistantClientError)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
setClientErrorSink(null)
|
||||
}
|
||||
}, [enabled])
|
||||
|
||||
const { data: conversations } = useQuery({
|
||||
queryKey: assistantKeys.conversations(),
|
||||
queryFn: () => listAssistantConversations(),
|
||||
enabled,
|
||||
staleTime: 1000 * 60,
|
||||
// Replies landing in background threads (another tab, a long turn): refetch while the server
|
||||
// reports one running, so the badge and rail catch up; idle, only the usual refetch on focus
|
||||
refetchInterval: (query) => ((query.state.data ?? []).some((conversation) => conversation.running) ? 8000 : false),
|
||||
})
|
||||
const unreadCount = useMemo(() => (conversations ?? []).reduce((total, conversation) => total + (conversation.unreadCount || 0), 0), [conversations])
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
// Tool result renders tolerate payloads with missing lists, and one bad part
|
||||
// cannot take down the reply around it.
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { AssistantMessage, AssistantRender } from '@/types/assistant'
|
||||
import { AssistantRenderView } from './AssistantRenders'
|
||||
import { AssistantMessageView } from './AssistantMessageView'
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
|
||||
|
||||
// The exact payload kof22 stored for a query that matched nothing (2026-10-16):
|
||||
// the server omitted the empty rows and columns lists.
|
||||
const emptyRecords = {
|
||||
type: 'records',
|
||||
tableName: 'db_perf_finding',
|
||||
tableLabel: 'Findings',
|
||||
openHref: '/app/db_perf_finding?filter=eyJib29sZWFuT3BlcmF0b3IiOiJBTkQifQ%3D%3D',
|
||||
totalCount: 0,
|
||||
truncated: false,
|
||||
} as unknown as AssistantRender
|
||||
|
||||
describe('AssistantRenderView', () => {
|
||||
it('renders a records payload without rows or columns as "no rows match"', () => {
|
||||
render(<AssistantRenderView render={emptyRecords} />)
|
||||
expect(screen.getByText('Findings: no rows match')).toBeInTheDocument()
|
||||
expect(screen.getByText('Open in Query screen')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders history and record payloads without their lists', () => {
|
||||
render(<AssistantRenderView render={{ type: 'history', tableName: 't', tableLabel: 'T', id: 1 } as unknown as AssistantRender} />)
|
||||
expect(screen.getByText('No changes recorded.')).toBeInTheDocument()
|
||||
const { container } = render(<AssistantRenderView render={{ type: 'record', tableName: 't', tableLabel: 'T', id: 7, href: '/app/t/7' } as unknown as AssistantRender} />)
|
||||
expect(container.querySelector('[data-qqq-id="assistant-record"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('AssistantMessageView', () => {
|
||||
it('shows the reply when a tool part carries the empty records payload', () => {
|
||||
const message: AssistantMessage = {
|
||||
id: 84, role: 'ASSISTANT', status: 'COMPLETE', turnId: 5, createDate: '2026-10-16T00:24:26Z',
|
||||
parts: [
|
||||
{ type: 'tool', toolCallId: 'toolu_x', name: 'query_records', summary: 'Queried Findings', outcome: 'OK', render: emptyRecords },
|
||||
{ type: 'text', text: 'Here are the main issues.' },
|
||||
],
|
||||
} as unknown as AssistantMessage
|
||||
render(<AssistantMessageView message={message} onSend={vi.fn()} sending={false} />)
|
||||
expect(screen.getByText('Here are the main issues.')).toBeInTheDocument()
|
||||
expect(screen.getByText('Findings: no rows match')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the rest of the reply when one part throws while rendering', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const broken = { type: 'count', tableName: 't', tableLabel: 'T', openHref: '/app/t' } as unknown as AssistantRender // no count: toLocaleString throws
|
||||
const message: AssistantMessage = {
|
||||
id: 85, role: 'ASSISTANT', status: 'COMPLETE', turnId: 6, createDate: '2026-10-16T00:30:00Z',
|
||||
parts: [
|
||||
{ type: 'tool', toolCallId: 'toolu_y', name: 'count_records', summary: 'Counted', outcome: 'OK', render: broken },
|
||||
{ type: 'text', text: 'Still readable.' },
|
||||
],
|
||||
} as unknown as AssistantMessage
|
||||
render(<AssistantMessageView message={message} onSend={vi.fn()} sending={false} />)
|
||||
expect(screen.getByText('Still readable.')).toBeInTheDocument()
|
||||
// the tool step (its label) stays; only its result is replaced
|
||||
expect(screen.getByText('Counted')).toBeInTheDocument()
|
||||
expect(screen.getByText("This result could not be shown.")).toBeInTheDocument()
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('isolates a part that throws outside a render, and shows unknown parts and renders as JSON', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const message = {
|
||||
id: 86, role: 'ASSISTANT', status: 'COMPLETE', turnId: 7, createDate: '2026-10-16T00:30:00Z',
|
||||
parts: [
|
||||
{ type: 'record_refs', refs: null }, // refs.length throws in RecordChips
|
||||
{ type: 'tool', toolCallId: 'toolu_z', name: 'future_tool', summary: 'Mapped', outcome: 'OK', render: { type: 'unknown', originalType: 'map', raw: { type: 'map', pins: 2 } } },
|
||||
{ type: 'unknown', originalType: 'approval', raw: { type: 'approval', id: 9 } },
|
||||
{ type: 'text', text: 'After the bad parts.' },
|
||||
],
|
||||
} as unknown as AssistantMessage
|
||||
render(<AssistantMessageView message={message} onSend={vi.fn()} sending={false} />)
|
||||
expect(screen.getByText('After the bad parts.')).toBeInTheDocument()
|
||||
expect(screen.getByText("This part could not be shown.")).toBeInTheDocument()
|
||||
expect(screen.getByText('Unsupported result (map)')).toBeInTheDocument()
|
||||
expect(screen.getByText('Unsupported content (approval)')).toBeInTheDocument()
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('offers Retry on a failed reply and Stop on a running one', async () => {
|
||||
const onRetry = vi.fn()
|
||||
const onStop = vi.fn()
|
||||
const failed = { id: 87, role: 'ASSISTANT', status: 'ERROR', turnId: 8, createDate: '2026-10-16T00:30:00Z', parts: [] } as unknown as AssistantMessage
|
||||
const { rerender } = render(<AssistantMessageView message={failed} onSend={vi.fn()} sending={false} onRetry={onRetry} />)
|
||||
expect(screen.getByText('The reply did not finish.')).toBeInTheDocument()
|
||||
screen.getByRole('button', { name: 'Retry' }).click()
|
||||
expect(onRetry).toHaveBeenCalledOnce()
|
||||
const running = { ...failed, status: 'STREAMING' } as AssistantMessage
|
||||
rerender(<AssistantMessageView message={running} onSend={vi.fn()} sending={false} onStop={onStop} />)
|
||||
screen.getByRole('button', { name: 'Stop' }).click()
|
||||
expect(onStop).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -113,10 +113,23 @@ export function RecordChips({ refs }: { refs: AssistantRecordRef[] }) {
|
||||
* @returns The records view.
|
||||
*/
|
||||
function RecordsView({ render }: { render: AssistantRecordsRender }) {
|
||||
const shown = render.rows.length
|
||||
// Older servers omit empty lists (a query that matched nothing): treat as [].
|
||||
const rows = Array.isArray(render.rows) ? render.rows : []
|
||||
const columns = Array.isArray(render.columns) ? render.columns : []
|
||||
const shown = rows.length
|
||||
const total = render.totalCount ?? shown
|
||||
const caption = `${render.tableLabel}: ${shown === total ? `${total} ${total === 1 ? 'row' : 'rows'}` : `${shown} of ${total} rows`}`
|
||||
const [firstColumn, ...otherColumns] = render.columns
|
||||
const [firstColumn, ...otherColumns] = columns
|
||||
if (shown === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2 rounded-lg border border-border bg-card px-3 py-2" data-qqq-id="assistant-records">
|
||||
<span className="truncate text-xs text-muted-foreground">{render.tableLabel}: no rows match</span>
|
||||
<SafeLink href={render.openHref} className={ACTION_LINK} qqqId="assistant-open-query">
|
||||
Open in Query screen<ArrowRight className="h-3 w-3" aria-hidden="true" />
|
||||
</SafeLink>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="@container rounded-lg border border-border bg-card" data-qqq-id="assistant-records">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-border px-3 py-2">
|
||||
@@ -130,17 +143,17 @@ function RecordsView({ render }: { render: AssistantRecordsRender }) {
|
||||
<table className="w-full text-left text-xs">
|
||||
<thead>
|
||||
<tr className="border-b border-border text-muted-foreground">
|
||||
{render.columns.map((column) => <th key={column.name} scope="col" className="whitespace-nowrap px-3 py-1.5 font-medium">{column.label}</th>)}
|
||||
{columns.map((column) => <th key={column.name} scope="col" className="whitespace-nowrap px-3 py-1.5 font-medium">{column.label}</th>)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{render.rows.map((row) => (
|
||||
{rows.map((row) => (
|
||||
<tr key={String(row.id)} className="border-b border-border last:border-0">
|
||||
{render.columns.map((column, index) => (
|
||||
{columns.map((column, index) => (
|
||||
<td key={column.name} className="max-w-[16rem] truncate px-3 py-1.5 text-foreground">
|
||||
{index === 0 ? (
|
||||
<SafeLink href={row.href} className="font-medium text-primary hover:underline">{row.values[column.name] ?? String(row.id)}</SafeLink>
|
||||
) : (row.values[column.name] ?? '')}
|
||||
<SafeLink href={row.href} className="font-medium text-primary hover:underline">{row.values?.[column.name] ?? String(row.id)}</SafeLink>
|
||||
) : (row.values?.[column.name] ?? '')}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
@@ -150,18 +163,18 @@ function RecordsView({ render }: { render: AssistantRecordsRender }) {
|
||||
</div>
|
||||
{/* narrow: one card per row */}
|
||||
<ul className="divide-y divide-border @lg:hidden">
|
||||
{render.rows.map((row) => (
|
||||
{rows.map((row) => (
|
||||
<li key={String(row.id)} className="px-3 py-2">
|
||||
{firstColumn && (
|
||||
<SafeLink href={row.href} className="block truncate text-sm font-medium text-primary hover:underline">
|
||||
{row.values[firstColumn.name] ?? String(row.id)}
|
||||
{row.values?.[firstColumn.name] ?? String(row.id)}
|
||||
</SafeLink>
|
||||
)}
|
||||
<dl className="mt-1 grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-xs">
|
||||
{otherColumns.slice(0, 4).map((column) => (
|
||||
<React.Fragment key={column.name}>
|
||||
<dt className="truncate text-muted-foreground">{column.label}</dt>
|
||||
<dd className="truncate text-foreground">{row.values[column.name] ?? ''}</dd>
|
||||
<dd className="truncate text-foreground">{row.values?.[column.name] ?? ''}</dd>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</dl>
|
||||
@@ -188,7 +201,7 @@ function RecordView({ render }: { render: AssistantRecordRender }) {
|
||||
<SafeLink href={render.href} className={ACTION_LINK}>Open<ArrowRight className="h-3 w-3" aria-hidden="true" /></SafeLink>
|
||||
</div>
|
||||
<dl className="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-xs">
|
||||
{render.fields.map((field) => (
|
||||
{(render.fields ?? []).map((field) => (
|
||||
<React.Fragment key={field.name}>
|
||||
<dt className="truncate text-muted-foreground">{field.label}</dt>
|
||||
<dd className="break-words text-foreground">{field.value ?? '—'}</dd>
|
||||
@@ -228,16 +241,16 @@ function CountView({ render }: { render: AssistantCountRender }) {
|
||||
* @returns The history list.
|
||||
*/
|
||||
function HistoryView({ render }: { render: AssistantHistoryRender }) {
|
||||
if (!render.entries.length) return <p className="text-xs text-muted-foreground">No changes recorded.</p>
|
||||
if (!render.entries?.length) return <p className="text-xs text-muted-foreground">No changes recorded.</p>
|
||||
return (
|
||||
<ol className="space-y-2 rounded-lg border border-border bg-card px-3 py-2" data-qqq-id="assistant-history">
|
||||
{render.entries.map((entry, index) => (
|
||||
<li key={index} className="text-xs">
|
||||
<p className="text-muted-foreground">{formatTimestamp(entry.timestamp)} · {entry.user}</p>
|
||||
<p className="text-foreground">{entry.message}</p>
|
||||
{entry.details.length > 0 && (
|
||||
{(entry.details?.length ?? 0) > 0 && (
|
||||
<ul className="mt-0.5 space-y-0.5 pl-3">
|
||||
{entry.details.map((detail, detailIndex) => (
|
||||
{(entry.details ?? []).map((detail, detailIndex) => (
|
||||
<li key={detailIndex} className="break-words text-muted-foreground">
|
||||
<span className="font-medium text-foreground">{detail.field}</span>: {detail.oldValue ?? '—'} {'→'} {detail.newValue ?? '—'}{detail.truncated ? ' …' : ''}
|
||||
</li>
|
||||
@@ -310,7 +323,36 @@ export function AssistantRenderView({ render }: { render: AssistantRender }) {
|
||||
<PendingActionCard render={render} />
|
||||
</Suspense>
|
||||
)
|
||||
case 'unknown':
|
||||
return <RawJsonView label={render.originalType ? `Unsupported result (${render.originalType})` : 'Unsupported result'} value={render.raw} />
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Longest JSON shown for an unsupported payload. */
|
||||
const RAW_JSON_LIMIT = 20_000
|
||||
|
||||
/**
|
||||
* Shows a payload this UI cannot render as formatted JSON behind a toggle, instead of failing.
|
||||
*
|
||||
* @param props - The label and the payload.
|
||||
* @param props.label - What the payload is.
|
||||
* @param props.value - The payload.
|
||||
* @returns A collapsed JSON view.
|
||||
*/
|
||||
export function RawJsonView({ label, value }: { label: string; value: unknown }) {
|
||||
let json: string
|
||||
try {
|
||||
json = JSON.stringify(value, null, 2) ?? String(value)
|
||||
} catch {
|
||||
json = String(value)
|
||||
}
|
||||
if (json.length > RAW_JSON_LIMIT) json = `${json.slice(0, RAW_JSON_LIMIT)}\n…`
|
||||
return (
|
||||
<details className="rounded-lg border border-border bg-card px-3 py-2 text-xs" data-qqq-id="assistant-raw-json">
|
||||
<summary className="cursor-pointer select-none text-muted-foreground">{label}</summary>
|
||||
<pre className="mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-words font-mono text-[11px] text-foreground">{json}</pre>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -15,14 +15,18 @@
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file ConversationRail — the panel's conversation list (pinned, recent, archived) as a
|
||||
* listbox: arrow keys move, Enter or Space opens, unread conversations show a dot.
|
||||
* @file ConversationRail — the panel's conversation list (pinned, recent, archived). A list of
|
||||
* rows, each a main button that opens the conversation plus Archive/Restore and Delete buttons.
|
||||
* (A listbox cannot hold buttons, so the rows are plain buttons with arrow-key navigation:
|
||||
* Up/Down/Home/End move between rows, Right reaches a row's actions, Left returns.) Running
|
||||
* conversations show a spinner, unread ones a dot and a bold title.
|
||||
*/
|
||||
|
||||
'use client'
|
||||
|
||||
import React, { useId, useRef } from 'react'
|
||||
import { Pin } from 'lucide-react'
|
||||
import React, { useEffect, useId, useRef, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { Archive, ArchiveRestore, ExternalLink, Loader2, Pin, Trash2 } from 'lucide-react'
|
||||
|
||||
import type { AssistantConversation, AssistantConversationStatus } from '@/types/assistant'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
@@ -46,6 +50,22 @@ interface ConversationRailProps {
|
||||
* @param id - The conversation id.
|
||||
*/
|
||||
onSelect: (id: number) => void
|
||||
/**
|
||||
* Archives a conversation (or restores it, in the archived list).
|
||||
*
|
||||
* @param conversation - The conversation.
|
||||
*/
|
||||
onArchive: (conversation: AssistantConversation) => void
|
||||
/**
|
||||
* Asks to delete a conversation (the panel confirms first).
|
||||
*
|
||||
* @param conversation - The conversation.
|
||||
*/
|
||||
onDelete: (conversation: AssistantConversation) => void
|
||||
/** Path of the standard table screen listing all conversations; the link is hidden without it. */
|
||||
manageHref?: string | null
|
||||
/** Called when the manage link is followed. */
|
||||
onManage?: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
@@ -59,79 +79,143 @@ export function conversationTitle(conversation: AssistantConversation | undefine
|
||||
return conversation?.title?.trim() || 'New conversation'
|
||||
}
|
||||
|
||||
/** Classes of a row's small icon buttons. */
|
||||
const ACTION_BUTTON = 'inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:h-11 pointer-coarse:w-11'
|
||||
|
||||
/**
|
||||
* The conversation list.
|
||||
*
|
||||
* @param props - Component properties.
|
||||
* @returns The rail.
|
||||
*/
|
||||
export function ConversationRail({ conversations, loading, activeId, status, onStatusChange, onSelect, className }: ConversationRailProps) {
|
||||
export function ConversationRail({ conversations, loading, activeId, status, onStatusChange, onSelect, onArchive, onDelete, manageHref, onManage, className }: ConversationRailProps) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const labelId = useId()
|
||||
const list = conversations ?? []
|
||||
const pinned = list.filter((conversation) => conversation.pinned)
|
||||
const recent = list.filter((conversation) => !conversation.pinned)
|
||||
const ordered = [...pinned, ...recent]
|
||||
const focusIndex = Math.max(0, ordered.findIndex((conversation) => conversation.id === activeId))
|
||||
const [focusedId, setFocusedId] = useState<number | null>(null)
|
||||
const tabId = [focusedId, activeId].find((id) => id !== null && ordered.some((conversation) => conversation.id === id)) ?? ordered[0]?.id
|
||||
const lastIndex = useRef(0)
|
||||
lastIndex.current = Math.max(0, ordered.findIndex((conversation) => conversation.id === focusedId))
|
||||
|
||||
// A row that disappears under the keyboard (archived, deleted) hands focus to its neighbour
|
||||
const count = ordered.length
|
||||
const previousCount = useRef(count)
|
||||
useEffect(() => {
|
||||
const shrank = count < previousCount.current
|
||||
previousCount.current = count
|
||||
if (!shrank || count === 0) return
|
||||
const active = document.activeElement
|
||||
if (active && active !== document.body && active.isConnected) return
|
||||
const mains = listRef.current?.querySelectorAll<HTMLElement>('[data-conversation-main]')
|
||||
mains?.[Math.min(lastIndex.current, count - 1)]?.focus()
|
||||
}, [count])
|
||||
|
||||
/**
|
||||
* Arrow-key navigation between options.
|
||||
* Arrow-key navigation between rows and from a row to its actions.
|
||||
*
|
||||
* @param event - The key event.
|
||||
*/
|
||||
const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const options = Array.from(listRef.current?.querySelectorAll<HTMLElement>('[role="option"]') ?? [])
|
||||
const current = options.indexOf(document.activeElement as HTMLElement)
|
||||
let next = -1
|
||||
if (event.key === 'ArrowDown') next = Math.min(options.length - 1, current + 1)
|
||||
else if (event.key === 'ArrowUp') next = Math.max(0, current - 1)
|
||||
else if (event.key === 'Home') next = 0
|
||||
else if (event.key === 'End') next = options.length - 1
|
||||
else if ((event.key === 'Enter' || event.key === ' ') && current >= 0) {
|
||||
const target = event.target as HTMLElement
|
||||
const rowElement = target.closest<HTMLElement>('[data-conversation-row]')
|
||||
if (!rowElement) return
|
||||
const mains = Array.from(listRef.current?.querySelectorAll<HTMLElement>('[data-conversation-main]') ?? [])
|
||||
const actions = Array.from(rowElement.querySelectorAll<HTMLElement>('[data-conversation-action]'))
|
||||
const onMain = target.hasAttribute('data-conversation-main')
|
||||
const main = rowElement.querySelector<HTMLElement>('[data-conversation-main]') as HTMLElement
|
||||
const current = mains.indexOf(main)
|
||||
let next: HTMLElement | undefined
|
||||
if (event.key === 'ArrowDown') next = mains[Math.min(mains.length - 1, current + 1)]
|
||||
else if (event.key === 'ArrowUp') next = mains[Math.max(0, current - 1)]
|
||||
else if (event.key === 'Home') next = mains[0]
|
||||
else if (event.key === 'End') next = mains[mains.length - 1]
|
||||
else if (event.key === 'ArrowRight') next = onMain ? actions[0] : actions[actions.indexOf(target) + 1]
|
||||
else if (event.key === 'ArrowLeft' && !onMain) next = actions[actions.indexOf(target) - 1] ?? main
|
||||
if (next) {
|
||||
event.preventDefault()
|
||||
onSelect(Number(options[current].dataset.conversationId))
|
||||
return
|
||||
}
|
||||
if (next >= 0 && options[next]) {
|
||||
event.preventDefault()
|
||||
options.forEach((option, index) => option.setAttribute('tabindex', index === next ? '0' : '-1'))
|
||||
options[next].focus()
|
||||
next.focus()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One option.
|
||||
* One row.
|
||||
*
|
||||
* @param conversation - The conversation.
|
||||
* @param index - Its position in keyboard order.
|
||||
* @returns The option.
|
||||
* @returns The row.
|
||||
*/
|
||||
const option = (conversation: AssistantConversation, index: number) => {
|
||||
const row = (conversation: AssistantConversation) => {
|
||||
const selected = conversation.id === activeId
|
||||
const unread = conversation.unreadCount > 0 && !selected
|
||||
const running = conversation.running === true
|
||||
const title = conversationTitle(conversation)
|
||||
const tabIndex = conversation.id === tabId ? 0 : -1
|
||||
const archived = conversation.status === 'ARCHIVED'
|
||||
return (
|
||||
<div
|
||||
<li
|
||||
key={conversation.id}
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
tabIndex={index === focusIndex ? 0 : -1}
|
||||
data-conversation-row
|
||||
data-conversation-id={conversation.id}
|
||||
onClick={() => onSelect(conversation.id)}
|
||||
className={cn(
|
||||
'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11',
|
||||
selected ? 'bg-primary/10 text-primary' : 'text-foreground hover:bg-accent'
|
||||
)}
|
||||
data-qqq-id="assistant-conversation"
|
||||
onFocus={() => setFocusedId(conversation.id)}
|
||||
className={cn('group relative flex items-center rounded-md', selected ? 'bg-primary/10 text-primary' : 'text-foreground hover:bg-accent')}
|
||||
>
|
||||
{conversation.pinned && <Pin className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />}
|
||||
<span className={cn('min-w-0 flex-1 truncate', unread && 'font-semibold')}>{conversationTitle(conversation)}</span>
|
||||
{unread && (
|
||||
<>
|
||||
<span className="h-2 w-2 shrink-0 rounded-full bg-primary" aria-hidden="true" data-qqq-id="assistant-conversation-unread" />
|
||||
<span className="sr-only">, unread</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
data-conversation-main
|
||||
aria-current={selected ? 'true' : undefined}
|
||||
tabIndex={tabIndex}
|
||||
onClick={() => onSelect(conversation.id)}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11"
|
||||
data-qqq-id="assistant-conversation"
|
||||
>
|
||||
<span className="flex h-3.5 w-3.5 shrink-0 items-center justify-center">
|
||||
{running ? (
|
||||
<>
|
||||
<Loader2 className="h-3.5 w-3.5 text-primary motion-safe:animate-spin" aria-hidden="true" data-qqq-id="assistant-conversation-running" />
|
||||
<span className="sr-only">Working: </span>
|
||||
</>
|
||||
) : null}
|
||||
{!running && unread ? <span className="h-2 w-2 rounded-full bg-primary" aria-hidden="true" data-qqq-id="assistant-conversation-unread" /> : null}
|
||||
</span>
|
||||
{conversation.pinned && <Pin className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />}
|
||||
<span className={cn('min-w-0 flex-1 truncate', unread && 'font-semibold')}>
|
||||
{title}
|
||||
{unread && <span className="sr-only">, unread</span>}
|
||||
</span>
|
||||
{running && unread && <span className="h-2 w-2 shrink-0 rounded-full bg-primary" aria-hidden="true" data-qqq-id="assistant-conversation-unread" />}
|
||||
</button>
|
||||
<div
|
||||
className="absolute right-1 top-1/2 flex -translate-y-1/2 items-center gap-0.5 rounded-md bg-sidebar opacity-0 shadow-sm focus-within:opacity-100 group-hover:opacity-100 pointer-coarse:static pointer-coarse:translate-y-0 pointer-coarse:bg-transparent pointer-coarse:opacity-100 pointer-coarse:shadow-none"
|
||||
data-qqq-id="assistant-conversation-actions"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
data-conversation-action
|
||||
tabIndex={tabIndex}
|
||||
aria-label={`${archived ? 'Restore' : 'Archive'} ${title}`}
|
||||
title={archived ? 'Restore' : 'Archive'}
|
||||
onClick={() => onArchive(conversation)}
|
||||
className={ACTION_BUTTON}
|
||||
data-qqq-id="assistant-conversation-archive"
|
||||
>
|
||||
{archived ? <ArchiveRestore className="h-3.5 w-3.5" aria-hidden="true" /> : <Archive className="h-3.5 w-3.5" aria-hidden="true" />}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-conversation-action
|
||||
tabIndex={tabIndex}
|
||||
aria-label={`Delete ${title}`}
|
||||
title="Delete"
|
||||
onClick={() => onDelete(conversation)}
|
||||
className={cn(ACTION_BUTTON, 'hover:text-destructive')}
|
||||
data-qqq-id="assistant-conversation-delete"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -150,25 +234,37 @@ export function ConversationRail({ conversations, loading, activeId, status, onS
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span id={labelId} className="sr-only">{status === 'ACTIVE' ? 'Conversations' : 'Archived conversations'}</span>
|
||||
<div ref={listRef} role="listbox" aria-labelledby={labelId} onKeyDown={onKeyDown} className="min-h-0 flex-1 space-y-0.5 overflow-y-auto p-1.5" data-qqq-id="assistant-conversation-list">
|
||||
<div ref={listRef} onKeyDown={onKeyDown} className="min-h-0 flex-1 space-y-0.5 overflow-y-auto p-1.5" data-qqq-id="assistant-conversation-list">
|
||||
{loading && <p className="px-2 py-1 text-xs text-muted-foreground" role="status">Loading...</p>}
|
||||
{!loading && ordered.length === 0 && (
|
||||
<p className="px-2 py-1 text-xs text-muted-foreground">{status === 'ACTIVE' ? 'No conversations yet.' : 'No archived conversations.'}</p>
|
||||
)}
|
||||
{pinned.length > 0 && (
|
||||
<div role="group" aria-label="Pinned">
|
||||
<p className="px-2 pb-0.5 pt-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground" aria-hidden="true">Pinned</p>
|
||||
{pinned.map((conversation, index) => option(conversation, index))}
|
||||
</div>
|
||||
<section aria-labelledby={`${labelId}-pinned`}>
|
||||
<h3 id={`${labelId}-pinned`} className="px-2 pb-0.5 pt-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Pinned</h3>
|
||||
<ul className="space-y-0.5">{pinned.map(row)}</ul>
|
||||
</section>
|
||||
)}
|
||||
{recent.length > 0 && (
|
||||
<div role="group" aria-label={status === 'ACTIVE' ? 'Recent' : 'Archived'}>
|
||||
{pinned.length > 0 && <p className="px-2 pb-0.5 pt-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground" aria-hidden="true">Recent</p>}
|
||||
{recent.map((conversation, index) => option(conversation, pinned.length + index))}
|
||||
</div>
|
||||
<section aria-labelledby={`${labelId}-recent`}>
|
||||
<h3 id={`${labelId}-recent`} className={cn('px-2 pb-0.5 pt-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground', pinned.length === 0 && 'sr-only')}>
|
||||
{status === 'ACTIVE' ? 'Recent' : 'Archived'}
|
||||
</h3>
|
||||
<ul className="space-y-0.5">{recent.map(row)}</ul>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
{manageHref && (
|
||||
<Link
|
||||
href={manageHref}
|
||||
onClick={onManage}
|
||||
className="flex shrink-0 items-center gap-1.5 border-t border-border px-3 py-2 text-xs font-medium text-primary hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:min-h-11"
|
||||
data-qqq-id="assistant-manage-conversations"
|
||||
>
|
||||
Manage all conversations
|
||||
<ExternalLink className="h-3 w-3" aria-hidden="true" />
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||