diff --git a/.github/scripts/e2e-support.sh b/.github/scripts/e2e-support.sh new file mode 100755 index 000000000..d5e15e4ec --- /dev/null +++ b/.github/scripts/e2e-support.sh @@ -0,0 +1,121 @@ +#!/usr/bin/env bash +# The support round-trip end to end (dembrane/frontend/e2e/support-roundtrip.spec.ts) against a +# whole stack this script brings up and tears down: a throwaway database, the bun API, and the +# built dashboard served by the web server, which forwards /api so sign-in cookies stay +# first-party. 22-e2e-support in .github/workflows/platform.yml runs exactly this. +# +# Locally, from the repository root, with the dev Postgres on :5433 and the user's own stack +# holding :8080 and :5173: +# +# E2E_DB_ADMIN_URL=postgres://echo:echo@localhost:5433/postgres \ +# E2E_API_PORT=8180 E2E_WEB_PORT=5273 .github/scripts/e2e-support.sh +# +# Everything it starts is stopped and the database dropped on the way out, failure included. +# Logs land in $E2E_LOG_DIR (default: a temporary directory) and are printed when a step fails. +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +platform=$root/dembrane/platform +frontend=$root/dembrane/frontend + +: "${E2E_DB_ADMIN_URL:=postgres://echo:echo@localhost:5432/postgres}" +: "${E2E_DB_NAME:=echo_e2e_support}" +: "${E2E_API_PORT:=8080}" +: "${E2E_WEB_PORT:=5173}" +: "${E2E_LOG_DIR:=$(mktemp -d)}" +# Throwaway logins on a throwaway database: no secret here is worth hiding. +: "${E2E_SUPPORT_CUSTOMER_EMAIL:=e2e-customer@example.test}" +: "${E2E_SUPPORT_CUSTOMER_PASSWORD:=e2e-support-customer-password}" +: "${E2E_SUPPORT_STAFF_EMAIL:=e2e-staff@example.test}" +: "${E2E_SUPPORT_STAFF_PASSWORD:=e2e-support-staff-password}" +export E2E_DB_ADMIN_URL E2E_DB_NAME +export E2E_SUPPORT_CUSTOMER_EMAIL E2E_SUPPORT_CUSTOMER_PASSWORD +export E2E_SUPPORT_STAFF_EMAIL E2E_SUPPORT_STAFF_PASSWORD + +db_url=${E2E_DB_ADMIN_URL%/*}/$E2E_DB_NAME +web_url=http://localhost:$E2E_WEB_PORT +api_url=http://localhost:$E2E_API_PORT +mkdir -p "$E2E_LOG_DIR" + +api_pid= +web_pid= +cleanup() { + local code=$? + [ -n "$api_pid" ] && kill "$api_pid" 2>/dev/null || true + [ -n "$web_pid" ] && kill "$web_pid" 2>/dev/null || true + wait "$api_pid" "$web_pid" 2>/dev/null || true + (cd "$platform" && bun apps/migrate/src/e2e-support-seed.ts down) || true + if [ "$code" -ne 0 ]; then + for log in "$E2E_LOG_DIR"/*.log; do + [ -e "$log" ] || continue + echo "::group::$(basename "$log")" + tail -n 200 "$log" + echo "::endgroup::" + done + fi + return $code +} +trap cleanup EXIT + +# Waits for a URL to answer, and fails naming the log when the process never came up. +wait_for() { + local url=$1 name=$2 tries=${3:-120} + for _ in $(seq 1 "$tries"); do + curl -sf -o /dev/null "$url" && return 0 + sleep 1 + done + echo "::error::$name did not answer $url" + return 1 +} + +echo "--- database $E2E_DB_NAME" +(cd "$platform" && bun apps/migrate/src/e2e-support-seed.ts up) + +# The API, on the throwaway database. Mail stays in memory and files on disk: no outside +# service is reachable from here, and the round trip needs none. +echo "--- api on :$E2E_API_PORT" +( + cd "$platform" + APP_ENV=test \ + PORT=$E2E_API_PORT \ + API_PUBLIC_URL=$api_url \ + DASHBOARD_URL=$web_url \ + PORTAL_URL=$web_url \ + DATABASE_URL=$db_url \ + AUTH_SECRET=e2e-support-auth-secret-0000000000000000 \ + INVITE_HASH_SECRET=e2e-support-invite-secret-0000 \ + FILES_LOCAL_ROOT=$E2E_LOG_DIR/files \ + AUDIO_LOCAL_ROOT=$E2E_LOG_DIR/audio \ + exec bun apps/api/src/main.ts +) >"$E2E_LOG_DIR/api.log" 2>&1 & +api_pid=$! +wait_for "$api_url/health" api + +# The dashboard, built once and served by the web server. A built bundle, not the dev server: +# the first page of a cold dev server compiles for as long as the test is allowed to run. +if [ "${E2E_SKIP_BUILD:-}" != "1" ]; then + echo "--- build the dashboard" + (cd "$frontend" && pnpm exec vite build) >"$E2E_LOG_DIR/build.log" 2>&1 +fi + +echo "--- dashboard on :$E2E_WEB_PORT" +( + cd "$platform" + APP_ENV=test \ + PORT=$E2E_WEB_PORT \ + API_PUBLIC_URL=$api_url \ + DASHBOARD_URL=$web_url \ + PORTAL_URL=$web_url \ + WEB_ROLE=dashboard \ + WEB_API_ORIGIN=$api_url \ + WEB_ANALYTICS=false \ + WEB_DIST_DIR=$frontend/dist \ + exec bun apps/web/src/main.ts +) >"$E2E_LOG_DIR/web.log" 2>&1 & +web_pid=$! +wait_for "$web_url/login" dashboard 60 + +echo "--- support round trip" +cd "$frontend" +E2E_BASE_URL=$web_url \ + pnpm exec playwright test -c e2e/playwright.config.ts e2e/support-roundtrip.spec.ts "$@" diff --git a/.github/workflows/platform.yml b/.github/workflows/platform.yml index 396396a0a..e73807029 100644 --- a/.github/workflows/platform.yml +++ b/.github/workflows/platform.yml @@ -6,7 +6,9 @@ name: platform # # A run checks only the side it changed: 00-plan diffs the commit against its base (a PR's base # branch, or the previous commit of a push) and skips the server checks when only -# dembrane/frontend changed, and the frontend checks the other way round. Each image is tagged +# dembrane/frontend changed, and the frontend checks the other way round. 22-e2e-support drives +# one support ticket through a whole stack it brings up itself, so it runs when either side +# changed. Each image is tagged # with a hash of its inputs, and an image whose inputs are already in the registry is tagged # for the new commit instead of built again (.github/scripts/build-images.sh). A PR preview rolls out # only the services whose image or settings changed (.github/scripts/deploy-env.sh). @@ -458,6 +460,103 @@ jobs: path: dembrane/frontend/node_modules/.vite/vitest key: vitest-${{ runner.os }}-${{ hashFiles('dembrane/frontend/pnpm-lock.yaml', 'dembrane/frontend/vite.config.ts') }}-${{ github.sha }} + # One support ticket end to end, through the real UI and the real API: a customer raises it, + # staff reply, the customer sees the reply and the badge, and opening the ticket clears it. + # The job owns a whole stack (.github/scripts/e2e-support.sh brings it up and tears it down): + # its own Postgres, the migrations, two seeded logins, the bun API, and the built dashboard + # served by the web server, which forwards /api so the sign-in cookie stays first-party. It + # runs whenever either side changed, because the round trip crosses both. + e2e-support: + name: 22-e2e-support + needs: plan + if: >- + needs.plan.outputs.teardown != 'true' + && (needs.plan.outputs.server == 'true' || needs.plan.outputs.frontend == 'true') + runs-on: ubuntu-latest + timeout-minutes: 20 + services: + postgres: + image: pgvector/pgvector:0.8.1-pg16 + env: { POSTGRES_USER: echo, POSTGRES_PASSWORD: echo, POSTGRES_DB: postgres } + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U echo -d postgres" --health-interval 1s --health-retries 60 + env: + E2E_DB_ADMIN_URL: postgres://echo:echo@localhost:5432/postgres + SAVE_CACHE: ${{ github.event_name != 'pull_request' }} + steps: + - name: Check out code + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: { ref: "${{ env.REF }}", persist-credentials: false } + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version-file: dembrane/platform/.bun-version + no-cache: ${{ github.event_name == 'pull_request' }} + - name: Restore Bun cache + id: bun-cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.bun/install/cache + key: bun-${{ hashFiles('dembrane/platform/bun.lock') }} + restore-keys: bun- + - name: Set up pnpm + uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0 + with: { version: 10 } + - name: Set up Node + uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0 + with: + node-version-file: .tool-versions + - name: Find pnpm store + id: pnpm + working-directory: dembrane/frontend + run: echo "store=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + - name: Restore pnpm cache + id: pnpm-cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ steps.pnpm.outputs.store }} + key: pnpm-${{ runner.os }}-${{ hashFiles('dembrane/frontend/pnpm-lock.yaml') }} + restore-keys: pnpm-${{ runner.os }}- + # The browser the spec drives. Only Chromium: the spec checks behaviour, not rendering. + - name: Restore Playwright cache + id: playwright-cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ hashFiles('dembrane/frontend/pnpm-lock.yaml') }} + restore-keys: playwright-${{ runner.os }}- + - name: Install dependencies + run: bun install --frozen-lockfile + - name: Install frontend dependencies + working-directory: dembrane/frontend + run: pnpm install --frozen-lockfile + - name: Install Chromium + working-directory: dembrane/frontend + run: pnpm exec playwright install --with-deps chromium + # Brings the stack up, runs the spec, and stops everything it started. + - name: Support round trip + working-directory: . + run: .github/scripts/e2e-support.sh + - name: Save pnpm cache + if: env.SAVE_CACHE == 'true' && steps.pnpm-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ steps.pnpm.outputs.store }} + key: pnpm-${{ runner.os }}-${{ hashFiles('dembrane/frontend/pnpm-lock.yaml') }} + - name: Save Bun cache + if: env.SAVE_CACHE == 'true' && steps.bun-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.bun/install/cache + key: bun-${{ hashFiles('dembrane/platform/bun.lock') }} + - name: Save Playwright cache + if: env.SAVE_CACHE == 'true' && steps.playwright-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ hashFiles('dembrane/frontend/pnpm-lock.yaml') }} + # Builds the images whose inputs changed and proves they start. A run that deploys a PR # preview or staging also pushes them, to that environment's registry, and tags every image # it did not need to build for this commit, so the deploy job only rolls out. prod pushes in @@ -568,7 +667,7 @@ jobs: deploy-pr: name: 50-deploy-pr-preview if: ${{ !cancelled() && needs.plan.outputs.deploy_pr == 'true' }} - needs: [plan, check-server, check-frontend, test-frontend, images] + needs: [plan, check-server, check-frontend, test-frontend, e2e-support, images] runs-on: ubuntu-latest timeout-minutes: 20 environment: pr-preview @@ -594,6 +693,7 @@ jobs: 10-check-server=${{ needs.check-server.result }} 20-check-frontend=${{ needs.check-frontend.result }} 21-test-frontend=${{ needs.test-frontend.result }} + 22-e2e-support=${{ needs.e2e-support.result }} 40-build-images=${{ needs.images.result }} run: | failed=$(awk -F= '$2 != "success" && $2 != "skipped" { printf "%s%s", (n++ ? ", " : ""), $1 }' <<<"$RESULTS") @@ -1015,7 +1115,7 @@ jobs: && ((github.event_name != 'pull_request' && needs.deploy-staging.result != 'failure' && needs.deploy-prod.result != 'failure') || (needs.plan.outputs.deploy_pr == 'true' && needs.deploy-pr.result != 'failure') || needs.plan.outputs.teardown == 'true') - needs: [plan, check-server, check-frontend, test-frontend, images, deploy-pr, teardown-pr, deploy-staging, deploy-prod] + needs: [plan, check-server, check-frontend, test-frontend, e2e-support, images, deploy-pr, teardown-pr, deploy-staging, deploy-prod] runs-on: ubuntu-latest timeout-minutes: 2 permissions: diff --git a/dembrane/frontend/e2e/flows.ts b/dembrane/frontend/e2e/flows.ts index f1430cf44..29cde86d9 100644 --- a/dembrane/frontend/e2e/flows.ts +++ b/dembrane/frontend/e2e/flows.ts @@ -100,6 +100,7 @@ export const flows: Record = { "usage-and-billing", "payments", "accounts", + "support", "partners", "managed-billing", "training", @@ -126,6 +127,9 @@ export const flows: Record = { roles: ["staff"], }, "/admin/accounts/new-demo": { roles: ["staff"] }, + "/admin/support/:ticketId": { + skip: "needs a support ticket; no fixture raises one", + }, "/check-your-email": { auth: false }, "/connect-agent": {}, "/invite/accept": TOKEN("invite"), @@ -166,6 +170,15 @@ export const flows: Record = { "/settings/agents/authorize": { skip: "an OAuth consent step: needs a pending agent authorisation request", }, + "/support": { + states: [{ clicks: ["support-ask-send"], name: "send empty" }], + }, + "/support/new": { + states: [{ clicks: ["support-ask-send"], name: "send empty" }], + }, + "/support/:ticketId": { + skip: "needs a support ticket the check's login can see; no fixture raises one", + }, "/verify-email": TOKEN("email-verification"), "/w/:workspaceId": REDIRECT, diff --git a/dembrane/frontend/e2e/routes.ts b/dembrane/frontend/e2e/routes.ts index a92e0f0a0..8bb656256 100644 --- a/dembrane/frontend/e2e/routes.ts +++ b/dembrane/frontend/e2e/routes.ts @@ -102,12 +102,19 @@ export function routerPaths( }; const out: RouterPath[] = []; - const walk = (list: ts.Expression, prefix: string, router: Router) => { + // A child with no element of its own shows its parent's page (SupportRoute draws the + // list and the open ticket itself), so it counts as that page at its own path. + const walk = ( + list: ts.Expression, + prefix: string, + router: Router, + inherited = "", + ) => { const arr = unwrap(list); if (!ts.isArrayLiteralExpression(arr)) return; for (const el of arr.elements) { if (ts.isSpreadElement(el)) { - walk(el.expression, prefix, router); + walk(el.expression, prefix, router, inherited); continue; } const o = unwrap(el); @@ -115,12 +122,13 @@ export function routerPaths( const p = prop(o, "path"); const here = p && ts.isStringLiteral(p) ? join(prefix, p.text) : join(prefix, ""); + const own = tagOf(prop(o, "element")); const children = prop(o, "children"); if (children) { - walk(children, here, router); + walk(children, here, router, own || inherited); continue; } - const element = tagOf(prop(o, "element")); + const element = own || inherited; if (!element) continue; out.push({ element, diff --git a/dembrane/frontend/e2e/support-roundtrip.spec.ts b/dembrane/frontend/e2e/support-roundtrip.spec.ts new file mode 100644 index 000000000..1d522f91c --- /dev/null +++ b/dembrane/frontend/e2e/support-roundtrip.spec.ts @@ -0,0 +1,143 @@ +import { type Browser, expect, type Page, test } from "@playwright/test"; + +// One support ticket end to end through the real UI and API: a customer raises it, staff reply, and the +// customer sees the reply and the unread badge, which opening the ticket clears. +// +// Needs the dashboard (E2E_BASE_URL, default :5173) on a running API with a migrated database, a customer +// login (E2E_SUPPORT_CUSTOMER_EMAIL, E2E_SUPPORT_CUSTOMER_PASSWORD) and a staff login +// (E2E_SUPPORT_STAFF_EMAIL, E2E_SUPPORT_STAFF_PASSWORD). Skips without them. +// +// A pull request gates on it: 22-e2e-support in .github/workflows/platform.yml brings the whole stack up +// with .github/scripts/e2e-support.sh and runs this file. The same script runs it locally, and the release +// runbook runs it against staging, where the logins already hold tickets. So nothing here assumes a clean +// account: the unread count is read before the reply and expected to rise by one, not to be one. +const customer = { + email: process.env.E2E_SUPPORT_CUSTOMER_EMAIL ?? "", + password: process.env.E2E_SUPPORT_CUSTOMER_PASSWORD ?? "", +}; +const staff = { + email: process.env.E2E_SUPPORT_STAFF_EMAIL ?? "", + password: process.env.E2E_SUPPORT_STAFF_PASSWORD ?? "", +}; + +test.skip( + !customer.email || !customer.password || !staff.email || !staff.password, + "set E2E_SUPPORT_CUSTOMER_EMAIL/_PASSWORD and E2E_SUPPORT_STAFF_EMAIL/_PASSWORD", +); + +// Each person in their own browser context, so their sessions never mix. +async function signedIn( + browser: Browser, + who: { email: string; password: string }, +): Promise { + const page = await (await browser.newContext()).newPage(); + await page.goto("/login"); + await page.getByTestId("auth-login-email-input").fill(who.email); + await page.getByTestId("auth-login-password-input").fill(who.password); + await page.getByTestId("auth-login-submit-button").click(); + const inApp = /\/(o|onboarding|w)\b/; + const chooser = page.getByRole("heading", { + name: "Choose a device to sign out", + }); + await Promise.race([ + page.waitForURL(inApp, { timeout: 20_000 }).catch(() => {}), + chooser.waitFor({ timeout: 20_000 }).catch(() => {}), + ]); + // A test login gathers sessions run after run: past the device limit, free the last one listed. + if (await chooser.isVisible()) { + await page.getByRole("radio").last().check(); + await page.getByTestId("auth-login-elsewhere-confirm").click(); + } + await page.waitForURL(inApp, { timeout: 20_000 }); + // An account that has not seen the newest release notes gets the "What's new" dialog over every + // page, and its overlay swallows the clicks below. Closing it records the release as seen. + const whatsNew = page.getByRole("dialog", { name: "What's new" }); + await whatsNew.waitFor({ timeout: 10_000 }).catch(() => {}); + if (await whatsNew.isVisible()) { + await whatsNew.getByRole("button", { name: "Got it" }).click(); + await expect(whatsNew).toHaveCount(0); + } + return page; +} + +// The sidebar's Support entry: the button with its count badge in the full sidebar, or the Help mark in +// the collapsed one, whose name carries the count. +const supportNav = (page: Page) => + page.getByRole("button", { name: /^Support\b|^Help\b/ }).first(); + +// How many unread replies the sidebar shows: the only number in that entry, 0 when it shows none. +// Read before the reply and after, so a ticket left unread by an earlier run cannot decide the test. +async function unreadShown(page: Page): Promise { + const text = await supportNav(page) + .textContent() + .catch(() => ""); + return Number(text?.match(/\d+/)?.[0] ?? 0); +} + +test("a customer's ticket gets a staff reply the customer sees, with the unread badge until opened", async ({ + browser, +}) => { + test.setTimeout(120_000); + const stamp = Date.now(); + const subject = `E2E round trip ${stamp}`; + const answer = `E2E staff reply ${stamp}`; + + const anna = await signedIn(browser, customer); + // New ticket is a page of its own, registered before :ticketId. + await anna.goto("/support/new"); + await anna.getByLabel("Subject").fill(subject); + await anna.getByLabel("Details").fill("Raised by the support e2e spec."); + await anna.locator("label", { hasText: "A question" }).click(); + await anna.getByTestId("support-ask-send").click(); + // Sending opens the ticket's own page: its address names the ticket, whatever + // tab the list would open on for an account that has run this before. + await expect(anna.getByRole("heading", { name: subject })).toBeVisible({ + timeout: 15_000, + }); + const ticketId = new URL(anna.url()).pathname.split("/").at(-1); + expect(ticketId).toMatch(/^[0-9a-f-]{36}$/); + const row = anna + .getByTestId("support-ticket-row") + .filter({ hasText: subject }); + // Whatever this account already carries. The reply must add exactly one to it. + const unreadBefore = await unreadShown(anna); + + const desk = await signedIn(browser, staff); + await desk.goto(`/admin/support/${ticketId}`); + await expect(desk.getByRole("heading", { name: subject })).toBeVisible({ + timeout: 15_000, + }); + // Stay on this ticket after replying, to see the reply land. + // By keyboard: a local dev toolbar can sit over the box and catch a click. + const openNext = desk.getByRole("checkbox", { + name: "Then open the next ticket", + }); + if (await openNext.isChecked()) { + await openNext.focus(); + await openNext.press("Space"); + } + await expect(openNext).not.toBeChecked(); + await desk.getByRole("textbox", { name: "Message" }).fill(answer); + await desk.getByRole("button", { name: "Reply", exact: true }).click(); + await expect(desk.getByText(answer)).toBeVisible({ timeout: 15_000 }); + + // Back on Support the customer finds the row marked and one more on the badge. + await anna.goto("/support"); + await expect + .poll(() => unreadShown(anna), { timeout: 15_000 }) + .toBe(unreadBefore + 1); + await expect(row.getByTestId("support-unread")).toBeVisible(); + await row.click(); + await expect( + anna.getByTestId("support-body").filter({ hasText: answer }), + ).toBeVisible(); + // Opening it reads it: the badge drops back, and the row's mark goes with it. + await expect + .poll(() => unreadShown(anna), { timeout: 15_000 }) + .toBe(unreadBefore); + await anna.getByTestId("support-back").click(); + await expect(row).toBeVisible(); + await expect(row.getByTestId("support-unread")).toHaveCount(0, { + timeout: 15_000, + }); +}); diff --git a/dembrane/frontend/src/DashboardRouter.paths.test.ts b/dembrane/frontend/src/DashboardRouter.paths.test.ts new file mode 100644 index 000000000..045f3ddbb --- /dev/null +++ b/dembrane/frontend/src/DashboardRouter.paths.test.ts @@ -0,0 +1,36 @@ +// @vitest-environment jsdom +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { RouteObject } from "react-router"; +import { expect, it } from "vitest"; +import { mainRouter } from "./DashboardRouter"; + +// The support trail names pages from the server's copy of these paths (came-from.ts). +const SNAPSHOT = resolve( + process.cwd(), + "../platform/packages/support/src/dashboard-paths.json", +); + +const leaves = (routes: readonly RouteObject[], base = ""): string[] => + routes.flatMap((r) => { + const path = + r.path === undefined + ? base + : r.path.startsWith("/") + ? r.path + : `${base}/${r.path}`; + return r.children ? leaves(r.children, path) : [path]; + }); + +it("the server's dashboard path snapshot matches the router", () => { + const paths = [ + ...new Set( + leaves(mainRouter.routes).map( + (p) => p.replace(/\/+/g, "/").replace(/^\/:language\?/, "") || "/", + ), + ), + ].sort(); + const snapshot = JSON.parse(readFileSync(SNAPSHOT, "utf8")); + // A route changed: update dashboard-paths.json, then name the page in came-from.ts SCREENS. + expect(paths).toEqual(snapshot); +}); diff --git a/dembrane/frontend/src/DashboardRouter.tsx b/dembrane/frontend/src/DashboardRouter.tsx index e30b7015a..62b979b08 100644 --- a/dembrane/frontend/src/DashboardRouter.tsx +++ b/dembrane/frontend/src/DashboardRouter.tsx @@ -135,6 +135,10 @@ const ReleaseNotesRoute = createLazyNamedRoute( () => import("./routes/ReleaseNotesRoute"), "ReleaseNotesRoute", ); +const SupportRoute = createLazyNamedRoute( + () => import("./features/support/SupportRoute"), + "SupportRoute", +); const ConnectAgentRoute = createLazyNamedRoute( () => import("./routes/agent-access/ConnectAgentRoute"), @@ -742,6 +746,27 @@ export const mainRouter = createBrowserRouter([ ), path: "settings", }, + { + children: [ + { + // The list keeps its place behind New ticket and an open ticket. + children: [ + { index: true }, + // Before :ticketId, so "new" is a page of its own and never read as an id. + { path: "new" }, + // SupportRoute draws the ticket itself, so its first open never waits on a lazy chunk. + { path: ":ticketId" }, + ], + element: , + }, + ], + element: ( + + + + ), + path: "support", + }, { // Staff-only — billing rollup, at-risk watch, partners, upgrades. // Client-side guard lives inside AdminSettingsRoute (reads @@ -749,6 +774,8 @@ export const mainRouter = createBrowserRouter([ children: [ { element: , index: true }, { element: , path: ":tab" }, + // The support inbox with a ticket open, inside the same admin page. + { element: , path: "support/:ticketId" }, { element: , path: "accounts/new-demo" }, { element: , path: "accounts/demos/:demoId" }, { diff --git a/dembrane/frontend/src/components/auth/hooks/index.ts b/dembrane/frontend/src/components/auth/hooks/index.ts index 6c2f2ed07..c36a77fc5 100644 --- a/dembrane/frontend/src/components/auth/hooks/index.ts +++ b/dembrane/frontend/src/components/auth/hooks/index.ts @@ -8,6 +8,7 @@ import { API_BASE_URL } from "@/config"; import { resetPromptSeen } from "@/features/accounts/help/tasksPromptState"; import { clearAllDrafts } from "@/features/accounts/signing/signingDraft"; import { useI18nNavigate } from "@/hooks/useI18nNavigate"; +import { fetchV2Me, V2_ME_KEY } from "@/hooks/useV2Me"; import { AuthError, hasSession, @@ -194,7 +195,11 @@ export const useLoginMutation = () => { resetSupportRequestSeen(); clearAllDrafts(); } - emitAuthCacheBoundary(); + // Who signed in keeps their support drafts; anyone else's go. + const me = await queryClient + .fetchQuery({ queryFn: fetchV2Me, queryKey: V2_ME_KEY }) + .catch(() => null); + emitAuthCacheBoundary({ signedIn: me?.directus_user_id ?? null }); await queryClient.invalidateQueries({ queryKey: ["auth", "session"] }); }, }); @@ -212,6 +217,8 @@ export const useLogoutMutation = () => { next?: string; reason?: string; doRedirect: boolean; + /** The session ran out: drafts stay for when their writer signs in again. */ + expired?: boolean; }) => { try { await signOut(); @@ -229,7 +236,7 @@ export const useLogoutMutation = () => { navigate(`/login${buildLoginQuery({ next, reason })}`); } }, - onMutate: async () => { + onMutate: async ({ expired }) => { await queryClient.cancelQueries(); // Wipe cache before re-setting session=false — prevents the next user // from briefly seeing the previous user's workspaces/projects. @@ -241,7 +248,7 @@ export const useLogoutMutation = () => { } catch {} clearAllDrafts(); } - emitAuthCacheBoundary(); + emitAuthCacheBoundary(expired ? "expired" : "signedOut"); }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ["auth", "session"] }); @@ -284,6 +291,7 @@ export const useAuthenticated = (doRedirect = false, enabled = true) => { : location.pathname + location.search + location.hash; logoutMutation.mutate({ doRedirect, + expired: true, next: nextUrl, reason: searchParams.get("reason") ?? "", }); diff --git a/dembrane/frontend/src/components/auth/hooks/sessionDrafts.test.tsx b/dembrane/frontend/src/components/auth/hooks/sessionDrafts.test.tsx new file mode 100644 index 000000000..cc347199c --- /dev/null +++ b/dembrane/frontend/src/components/auth/hooks/sessionDrafts.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { MemoryRouter } from "react-router"; +import { afterEach, expect, it, vi } from "vitest"; +import { emitAuthCacheBoundary } from "@/lib/authCacheBoundary"; +import { keepDraft, readDraft } from "@/lib/drafts"; +import { useAuthenticated, useLoginMutation, useLogoutMutation } from "."; + +vi.mock("@/hooks/useI18nNavigate", () => ({ useI18nNavigate: () => vi.fn() })); +vi.mock("@posthog/react", () => ({ usePostHog: () => null })); + +const ANNA = "0199a1bd-0000-7000-8000-00000000a001"; +const BEN = "0199a1bd-0000-7000-8000-00000000b001"; +const question = { fields: { subject: "Upload stuck" }, id: "d1", images: 0 }; + +// The auth server and /v2/me as the browser meets them; `who` is whoever signs in. +function serve(who: { me: string | null; session: boolean }) { + vi.stubGlobal( + "fetch", + vi.fn(async (url: string) => { + const path = new URL(url, "http://localhost").pathname; + if (path.endsWith("/get-session")) + return Response.json(who.session ? { session: {} } : null); + if (path.endsWith("/v2/me")) + return who.me + ? Response.json({ directus_user_id: who.me }) + : new Response(null, { status: 401 }); + return Response.json({}); + }), + ); +} + +const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + +); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + emitAuthCacheBoundary(); + sessionStorage.clear(); +}); + +it("a session that runs out keeps the ask box, and signing back in brings it back", async () => { + keepDraft(ANNA, "ask", question); + serve({ me: null, session: false }); + renderHook(() => useAuthenticated(true), { wrapper }); + await waitFor(() => expect(fetch).toHaveBeenCalledWith( + expect.stringContaining("/sign-out"), + expect.anything(), + )); + expect(readDraft(ANNA, "ask")?.fields.subject).toBe("Upload stuck"); + + serve({ me: ANNA, session: true }); + const login = renderHook(() => useLoginMutation(), { wrapper }); + await act(() => + login.result.current.mutateAsync({ email: "anna@x.nl", password: "pw" }), + ); + expect(readDraft(ANNA, "ask")?.fields.subject).toBe("Upload stuck"); +}); + +it("signing in as someone else drops the last person's drafts", async () => { + keepDraft(ANNA, "ask", question); + serve({ me: BEN, session: true }); + const login = renderHook(() => useLoginMutation(), { wrapper }); + await act(() => + login.result.current.mutateAsync({ email: "ben@x.nl", password: "pw" }), + ); + expect(readDraft(ANNA, "ask")).toBeNull(); +}); + +it("signing out forgets every draft in this tab", async () => { + keepDraft(ANNA, "ask", question); + serve({ me: ANNA, session: true }); + const logout = renderHook(() => useLogoutMutation(), { wrapper }); + await act(() => logout.result.current.mutateAsync({ doRedirect: false })); + expect(readDraft(ANNA, "ask")).toBeNull(); +}); diff --git a/dembrane/frontend/src/components/chat/AgenticChatPanel.test.tsx b/dembrane/frontend/src/components/chat/AgenticChatPanel.test.tsx index ee7e9f958..3347b3af4 100644 --- a/dembrane/frontend/src/components/chat/AgenticChatPanel.test.tsx +++ b/dembrane/frontend/src/components/chat/AgenticChatPanel.test.tsx @@ -379,6 +379,58 @@ describe("AgenticChatPanel, tool groups and the live indicator", () => { expect(group.textContent).toContain("Worked through 3 steps"); }); + it("links a logged support request to its ticket, alone or among other steps", async () => { + const logged = { + ...toolEvent(3, "end", "call-s", "reachOutToDembraneSupport"), + payload: { + data: { + output: { + kwargs: { + content: JSON.stringify({ + sent: true, + ticket_number: 12, + ticket_url: "/support/t1", + }), + }, + }, + }, + name: "reachOutToDembraneSupport", + run_id: "call-s", + }, + }; + const asked = messageEvent(1, "user", "the export is broken"); + const answered = messageEvent(9, "assistant", "logged it."); + const start = toolEvent(2, "start", "call-s", "reachOutToDembraneSupport"); + runState.events = [asked, start, logged, answered]; + runState.status = "completed"; + renderPanel(); + const link = await screen.findByRole("link", { + name: "Logged as ticket #12", + }); + expect(link.getAttribute("href")).toMatch(/\/support\/t1$/); + cleanup(); + + runState.events = [ + asked, + toolEvent(4, "start", "call-a"), + toolEvent(5, "end", "call-a"), + start, + logged, + answered, + ]; + renderPanel(); + const collapsed = await screen.findByRole("link", { + name: "Logged as ticket #12", + }); + expect(collapsed.getAttribute("href")).toMatch(/\/support\/t1$/); + fireEvent.click(screen.getByRole("button", { name: "Show steps" })); + await waitFor(() => + expect( + screen.getAllByRole("link", { name: "Logged as ticket #12" }), + ).toHaveLength(1), + ); + }); + it("still shows a group as running while one of its own steps is running", async () => { // The other direction: a group must not go quiet when a step really is in // progress. This is what #938 was originally protecting. diff --git a/dembrane/frontend/src/components/chat/AgenticChatPanel.tsx b/dembrane/frontend/src/components/chat/AgenticChatPanel.tsx index 4bcead683..e9bce3537 100644 --- a/dembrane/frontend/src/components/chat/AgenticChatPanel.tsx +++ b/dembrane/frontend/src/components/chat/AgenticChatPanel.tsx @@ -2,6 +2,7 @@ import { t } from "@lingui/core/macro"; import { Plural, Trans } from "@lingui/react/macro"; import { Alert, + Anchor, Box, Button, Collapse, @@ -49,6 +50,7 @@ import { useUpdateChatMutation, } from "@/components/chat/hooks"; import { consumeChatPrefill } from "@/components/chat/prefill"; +import { I18nLink } from "@/components/common/i18nLink"; import { useStickToBottom } from "@/components/common/useStickToBottom"; import { ConversationLinks } from "@/components/conversation/ConversationLinks"; import { @@ -554,6 +556,15 @@ const tryParseTimelineSuggestion = ( type ToolActivityItem = Extract; +const StepHeadline = ({ item }: { item: ToolActivityItem }) => + item.link ? ( + + {item.headline} + + ) : ( + item.headline + ); + /** A single humane tool-activity line: status dot, plain-language headline, * and a timestamp. Raw tool input/output is intentionally NOT shown here — it * is internal machinery and lives on the /debug page, not in the host chat. */ @@ -573,7 +584,7 @@ const ToolActivityRow = ({ item }: { item: ToolActivityItem }) => { style={{ backgroundColor: statusMeta.dotColor }} /> - {item.headline} + @@ -601,6 +612,7 @@ const ToolActivityGroup = ({ const running = runningItem !== undefined; const errored = items.some((i) => i.status === "error"); const isSingle = items.length === 1; + const linked = items.filter((item) => item.link); // Steps whose start/end ranges overlap ran at the same time; say so // instead of pretending they were sequential. const ranAllAtOnce = @@ -612,13 +624,15 @@ const ToolActivityGroup = ({ (item.startSeq < other.endSeq && other.startSeq < item.endSeq), ), ); - const summary = runningItem - ? runningItem.headline - : isSingle - ? items[0].headline - : ranAllAtOnce - ? t`Ran ${items.length} steps at once` - : t`Worked through ${items.length} steps`; + const summary = runningItem ? ( + runningItem.headline + ) : isSingle ? ( + + ) : ranAllAtOnce ? ( + t`Ran ${items.length} steps at once` + ) : ( + t`Worked through ${items.length} steps` + ); const dotColor = errored ? "var(--agentic-tool-status-error-dot)" : running @@ -637,10 +651,11 @@ const ToolActivityGroup = ({ {...testId("agentic-tool-group")} > {/* The whole summary row is the toggle (keyboard included); the - chevron is decoration. Time shows once here, not per row. */} + chevron is decoration. Time shows once here, not per row. A + lone step is no toggle: a div, so its link takes clicks. */} + {!isSingle && !expanded && linked.length > 0 && ( + + {linked.map((item) => ( + + ))} + + )} {!isSingle && ( {/* pl-3.5 = dot width (6px) + gap (8px): sub-step dots line up diff --git a/dembrane/frontend/src/components/chat/agenticToolActivity.test.ts b/dembrane/frontend/src/components/chat/agenticToolActivity.test.ts index 50c94cd3f..c49f62f5a 100644 --- a/dembrane/frontend/src/components/chat/agenticToolActivity.test.ts +++ b/dembrane/frontend/src/components/chat/agenticToolActivity.test.ts @@ -14,6 +14,7 @@ const baseActivity = ( endSeq: 2, headline: "Noting this for the dembrane team", id: "tool-noteInsight-call-1", + link: null, rawError: null, rawInput: null, rawOutput: null, @@ -174,6 +175,42 @@ describe("extractTopLevelToolActivity", () => { timestamp: "2026-07-09T00:00:00Z", }); + const supportEnd = (seq: number, result: Record) => ({ + ...toolEvent(seq, "end", "reachOutToDembraneSupport"), + payload: { + data: { output: { kwargs: { content: JSON.stringify(result) } } }, + name: "reachOutToDembraneSupport", + run_id: "call-reachOutToDembraneSupport", + }, + }); + + it("names the ticket a logged support request became and links to it", () => { + const [logged] = extractTopLevelToolActivity([ + toolEvent(1, "start", "reachOutToDembraneSupport"), + supportEnd(2, { + sent: true, + ticket_number: 12, + ticket_url: "/support/0199a1bd-0000-7000-8000-0000000000a1", + }), + ]); + expect(logged?.headline).toBe("Logged as ticket #12"); + expect(logged?.link).toBe("/support/0199a1bd-0000-7000-8000-0000000000a1"); + }); + + it("keeps the plain line when no ticket came back or the link leaves Support", () => { + for (const result of [ + { error: "down", sent: false }, + { sent: true, ticket_number: 12, ticket_url: "https://evil.example/x" }, + ]) { + const [step] = extractTopLevelToolActivity([ + toolEvent(1, "start", "reachOutToDembraneSupport"), + supportEnd(2, result), + ]); + expect(step?.headline).toBe("Logging this with the dembrane team"); + expect(step?.link).toBeNull(); + } + }); + it("hides sendProgressUpdate steps; its output is already a chat message", () => { const activities = extractTopLevelToolActivity([ toolEvent(1, "start", "listProjectConversations"), diff --git a/dembrane/frontend/src/components/chat/agenticToolActivity.ts b/dembrane/frontend/src/components/chat/agenticToolActivity.ts index f4ec8b38f..9fdb47a7b 100644 --- a/dembrane/frontend/src/components/chat/agenticToolActivity.ts +++ b/dembrane/frontend/src/components/chat/agenticToolActivity.ts @@ -16,6 +16,7 @@ export type ToolActivity = { endSeq: number; timestamp: string; headline: string; + link: string | null; rawInput: string | null; rawOutput: string | null; rawError: string | null; @@ -97,6 +98,7 @@ const humanizeToolName = (toolName: string) => { type ToolContext = { query: string | null; participantName: string | null; + ticketNumber: number | null; }; // Gerund phrasing throughout: these lines double as the live status text in @@ -167,8 +169,12 @@ const buildHeadline = (toolName: string, context: ToolContext) => { case "forgetMemory": return t`Forgetting a saved memory`; case "reachOutToDembraneSupport": - case "reachOutToDembrane": - return t`Logging this with the dembrane team`; + case "reachOutToDembrane": { + const n = context.ticketNumber; + return n === null + ? t`Logging this with the dembrane team` + : t`Logged as ticket #${n}`; + } default: { return humanizeToolName(toolName); } @@ -249,9 +255,17 @@ const parseToolEvent = (event: AgenticRunEvent): ParsedToolEvent | null => { outputContent?.participant_name, input?.participant_name, ); + // Non-Support paths stay plain text. + const ticketNumber = outputContent?.ticket_number; + const ticketUrl = asString(outputContent?.ticket_url); + const ticket = + typeof ticketNumber === "number" && ticketUrl?.startsWith("/support/") + ? { number: ticketNumber, url: ticketUrl } + : null; const context: ToolContext = { participantName, query, + ticketNumber: ticket?.number ?? null, }; const headline = buildHeadline(toolName, context); @@ -262,6 +276,7 @@ const parseToolEvent = (event: AgenticRunEvent): ParsedToolEvent | null => { return { callId, headline, + link: ticket?.url ?? null, rawError, rawInput, rawOutput, @@ -337,6 +352,7 @@ export const extractTopLevelToolActivity = ( ...existing, endSeq: parsed.seq, headline: parsed.headline || existing.headline, + link: parsed.link ?? existing.link, rawError: parsed.rawError ?? existing.rawError, rawInput: existing.rawInput ?? parsed.rawInput, rawOutput: parsed.rawOutput ?? existing.rawOutput, diff --git a/dembrane/frontend/src/components/common/ImageDrafts.test.tsx b/dembrane/frontend/src/components/common/ImageDrafts.test.tsx new file mode 100644 index 000000000..79b388adf --- /dev/null +++ b/dembrane/frontend/src/components/common/ImageDrafts.test.tsx @@ -0,0 +1,57 @@ +// @vitest-environment jsdom +import { act, cleanup, renderHook, screen } from "@testing-library/react"; +import { afterEach, beforeAll, expect, it, vi } from "vitest"; +import { png, renderAt, setupDom } from "@/features/support/testing"; + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock("@/components/common/Toaster", () => ({ + toast: { error: toastError }, +})); + +const { ImageDraftList, useImageDrafts } = await import("./ImageDrafts"); + +beforeAll(setupDom); +afterEach(cleanup); + +it("images added twice in one turn are both kept, and the limit counts them all", () => { + const { result } = renderHook(() => useImageDrafts()); + act(() => { + result.current.add([png("a.png")]); + result.current.add([png("b.png")]); + }); + expect(result.current.files.map((f) => f.name)).toEqual(["a.png", "b.png"]); + act(() => { + result.current.add([png("c.png"), png("d.png")]); + result.current.add([png("e.png")]); + }); + expect(result.current.files.map((f) => f.name)).toEqual([ + "a.png", + "b.png", + "c.png", + "d.png", + ]); + expect(toastError).toHaveBeenLastCalledWith("Up to 4 images"); + act(() => { + result.current.remove(0); + result.current.remove(0); + }); + expect(result.current.files.map((f) => f.name)).toEqual(["c.png", "d.png"]); +}); + +it("draws waiting images as square thumbnails", () => { + const Drafts = () => { + const drafts = useImageDrafts(); + return ( + <> + + + + ); + }; + renderAt("/", ); + act(() => screen.getByRole("button", { name: "add" }).click()); + const img = screen.getByRole("img", { name: "shot.png" }); + expect(img.style.getPropertyValue("--image-radius")).not.toMatch(/radius-/); +}); diff --git a/dembrane/frontend/src/components/common/ImageDrafts.tsx b/dembrane/frontend/src/components/common/ImageDrafts.tsx new file mode 100644 index 000000000..5ee63d313 --- /dev/null +++ b/dembrane/frontend/src/components/common/ImageDrafts.tsx @@ -0,0 +1,240 @@ +import { t } from "@lingui/core/macro"; +import { Trans } from "@lingui/react/macro"; +import { + Button, + type ButtonVariant, + CloseButton, + FileButton, + Group, + Image, + Text, + Tooltip, + UnstyledButton, +} from "@mantine/core"; +import { Paperclip } from "@phosphor-icons/react"; +import { + type ClipboardEvent, + type DragEvent, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { toast } from "@/components/common/Toaster"; + +export const ALLOWED_TYPES = [ + "image/png", + "image/jpeg", + "image/webp", + "image/gif", +]; +export const MAX_FILES = 4; +const MAX_FILE_MB = 10; + +/** Images waiting to go with a message, added by button or by pasting a screenshot. */ +export function useImageDrafts( + initial: readonly File[] = [], + /** Told of every change as it happens, even after the composer has gone. */ + onChange?: (files: readonly File[]) => void, +) { + const [files, setFiles] = useState(() => [...initial]); + // Changes in one turn build on each other, as a state updater would. + const latest = useRef(files); + const changed = useRef(onChange); + changed.current = onChange; + const show = useCallback((next: File[]) => { + latest.current = next; + setFiles(next); + changed.current?.(next); + }, []); + const resetRef = useRef<() => void>(null); + const previews = useMemo( + () => files.map((file) => URL.createObjectURL(file)), + [files], + ); + + useEffect( + () => () => { + for (const url of previews) URL.revokeObjectURL(url); + }, + [previews], + ); + + // Outside setState so toasts fire once. + const add = useCallback( + (incoming: File[]) => { + const now = latest.current; + const accepted: File[] = []; + let error: string | undefined; + for (const file of incoming) { + if (!ALLOWED_TYPES.includes(file.type)) { + error ??= t`Only images can be attached`; + continue; + } + if (file.size > MAX_FILE_MB * 1024 * 1024) { + error ??= t`Images must be under ${MAX_FILE_MB}MB`; + continue; + } + if (now.length + accepted.length >= MAX_FILES) { + error ??= t`Up to ${MAX_FILES} images`; + break; + } + accepted.push(file); + } + if (error) toast.error(error); + if (accepted.length > 0) show([...now, ...accepted]); + // Without this the same file cannot be picked again after removing it. + resetRef.current?.(); + }, + [show], + ); + + const onPaste = useCallback( + (event: ClipboardEvent) => { + const pasted = Array.from(event.clipboardData.files); + if (pasted.length > 0) add(pasted); + }, + [add], + ); + + return { + add, + clear: () => show([]), + /** Takes out these images, e.g. once they were sent. */ + drop: (sent: readonly File[]) => + show(latest.current.filter((f) => !sent.includes(f))), + files, + onPaste, + previews, + remove: (index: number) => + show(latest.current.filter((_, i) => i !== index)), + resetRef, + }; +} + +export type ImageDrafts = ReturnType; + +export function ImageDraftList({ drafts }: { drafts: ImageDrafts }) { + if (drafts.files.length === 0) return null; + return ( + + {drafts.files.map((file, index) => ( + + {file.name} + drafts.remove(index)} + /> + + ))} + + ); +} + +/** "Add images", with the limit in its tooltip. */ +export function AddImagesButton({ + drafts, + variant, +}: { + drafts: ImageDrafts; + variant?: ButtonVariant; +}) { + return ( + + {(props) => ( + + + + )} + + ); +} + +/** The whole area picks images on click and takes them when dropped on it. */ +export function ImageDropArea({ + drafts, + className, + hint, +}: { + drafts: ImageDrafts; + className?: string; + /** A line after the limit, e.g. that pasting works too. */ + hint?: string; +}) { + const [over, setOver] = useState(false); + // A file dropped beside the area would open in place of the page. + useEffect(() => { + const guard = (e: globalThis.DragEvent) => { + if (e.defaultPrevented || !e.dataTransfer?.types.includes("Files")) + return; + e.preventDefault(); + e.dataTransfer.dropEffect = "none"; + }; + window.addEventListener("dragover", guard); + window.addEventListener("drop", guard); + return () => { + window.removeEventListener("dragover", guard); + window.removeEventListener("drop", guard); + }; + }, []); + const drop = (event: DragEvent) => { + event.preventDefault(); + setOver(false); + drafts.add(Array.from(event.dataTransfer.files)); + }; + return ( + + {(props) => ( + { + e.preventDefault(); + setOver(true); + }} + onDragLeave={() => setOver(false)} + onDrop={drop} + data-testid="image-drop-area" + > + + + Add images + + + {t`Up to ${MAX_FILES} images. Click, drop them here, or paste a screenshot.`} + {hint ? ` ${hint}` : ""} + + + )} + + ); +} diff --git a/dembrane/frontend/src/components/common/StaffOnlyNotice.tsx b/dembrane/frontend/src/components/common/StaffOnlyNotice.tsx new file mode 100644 index 000000000..d6847d18a --- /dev/null +++ b/dembrane/frontend/src/components/common/StaffOnlyNotice.tsx @@ -0,0 +1,19 @@ +import { Trans } from "@lingui/react/macro"; +import { Container, Stack, Text, Title } from "@mantine/core"; + +/** What a signed-in person who is not staff sees on a staff page. */ +export const StaffOnlyNotice = () => ( + + + + <Trans>Staff only</Trans> + + + + This area is for dembrane staff. If you think you should have access, + email support@dembrane.com. + + + + +); diff --git a/dembrane/frontend/src/components/error/ErrorNotice.tsx b/dembrane/frontend/src/components/error/ErrorNotice.tsx index f32980617..82d531248 100644 --- a/dembrane/frontend/src/components/error/ErrorNotice.tsx +++ b/dembrane/frontend/src/components/error/ErrorNotice.tsx @@ -2,6 +2,7 @@ import { useLingui } from "@lingui/react"; import { Alert, Anchor, Button, Group, Text } from "@mantine/core"; import { WarningCircleIcon } from "@phosphor-icons/react"; import { actionTarget } from "./actions"; +import { useContactSupport } from "./contactSupport"; import { useErrorPresentation } from "./useErrorPresentation"; /** @@ -13,16 +14,24 @@ export const ErrorNotice = ({ onRetry, title, className, + inSupport, }: { error: unknown; onRetry?: () => void; title?: string; className?: string; + /** In a form that writes to support: a failure offers Try again instead of Contact support. */ + inSupport?: boolean; }) => { const { i18n } = useLingui(); const presented = useErrorPresentation(error); + const contactSupport = useContactSupport(); if (!presented) return null; - const target = actionTarget(presented, i18n, onRetry ? { onRetry } : {}); + const target = actionTarget(presented, i18n, { + contactSupport, + inSupport, + onRetry, + }); return ( fine

, + errorElement: , + loader: () => { + throw thrown; + }, + path: "/", + }, + ]); + render( + + + + + , + ); +} + +it("offers Contact support beside Reload page, with the route error", async () => { + const compose = vi.fn(); + const stop = provideContactSupport(compose); + failWith(new Response("", { status: 500, statusText: "Server Error" })); + await screen.findByRole("button", { name: "Reload page" }); + fireEvent.click(screen.getByRole("button", { name: "Contact support" })); + expect(compose).toHaveBeenCalledWith({ + error_code: "http_500", + subject: "Problem: 500 Server Error", + }); + stop(); +}); + +it("names a crash by its title", async () => { + const compose = vi.fn(); + const stop = provideContactSupport(compose); + failWith(new Error("boom")); + fireEvent.click( + await screen.findByRole("button", { name: "Contact support" }), + ); + expect(compose).toHaveBeenCalledWith({ + error_code: "page_error", + subject: "Problem: Something went wrong", + }); + stop(); +}); + +it("has no Contact support when signed out, or on a missing page", async () => { + failWith(new Error("boom")); + await screen.findByRole("button", { name: "Reload page" }); + expect(screen.queryByRole("button", { name: "Contact support" })).toBeNull(); + cleanup(); + const stop = provideContactSupport(() => {}); + failWith(new Response("", { status: 404, statusText: "Not Found" })); + await screen.findByRole("link", { name: "Return home" }); + expect(screen.queryByRole("button", { name: "Contact support" })).toBeNull(); + stop(); +}); diff --git a/dembrane/frontend/src/components/error/ErrorPageContent.tsx b/dembrane/frontend/src/components/error/ErrorPageContent.tsx index e9686220c..3f58c4dc3 100644 --- a/dembrane/frontend/src/components/error/ErrorPageContent.tsx +++ b/dembrane/frontend/src/components/error/ErrorPageContent.tsx @@ -1,7 +1,15 @@ -import { Trans } from "@lingui/react/macro"; +import { Trans, useLingui } from "@lingui/react/macro"; import { Box, Button, Group, Paper, Stack, Text, Title } from "@mantine/core"; import { isRouteErrorResponse, useRouteError } from "react-router"; import { DEBUG_MODE } from "@/config"; +import { readApiError } from "@/lib/errors/read"; +import { supportDraft, useContactSupport } from "./contactSupport"; + +function errorCode(error: unknown): string { + if (isRouteErrorResponse(error)) return `http_${error.status}`; + const info = readApiError(error); + return info.code ?? (info.status ? `http_${info.status}` : "page_error"); +} /** * The route error (or 404) message on its own, with no layout around it, so the @@ -10,6 +18,8 @@ import { DEBUG_MODE } from "@/config"; */ export const ErrorPageContent = ({ homeHref = "/" }: { homeHref?: string }) => { const error = useRouteError(); + const { i18n, t } = useLingui(); + const contactSupport = useContactSupport(); // An unmatched URL (catch-all route) carries no route error: treat as 404. const isNotFound = @@ -53,6 +63,23 @@ export const ErrorPageContent = ({ homeHref = "/" }: { homeHref?: string }) => { Reload page )} + {!isNotFound && contactSupport && ( + + )}