Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
refactor(frontend): centralize document <title> in a single registry
Sergey Kozyrenkof369b411ed83
diff --git a/frontend/src/app.tsx b/frontend/src/app.tsxindex 4d2da73b..7e3e9d93 100644--- a/frontend/src/app.tsx+++ b/frontend/src/app.tsx@@ -17,10 +17,9 @@ import ProtectedRoute from '@/components/routes/protected-route';import PublicRoute from '@/components/routes/public-route';import { DocumentTitle } from '@/components/shared/document-title';import PageLoader from '@/components/shared/page-loader';-import { FlowTitle, KnowledgeTitle, ProviderTitle, TemplateTitle } from '@/components/shared/resource-titles';import { Toaster } from '@/components/ui/sonner';import client from '@/lib/apollo';-import { formatPromptId } from '@/lib/utils/format-prompt-id';+import { routeTitles } from '@/lib/route-titles';import { FavoritesProvider } from '@/providers/favorites-provider';import { FlowProvider } from '@/providers/flow-provider';import { KnowledgesProvider } from '@/providers/knowledges-provider';@@ -134,7 +133,7 @@ const router = createBrowserRouter(<Route element={<MainLayout />}><Routeelement={<Dashboard />}- handle={{ title: 'Dashboard' }}+ handle={routeTitles.dashboard}path="dashboard"/>@@ -142,48 +141,48 @@ const router = createBrowserRouter(<Route element={<FlowsLayout />}><Routeelement={<Flows />}- handle={{ title: 'Flows' }}+ handle={routeTitles.flows}path="flows"/><Routeelement={<NewFlow />}- handle={{ title: 'New flow' }}+ handle={routeTitles.newFlow}path="flows/new"/><Routeelement={<FlowWithProvider />}- handle={{ titleComponent: FlowTitle }}+ handle={routeTitles.flow}path="flows/:flowId"/></Route><Routeelement={<Templates />}- handle={{ title: 'Templates' }}+ handle={routeTitles.templates}path="templates"/><Routeelement={<Template />}- handle={{ titleComponent: TemplateTitle }}+ handle={routeTitles.template}path="templates/:templateId"/><Route element={<KnowledgesLayout />}><Routeelement={<Knowledges />}- handle={{ title: 'Knowledges' }}+ handle={routeTitles.knowledges}path="knowledges"/><Routeelement={<Knowledge />}- handle={{ titleComponent: KnowledgeTitle }}+ handle={routeTitles.knowledge}path="knowledges/:knowledgeId"/></Route><Routeelement={<Resources />}- handle={{ title: 'Resources' }}+ handle={routeTitles.resources}path="resources"/></Route>@@ -204,30 +203,27 @@ const router = createBrowserRouter(/><Routeelement={<SettingsProviders />}- handle={{ title: 'Providers' }}+ handle={routeTitles.providers}path="providers"/><Routeelement={<SettingsProvider />}- handle={{ titleComponent: ProviderTitle }}+ handle={routeTitles.provider}path="providers/:providerId"/><Routeelement={<SettingsPrompts />}- handle={{ title: 'Prompts' }}+ handle={routeTitles.prompts}path="prompts"/><Routeelement={<SettingsPrompt />}- handle={{- title: (params: Record<string, string | undefined>) =>- params.promptId ? formatPromptId(params.promptId) : 'Prompt',- }}+ handle={routeTitles.prompt}path="prompts/:promptId"/><Routeelement={<SettingsAPITokens />}- handle={{ title: 'API tokens' }}+ handle={routeTitles.apiTokens}path="api-tokens"/>{/* Catch-all route for unknown settings paths */}@@ -246,20 +242,20 @@ const router = createBrowserRouter({/* report routes */}<Routeelement={<ProtectedReportLayout />}- handle={{ title: 'Flow report' }}+ handle={routeTitles.flowReport}path="flows/:flowId/report"/>{/* public routes */}<Routeelement={<PublicLoginLayout />}- handle={{ title: 'Login' }}+ handle={routeTitles.login}path="login"/><Routeelement={<OAuthResult />}- handle={{ title: 'OAuth' }}+ handle={routeTitles.oauth}path="oauth/result"/>diff --git a/frontend/src/components/shared/document-title.test.tsx b/frontend/src/components/shared/document-title.test.tsxindex cffe906c..4d1675dc 100644--- a/frontend/src/components/shared/document-title.test.tsx+++ b/frontend/src/components/shared/document-title.test.tsx@@ -100,16 +100,17 @@ describe('DocumentTitle', () => {await waitFor(() => expect(document.title).toBe('API tokens — PentAGI'));});- it('renders a title from handle.titleComponent', async () => {+ it('renders a title from a PascalCase-named component', async () => {+ // PascalCase-named function = component (apolloTitle returns one).function CustomTitle({ params }: { params: Record<string, string | undefined> }) {- // React 19 only hoists <title> when the child is a single string- // (not text + interpolation + text), so compute the string ahead.+ // React 19 only hoists <title> when the child is a single string,+ // so compute the string ahead of the JSX.return <title>{`Custom #${params.id} — PentAGI`}</title>;}renderAt('/items/42', [{- children: [{ element: <span>page</span>, handle: { titleComponent: CustomTitle }, path: 'items/:id' }],+ children: [{ element: <span>page</span>, handle: { title: CustomTitle }, path: 'items/:id' }],element: (<><DocumentTitle />@@ -123,20 +124,17 @@ describe('DocumentTitle', () => {await waitFor(() => expect(document.title).toBe('Custom #42 — PentAGI'));});- it('prefers titleComponent over static title when both are present on the same handle', async () => {- function CustomTitle() {- return <title>From component — PentAGI</title>;+ it('treats a lowercase-named function as a plain resolver, not a component', async () => {+ // A named function starting with a lowercase letter is detected as a+ // resolver: DocumentTitle calls it with params and wraps the returned+ // string with the standard "X — PentAGI" template.+ function resolveTitle(params: Record<string, string | undefined>) {+ return `Item ${params.id}`;}- renderAt('/x', [+ renderAt('/items/7', [{- children: [- {- element: <span>page</span>,- handle: { title: 'From static', titleComponent: CustomTitle },- path: 'x',- },- ],+ children: [{ element: <span>page</span>, handle: { title: resolveTitle }, path: 'items/:id' }],element: (<><DocumentTitle />@@ -147,7 +145,7 @@ describe('DocumentTitle', () => {},]);- await waitFor(() => expect(document.title).toBe('From component — PentAGI'));+ await waitFor(() => expect(document.title).toBe('Item 7 — PentAGI'));});it('falls back to APP_NAME when handle.title returns an empty string', async () => {diff --git a/frontend/src/components/shared/document-title.tsx b/frontend/src/components/shared/document-title.tsxindex 891a61b7..d0f837df 100644--- a/frontend/src/components/shared/document-title.tsx+++ b/frontend/src/components/shared/document-title.tsx@@ -2,28 +2,11 @@ import type { ComponentType } from 'react';import { useMatches } from 'react-router-dom';-const APP_NAME = 'PentAGI';--export interface RouteHandleWithTitle {- /**- * Static string or a pure function of route params. Use for routes- * where the title is known synchronously — listing pages, /new routes,- * params-derived titles like `/settings/prompts/:promptId`.- */- title?: TitleResolver;- /**- * Component that renders `<title>` and may subscribe to Apollo cache or- * other reactive sources. Use when the title depends on resource data- * that needs to react to cache updates after the page mounts.- */- titleComponent?: TitleComponent;-}--type RouteParams = Record<string, string | undefined>;+import { renderTitle, type RouteParams } from '@/lib/route-titles/render-title';type TitleComponent = ComponentType<{ params: RouteParams }>;-type TitleResolver = ((params: RouteParams) => string) | string;+type TitleResolver = ((params: RouteParams) => string) | string | TitleComponent;const hasTitle = (handle: unknown): handle is { title: TitleResolver } => {if (typeof handle !== 'object' || handle === null || !('title' in handle)) {@@ -35,49 +18,54 @@ const hasTitle = (handle: unknown): handle is { title: TitleResolver } => {return typeof value === 'string' || typeof value === 'function';};-const hasTitleComponent = (handle: unknown): handle is { titleComponent: TitleComponent } =>- typeof handle === 'object' &&- handle !== null &&- 'titleComponent' in handle &&- typeof (handle as { titleComponent: unknown }).titleComponent === 'function';+// Distinguishes a React component from a plain resolver by the PascalCase+// convention — components must start with an uppercase letter (Apollo title+// factories return named `ApolloTitle`, regular resolvers are anonymous+// arrow functions). This mirrors how React itself differentiates them in+// JSX, so we don't need an extra marker on the function.+const isTitleComponent = (fn: (params: RouteParams) => unknown): fn is TitleComponent => {+ const first = fn.name.charAt(0);-const renderTitle = (label: null | string) => <title>{label ? `${label} — ${APP_NAME}` : APP_NAME}</title>;+ return first === first.toUpperCase() && first !== first.toLowerCase();+};/**- * Renders the document `<title>` driven by react-router route handles. The- * deepest match exposing `handle.title` or `handle.titleComponent` wins.+ * Document `<title>` driver. Walks `useMatches()` for the deepest route+ * exposing `handle.title` and renders accordingly:*- * - `handle.title: string` — static (e.g. "Dashboard").- * - `handle.title: (params) => string` — derived from route params- * (e.g. `/settings/prompts/:promptId` formatting the id).- * - `handle.titleComponent` — reactive component that subscribes to Apollo- * cache for resource-driven titles that need to react to cache updates.+ * handle: { title: 'Dashboard' } // static+ * handle: { title: (p) => formatPromptId(p.promptId!) } // params-derived+ * handle: { title: FlowTitle } // reactive (Apollo)** Living in the app shell, this component survives navigation between- * sibling detail routes — fixing the previous "Provider — PentAGI" flash- * during DetailNavigation prev/next.+ * sibling detail routes — no flash of a generic fallback during the+ * destination page's data fetch.+ *+ * IMPORTANT: do not render `<title>` anywhere else in the tree. React 19+ * hoists every `<title>` into `<head>`, and multiple simultaneous titles+ * lead to undefined browser/SEO behavior. The only safe `<title>` outside+ * this module is inside `<svg>` (icons), which React treats as SVG-title.+ * See https://react.dev/reference/react-dom/components/title.*/export function DocumentTitle() {const matches = useMatches();- const match = matches.findLast((m) => hasTitleComponent(m.handle) || hasTitle(m.handle));+ const match = matches.findLast((m) => hasTitle(m.handle));- if (!match) {+ if (!match || !hasTitle(match.handle)) {return renderTitle(null);}- const handle = match.handle;-- if (hasTitleComponent(handle)) {- const TitleComponent = handle.titleComponent;+ const value = match.handle.title;- return <TitleComponent params={match.params} />;+ if (typeof value === 'string') {+ return renderTitle(value);}- if (hasTitle(handle)) {- const resolved = typeof handle.title === 'function' ? handle.title(match.params) : handle.title;+ if (isTitleComponent(value)) {+ const TitleComp = value;- return renderTitle(resolved);+ return <TitleComp params={match.params} />;}- return renderTitle(null);+ return renderTitle(value(match.params));}diff --git a/frontend/src/components/shared/resource-titles.tsx b/frontend/src/components/shared/resource-titles.tsxdeleted file mode 100644index 5f3efee6..00000000--- a/frontend/src/components/shared/resource-titles.tsx+++ /dev/null@@ -1,80 +0,0 @@-import {- useFlowQuery,- useFlowTemplateQuery,- useKnowledgeDocumentQuery,- useSettingsProvidersQuery,-} from '@/graphql/types';--const APP_NAME = 'PentAGI';--type RouteParams = Record<string, string | undefined>;--const renderTitle = (label: null | string) => <title>{label ? `${label} — ${APP_NAME}` : APP_NAME}</title>;--// Reactive title components used by detail routes via `handle.titleComponent`.-// Each uses `fetchPolicy: 'cache-only'` so it subscribes to the Apollo cache-// without issuing a duplicate HTTP request — the destination page's own-// query fills the cache. The variables shape mirrors the page so cache-// lookups hit.--export function FlowTitle({ params }: { params: RouteParams }) {- const flowId = params.flowId;- const { data } = useFlowQuery({- fetchPolicy: 'cache-only',- skip: !flowId,- variables: flowId ? { id: flowId } : undefined,- });-- const flowTitle = data?.flow?.title;-- return renderTitle(flowTitle && flowId ? `Flow #${flowId} — ${flowTitle}` : 'Flow');-}--export function KnowledgeTitle({ params }: { params: RouteParams }) {- const knowledgeId = params.knowledgeId;- const isNew = knowledgeId === 'new';- const { data } = useKnowledgeDocumentQuery({- fetchPolicy: 'cache-only',- skip: isNew || !knowledgeId,- variables: !isNew && knowledgeId ? { id: knowledgeId } : undefined,- });-- if (isNew) {- return renderTitle('New knowledge');- }-- return renderTitle(data?.knowledgeDocument?.question || 'Knowledge');-}--export function ProviderTitle({ params }: { params: RouteParams }) {- const providerId = params.providerId;- const isNew = providerId === 'new';- const { data } = useSettingsProvidersQuery({- fetchPolicy: 'cache-only',- skip: isNew,- });-- if (isNew) {- return renderTitle('New provider');- }-- const provider = data?.settingsProviders.userDefined?.find((candidate) => String(candidate.id) === providerId);-- return renderTitle(provider?.name || 'Provider');-}--export function TemplateTitle({ params }: { params: RouteParams }) {- const templateId = params.templateId;- const isNew = templateId === 'new';- const { data } = useFlowTemplateQuery({- fetchPolicy: 'cache-only',- skip: isNew || !templateId,- variables: templateId && !isNew ? { templateId } : undefined,- });-- if (isNew) {- return renderTitle('New template');- }-- return renderTitle(data?.flowTemplate?.title || 'Template');-}diff --git a/frontend/src/lib/route-titles/apollo-title.tsx b/frontend/src/lib/route-titles/apollo-title.tsxnew file mode 100644index 00000000..f33ad343--- /dev/null+++ b/frontend/src/lib/route-titles/apollo-title.tsx@@ -0,0 +1,52 @@+import type { QueryHookOptions, QueryResult } from '@apollo/client/react';+import type { ComponentType } from 'react';++import { renderTitle, type RouteParams } from './render-title';++// Apollo codegen hook signature — `useXxxQuery({ variables, skip? })` or+// `useXxxQuery({ skip: true })`. We narrow to `cache-only` so the title+// component never issues an HTTP request — the destination page's own query+// fills the cache.+type ApolloQueryHook<TData, TVars extends Record<string, unknown>> = (+ options: QueryHookOptions<TData, TVars> &+ ({ skip: boolean; variables?: TVars } | { skip?: boolean; variables: TVars }),+) => QueryResult<TData, TVars>;++interface ApolloTitleOpts<TData, TVars extends Record<string, unknown>> {+ /**+ * Compute the label from the cached data and route params. Receives+ * `undefined` when the query is skipped or the cache is empty.+ */+ select: (data: null | TData | undefined, params: RouteParams) => string;+ /**+ * Apollo codegen hook for the target query.+ */+ useQuery: ApolloQueryHook<TData, TVars>;+ /**+ * Return the variables for the query, or `null` to skip the query+ * entirely (used for `:id === 'new'` routes and missing params).+ */+ variables: (params: RouteParams) => null | TVars;+}++/**+ * Factory for Apollo-cache-driven `<title>` components used by route handles.+ *+ * Returns a named `ApolloTitle` component so `DocumentTitle` can detect it as+ * a component (PascalCase convention) versus a plain `(params) => string`+ * resolver.+ */+export function apolloTitle<TData, TVars extends Record<string, unknown>>(+ opts: ApolloTitleOpts<TData, TVars>,+): ComponentType<{ params: RouteParams }> {+ return function ApolloTitle({ params }: { params: RouteParams }) {+ const vars = opts.variables(params);+ const { data } = opts.useQuery(+ vars === null+ ? { fetchPolicy: 'cache-only', skip: true }+ : { fetchPolicy: 'cache-only', skip: false, variables: vars },+ );++ return renderTitle(opts.select(data, params));+ };+}diff --git a/frontend/src/lib/utils/format-prompt-id.ts b/frontend/src/lib/route-titles/format-prompt-id.tssimilarity index 66%rename from frontend/src/lib/utils/format-prompt-id.tsrename to frontend/src/lib/route-titles/format-prompt-id.tsindex 3c0d3f36..e0f61b79 100644--- a/frontend/src/lib/utils/format-prompt-id.ts+++ b/frontend/src/lib/route-titles/format-prompt-id.ts@@ -1,7 +1,7 @@/*** Converts a camelCase prompt key (e.g. "agentSelector") into a display- * label ("Agent Selector"). Used in the prompt detail page and route- * handle title to keep the two in sync.+ * label ("Agent Selector"). Shared between the prompt detail page header+ * and the route handle title.*/export const formatPromptId = (key: string): string =>key.replaceAll(/([A-Z])/g, ' $1').replace(/^./, (str) => str.toUpperCase());diff --git a/frontend/src/lib/route-titles/index.ts b/frontend/src/lib/route-titles/index.tsnew file mode 100644index 00000000..3cd8eb77--- /dev/null+++ b/frontend/src/lib/route-titles/index.ts@@ -0,0 +1,96 @@+import type { ComponentType } from 'react';++import {+ useFlowQuery,+ useFlowTemplateQuery,+ useKnowledgeDocumentQuery,+ useSettingsProvidersQuery,+} from '@/graphql/types';++import { apolloTitle } from './apollo-title';+import { formatPromptId } from './format-prompt-id';+import { type RouteParams } from './render-title';++export interface RouteTitleHandle {+ title: TitleResolver;+}++/**+ * A `handle.title` value can be one of three forms:+ * - `string` — fully static, known at build time.+ * - `(params) => string` — derived synchronously from URL params.+ * - `ComponentType<{ params }>` — reactive (e.g. subscribes to Apollo+ * cache for resource-driven titles). Must be PascalCase-named so the+ * runtime detector in `DocumentTitle` distinguishes it from a plain+ * resolver function.+ */+export type TitleResolver = ((params: RouteParams) => string) | ComponentType<{ params: RouteParams }> | string;++/**+ * Single source of truth for every route's document `<title>`. `app.tsx`+ * imports nothing from Apollo for title purposes — it only spreads handles+ * from this registry onto the matching <Route>.+ */+export const routeTitles = {+ apiTokens: { title: 'API tokens' },+ dashboard: { title: 'Dashboard' },+ flow: {+ title: apolloTitle({+ select: (data, { flowId }) =>+ data?.flow?.title && flowId ? `Flow #${flowId} — ${data.flow.title}` : 'Flow',+ useQuery: useFlowQuery,+ variables: ({ flowId }) => (flowId ? { id: flowId } : null),+ }),+ },+ flowReport: { title: 'Flow report' },+ flows: { title: 'Flows' },+ knowledge: {+ title: apolloTitle({+ select: (data, { knowledgeId }) =>+ knowledgeId === 'new' ? 'New knowledge' : data?.knowledgeDocument?.question || 'Knowledge',+ useQuery: useKnowledgeDocumentQuery,+ variables: ({ knowledgeId }) => (!knowledgeId || knowledgeId === 'new' ? null : { id: knowledgeId }),+ }),+ },+ knowledges: { title: 'Knowledges' },+ login: { title: 'Login' },+ newFlow: { title: 'New flow' },+ oauth: { title: 'OAuth' },+ prompt: {+ title: (params: RouteParams) => (params.promptId ? formatPromptId(params.promptId) : 'Prompt'),+ },+ prompts: { title: 'Prompts' },++ provider: {+ title: apolloTitle({+ select: (data, { providerId }) => {+ if (providerId === 'new') {+ return 'New provider';+ }++ const provider = data?.settingsProviders.userDefined?.find(+ (candidate) => String(candidate.id) === providerId,+ );++ return provider?.name || 'Provider';+ },+ useQuery: useSettingsProvidersQuery,+ variables: ({ providerId }) => (providerId === 'new' ? null : {}),+ }),+ },++ providers: { title: 'Providers' },++ resources: { title: 'Resources' },++ template: {+ title: apolloTitle({+ select: (data, { templateId }) =>+ templateId === 'new' ? 'New template' : data?.flowTemplate?.title || 'Template',+ useQuery: useFlowTemplateQuery,+ variables: ({ templateId }) => (!templateId || templateId === 'new' ? null : { templateId }),+ }),+ },++ templates: { title: 'Templates' },+} as const satisfies Record<string, RouteTitleHandle>;diff --git a/frontend/src/lib/route-titles/render-title.tsx b/frontend/src/lib/route-titles/render-title.tsxnew file mode 100644index 00000000..a1276a8e--- /dev/null+++ b/frontend/src/lib/route-titles/render-title.tsx@@ -0,0 +1,8 @@+export const APP_NAME = 'PentAGI';++export type RouteParams = Record<string, string | undefined>;++// React 19 hoists <title> into <head> automatically. The child must be a+// single string of text (template literals are fine — they collapse to one+// string at render time). An empty label falls back to APP_NAME alone.+export const renderTitle = (label: null | string) => <title>{label ? `${label} — ${APP_NAME}` : APP_NAME}</title>;diff --git a/frontend/src/pages/settings/settings-prompt.tsx b/frontend/src/pages/settings/settings-prompt.tsxindex 67a99520..1ebd6b12 100644--- a/frontend/src/pages/settings/settings-prompt.tsx+++ b/frontend/src/pages/settings/settings-prompt.tsx@@ -36,8 +36,8 @@ import {useUpdatePromptMutation,useValidatePromptMutation,} from '@/graphql/types';+import { formatPromptId } from '@/lib/route-titles/format-prompt-id';import { cn } from '@/lib/utils';-import { formatPromptId } from '@/lib/utils/format-prompt-id';// Form schemas for each tabconst systemFormSchema = z.object({