Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afb9d75c75
|
||
|
|
119f1211d0
|
||
|
|
3d162dce74
|
||
|
|
d04cfa4b58
|
||
|
|
94424b3f46
|
||
|
|
e31716aa52 |
No files matched your search
@@ -6,3 +6,5 @@ playwright-report
|
||||
coverage
|
||||
.env*
|
||||
*.log
|
||||
|
||||
.pnpm-store
|
||||
@@ -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,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,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 ./
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
## Features
|
||||
|
||||
- **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`):
|
||||
|
||||
+2
-2
@@ -57,7 +57,7 @@
|
||||
"dompurify": "^3.4.16",
|
||||
"lodash": "^4.18.1",
|
||||
"lucide-react": "^0.485.0",
|
||||
"next": "16.3.8",
|
||||
"next": "16.4.1",
|
||||
"rapidoc": "10.1.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
@@ -93,7 +93,7 @@
|
||||
"@vitest/ui": "^4.1.11",
|
||||
"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",
|
||||
|
||||
Generated
+310
-292
File diff suppressed because it is too large.
Load diff
@@ -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'
|
||||
@@ -113,6 +113,10 @@ function renderPage() {
|
||||
}
|
||||
|
||||
describe('RecordDeveloperViewPage', () => {
|
||||
// Transform the real lazy module before DOM waits begin. Cold Vitest transforms
|
||||
// on Windows can otherwise consume the first test's entire five-second wait.
|
||||
beforeAll(async () => { await import('@/components/developer/RecordDeveloperView') })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getRecord).mockResolvedValue(record)
|
||||
vi.mocked(getRecordDeveloperData).mockResolvedValue({
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* 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 Access editor behavior: stable selections, grant sources and API failures. */
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type { QWidgetMetaData } from '@/types'
|
||||
import { fetchWidgetData } from '@/lib/api/widgets'
|
||||
import { fetchPossibleValues } from '@/lib/api/possible-values'
|
||||
import AuthentikAccessEditorWidget from './AuthentikAccessEditorWidget'
|
||||
|
||||
vi.mock('@/lib/api/widgets', () => ({ fetchWidgetData: vi.fn() }))
|
||||
vi.mock('@/lib/api/possible-values', () => ({ fetchPossibleValues: vi.fn() }))
|
||||
const widget = { name: 'access', type: 'AUTHENTIK_ACCESS_EDITOR' } as QWidgetMetaData
|
||||
|
||||
/**
|
||||
* Render with an isolated query cache.
|
||||
* @param fields - Editor fields.
|
||||
* @returns Process value callback.
|
||||
*/
|
||||
function setup(fields: Record<string, unknown>[]) {
|
||||
const changed = vi.fn()
|
||||
render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<AuthentikAccessEditorWidget widgetMetaData={widget} data={{ fields }} onWidgetData={changed} />
|
||||
</QueryClientProvider>)
|
||||
return changed
|
||||
}
|
||||
|
||||
describe('Access editor', () => {
|
||||
it('preserves unknown grants and displays inherited access without making it editable', async () => {
|
||||
const changed = setup([{ name: 'permissions', label: 'Direct permissions', selected: [{ id: 'legacy.read', label: 'legacy.read' }],
|
||||
choices: [{ id: 'posts.edit', label: 'Edit posts' }], inherited: { 'posts.read': ['Readers'] } }])
|
||||
expect(screen.getByLabelText('legacy.read')).toBeChecked()
|
||||
await userEvent.click(screen.getByLabelText('Edit posts'))
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'legacy.read\nposts.edit' })
|
||||
expect(screen.queryByRole('checkbox', { name: /posts.read/ })).not.toBeInTheDocument()
|
||||
expect(screen.getByText('posts.read — Readers')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('searches the server and preserves selected IDs when results change', async () => {
|
||||
vi.mocked(fetchPossibleValues).mockImplementation(async (_source, request) => request?.searchTerm === 'alex'
|
||||
? [{ id: 42, label: 'Alex' }] : [{ id: 3, label: 'Sam' }])
|
||||
const changed = setup([{ name: 'userIds', label: 'Users', source: 'identityUsers', selected: [] }])
|
||||
await userEvent.click(await screen.findByLabelText('Sam'))
|
||||
await userEvent.type(screen.getByLabelText('Search users'), 'alex')
|
||||
await userEvent.click(await screen.findByLabelText('Alex'))
|
||||
expect(screen.getByLabelText('Sam')).toBeChecked()
|
||||
expect(changed).toHaveBeenLastCalledWith({ userIds: '3\n42' })
|
||||
expect(fetchPossibleValues).toHaveBeenLastCalledWith('identityUsers', { searchTerm: 'alex', useCase: 'form' })
|
||||
})
|
||||
|
||||
it('keeps existing assignments when the directory search fails', async () => {
|
||||
vi.mocked(fetchPossibleValues).mockRejectedValue(new Error('Offline'))
|
||||
const changed = setup([{ name: 'parentIds', label: 'Roles', source: 'roles', selected: [{ id: 'role-1', label: 'Reader' }] }])
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Could not load choices'))
|
||||
expect(screen.getByLabelText('Reader')).toBeChecked()
|
||||
expect(changed).toHaveBeenCalledWith({ parentIds: 'role-1' })
|
||||
})
|
||||
|
||||
it('rejects malformed payloads without submitting an empty permission list', () => {
|
||||
const changed = setup([{ name: 'permissions', label: 'Permissions', selected: 'broken' }])
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('unavailable')
|
||||
expect(changed).toHaveBeenCalledWith({ __accessEditorReady: false })
|
||||
expect(changed).not.toHaveBeenCalledWith({ permissions: '' })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Paged permission matrix', () => {
|
||||
it('accepts the live QQQ payload that omits empty application names and IDs', async () => {
|
||||
vi.mocked(fetchWidgetData).mockResolvedValue({ type: 'AUTHENTIK_ACCESS_EDITOR', fields: [{
|
||||
total: 1, page: 0, pageSize: 25, apps: [{ label: 'Other' }],
|
||||
rows: [{ name: 'documents', label: 'Documents', kind: 'TABLE', permissions: [{ id: 'documents.read', label: 'read' }] }],
|
||||
}] })
|
||||
const changed = setup([{ name: 'permissions', label: 'Direct permissions', catalogWidget: 'grantEditor', selected: [] }])
|
||||
await userEvent.click(await screen.findByRole('checkbox', { name: 'documents.read' }))
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'documents.read' })
|
||||
await userEvent.selectOptions(screen.getByLabelText('Application'), '')
|
||||
await waitFor(() => expect(fetchWidgetData).toHaveBeenLastCalledWith('grantEditor', expect.objectContaining({ app: '' })))
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps unknown and off-page grants across bulk page edits and failed searches', async () => {
|
||||
vi.mocked(fetchWidgetData).mockImplementation(async (_widget, params) => {
|
||||
if (params?.search === 'offline') throw new Error('Offline')
|
||||
const page = Number(params?.page ?? 0)
|
||||
return { type: 'AUTHENTIK_ACCESS_EDITOR', fields: [{ total: 1000, page, pageSize: 25, apps: [{ id: 'sales', label: 'Sales' }],
|
||||
rows: Array.from({ length: 25 }, (_, i) => ({ name: 'table' + (page * 25 + i), label: 'Table ' + (page * 25 + i), kind: 'TABLE', app: 'sales', permissions: [{ id: 'table' + (page * 25 + i) + '.read', label: 'read' }] })) }] }
|
||||
})
|
||||
const changed = setup([{ name: 'permissions', label: 'Direct permissions', catalogWidget: 'grantEditor', selected: [{ id: 'legacy.read', label: 'legacy.read' }], inherited: { 'table999.read': ['Readers'] } }])
|
||||
await screen.findByLabelText('table0.read')
|
||||
expect(screen.getAllByRole('checkbox')).toHaveLength(25)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Select 25 permissions on this page' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Next' }))
|
||||
await screen.findByLabelText('table25.read')
|
||||
await userEvent.click(screen.getByLabelText('table25.read'))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Previous' }))
|
||||
await screen.findByLabelText('table0.read')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Clear 25 permissions on this page' }))
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'legacy.read\ntable25.read' })
|
||||
await userEvent.type(screen.getByLabelText('Search permissions or resources'), 'offline')
|
||||
await screen.findByRole('alert')
|
||||
expect(changed).toHaveBeenLastCalledWith({ permissions: 'legacy.read\ntable25.read' })
|
||||
await userEvent.clear(screen.getByLabelText('Search permissions or resources'))
|
||||
await userEvent.selectOptions(screen.getByLabelText('Show'), 'inherited')
|
||||
expect(screen.getByText('table999.read — Readers')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* 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 Structured named grants and searchable membership assignments. */
|
||||
'use client'
|
||||
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import type { WidgetComponentProps } from '@/components/widgets/widget-types'
|
||||
import { fetchPossibleValues } from '@/lib/api/possible-values'
|
||||
import { PermissionMatrix } from './PermissionMatrix'
|
||||
import { INPUT_CLASS, ALERT_CLASS } from '@/components/ui/controls'
|
||||
|
||||
const optionSchema = z.object({ id: z.string(), label: z.string() })
|
||||
const fieldSchema = z.object({
|
||||
catalogWidget: z.string().optional(), name: z.string().min(1), label: z.string(), source: z.string().optional(),
|
||||
selected: z.array(optionSchema).default([]), choices: z.array(optionSchema).optional(),
|
||||
inherited: z.record(z.array(z.string())).optional(), policyPermissions: z.array(z.string()).optional(),
|
||||
})
|
||||
const payloadSchema = z.object({ fields: z.array(fieldSchema) })
|
||||
type Field = z.infer<typeof fieldSchema>
|
||||
type Option = z.infer<typeof optionSchema>
|
||||
|
||||
/**
|
||||
* Edit one structured field while keeping selection independent of search results.
|
||||
* @param props - Server metadata and the process value callback.
|
||||
* @returns A checkbox list and, for assignments, a server-backed search box.
|
||||
*/
|
||||
function AccessField({ field, onChange }: { field: Field; onChange: (values: Record<string, unknown>) => void }) {
|
||||
const [selected, setSelected] = useState<Option[]>(field.selected)
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [debounced, setDebounced] = useState('')
|
||||
const id = useId()
|
||||
useEffect(() => { const timer = setTimeout(() => setDebounced(search), 250); return () => clearTimeout(timer) }, [search])
|
||||
const options = useQuery({
|
||||
queryKey: ['access-editor-options', field.source, debounced],
|
||||
queryFn: () => fetchPossibleValues(field.source!, { searchTerm: debounced, useCase: 'form' }),
|
||||
enabled: Boolean(field.source),
|
||||
})
|
||||
useEffect(() => { onChange({ [field.name]: selected.map(option => option.id).join('\n') }) }, [selected, field.name, onChange])
|
||||
const choices: Option[] = field.source
|
||||
? (options.data ?? []).map(option => ({ id: String(option.id), label: option.label }))
|
||||
: (field.choices ?? []).filter(option => option.label.toLowerCase().includes(search.toLowerCase()))
|
||||
const selectedIds = new Set(selected.map(option => option.id))
|
||||
const displayed = [...selected, ...choices.filter(option => !selectedIds.has(option.id))].filter(option => Boolean(field.source) || option.label.toLowerCase().includes(search.toLowerCase()))
|
||||
const currentPage = Math.min(page, Math.max(0, Math.ceil(displayed.length / 25) - 1))
|
||||
return <fieldset className="space-y-3 rounded-lg border border-border p-4">
|
||||
<legend className="px-2 font-semibold">{field.label}</legend>
|
||||
<label htmlFor={id} className="block text-sm">Search {field.label.toLowerCase()}</label>
|
||||
<input id={id} data-qqq-id={'access-search-' + field.name} className={INPUT_CLASS} value={search} onChange={event => { setSearch(event.target.value); setPage(0) }} />
|
||||
{options.isFetching && field.source && <p role="status" className="text-sm">Searching…</p>}
|
||||
{options.isError && <p role="alert" className={ALERT_CLASS}>Could not load choices. Your selections are preserved. Change the search to try again.</p>}
|
||||
<p className="text-sm text-muted-foreground">{selected.length} selected. Review validates every change before saving.</p>
|
||||
<div className="max-h-80 space-y-2 overflow-auto">
|
||||
{displayed.slice(currentPage * 25, currentPage * 25 + 25).map(option => <label key={option.id} className="flex items-start gap-2 text-sm">
|
||||
<input type="checkbox" data-qqq-id={'access-choice-' + field.name + '-' + option.id} checked={selectedIds.has(option.id)}
|
||||
onChange={event => setSelected(current => event.target.checked ? [...current, option] : current.filter(item => item.id !== option.id))} />
|
||||
<span>{option.label}</span>
|
||||
</label>)}
|
||||
{!options.isFetching && displayed.length === 0 && <p className="text-sm text-muted-foreground">No choices found.</p>}
|
||||
</div>
|
||||
{displayed.length > 25 && <div className="flex gap-4">
|
||||
<button type="button" disabled={currentPage === 0} onClick={() => setPage(currentPage - 1)}>Previous choices</button>
|
||||
<span>Page {currentPage + 1} of {Math.ceil(displayed.length / 25)}</span>
|
||||
<button type="button" disabled={(currentPage + 1) * 25 >= displayed.length} onClick={() => setPage(currentPage + 1)}>Next choices</button>
|
||||
</div>}
|
||||
{field.inherited && Object.keys(field.inherited).length > 0 && <details>
|
||||
<summary className="cursor-pointer text-sm font-medium">Inherited access — edit the source to remove it</summary>
|
||||
<ul className="mt-2 space-y-1 text-sm">{Object.entries(field.inherited).map(([permission, sources]) => <li key={permission}>{permission} — {sources.join(', ')}</li>)}</ul>
|
||||
</details>}
|
||||
{Boolean(field.policyPermissions?.length) && <details>
|
||||
<summary className="cursor-pointer text-sm font-medium">Access from this item’s policy — use Edit Policy to change it</summary>
|
||||
<ul className="mt-2 text-sm">{field.policyPermissions?.map(permission => <li key={permission}>{permission}</li>)}</ul>
|
||||
</details>}
|
||||
</fieldset>
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate server-provided metadata before rendering editable process values.
|
||||
* @param props - Standard widget payload and process callback.
|
||||
* @returns The access editor or a contained error.
|
||||
*/
|
||||
export default function AuthentikAccessEditorWidget({ data, onWidgetData }: WidgetComponentProps<Record<string, unknown>>) {
|
||||
const payload = payloadSchema.safeParse(data)
|
||||
const ready = payload.success
|
||||
useEffect(() => { onWidgetData?.({ __accessEditorReady: ready }) }, [ready, onWidgetData])
|
||||
if (!payload.success || !onWidgetData) return <p role="alert" className={ALERT_CLASS}>The access editor is unavailable. Reopen the action before continuing.</p>
|
||||
return <div className="space-y-4">{payload.data.fields.map(field => field.catalogWidget ? <PermissionMatrix key={field.name} field={field} onChange={onWidgetData} /> : <AccessField key={field.name} field={field} onChange={onWidgetData} />)}</div>
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
// Tests for the AUTHENTIK_POLICY_EDITOR widget: matrix, select-all, search, unknowns, JSON output
|
||||
|
||||
import React from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { fetchWidgetData } from '@/lib/api/widgets'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { axe } from 'jest-axe'
|
||||
@@ -27,6 +29,8 @@ import { WidgetRenderer } from '@/components/widgets/WidgetRenderer'
|
||||
import { AuthentikPolicyEditorWidget, isPolicyPermission } from './AuthentikPolicyEditorWidget'
|
||||
import type { PolicyEditorPayload } from './AuthentikPolicyEditorWidget'
|
||||
|
||||
vi.mock('@/lib/api/widgets', () => ({ fetchWidgetData: vi.fn() }))
|
||||
|
||||
const widget = { name: 'authentikPolicyEditor', type: 'AUTHENTIK_POLICY_EDITOR', label: 'Policy' } as unknown as QWidgetMetaData
|
||||
|
||||
const payload = (overrides: Partial<PolicyEditorPayload> = {}): PolicyEditorPayload => ({
|
||||
@@ -74,7 +78,7 @@ const documentFor = (actions: string[], resources = ['person']) => JSON.stringif
|
||||
*/
|
||||
function setup(data: PolicyEditorPayload) {
|
||||
const onWidgetData = vi.fn()
|
||||
const view = render(<AuthentikPolicyEditorWidget widgetMetaData={widget} data={data as unknown as Record<string, unknown>} onWidgetData={onWidgetData} />)
|
||||
const view = render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}><AuthentikPolicyEditorWidget widgetMetaData={widget} data={data as unknown as Record<string, unknown>} onWidgetData={onWidgetData} /></QueryClientProvider>)
|
||||
const last = () => String(onWidgetData.mock.calls.at(-1)?.[0]?.policyDocument ?? '')
|
||||
return { onWidgetData, last, ...view }
|
||||
}
|
||||
@@ -375,3 +379,41 @@ describe('AuthentikPolicyEditorWidget', () => {
|
||||
expect(isPolicyPermission('a.b.read')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Large policy catalogs', () => {
|
||||
it('bounds rendering and preserves off-page grants when selecting one page', async () => {
|
||||
const { last } = setup(payload({ catalog: [{ app: 'large', label: 'Large', resources: Array.from({ length: 1000 }, (_, i) => ({ name: 'resource' + i, label: 'Resource ' + i, kind: 'TABLE', actions: ['read'] })) }] }))
|
||||
expect(screen.getByLabelText('Read: Resource 0')).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Read: Resource 25')).not.toBeInTheDocument()
|
||||
await userEvent.click(screen.getByLabelText('Everything in Large (this page)'))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Next resources' }))
|
||||
expect(screen.queryByLabelText('Read: Resource 0')).not.toBeInTheDocument()
|
||||
await userEvent.click(screen.getByLabelText('Read: Resource 25'))
|
||||
const doc = JSON.parse(last())
|
||||
const resources = doc.Statement.flatMap((statement: { Resource: string[] }) => statement.Resource)
|
||||
expect(resources).toHaveLength(26)
|
||||
expect(resources).toContain('resource0')
|
||||
expect(resources).toContain('resource25')
|
||||
await userEvent.type(screen.getByLabelText('Find a resource'), 'Resource 999')
|
||||
expect(screen.getByLabelText('Read: Resource 999')).toBeInTheDocument()
|
||||
expect(JSON.parse(last())).toEqual(doc)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('Server-paged policies', () => {
|
||||
it('keeps controlled selection synchronized with unknown removal and clear all', async () => {
|
||||
vi.mocked(fetchWidgetData).mockResolvedValue({ type: 'AUTHENTIK_ACCESS_EDITOR', fields: [{ total: 1, page: 0, pageSize: 25, apps: [], rows: [{ name: 'cms_page', label: 'Pages', kind: 'TABLE', app: '', permissions: [{ id: 'cms_page.read', label: 'read' }, { id: 'cms_page.edit', label: 'edit' }] }] }] })
|
||||
const { last } = setup(payload({ catalog: [], catalogWidget: 'pagedPolicy', unknownPermissions: ['legacy.read'], document: documentFor(['read'], ['legacy']) }))
|
||||
await userEvent.click(await screen.findByLabelText('cms_page.read'))
|
||||
expect(last()).toContain('legacy')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Remove legacy.read' }))
|
||||
await userEvent.click(screen.getByLabelText('cms_page.edit'))
|
||||
expect(last()).not.toContain('legacy')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Clear all' }))
|
||||
expect(screen.getByLabelText('cms_page.read')).not.toBeChecked()
|
||||
expect(screen.getByLabelText('cms_page.edit')).not.toBeChecked()
|
||||
expect(JSON.parse(last()).Statement).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -29,6 +29,7 @@ import React, { lazy, Suspense, useEffect, useId, useMemo, useRef, useState } fr
|
||||
import type { WidgetComponentProps } from '@/components/widgets/widget-types'
|
||||
import { asList, isPlainObject } from '@/components/widgets/widget-types'
|
||||
import { ALERT_CLASS, INPUT_CLASS, WARNING_CLASS, buttonClass } from '@/components/ui/controls'
|
||||
import { PermissionMatrix } from './PermissionMatrix'
|
||||
import { cn } from '@/lib/utils/cn'
|
||||
import type { PolicyAction, PolicyFormat } from './policy-document'
|
||||
import { ACTION_LABELS, FULL_ACCESS_PERMISSION, POLICY_ACTIONS, generatePolicy, parsePolicy, permissionName, roundTrips, splitPermission } from './policy-document'
|
||||
@@ -65,6 +66,10 @@ export interface PolicyEditorPayload {
|
||||
/** The group the policy belongs to (display only). */
|
||||
groupLabel?: string
|
||||
catalog: PolicyCatalogGroup[]
|
||||
/** Server-paged catalog source; older hosts send the full catalog. */
|
||||
catalogWidget?: string
|
||||
/** Unknown grants identified against the complete server catalog. */
|
||||
unknownPermissions?: string[]
|
||||
/** The group's current document (JSON text), or empty for none. */
|
||||
document?: string
|
||||
/** Whether the current document grants full access; older servers omit this. */
|
||||
@@ -172,11 +177,12 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
const [selected, setSelected] = useState<Set<string>>(() => new Set(initial.permissions))
|
||||
const fullAccess = selected.has(FULL_ACCESS_PERMISSION)
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [memberUsername, setMemberUsername] = useState('')
|
||||
const member = payload.members?.find((candidate) => candidate.username === memberUsername)
|
||||
|
||||
const generated = useMemo(() => generatePolicy(selected, format), [format, selected])
|
||||
const unknown = useMemo(() => fullAccess ? [] : [...selected].filter((permission) => !known.has(permission)).sort(), [fullAccess, known, selected])
|
||||
const unknown = useMemo(() => fullAccess ? [] : [...selected].filter((permission) => payload.catalogWidget ? payload.unknownPermissions?.includes(permission) : !known.has(permission)).sort(), [fullAccess, known, selected, payload.catalogWidget, payload.unknownPermissions])
|
||||
const valid = useMemo(() => roundTrips(selected, format), [format, selected])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -194,6 +200,16 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
}))
|
||||
.filter((group) => group.resources.length > 0), [catalog, term])
|
||||
|
||||
const matchingCount = visibleGroups.reduce((sum, group) => sum + group.resources.length, 0)
|
||||
const currentPage = Math.min(page, Math.max(0, Math.ceil(matchingCount / 25) - 1))
|
||||
const pageResources = visibleGroups.flatMap((group) => group.resources.map((resource) => ({ group, resource })))
|
||||
.slice(currentPage * 25, (currentPage + 1) * 25)
|
||||
const pageGroups = visibleGroups.map((group) => ({
|
||||
...group,
|
||||
resources: pageResources.filter((entry) => entry.group === group).map((entry) => entry.resource),
|
||||
label: matchingCount > 25 ? group.label + ' (this page)' : group.label,
|
||||
})).filter((group) => group.resources.length > 0)
|
||||
|
||||
const set = (permissions: string[], on: boolean) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current)
|
||||
@@ -235,7 +251,7 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
|
||||
<fieldset disabled={fullAccess} aria-disabled={fullAccess} hidden={fullAccess} className="min-w-0">
|
||||
<div className="flex flex-col gap-2 @xl:flex-row @xl:items-end @xl:justify-between">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<div hidden={Boolean(payload.catalogWidget)} className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<label htmlFor={searchId} className="text-sm font-medium text-foreground">Find a resource</label>
|
||||
<input
|
||||
id={searchId}
|
||||
@@ -244,7 +260,7 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
placeholder="App, table, process or report"
|
||||
value={search}
|
||||
aria-disabled={fullAccess}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
onChange={(event) => { setSearch(event.target.value); setPage(0) }}
|
||||
data-qqq-id="policy-editor-search"
|
||||
/>
|
||||
</div>
|
||||
@@ -262,11 +278,18 @@ export function AuthentikPolicyEditorWidget({ widgetMetaData, data, onWidgetData
|
||||
{fullAccess && <p className="rounded-md border border-border bg-muted p-3 text-sm text-muted-foreground">Individual resource selection is disabled while full access is on.</p>}
|
||||
<div hidden={fullAccess}>
|
||||
<div className="flex min-w-0 flex-col gap-3">
|
||||
{payload.catalogWidget ? <PermissionMatrix field={{ name: 'policyPermissions', label: 'Policy permissions', catalogWidget: payload.catalogWidget, selected: [] }} selection={selected} onSelectionChange={setSelected} /> : <>
|
||||
{resourceCount === 0 && <p className="text-sm text-muted-foreground">This app has no resources that a policy can grant.</p>}
|
||||
{resourceCount > 0 && visibleGroups.length === 0 && <p className="text-sm text-muted-foreground" role="status">No resource matches the search.</p>}
|
||||
{visibleGroups.map((group) => (
|
||||
{matchingCount > 25 && <div className="flex items-center gap-3 text-sm">
|
||||
<button type="button" className={buttonClass('secondary', 'sm')} disabled={currentPage === 0} onClick={() => setPage(currentPage - 1)}>Previous resources</button>
|
||||
<span role="status">{matchingCount} resources · Page {currentPage + 1} of {Math.ceil(matchingCount / 25)}. Bulk controls affect only this page.</span>
|
||||
<button type="button" className={buttonClass('secondary', 'sm')} disabled={(currentPage + 1) * 25 >= matchingCount} onClick={() => setPage(currentPage + 1)}>Next resources</button>
|
||||
</div>}
|
||||
{pageGroups.map((group) => (
|
||||
<PolicyGroupSection key={group.app ?? '(other)'} group={group} selected={selected} onSet={set} />
|
||||
))}
|
||||
</>}
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* 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 Bounded permission catalog and grant source views. */
|
||||
'use client'
|
||||
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { fetchWidgetData } from '@/lib/api/widgets'
|
||||
import { INPUT_CLASS, ALERT_CLASS } from '@/components/ui/controls'
|
||||
|
||||
const optionSchema = z.object({ id: z.string(), label: z.string() })
|
||||
// QQQ omits empty strings on the wire. Only application membership uses the
|
||||
// empty string as a valid identity (the Other/unassigned application bucket).
|
||||
const appOptionSchema = optionSchema.extend({ id: z.string().default('') })
|
||||
const pageSchema = z.object({ fields: z.array(z.object({
|
||||
rows: z.array(z.object({ name: z.string(), label: z.string(), kind: z.string(), app: z.string().default(''), permissions: z.array(optionSchema) })),
|
||||
total: z.number().int().nonnegative(), page: z.number().int().nonnegative(), pageSize: z.number().int().positive(), apps: z.array(appOptionSchema),
|
||||
})).min(1) })
|
||||
type Option = z.infer<typeof optionSchema>
|
||||
interface Field {
|
||||
name: string; label: string; catalogWidget?: string; selected: Option[]
|
||||
inherited?: Record<string, string[]>; policyPermissions?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Paged resource matrix. Selection is independent of catalog pages and requests.
|
||||
* @param props - Initial grants, catalog source, and process output callback.
|
||||
* @returns A searchable matrix with page-scoped bulk actions.
|
||||
*/
|
||||
export function PermissionMatrix({ field, onChange, selection, onSelectionChange }: {
|
||||
field: Field; onChange?: (values: Record<string, unknown>) => void
|
||||
selection?: Set<string>; onSelectionChange?: (selection: Set<string>) => void
|
||||
}) {
|
||||
const [localSelected, setSelected] = useState(() => new Map(field.selected.map(option => [option.id, option])))
|
||||
const selected = useMemo(() => selection ? new Map([...selection].map(id => [id, { id, label: id }])) : localSelected, [selection, localSelected])
|
||||
const [search, setSearch] = useState('')
|
||||
const [debounced, setDebounced] = useState('')
|
||||
const [app, setApp] = useState('*')
|
||||
const [kind, setKind] = useState('*')
|
||||
const [page, setPage] = useState(0)
|
||||
const [view, setView] = useState('catalog')
|
||||
const id = useId()
|
||||
useEffect(() => { const timer = setTimeout(() => { setDebounced(search); setPage(0) }, 250); return () => clearTimeout(timer) }, [search])
|
||||
useEffect(() => { if (!selection) onChange?.({ [field.name]: [...selected.keys()].join('\n') }) }, [selected, field.name, onChange, selection])
|
||||
const catalog = useQuery({
|
||||
queryKey: ['access-catalog', field.catalogWidget, debounced, app, kind, page],
|
||||
queryFn: async () => pageSchema.parse(await fetchWidgetData(field.catalogWidget!, { accessCatalog: true, search: debounced, app, kind, page })).fields[0],
|
||||
enabled: view === 'catalog',
|
||||
})
|
||||
const data = catalog.data
|
||||
const busy = catalog.isFetching || search !== debounced
|
||||
const visible = data?.rows.flatMap(row => row.permissions) ?? []
|
||||
const actions = [...new Set(visible.map(option => option.label))]
|
||||
const change = (options: Option[], checked: boolean) => {
|
||||
const next = new Map(selected)
|
||||
options.forEach(option => { if (checked) next.set(option.id, option); else next.delete(option.id) })
|
||||
if (selection) onSelectionChange?.(new Set(next.keys()))
|
||||
else setSelected(next)
|
||||
}
|
||||
const localEntries = (view === 'selected' ? [...selected.values()].map(option => [option.id, 'Direct grant'] as const)
|
||||
: [...Object.entries(field.inherited ?? {}).map(([permission, sources]) => [permission, sources.join(', ')] as const),
|
||||
...(field.policyPermissions ?? []).map(permission => [permission, 'This item’s policy'] as const)])
|
||||
.filter(([permission, source]) => (permission + ' ' + source).toLowerCase().includes(search.toLowerCase()))
|
||||
const localPage = Math.min(page, Math.max(0, Math.ceil(localEntries.length / 25) - 1))
|
||||
const currentPage = view === 'catalog' ? (data?.page ?? 0) : localPage
|
||||
const total = view === 'catalog' ? (data?.total ?? 0) : localEntries.length
|
||||
return <fieldset className="space-y-3 rounded-lg border border-border p-4" data-qqq-id="access-permission-matrix">
|
||||
<legend className="px-2 font-semibold">{field.label}</legend>
|
||||
<p className="text-sm">{selected.size} direct permissions selected. Changes affect named permissions on existing resources. Future resources are not included.</p>
|
||||
<label htmlFor={id + '-view'}>Show</label>
|
||||
<select id={id + '-view'} className={INPUT_CLASS} value={view} onChange={event => { setView(event.target.value); setPage(0) }}>
|
||||
<option value="catalog">Permission catalog</option><option value="selected">Selected direct grants</option><option value="inherited">Why access is granted</option>
|
||||
</select>
|
||||
<label htmlFor={id + '-search'}>Search permissions or resources</label>
|
||||
<input id={id + '-search'} className={INPUT_CLASS} value={search} onChange={event => setSearch(event.target.value)} />
|
||||
{view === 'catalog' && <>
|
||||
<label htmlFor={id + '-app'}>Application</label>
|
||||
<select id={id + '-app'} className={INPUT_CLASS} value={app} onChange={event => { setApp(event.target.value); setPage(0) }}>
|
||||
<option value="*">All applications</option>{data?.apps.map(option => <option key={option.id} value={option.id}>{option.label}</option>)}
|
||||
</select>
|
||||
<label htmlFor={id + '-kind'}>Resource type</label>
|
||||
<select id={id + '-kind'} className={INPUT_CLASS} value={kind} onChange={event => { setKind(event.target.value); setPage(0) }}>
|
||||
<option value="*">All resource types</option>{['APP', 'TABLE', 'PROCESS', 'REPORT', 'WIDGET', 'OTHER'].map(value => <option key={value}>{value}</option>)}
|
||||
</select>
|
||||
{busy && <p role="status">Loading permission page…</p>}
|
||||
{catalog.isError && <p role="alert" className={ALERT_CLASS}>Could not load permissions. Your selections are preserved. <button type="button" onClick={() => void catalog.refetch()}>Retry</button></p>}
|
||||
<div className="flex gap-4">
|
||||
<button type="button" disabled={busy || !visible.length || catalog.isError} onClick={() => change(visible, true)}>Select {visible.length} permissions on this page</button>
|
||||
<button type="button" disabled={busy || !visible.length || catalog.isError} onClick={() => change(visible, false)}>Clear {visible.length} permissions on this page</button>
|
||||
</div>
|
||||
<div className="overflow-auto"><table className="w-full text-sm"><caption className="sr-only">Direct permissions by resource and action</caption>
|
||||
<thead><tr><th scope="col" className="text-left">Resource</th>{actions.map(action => <th scope="col" key={action}>{action === 'insert' ? 'Create' : action === 'hasAccess' ? 'Access' : action}</th>)}</tr></thead>
|
||||
<tbody>{data?.rows.map(row => <tr key={row.name}><th scope="row" className="text-left"><span>{row.label}</span><small className="block font-normal">{row.name} · {row.kind}</small></th>
|
||||
{actions.map(action => { const option = row.permissions.find(item => item.label === action); return <td key={action} className="p-2 text-center">{option ? <input type="checkbox" aria-label={option.id} data-qqq-id={'access-choice-permissions-' + option.id} checked={selected.has(option.id)} disabled={busy} onChange={event => change([option], event.target.checked)} /> : '—'}</td> })}
|
||||
</tr>)}</tbody>
|
||||
</table></div>
|
||||
</>}
|
||||
{view !== 'catalog' && <ul className="space-y-2">{localEntries.slice(localPage * 25, localPage * 25 + 25).map(([permission, source]) => <li key={permission + source}>
|
||||
{view === 'selected' ? <label><input type="checkbox" checked aria-label={permission} onChange={() => change([{ id: permission, label: permission }], false)} /> {permission}</label> : <span>{permission} — {source}</span>}
|
||||
</li>)}</ul>}
|
||||
<p role="status">{total} {view === 'catalog' ? 'resources' : 'permissions'} · Page {currentPage + 1} of {Math.max(1, Math.ceil(total / 25))}</p>
|
||||
<div className="flex gap-4"><button type="button" disabled={currentPage === 0 || (view === 'catalog' && busy)} onClick={() => setPage(currentPage - 1)}>Previous</button>
|
||||
<button type="button" disabled={(currentPage + 1) * 25 >= total || (view === 'catalog' && busy)} onClick={() => setPage(currentPage + 1)}>Next</button></div>
|
||||
{view === 'inherited' && <p className="text-sm">Inherited grants must be changed at their source. Policy grants use Edit Policy.</p>}
|
||||
</fieldset>
|
||||
}
|
||||
@@ -25,7 +25,10 @@
|
||||
import React from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Bug, ChevronDown, LogOut, Moon, Settings } from 'lucide-react'
|
||||
import { Bug, ChevronDown, LogOut, Moon, Settings, Wrench } from 'lucide-react'
|
||||
|
||||
import { useMetaData } from '@/lib/hooks/use-metadata'
|
||||
import { toolsTarget } from '@/components/tools/tools-catalog'
|
||||
|
||||
import { getPreferences } from '@/lib/api/preferences'
|
||||
import { useMediaQuery } from '@/lib/hooks/use-media-query'
|
||||
@@ -107,6 +110,8 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
|
||||
compactItems?: (close: (then?: () => void) => void) => React.ReactNode
|
||||
}) {
|
||||
const { theme, isDarkMode, setDarkMode } = useTheme()
|
||||
const metadata = useMetaData()
|
||||
const tools = toolsTarget(metadata.data)
|
||||
const capability = useQaCaptureCapability()
|
||||
const preferences = useQuery({ queryKey: queryKeys.preferencesIndex(), queryFn: getPreferences, retry: false })
|
||||
const qaSection = capability?.enabled && capability.reason === 'QA_MODE' ? capability.qaMode.preferenceSection : undefined
|
||||
@@ -127,6 +132,9 @@ function AccountMenuItems({ displayName, userEmail, logout, close, compactItems
|
||||
<HeaderMenuSeparator />
|
||||
</div>
|
||||
)}
|
||||
{tools && <Link href={tools.path} role="menuitem" onClick={() => close()} className={HEADER_MENU_ITEM_CLASS} data-qqq-id="menu-item-tools">
|
||||
<Wrench className="h-4 w-4 text-muted-foreground" aria-hidden="true" />{tools.label}
|
||||
</Link>}
|
||||
<Link href="/app/preferences" role="menuitem" onClick={() => close()} className={HEADER_MENU_ITEM_CLASS} data-qqq-id="menu-item-preferences">
|
||||
<Settings className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
|
||||
Preferences
|
||||
|
||||
@@ -87,7 +87,7 @@ function NamedWidget({ widget, seeded, index }: { widget: QWidgetMetaData; seede
|
||||
produced.current = type === 'childRecordList' ? { frontendRecords: frontendRecordsJson(data) } : { ...(produced.current ?? {}), ...data }
|
||||
}, [type])
|
||||
|
||||
useSubmitContributor(`widget-${index}-${widget.name}`, () => ({ maySubmit: true, values: produced.current ?? undefined }))
|
||||
useSubmitContributor(`widget-${index}-${widget.name}`, () => ({ maySubmit: type !== 'AUTHENTIK_ACCESS_EDITOR' || produced.current?.__accessEditorReady === true, values: produced.current ?? undefined }))
|
||||
|
||||
return (
|
||||
<div data-qqq-id={`process-widget-${widget.name}`}>
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* 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 { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { axe } from 'jest-axe'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { QInstance } from '@/types'
|
||||
import ToolsWidget from './ToolsWidget'
|
||||
import { connectionUrl, toolsTarget } from './tools-catalog'
|
||||
import backendCatalog from '../../../tests/e2e/fixtures/tools-catalog.json'
|
||||
|
||||
const metadata = {
|
||||
apps: {},
|
||||
appTree: [],
|
||||
widgets: {},
|
||||
tables: {},
|
||||
processes: {},
|
||||
reports: {},
|
||||
branding: {},
|
||||
} as QInstance
|
||||
vi.mock('@/lib/hooks/use-metadata', () => ({ useMetaData: () => ({ data: metadata }) }))
|
||||
const terminal = {
|
||||
id: 'terminal',
|
||||
label: 'CLI & Terminal UI',
|
||||
summary: 'Use QQQ from a terminal.',
|
||||
platforms: 'Windows, macOS and Linux',
|
||||
available: true,
|
||||
downloadUrl: 'https://example.test/releases',
|
||||
downloadLabel: 'Get CLI & TUI',
|
||||
guideUrl: 'https://example.test/guide',
|
||||
note: 'Standalone includes both.',
|
||||
steps: ['Install the client.', 'Sign in.'],
|
||||
commands: ['qqq login --server {server}', 'qqq ui'],
|
||||
manageApp: 'printing',
|
||||
}
|
||||
const payload = {
|
||||
serverUrl: 'https://example.test/customer',
|
||||
tools: [terminal, { ...terminal, id: 'scanner', label: 'Mobile Scanners', available: false }],
|
||||
}
|
||||
|
||||
describe('Tools', () => {
|
||||
it('renders the actual Java payload with omitted empty command lists', () => {
|
||||
render(<ToolsWidget data={backendCatalog} />)
|
||||
expect(screen.getByRole('button', { name: 'Set up Print Client' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Set up Mobile Scanners' })).toBeInTheDocument()
|
||||
})
|
||||
it('renders available downloads, collapses unavailable tools and copies an instance-specific sign-in command', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
|
||||
const { container } = render(<ToolsWidget data={payload} />)
|
||||
expect(screen.getByRole('link', { name: /Get CLI/ })).toHaveAttribute(
|
||||
'href',
|
||||
'https://example.test/releases'
|
||||
)
|
||||
expect(container.querySelector('[data-qqq-id="tools-unavailable"]')).not.toHaveAttribute('open')
|
||||
expect(container.querySelector('[data-qqq-id="tools-card-scanner"] a')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Set up CLI & Terminal UI' }))
|
||||
fireEvent.click(screen.getByLabelText('Copy CLI & Terminal UI command 1'))
|
||||
await waitFor(() =>
|
||||
expect(writeText).toHaveBeenCalledWith('qqq login --server "https://example.test/customer"')
|
||||
)
|
||||
expect(screen.queryByText(/Open Printing/)).not.toBeInTheDocument()
|
||||
expect(await axe(container)).toHaveNoViolations()
|
||||
})
|
||||
|
||||
it('switches the setup workspace without hiding other tools', () => {
|
||||
render(<ToolsWidget data={backendCatalog} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Set up Print Client' }))
|
||||
expect(screen.getByRole('heading', { name: 'Print Client' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: /Get Print Client/ })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Set up CLI & Terminal UI' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'false'
|
||||
)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Set up Mobile Scanners' }))
|
||||
expect(screen.getByRole('heading', { name: 'Mobile Scanners' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: /Get Print Client/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('switches platform installers and copies the selected command', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
|
||||
render(<ToolsWidget data={backendCatalog} />)
|
||||
fireEvent.change(screen.getByLabelText('Install platform'), { target: { value: 'windows' } })
|
||||
expect(screen.getByText('scoop install qqq')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByLabelText('Copy Scoop install command 2'))
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalledWith('scoop install qqq'))
|
||||
fireEvent.change(screen.getByLabelText('Install platform'), { target: { value: 'macos' } })
|
||||
expect(screen.getByText('brew install qrun-io/tap/qqq')).toBeInTheDocument()
|
||||
fireEvent.change(screen.getByLabelText('Install method'), {
|
||||
target: { value: 'curl installer' },
|
||||
})
|
||||
expect(screen.getByText(/curl -fsSL/)).toBeInTheDocument()
|
||||
fireEvent.change(screen.getByLabelText('Install platform'), { target: { value: 'linux' } })
|
||||
expect(screen.getByLabelText('Install method')).toHaveValue('curl installer')
|
||||
})
|
||||
|
||||
it('copies complete printer and mobile installer scripts with preserved newlines', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
|
||||
render(<ToolsWidget data={backendCatalog} />)
|
||||
for (const [label, id] of [
|
||||
['Print Client', 'printing'],
|
||||
['Mobile Scanners', 'scanner'],
|
||||
]) {
|
||||
fireEvent.click(screen.getByRole('button', { name: `Set up ${label}` }))
|
||||
fireEvent.change(screen.getByLabelText('Install platform'), { target: { value: 'windows' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Copy install script' }))
|
||||
const script = backendCatalog.tools.find((tool) => tool.id === id)!.installOptions[0]
|
||||
.commands![0]
|
||||
await waitFor(() => expect(writeText).toHaveBeenLastCalledWith(script))
|
||||
expect(script).toContain('\n')
|
||||
}
|
||||
fireEvent.change(screen.getByLabelText('Install platform'), { target: { value: 'android' } })
|
||||
expect(screen.queryByRole('button', { name: 'Copy install script' })).not.toBeInTheDocument()
|
||||
expect(screen.getByText(/In the handheld's Files app/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a recovery path when clipboard access fails', async () => {
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },
|
||||
})
|
||||
render(<ToolsWidget data={payload} />)
|
||||
fireEvent.click(screen.getByLabelText('Copy server address'))
|
||||
expect(
|
||||
await screen.findByText('Could not copy. Select and copy the text above.')
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('rejects malformed payloads and unsafe download links', () => {
|
||||
const view = render(<ToolsWidget data={{}} />)
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('could not be loaded')
|
||||
view.rerender(
|
||||
<ToolsWidget
|
||||
data={{ ...payload, tools: [{ ...terminal, downloadUrl: 'javascript:alert(1)' }] }}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByRole('link', { name: /Get CLI/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('resolves public roots without losing proxy paths or accepting credentials and shell syntax', () => {
|
||||
expect(connectionUrl(null, '/tenant/qqq/v1', 'https://example.test')).toBe(
|
||||
'https://example.test/tenant'
|
||||
)
|
||||
expect(connectionUrl(null, 'https://api.test/qqq/v1/', 'https://example.test')).toBe(
|
||||
'https://api.test'
|
||||
)
|
||||
expect(connectionUrl(null, '/unknown', 'https://example.test')).toBeUndefined()
|
||||
expect(connectionUrl(null, '/qqq/v1', 'http://localhost:8077')).toBe('http://localhost:8077')
|
||||
for (const value of [
|
||||
'https://user:pass@example.test',
|
||||
'https://example.test?token=secret',
|
||||
'http://example.test',
|
||||
'https://example.test/$HOME',
|
||||
]) {
|
||||
expect(connectionUrl(value, '/qqq/v1', 'https://example.test')).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('finds the menu shortcut by visible widget metadata, including renamed apps', () => {
|
||||
const instance = {
|
||||
...metadata,
|
||||
apps: { downloads: { name: 'downloads', label: 'Company Tools', widgets: ['catalog'] } },
|
||||
widgets: {
|
||||
catalog: { name: 'catalog', label: 'Tools', type: 'QQQ_TOOLS', hasPermission: true },
|
||||
},
|
||||
appTree: [{ name: 'downloads', label: 'Company Tools', type: 'APP' as const }],
|
||||
}
|
||||
expect(toolsTarget(instance)?.path).toBe('/app/downloads')
|
||||
expect(toolsTarget({ ...instance, appTree: [] })).toBeUndefined()
|
||||
instance.widgets.catalog.hasPermission = false
|
||||
expect(toolsTarget(instance)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,458 @@
|
||||
/*
|
||||
* 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 Companion tools with a compact chooser and focused setup workspace. */
|
||||
'use client'
|
||||
|
||||
import React, { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import {
|
||||
ArrowDownToLine,
|
||||
ArrowUpRight,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
Copy,
|
||||
Info,
|
||||
Monitor,
|
||||
Printer,
|
||||
Smartphone,
|
||||
Terminal,
|
||||
Wrench,
|
||||
} from 'lucide-react'
|
||||
import apiClient from '@/lib/api/client'
|
||||
import { useMetaData } from '@/lib/hooks/use-metadata'
|
||||
import { useAppTreeRoutes } from '@/lib/hooks/use-routes'
|
||||
import { connectionUrl, downloadLink, toolsCatalogSchema, type Tool } from './tools-catalog'
|
||||
|
||||
const actionClass =
|
||||
'inline-flex min-h-10 items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'
|
||||
|
||||
/** Copy without breaking commands across lines.
|
||||
* @param props - Text, accessible label and optional terminal treatment.
|
||||
* @returns Scrollable text and clipboard feedback.
|
||||
*/
|
||||
function CopyValue({
|
||||
value,
|
||||
label,
|
||||
terminal = false,
|
||||
}: {
|
||||
value: string
|
||||
label: string
|
||||
terminal?: boolean
|
||||
}) {
|
||||
const [status, setStatus] = useState('')
|
||||
const multiline = value.includes('\n')
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<div
|
||||
className={`flex min-w-0 gap-2 ${multiline ? 'flex-col items-stretch' : 'items-center'} ${terminal ? 'py-2' : 'rounded-lg border border-border bg-background px-3 py-2'}`}
|
||||
>
|
||||
<code
|
||||
className={`min-w-0 flex-1 max-h-64 overflow-auto whitespace-pre py-1 text-xs leading-6 ${terminal ? 'text-slate-100' : 'text-foreground'}`}
|
||||
tabIndex={0}
|
||||
aria-label={label}
|
||||
>
|
||||
{value}
|
||||
</code>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={multiline ? 'Copy install script' : `Copy ${label}`}
|
||||
title={`Copy ${label}`}
|
||||
className={`flex h-9 shrink-0 items-center justify-center gap-2 rounded-md ${multiline ? 'w-full border border-slate-600 px-3 text-xs' : 'w-9'} transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring ${terminal ? 'text-slate-300 hover:bg-white/10 hover:text-white' : 'text-muted-foreground hover:bg-muted hover:text-foreground'}`}
|
||||
data-qqq-id={`tools-copy-${label.replace(/ /g, '-')}`}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
setStatus('Copied')
|
||||
} catch {
|
||||
setStatus('Could not copy. Select and copy the text above.')
|
||||
}
|
||||
}}
|
||||
>
|
||||
{status === 'Copied' ? (
|
||||
<Check className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
{multiline &&
|
||||
(status === 'Copied' ? 'Copied � paste into your terminal' : 'Copy install script')}
|
||||
</button>
|
||||
</div>
|
||||
<span
|
||||
role="status"
|
||||
className={
|
||||
status && status !== 'Copied'
|
||||
? `block py-1 text-xs ${terminal ? 'text-slate-200' : 'text-muted-foreground'}`
|
||||
: 'sr-only'
|
||||
}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Stable product icon with a fallback for future catalog entries.
|
||||
* @param props - Tool identifier and icon classes.
|
||||
* @returns Product icon.
|
||||
*/
|
||||
function ToolIcon({ id, className }: { id: string; className?: string }) {
|
||||
const Icon =
|
||||
(
|
||||
{ terminal: Terminal, scanner: Smartphone, printing: Printer } as Record<
|
||||
string,
|
||||
typeof Wrench
|
||||
>
|
||||
)[id] ?? Wrench
|
||||
return <Icon className={className} aria-hidden="true" />
|
||||
}
|
||||
|
||||
/** Platform and package-manager choices supplied by the catalog.
|
||||
* @param props - Selected tool with supported install methods.
|
||||
* @returns In-app installation instructions and copyable commands.
|
||||
*/
|
||||
function InstallInstructions({ tool }: { tool: Tool }) {
|
||||
const [platform, setPlatform] = useState(() => {
|
||||
const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent.toLowerCase()
|
||||
return ua.includes('win')
|
||||
? 'windows'
|
||||
: ua.includes('mac')
|
||||
? 'macos'
|
||||
: ua.includes('android')
|
||||
? 'android'
|
||||
: 'linux'
|
||||
})
|
||||
const [method, setMethod] = useState('')
|
||||
const options = tool.installOptions
|
||||
if (options.length === 0) return null
|
||||
const platforms = options.filter(
|
||||
(option, index) => options.findIndex((other) => other.platform === option.platform) === index
|
||||
)
|
||||
const selectedPlatform = platforms.some((option) => option.platform === platform)
|
||||
? platform
|
||||
: platforms[0].platform
|
||||
const methods = options.filter((option) => option.platform === selectedPlatform)
|
||||
const selected = methods.find((option) => option.method === method) ?? methods[0]
|
||||
return (
|
||||
<div className="mb-6 border-b border-border pb-6" data-qqq-id="tools-install-instructions">
|
||||
<h3 className="mb-3 text-sm font-semibold">Install {tool.label}</h3>
|
||||
<div className="mb-3 flex flex-wrap gap-3">
|
||||
<label className="flex min-w-0 flex-1 flex-col gap-1 text-xs text-muted-foreground">
|
||||
Platform
|
||||
<select
|
||||
aria-label="Install platform"
|
||||
value={selectedPlatform}
|
||||
onChange={(event) => {
|
||||
setPlatform(event.target.value)
|
||||
setMethod('')
|
||||
}}
|
||||
data-qqq-id="tools-install-platform"
|
||||
className="min-h-10 min-w-0 w-full rounded-lg border border-border bg-background px-3 text-sm text-foreground focus-visible:outline-ring"
|
||||
>
|
||||
{platforms.map((option) => (
|
||||
<option key={option.platform} value={option.platform}>
|
||||
{option.platformLabel}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex min-w-0 flex-1 flex-col gap-1 text-xs text-muted-foreground">
|
||||
Install with
|
||||
<select
|
||||
aria-label="Install method"
|
||||
value={selected.method}
|
||||
onChange={(event) => setMethod(event.target.value)}
|
||||
data-qqq-id="tools-install-method"
|
||||
className="min-h-10 min-w-0 w-full rounded-lg border border-border bg-background px-3 text-sm text-foreground focus-visible:outline-ring"
|
||||
>
|
||||
{methods.map((option) => (
|
||||
<option key={option.method}>{option.method}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p className="mb-3 text-xs leading-relaxed text-muted-foreground">{selected.instructions}</p>
|
||||
{selected.commands.length > 0 && (
|
||||
<div className="min-w-0 overflow-hidden rounded-xl bg-slate-950 p-3">
|
||||
<p className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-slate-400">
|
||||
{selected.shell}
|
||||
</p>
|
||||
{selected.commands.map((command, index) => (
|
||||
<CopyValue
|
||||
key={command}
|
||||
terminal
|
||||
value={command}
|
||||
label={`${selected.method} install command ${index + 1}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Render an available tool's setup in one consistently sized workspace.
|
||||
* @param props - Selected tool, public server and visible management destination.
|
||||
* @returns Setup panel.
|
||||
*/
|
||||
function SetupPanel({
|
||||
tool,
|
||||
server,
|
||||
management,
|
||||
}: {
|
||||
tool: Tool
|
||||
server?: string
|
||||
management?: { path: string; label: string }
|
||||
}) {
|
||||
const download = downloadLink(tool.downloadUrl)
|
||||
const guide = downloadLink(tool.guideUrl)
|
||||
return (
|
||||
<section
|
||||
id="tools-setup-panel"
|
||||
aria-labelledby="tools-setup-heading"
|
||||
className="overflow-hidden rounded-2xl border border-border bg-card shadow-sm"
|
||||
data-qqq-id={`tools-setup-${tool.id}`}
|
||||
>
|
||||
<header className="flex flex-wrap items-start justify-between gap-5 border-b border-border px-5 py-5 sm:px-6">
|
||||
<div className="min-w-0 flex-1 basis-64">
|
||||
<p className="mb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
|
||||
Setup guide
|
||||
</p>
|
||||
<h2 id="tools-setup-heading" className="text-xl font-semibold tracking-tight">
|
||||
{tool.label}
|
||||
</h2>
|
||||
<p className="mt-2 max-w-xl text-sm leading-relaxed text-muted-foreground">
|
||||
{tool.summary}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{download && (
|
||||
<a
|
||||
className={`${actionClass} bg-primary text-primary-foreground shadow-sm hover:bg-primary/90`}
|
||||
href={download}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
data-qqq-id={`tools-download-${tool.id}`}
|
||||
>
|
||||
<ArrowDownToLine className="h-4 w-4" aria-hidden="true" />
|
||||
{tool.downloadLabel}
|
||||
<span className="sr-only"> (opens in a new tab)</span>
|
||||
</a>
|
||||
)}
|
||||
{guide && (
|
||||
<a
|
||||
className={`${actionClass} border border-border hover:bg-muted`}
|
||||
href={guide}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
data-qqq-id={`tools-guide-${tool.id}`}
|
||||
>
|
||||
Installation guide
|
||||
<ArrowUpRight className="h-4 w-4" aria-hidden="true" />
|
||||
<span className="sr-only"> (opens in a new tab)</span>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
<div className="grid min-w-0 xl:grid-cols-2">
|
||||
<div className="min-w-0 px-5 py-6 sm:px-6">
|
||||
<InstallInstructions tool={tool} />
|
||||
<h3 className="mb-5 text-sm font-semibold">Connect and start using it</h3>
|
||||
<ol className="space-y-6">
|
||||
{tool.steps.map((step, index) => (
|
||||
<li key={index} className="flex gap-3">
|
||||
<span
|
||||
className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-semibold text-primary"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{index + 1}
|
||||
</span>
|
||||
<span className="pt-0.5 text-sm leading-relaxed">
|
||||
<span className="sr-only">Step {index + 1}. </span>
|
||||
{step}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{management && (
|
||||
<Link
|
||||
href={management.path}
|
||||
className={`${actionClass} mt-5 border border-border hover:bg-muted`}
|
||||
data-qqq-id={`tools-manage-${tool.id}`}
|
||||
>
|
||||
Open {management.label}
|
||||
<ArrowUpRight className="h-4 w-4" aria-hidden="true" />
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
role="group"
|
||||
className="min-w-0 space-y-5 border-t border-border bg-muted/25 px-5 py-6 sm:px-6 xl:border-l xl:border-t-0"
|
||||
aria-label="Connection details"
|
||||
>
|
||||
<div>
|
||||
<h3 className="mb-1 flex items-center gap-2 text-sm font-semibold">
|
||||
<Monitor className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
|
||||
Connect to this instance
|
||||
</h3>
|
||||
<p className="mb-3 text-xs leading-relaxed text-muted-foreground">
|
||||
Use this server address and sign in with your QQQ account.
|
||||
</p>
|
||||
{server ? (
|
||||
<CopyValue key={server} value={server} label="server address" />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Ask your administrator for the public HTTPS server address before connecting a
|
||||
client.
|
||||
</p>
|
||||
)}
|
||||
{server && /^http:\/\//.test(server) && (
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
Local development only. Other devices need a reachable HTTPS address.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{tool.commands.length > 0 && (
|
||||
<div className="min-w-0 overflow-hidden rounded-xl bg-slate-950 p-4 text-slate-100">
|
||||
<div className="mb-2 flex items-center gap-2 border-b border-slate-700 pb-3 text-xs font-medium text-slate-300">
|
||||
<Terminal className="h-4 w-4" aria-hidden="true" />
|
||||
Terminal commands
|
||||
</div>
|
||||
{tool.commands.map((command, index) =>
|
||||
command.includes('{server}') && !server ? null : (
|
||||
<CopyValue
|
||||
key={`${command}-${server}`}
|
||||
terminal
|
||||
label={`${tool.label} command ${index + 1}`}
|
||||
value={command.replace(/\{server\}/g, `"${server}"`)}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
Your existing permissions apply. Each device signs in separately.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<footer className="flex items-start gap-2 border-t border-border px-5 py-4 text-xs leading-relaxed text-muted-foreground sm:px-6">
|
||||
<Info className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
{tool.note}
|
||||
</footer>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** Render the catalog with one selected tool, keeping every available tool visible.
|
||||
* @param props - Standard widget payload.
|
||||
* @returns Tool chooser and setup panel, or a recoverable error.
|
||||
*/
|
||||
export default function ToolsWidget({ data }: { data: unknown }) {
|
||||
const metadata = useMetaData()
|
||||
const { navTargets } = useAppTreeRoutes(metadata.data)
|
||||
const [selectedId, setSelectedId] = useState<string>()
|
||||
const parsed = toolsCatalogSchema.safeParse(data)
|
||||
if (!parsed.success)
|
||||
return (
|
||||
<p role="alert">
|
||||
Tools information could not be loaded. Refresh the page or contact your administrator.
|
||||
</p>
|
||||
)
|
||||
const catalog = parsed.data
|
||||
const server =
|
||||
typeof window === 'undefined'
|
||||
? undefined
|
||||
: connectionUrl(
|
||||
catalog.serverUrl,
|
||||
apiClient.getInstance().defaults.baseURL ?? '',
|
||||
window.location.origin
|
||||
)
|
||||
const available = catalog.tools.filter((tool) => tool.available)
|
||||
const unavailable = catalog.tools.filter((tool) => !tool.available)
|
||||
const selected = available.find((tool) => tool.id === selectedId) ?? available[0]
|
||||
return (
|
||||
<div className="space-y-5" data-qqq-id="tools-catalog">
|
||||
<p className="max-w-2xl text-sm leading-relaxed text-muted-foreground">
|
||||
Your workspace, beyond the browser. Choose a tool to download it and connect to this
|
||||
instance.
|
||||
</p>
|
||||
<div className="grid gap-3 md:grid-cols-3" aria-label="Choose a tool">
|
||||
{available.map((tool) => (
|
||||
<button
|
||||
key={tool.id}
|
||||
type="button"
|
||||
aria-pressed={selected?.id === tool.id}
|
||||
aria-controls="tools-setup-panel"
|
||||
aria-label={`Set up ${tool.label}`}
|
||||
data-qqq-id={`tools-card-${tool.id}`}
|
||||
onClick={() => setSelectedId(tool.id)}
|
||||
className={`group flex min-w-0 items-center gap-3 rounded-xl border p-4 text-left transition-all focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring md:items-start ${selected?.id === tool.id ? 'border-primary bg-primary/5 shadow-[inset_0_0_0_1px_var(--primary)]' : 'border-border bg-card hover:border-primary/40 hover:bg-muted/30'}`}
|
||||
>
|
||||
<span
|
||||
className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${selected?.id === tool.id ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'}`}
|
||||
>
|
||||
<ToolIcon id={tool.id} className="h-5 w-5" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-semibold">{tool.label}</span>
|
||||
<span className="mt-1 block text-xs leading-relaxed text-muted-foreground">
|
||||
{tool.platforms}
|
||||
</span>
|
||||
</span>
|
||||
{selected?.id === tool.id && (
|
||||
<Check className="h-4 w-4 shrink-0 text-primary" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{selected && (
|
||||
<SetupPanel
|
||||
key={selected.id}
|
||||
tool={selected}
|
||||
server={server}
|
||||
management={navTargets.find(
|
||||
(target) => target.nodeType === 'APP' && target.key === selected.manageApp
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{unavailable.length > 0 && (
|
||||
<details
|
||||
className="rounded-xl border border-dashed border-border px-4 py-3"
|
||||
data-qqq-id="tools-unavailable"
|
||||
>
|
||||
<summary className="cursor-pointer text-xs font-medium text-muted-foreground">
|
||||
More tools � {unavailable.length} not enabled
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3 md:grid-cols-3">
|
||||
{unavailable.map((tool) => (
|
||||
<div
|
||||
key={tool.id}
|
||||
className="rounded-lg bg-muted/40 p-3"
|
||||
data-qqq-id={`tools-card-${tool.id}`}
|
||||
>
|
||||
<h2 className="text-sm font-medium">{tool.label}</h2>
|
||||
<p className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
Not enabled on this instance. Ask your administrator about enabling this tool.
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* 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 Tools catalog contract and metadata-based navigation. */
|
||||
import { z } from 'zod'
|
||||
import type { QInstance } from '@/types'
|
||||
import { buildRouteMap } from '@/lib/hooks/use-routes'
|
||||
|
||||
export const toolsCatalogSchema = z.object({
|
||||
serverUrl: z.string().nullish(),
|
||||
tools: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
summary: z.string(),
|
||||
platforms: z.string(),
|
||||
available: z.boolean(),
|
||||
downloadUrl: z.string().nullish(),
|
||||
downloadLabel: z.string(),
|
||||
guideUrl: z.string(),
|
||||
manageApp: z.string().nullish(),
|
||||
note: z.string(),
|
||||
steps: z.array(z.string()),
|
||||
commands: z.array(z.string()).default([]),
|
||||
installOptions: z
|
||||
.array(
|
||||
z.object({
|
||||
platform: z.string(),
|
||||
platformLabel: z.string(),
|
||||
method: z.string(),
|
||||
shell: z.string().default(''),
|
||||
instructions: z.string(),
|
||||
commands: z.array(z.string()).default([]),
|
||||
})
|
||||
)
|
||||
.default([]),
|
||||
})
|
||||
),
|
||||
})
|
||||
export type Tool = z.infer<typeof toolsCatalogSchema>['tools'][number]
|
||||
|
||||
/** Find the visible app that hosts the tools widget, independent of app naming.
|
||||
* @param metadata - Permission-filtered instance metadata.
|
||||
* @returns The Tools destination, if visible.
|
||||
*/
|
||||
export function toolsTarget(metadata: QInstance | undefined) {
|
||||
return buildRouteMap(metadata).navTargets.find(
|
||||
(target) =>
|
||||
target.nodeType === 'APP' &&
|
||||
metadata?.apps[target.key]?.widgets?.some(
|
||||
(name) =>
|
||||
metadata.widgets[name]?.type === 'QQQ_TOOLS' &&
|
||||
metadata.widgets[name]?.hasPermission !== false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/** HTTPS external links only.
|
||||
* @param value - Configured download or guide URL.
|
||||
* @returns Safe external URL, or undefined.
|
||||
*/
|
||||
export function downloadLink(value: string | null | undefined): string | undefined {
|
||||
if (!value) return undefined
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return url.protocol === 'https:' && !url.username && !url.password ? url.href : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve the client-facing server root, retaining reverse-proxy path prefixes.
|
||||
* @param configured - Optional explicit public server root.
|
||||
* @param apiBase - Configured UI API base.
|
||||
* @param origin - Browser origin for relative API paths.
|
||||
* @returns Safe server root, or undefined when configuration is ambiguous.
|
||||
*/
|
||||
export function connectionUrl(
|
||||
configured: string | null | undefined,
|
||||
apiBase: string,
|
||||
origin: string
|
||||
): string | undefined {
|
||||
try {
|
||||
const url = new URL(configured || apiBase, origin)
|
||||
if (!configured) {
|
||||
if (!url.pathname.replace(/\/+$/, '').endsWith('/qqq/v1')) return undefined
|
||||
url.pathname = url.pathname.replace(/\/qqq\/v1\/*$/, '')
|
||||
}
|
||||
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return undefined
|
||||
if (url.username || url.password || url.search || url.hash) return undefined
|
||||
const value = url.href.replace(/\/+$/, '')
|
||||
// Safe inside quoted shell commands on Windows, macOS and Linux.
|
||||
return /^https?:\/\/[A-Za-z0-9.:/_[\]~%+-]+$/.test(value) ? value : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,9 @@ const LineChartWidget = lazy(() => import('./LineChartWidget').then((m) => ({ de
|
||||
const PieChartWidget = lazy(() => import('./PieChartWidget').then((m) => ({ default: m.PieChartWidget })))
|
||||
const FilterAndColumnsSetupWidget = lazy(() => import('./FilterAndColumnsSetupWidget').then((m) => ({ default: m.FilterAndColumnsSetupWidget })))
|
||||
const PivotTableSetupWidget = lazy(() => import('./PivotTableSetupWidget').then((m) => ({ default: m.PivotTableSetupWidget })))
|
||||
const ToolsWidget = lazy(() => import('@/components/tools/ToolsWidget'))
|
||||
const SqlWorkbenchWidget = lazy(() => import('@/components/sql-workbench/SqlWorkbenchWidget'))
|
||||
const AuthentikAccessEditorWidget = lazy(() => import('@/components/authentik/AuthentikAccessEditorWidget'))
|
||||
const AuthentikPolicyEditorWidget = lazy(() => import('@/components/authentik/AuthentikPolicyEditorWidget'))
|
||||
const RowBuilderWidget = lazy(() => import('./RowBuilderWidget').then((m) => ({ default: m.RowBuilderWidget })))
|
||||
|
||||
@@ -152,6 +154,8 @@ export function WidgetRenderer({ widgetMetaData, data, recordContext, formContex
|
||||
}
|
||||
|
||||
switch (resolvedType) {
|
||||
case 'QQQ_TOOLS':
|
||||
return <Suspense fallback={SetupFallback}><ToolsWidget data={data} /></Suspense>
|
||||
case 'statistics':
|
||||
return 'count' in data
|
||||
? <QqqStatisticsWidget {...common} data={data} />
|
||||
@@ -219,6 +223,8 @@ export function WidgetRenderer({ widgetMetaData, data, recordContext, formContex
|
||||
return <EsbOverviewWidget widgetMetaData={widgetMetaData} />
|
||||
case 'SQL_WORKBENCH':
|
||||
return <Suspense fallback={SetupFallback}><SqlWorkbenchWidget widgetMetaData={widgetMetaData} /></Suspense>
|
||||
case 'AUTHENTIK_ACCESS_EDITOR':
|
||||
return <Suspense fallback={SetupFallback}><AuthentikAccessEditorWidget {...common} data={data} /></Suspense>
|
||||
case 'AUTHENTIK_POLICY_EDITOR':
|
||||
return <Suspense fallback={SetupFallback}><AuthentikPolicyEditorWidget {...common} data={data} /></Suspense>
|
||||
case 'recordGrid':
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
/** @file Exercises the real variant lifecycle with only process and filesystem boundaries replaced. */
|
||||
import { EventEmitter } from 'node:events'
|
||||
import path from 'node:path'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
@@ -39,7 +40,7 @@ vi.mock('node:child_process', () => {
|
||||
// Existing stale export and build files cannot determine the browser's selected server.
|
||||
vi.mock('node:fs', async (original) => {
|
||||
const fs = {
|
||||
...await original<typeof import('node:fs')>(), existsSync: (file: string) => file.endsWith('next-dashboard/index.html') ? state.hasExport : true, mkdirSync: () => {}, rmSync: () => {},
|
||||
...await original<typeof import('node:fs')>(), existsSync: (file: string) => file.endsWith(path.join('next-dashboard', 'index.html')) ? state.hasExport : true, mkdirSync: () => {}, rmSync: () => {},
|
||||
readdirSync: () => ['Fixture.java'],
|
||||
readFileSync: (file: string) => file.endsWith('routes-manifest.json')
|
||||
? JSON.stringify({ rewrites: { beforeFiles: [], afterFiles: ['qqq', 'data', 'widget', 'metaData', 'download', 'processes', 'possibleValues', 'reports', 'manageSession', 'apis.json', 'api', 'qa'].map((prefix) => ({ source: `/${prefix}/:path*`, destination: `http://127.0.0.1:${state.wrongTarget ? '18765' : '18775'}/${prefix}/:path*` })), fallback: [] } })
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"serverUrl":"https://example.test/customer","tools":[{"id":"terminal","label":"CLI & Terminal UI","summary":"Work with your QQQ apps from a command line or an interactive terminal.","platforms":"Windows, macOS and Linux","available":true,"downloadUrl":"https://github.com/QRun-IO/qqq-cli/releases","downloadLabel":"Get CLI & TUI","guideUrl":"https://github.com/QRun-IO/qqq-cli#install","note":"Download the standalone binary for both CLI and TUI. The npm package includes only the CLI.","steps":["Sign in to this instance using the command below. Follow the sign-in prompts on your computer.","Run qqq ui for the terminal app, or qqq --help for command-line options."],"commands":["qqq login --server {server}","qqq whoami","qqq ui"],"installOptions":[{"platform":"windows","platformLabel":"Windows","method":"Scoop","shell":"PowerShell","instructions":"With Scoop installed, run these commands in PowerShell. This installs the CLI and terminal UI together.","commands":["scoop bucket add qrun https://github.com/QRun-IO/scoop-bucket","scoop install qqq"]},{"platform":"macos","platformLabel":"macOS","method":"Homebrew","shell":"Terminal","instructions":"With Homebrew installed, run this command. It installs the CLI, terminal UI and shell completions.","commands":["brew install qrun-io/tap/qqq"]},{"platform":"macos","platformLabel":"macOS","method":"curl installer","shell":"Terminal","instructions":"No package manager required. Installs the CLI and terminal UI into ~/.local/bin and checks the release SHA-256 checksum. Ensure ~/.local/bin is on your PATH.","commands":["curl -fsSL https://raw.githubusercontent.com/QRun-IO/qqq-cli/main/scripts/install.sh | sh"]},{"platform":"linux","platformLabel":"Linux","method":"curl installer","shell":"Shell","instructions":"No package manager required. Installs into ~/.local/bin and checks the release SHA-256 checksum. Ensure ~/.local/bin is on your PATH. On Alpine, install libstdc++ and libgcc first.","commands":["curl -fsSL https://raw.githubusercontent.com/QRun-IO/qqq-cli/main/scripts/install.sh | sh"]},{"platform":"linux","platformLabel":"Linux","method":"Homebrew","shell":"Shell","instructions":"If you already use Homebrew on Linux, this installs the CLI, terminal UI and shell completions.","commands":["brew install qrun-io/tap/qqq"]}]},{"id":"scanner","label":"Mobile Scanners","summary":"Capture barcodes with an approved Android handheld and your QQQ scanning apps.","platforms":"Supported Android handhelds","available":true,"downloadUrl":"https://git.kof22.com/QRun-IO/qqq-android/releases/tag/scanner-v1.0.0","downloadLabel":"Get signed preview APK","guideUrl":"https://git.kof22.com/QRun-IO/qqq-android/src/branch/main/docs/INSTALLATION.md","manageApp":"mobileScannerAdmin","note":"Signed preview 1.0.0, not a stable release. Forge sign-in is required to download. Devices running a development-signed build need a planned migration; never uninstall or reset to bypass an installation refusal.","steps":["Enter this instance's server address and sign in with your own QQQ account.","Enroll the device and ask an administrator to approve it. Open an available scanning app after approval."],"installOptions":[{"platform":"windows","platformLabel":"Windows computer","method":"USB install - signed preview 1.0.0","shell":"PowerShell","instructions":"For a USB install, connect one handheld to this computer. On the handheld, open Settings > About phone, tap Build number seven times, then enable USB debugging in Developer options. Unlock it and accept the computer trust prompt. The script downloads Google's Platform Tools, opens the exact signed-preview release, verifies the downloaded APK and installs it. Forge login and APK download happen in your browser. Open PowerShell, paste the whole block and follow its prompts.","commands":["# QQQ Mobile signed preview 1.0.0 - run this whole block in PowerShell.\n# Connect ONE handheld by USB, enable USB debugging and accept its trust prompt.\n& {\n $ErrorActionPreference = 'Stop'\n $release = 'https://git.kof22.com/QRun-IO/qqq-android/releases/tag/scanner-v1.0.0'\n $expected = 'EE5AC896B8985AF6F11B2E883955925D6571A2913D74A4AACCDB564B79394D51'\n $folder = Join-Path ([IO.Path]::GetTempPath()) ('qqq-mobile-' + [guid]::NewGuid())\n New-Item -ItemType Directory -Path $folder | Out-Null\n Invoke-WebRequest 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip' -OutFile \"$folder\\tools.zip\" -UseBasicParsing\n Expand-Archive -LiteralPath \"$folder\\tools.zip\" -DestinationPath $folder\n $adb = Join-Path $folder 'platform-tools\\adb.exe'\n Start-Process $release\n Write-Host 'Sign in on the release page and download QQQ-Mobile-1.0.0.apk to Downloads.'\n Read-Host 'After the download finishes, press Enter' | Out-Null\n $apk = Join-Path $env:USERPROFILE 'Downloads\\QQQ-Mobile-1.0.0.apk'\n if(-not (Test-Path -LiteralPath $apk)) {\n $apk = (Read-Host 'Paste the full path of the downloaded QQQ-Mobile-1.0.0.apk').TriLine truncated
|
||||
@@ -22,8 +22,11 @@ test.describe('Keyboard shortcuts', () => {
|
||||
await page.route('**/qqq/v1/preferences/keyboard', (route) => route.fulfill({ status: 404, json: { error: 'No keyboard section' } }))
|
||||
await page.goto('/app/person')
|
||||
await waitForAppReady(page)
|
||||
// Ensure no input is focused so single-key shortcuts fire
|
||||
await page.locator('body').click()
|
||||
// Clear focus without clicking a record at the center of the page.
|
||||
await page.evaluate(() => {
|
||||
if (document.activeElement instanceof HTMLElement) document.activeElement.blur()
|
||||
})
|
||||
await expect(page).toHaveURL(/\/app\/person\/?$/)
|
||||
})
|
||||
|
||||
// ── '.' key — opens command palette ──────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import AxeBuilder from '@axe-core/playwright'
|
||||
import catalog from './fixtures/tools-catalog.json'
|
||||
import { METADATA, setupApiMocks } from './api-mocks'
|
||||
|
||||
for (const width of [1440, 390]) {
|
||||
test(`Tools is discoverable and usable at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 1000 })
|
||||
await setupApiMocks(page)
|
||||
const app = {
|
||||
name: 'qqqTools',
|
||||
label: 'Tools',
|
||||
widgets: ['qqqToolsCatalog'],
|
||||
children: [],
|
||||
sections: [],
|
||||
}
|
||||
await page.route(/\/qqq\/v1\/metaData(?:\?.*)?$/, (route) =>
|
||||
route.fulfill({
|
||||
json: {
|
||||
...METADATA,
|
||||
apps: { ...METADATA.apps, qqqTools: app },
|
||||
appTree: [
|
||||
...METADATA.appTree,
|
||||
{ name: app.name, label: app.label, type: 'APP', iconName: 'build' },
|
||||
],
|
||||
widgets: {
|
||||
qqqToolsCatalog: {
|
||||
name: 'qqqToolsCatalog',
|
||||
label: 'Take QQQ with you',
|
||||
type: 'QQQ_TOOLS',
|
||||
hasPermission: true,
|
||||
gridColumns: 12,
|
||||
isCard: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
await page.route('**/qqq/v1/widget/qqqToolsCatalog**', (route) =>
|
||||
route.fulfill({ json: catalog })
|
||||
)
|
||||
await page.goto('/app')
|
||||
await page.locator('[data-qqq-id="button-account"]').click()
|
||||
await page.getByRole('menuitem', { name: 'Tools', exact: true }).click()
|
||||
await expect(page).toHaveURL(/\/app\/qqqTools$/)
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'CLI & Terminal UI', exact: true })
|
||||
).toBeVisible()
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Set up Mobile Scanners', exact: true })
|
||||
).toBeVisible()
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Set up Print Client', exact: true })
|
||||
).toBeVisible()
|
||||
await page.getByRole('button', { name: 'Set up Print Client', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: 'Print Client', exact: true })).toBeVisible()
|
||||
await expect(page.locator('[data-qqq-id="tools-download-printing"]')).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Copy install script' })).toBeVisible()
|
||||
await page.getByRole('button', { name: 'Set up Mobile Scanners', exact: true }).click()
|
||||
await page.getByLabel('Install platform').selectOption('windows')
|
||||
await expect(page.getByRole('button', { name: 'Copy install script' })).toBeVisible()
|
||||
await expect(page.locator('[data-qqq-id="tools-download-scanner"]')).toBeVisible()
|
||||
expect(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
|
||||
).toBeTruthy()
|
||||
expect(
|
||||
(await new AxeBuilder({ page }).include('[data-qqq-id="tools-catalog"]').analyze()).violations
|
||||
).toEqual([])
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath(`mobile-setup-${width}.png`),
|
||||
fullPage: true,
|
||||
})
|
||||
await page.getByRole('button', { name: 'Set up CLI & Terminal UI', exact: true }).click()
|
||||
await expect(
|
||||
page.getByText('qqq login --server "https://example.test/customer"', { exact: true })
|
||||
).toBeVisible()
|
||||
await page.getByLabel('Install platform').selectOption('windows')
|
||||
await expect(page.getByText('scoop install qqq', { exact: true })).toBeVisible()
|
||||
await page.getByLabel('Install platform').selectOption('macos')
|
||||
await expect(page.getByText('brew install qrun-io/tap/qqq', { exact: true })).toBeVisible()
|
||||
await page.getByLabel('Install platform').selectOption('linux')
|
||||
await expect(page.getByText(/curl -fsSL/)).toBeVisible()
|
||||
await page.getByLabel('Install platform').selectOption('windows')
|
||||
await expect(page.locator('[data-qqq-id="tools-manage-printing"]')).toHaveCount(0)
|
||||
expect(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
|
||||
).toBeTruthy()
|
||||
const accessibility = await new AxeBuilder({ page })
|
||||
.include('[data-qqq-id="tools-catalog"]')
|
||||
.analyze()
|
||||
expect(accessibility.violations).toEqual([])
|
||||
await page.screenshot({ path: test.info().outputPath(`tools-${width}.png`), fullPage: true })
|
||||
})
|
||||
}
|
||||
@@ -49,8 +49,14 @@ it('keeps the variant build, static assets and entrypoint after the main build d
|
||||
expect(readFileSync(path.join(staged, 'public/icon.svg'), 'utf8')).toBe('<svg/>')
|
||||
expect(readFileSync(path.join(staged, 'qqq-server.mjs'), 'utf8')).toBe('container entrypoint')
|
||||
expect(readFileSync(path.join(staged, 'branding-assets.mjs'), 'utf8')).toBe('declared branding aliases')
|
||||
expect(readlinkSync(path.join(staged, 'node_modules/example'))).toBe('.pnpm/example')
|
||||
expect(path.normalize(readlinkSync(path.join(staged, 'node_modules/example')))).toBe(path.join('.pnpm', 'example'))
|
||||
expect(readFileSync(path.join(staged, 'node_modules/example/index.js'), 'utf8')).toBe('independent dependency')
|
||||
})
|
||||
|
||||
// Windows permissions are ACL-based; Node's mode bits do not represent this policy.
|
||||
it.skipIf(process.platform === 'win32')('restricts staged Unix file and directory permissions', () => {
|
||||
const { source, staged } = fixture()
|
||||
stageStandalone(staged, backend, source)
|
||||
expect(statSync(path.join(staged, 'server.js')).mode & 0o777).toBe(0o600)
|
||||
expect(statSync(path.join(staged, '.next/static')).mode & 0o777).toBe(0o700)
|
||||
})
|
||||
|
||||
@@ -5,6 +5,8 @@ import { resolve } from 'path'
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
test: {
|
||||
// Keep DOM suites within a predictable memory/CPU budget on shared build hosts.
|
||||
maxWorkers: 4,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./tests/setup.ts'],
|
||||
|
||||
Reference in new issue
Block a user