Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions apps/web/e2e/QUARANTINE.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,53 @@ id IN (SELECT post_id FROM post_votes WHERE principal_id = $1)`. owner:
just stays open. Same component backs user attributes (PPL-U-51). Fix:
catch in `handleCreate` (and the edit/delete handlers) and toast the
error message. owner: unassigned, review by: 2026-12-03.
### Product suite: help center
Each test asserts the right behaviour and fails on the product bug named.
owner: unassigned, review by: 2026-12-03 for every entry.
- `help-center/admin-articles.spec.ts` › HC-A-15 emptying the description in
the editor clears it (HC-B12). `article-modal.tsx` sends
`description: data.description?.trim() || undefined`, and `updateArticle`
(`help-center.article.service.ts`) treats `undefined` as "leave unchanged",
so the old description stays. Fix: send `''` (or `null`) for an emptied
field; the service already stores `'' || null` as null.
- `help-center/admin-articles.spec.ts` › HC-A-20 an unknown article id in the
URL says the article was not found (HC-B18). `use-url-modal.ts` opens the
dialog whenever `?article=` is set and `article-modal.tsx` renders a spinner
until the article loads, so a missing or deleted id spins forever. Fix: when
the detail query errors (ARTICLE_NOT_FOUND), show a not-found state or close
the modal and drop the param.
- `help-center/api-rest.spec.ts` › HC-A-16 a whitespace-only title or
category name is refused on update (HC-B13). `updateArticleSchema` and
`updateCategorySchema` (`lib/shared/schemas/help-center.ts`, and the REST
bodies) check `min(1)` before trimming; `updateArticle` / `updateCategory`
then store the trimmed empty string. Fix: `.trim().min(1)` in the update
schemas, or refuse an empty trimmed value in the services as create does.
- `help-center/api-rest.spec.ts` › HC-A-76 a key without help_center.manage
cannot read drafts or private categories (HC-B3). The GET handlers in
`routes/api/v1/help-center/articles/index.ts`, `articles/$articleId.ts`,
`categories/index.ts` and `categories/$categoryId.ts` call
`withApiKeyAuth(request)` with no permission and read at team scope, so a
Contributor's key gets drafts and private categories. Fix: pass
`{ permission: PERMISSIONS.HELP_CENTER_MANAGE }` (as MCP does), or read with
the public visibility rules for keys without it.
- `help-center/admin-trash.spec.ts` › HC-A-26 the delete dialogs say a
deleted article or category can be restored (HC-B5). The article confirm
(`components/admin/help-center/help-center-list.tsx`, ConfirmDialog
description) says "This action cannot be undone. The article will be
permanently deleted." and the category confirm says "the UI provides no
restore flow", but both are soft deletes that Other › Deleted items restores
for 30 days. Fix: reword both to point at Deleted items.
- `help-center/admin-settings.spec.ts` › HC-A-67 a protocol-relative header
link is refused (HC-B20; `@isolated`). `helpCenterHeaderLinkUrl`
(`lib/shared/schemas/help-center.ts`) accepts any value starting with `/`,
so `//example.com` is stored, and `components/public/portal-header.tsx`
decides "external" by `!startsWith('/')`, rendering it as an in-tab internal
link to another host. Fix: require `startsWith('/') && !startsWith('//')`
in the schema (and treat `//` as external in the header).
- `help-center/translations.spec.ts` › HC-A-53 Save draft on a published
translation does not change the live page (HC-B9; `@isolated`). The
dialog's Save draft (`components/admin/help-center/article-translations-dialog.tsx`)
calls `upsertArticleTranslationFn`, which never touches `status`, so a
published translation's live text changes at once. Fix: either set
`status: 'draft'` on that save, or label the button "Save" when the
translation is published.
229 changes: 229 additions & 0 deletions apps/web/e2e/product/help-center.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
/**
* Help center helpers for the product suite (e2e/tests/help-center/).
*
* const hc = await hcApi(playwright) // REST as the admin (personal key)
* const cat = await hcCategory(hc, `Guides ${marker}`)
* const art = await hcArticle(hc, { categoryId: cat.id, title: `... ${word}`, publish: true })
* await page.goto(articlePath(art)) // /hc/en/articles/<urlId>-<slug>
*
* Seeding goes through the product's REST API (markdown in, the editor JSON
* and the search vector built by the app), so a seeded article looks exactly
* like one an admin wrote. Rows are found by the marker in their names.
*
* Search note: the fake AI's embeddings are hash vectors, so only keyword
* matching finds anything. Put a single alphanumeric `searchWord()` in a title
* and search for it; the hyphenated marker is split by the text parser.
*/
import { randomBytes } from 'node:crypto'
import { readFileSync } from 'node:fs'
import type { APIRequestContext, PlaywrightWorkerArgs } from '@playwright/test'
import { expect } from '@playwright/test'
import { fromUuid, generateId, toUuid } from '@quackback/ids'
import { apiFor, createKey, expectJson, type Wire } from '../support/api-client'
import { supportDb } from '../support/db'
import { supportEnv } from '../support/env'
import { SEEDED_PEOPLE_FILE, SUPPORT_PEOPLE, type SeededPeople } from '../support/people'

/** One admin personal key per worker (minting one runs a script). */
let adminKey: string | null = null

export function hcAdminKey(): string {
adminKey ??= createKey({ creatorEmail: SUPPORT_PEOPLE.admin.email, kind: 'personal' }).key
return adminKey
}

/** The seeded admin's principal TypeID (the default article author). */
export function adminPrincipalId(): string {
const seeded = JSON.parse(readFileSync(SEEDED_PEOPLE_FILE, 'utf8')) as SeededPeople
return seeded.people.admin.principalId
}

/** A REST context authenticated as the admin, with its own client address. */
export function hcApi(playwright: PlaywrightWorkerArgs['playwright']): Promise<APIRequestContext> {
return apiFor(playwright, supportEnv().baseUrl, hcAdminKey())
}

/** A token the search parser keeps whole: `zq` and hex, no hyphen. */
export function searchWord(): string {
return `zq${randomBytes(5).toString('hex')}`
}

export interface HcCategory {
/** TypeID, kb_category_... */
id: string
uuid: string
slug: string
name: string
urlId: number
}

export interface HcArticle {
/** TypeID, article_... */
id: string
uuid: string
slug: string
title: string
urlId: number
categoryId: string
categorySlug: string
}

/** A category through REST (public unless `isPublic: false`). */
export async function hcCategory(
api: APIRequestContext,
name: string,
opts: {
parentId?: string | null
isPublic?: boolean
description?: string
icon?: string
position?: number
} = {}
): Promise<HcCategory> {
const res = await api.post('/api/v1/help-center/categories', { data: { name, ...opts } })
const { data } = await expectJson<{ data: Wire }>(res, 201)
const [row] =
await supportDb()`SELECT id, url_id FROM kb_categories WHERE id = ${uuidOfTypeId(data.id)}`
return {
id: data.id as string,
uuid: row.id as string,
slug: data.slug as string,
name: data.name as string,
urlId: row.url_id as number,
}
}

/** An article through REST; `publish: true` publishes it after the create. */
export async function hcArticle(
api: APIRequestContext,
input: {
categoryId: string
title: string
content?: string
description?: string
slug?: string
publish?: boolean
}
): Promise<HcArticle> {
const { publish, ...body } = input
// API keys act as service principals, which need an explicit byline.
const res = await api.post('/api/v1/help-center/articles', {
data: { content: `Body of ${input.title}.`, authorId: adminPrincipalId(), ...body },
})
const { data } = await expectJson<{ data: Wire }>(res, 201)
if (publish) {
const pub = await api.patch(`/api/v1/help-center/articles/${data.id}`, {
data: { publishedAt: new Date().toISOString() },
})
await expectJson(pub, 200)
}
const [row] =
await supportDb()`SELECT id, url_id FROM kb_articles WHERE id = ${uuidOfTypeId(data.id)}`
return {
id: data.id as string,
uuid: row.id as string,
slug: data.slug as string,
title: data.title as string,
urlId: row.url_id as number,
categoryId: data.category.id as string,
categorySlug: data.category.slug as string,
}
}

/** A category with one published article in it, both carrying `word`. */
export async function hcPublishedArticle(
api: APIRequestContext,
marker: string,
opts: { word?: string; content?: string; isPublic?: boolean } = {}
): Promise<{ category: HcCategory; article: HcArticle; word: string }> {
const word = opts.word ?? searchWord()
const category = await hcCategory(api, `Guides ${marker}`, { isPublic: opts.isPublic })
const article = await hcArticle(api, {
categoryId: category.id,
title: `Setting up the ${word} gadget`,
content: opts.content ?? `Hold the ${word} button for five seconds. ${marker}`,
publish: true,
})
return { category, article, word }
}

/** The canonical public article path, /hc/<locale>/articles/<urlId>-<slug>. */
export function articlePath(a: Pick<HcArticle, 'urlId' | 'slug'>, locale = 'en'): string {
return `/hc/${locale}/articles/${a.urlId}-${a.slug}`
}

/** The canonical public collection path, /hc/<locale>/collections/<urlId>-<slug>. */
export function collectionPath(c: Pick<HcCategory, 'urlId' | 'slug'>, locale = 'en'): string {
return `/hc/${locale}/collections/${c.urlId}-${c.slug}`
}

/** The admin editor deep link for an article. */
export function editorPath(a: Pick<HcArticle, 'id'>): string {
return `/admin/help-center?article=${a.id}`
}

/** The uuid behind a TypeID (`article_...`, `kb_category_...`). */
export function uuidOfTypeId(typeId: string): string {
return toUuid(typeId as Parameters<typeof toUuid>[0])
}

/** The stored article row (snake_case columns), or undefined. */
export async function articleRow(uuid: string): Promise<Record<string, unknown> | undefined> {
const [row] = await supportDb()`SELECT * FROM kb_articles WHERE id = ${uuid}`
return row
}

/** The stored category row, or undefined. */
export async function categoryRow(uuid: string): Promise<Record<string, unknown> | undefined> {
const [row] = await supportDb()`SELECT * FROM kb_categories WHERE id = ${uuid}`
return row
}

/**
* A manual segment of this test's own (SQL), with `members` (principal
* uuids) in it. Gates store the segment's TypeID.
*/
export async function hcSegment(
marker: string,
members: string[] = []
): Promise<{ id: string; uuid: string; name: string }> {
const sql = supportDb()
const uuid = toUuid(generateId('segment'))
const name = `Segment ${marker} ${randomBytes(2).toString('hex')}`
await sql`INSERT INTO segments (id, name, slug, type, created_at, updated_at)
VALUES (${uuid}, ${name}, ${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}, 'manual', NOW(), NOW())`
for (const principalUuid of members) {
await sql`INSERT INTO user_segments (principal_id, segment_id, added_by)
VALUES (${principalUuid}, ${uuid}, 'manual')`
}
return { id: fromUuid('segment', uuid), uuid, name }
}

/** Gate a category or an article to segments (SQL; the admin UI is tested on its own). */
export async function gateToSegments(
target: { kind: 'category' | 'article'; uuid: string },
segmentIds: string[]
): Promise<void> {
const sql = supportDb()
const json = sql.json(segmentIds)
if (target.kind === 'category') {
await sql`UPDATE kb_categories SET segment_ids = ${json} WHERE id = ${target.uuid}`
} else {
await sql`UPDATE kb_articles SET segment_ids = ${json} WHERE id = ${target.uuid}`
}
const table = target.kind === 'category' ? 'kb_categories' : 'kb_articles'
const [row] =
await sql`SELECT jsonb_typeof(segment_ids) AS t FROM ${sql(table)} WHERE id = ${target.uuid}`
if (row?.t !== 'array') throw new Error(`segment_ids stored as ${row?.t}`)
}

/** Fetch a public page as a signed-out visitor, bypassing the shared cache. */
export async function publicGet(
request: APIRequestContext,
path: string
): Promise<{ status: number; text: string }> {
const res = await request.get(path, { maxRedirects: 0, headers: { 'cache-control': 'no-cache' } })
return { status: res.status(), text: await res.text() }
}

export { expect }
41 changes: 41 additions & 0 deletions apps/web/e2e/tests/help-center/admin-access.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Help center admin access: the permission and the product switch.
*
* Journeys: HC-A-01.
*/
import { test, expect } from '../../support/fixtures'
import { ISOLATED, ISOLATED_SKIP } from '../../support/automation'
import { withSettings } from '../../support/isolated-settings'

test(
'HC-A-01 the admin sees the help center; a role without help_center.manage gets no access',
{ tag: '@core' },
async ({ asPerson }) => {
const admin = await asPerson('admin')
await admin.goto('/admin/help-center')
await expect(admin.getByRole('button', { name: 'New category' })).toBeVisible()
await expect(admin.getByRole('button', { name: 'New article' }).first()).toBeVisible()
await expect(admin.getByRole('option', { name: 'Draft', exact: true })).toBeVisible()

const contributor = await asPerson('contributor')
await contributor.goto('/admin/help-center')
await expect(contributor.getByText(/You don.t have access/)).toBeVisible()
await expect(contributor.getByRole('button', { name: 'New category' })).toBeHidden()
await expect(contributor.getByRole('link', { name: 'Help center', exact: true })).toBeHidden()
}
)

test(
'HC-A-01 with the product off the help center admin page redirects elsewhere',
{ tag: ['@core', '@isolated'] },
async ({ asPerson }) => {
test.skip(!ISOLATED, ISOLATED_SKIP)
await withSettings({ feature_flags: { helpCenter: false } }, async () => {
const admin = await asPerson('admin')
await admin.goto('/admin/help-center')
await expect(admin).not.toHaveURL(/\/admin\/help-center/)
await expect(admin).toHaveURL(/\/admin\//)
await expect(admin.getByRole('link', { name: 'Help center', exact: true })).toBeHidden()
})
}
)
Loading
Loading