Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

fix(webui): resolve 53 pre-existing TypeScript errors

Sergey Kozyrenko3b6464e7101b
diff --git a/frontend/src/components/shared/detail-navigation/detail-navigation-sheet.tsx b/frontend/src/components/shared/detail-navigation/detail-navigation-sheet.tsx
index 47941c62..b8df16fa 100644
--- a/frontend/src/components/shared/detail-navigation/detail-navigation-sheet.tsx
+++ b/frontend/src/components/shared/detail-navigation/detail-navigation-sheet.tsx
@@ -1,5 +1,5 @@
import { Search, X } from 'lucide-react';
-import { type KeyboardEvent, type ReactNode, startTransition, useCallback, useMemo, useRef, useState } from 'react';
+import { type ReactNode, startTransition, useCallback, useMemo, useRef, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';
@@ -81,7 +81,11 @@ export function DetailNavigationSheet<T extends { id: string }>({
enabled: shouldVirtualize,
estimateSize: estimateRowSize,
gap: 2,
- getItemKey: (index) => String(getId(items[index])),
+ getItemKey: (index) => {
+ const item = items[index];
+
+ return item ? String(getId(item)) : index;
+ },
getScrollElement: () => scrollEl,
overscan: 10,
padding: 8,
@@ -181,7 +185,7 @@ export function DetailNavigationSheet<T extends { id: string }>({
);
const handleListKeyDown = useCallback(
- (event: KeyboardEvent<HTMLUListElement>) => {
+ (event: React.KeyboardEvent<HTMLUListElement>) => {
if (!hasEntries || focusedId === null) {
return;
}
@@ -426,12 +430,19 @@ export function DetailNavigationSheet<T extends { id: string }>({
{virtualItems.map((virtualRow) => {
const item = items[virtualRow.index];
+ if (!item) {
+ return null;
+ }
+
return (
<li
className="absolute inset-x-0 min-w-0 px-2"
key={String(getId(item))}
role="presentation"
- style={{ height: ROW_HEIGHT, transform: `translateY(${virtualRow.start}px)` }}
+ style={{
+ height: ROW_HEIGHT,
+ transform: `translateY(${virtualRow.start}px)`,
+ }}
>
{renderOptionButton(item, virtualRow.index)}
</li>
diff --git a/frontend/src/components/shared/detail-navigation/use-detail-navigation.test.tsx b/frontend/src/components/shared/detail-navigation/use-detail-navigation.test.tsx
index a9797427..66dc0940 100644
--- a/frontend/src/components/shared/detail-navigation/use-detail-navigation.test.tsx
+++ b/frontend/src/components/shared/detail-navigation/use-detail-navigation.test.tsx
@@ -11,11 +11,11 @@ interface Item {
title: string;
}
-const ITEMS: readonly Item[] = [
+const ITEMS = [
{ id: 'a', title: 'Alpha' },
{ id: 'b', title: 'Bravo' },
{ id: 'c', title: 'Charlie' },
-] as const;
+] as const satisfies readonly Item[];
const getHref = (item: Item) => `/items/${item.id}`;
const getLabel = (item: Item) => item.title;
diff --git a/frontend/src/components/shared/document-title.tsx b/frontend/src/components/shared/document-title.tsx
index 5b4cd327..e98c9144 100644
--- a/frontend/src/components/shared/document-title.tsx
+++ b/frontend/src/components/shared/document-title.tsx
@@ -1,13 +1,9 @@
-import type { ComponentType } from 'react';
-
import { useMatches } from 'react-router-dom';
-import { isApolloTitle } from '@/lib/route-titles/apollo-title';
+import { type ApolloTitleComponent, isApolloTitle } from '@/lib/route-titles/apollo-title';
import { renderTitle, type RouteParams } from '@/lib/route-titles/render-title';
-type TitleComponent = ComponentType<{ params: RouteParams }>;
-
-type TitleResolver = ((params: RouteParams) => string) | string | TitleComponent;
+type TitleResolver = ((params: RouteParams) => string) | ApolloTitleComponent | string;
const hasTitle = (handle: unknown): handle is { title: TitleResolver } => {
if (typeof handle !== 'object' || handle === null || !('title' in handle)) {
diff --git a/frontend/src/components/shared/markdown.tsx b/frontend/src/components/shared/markdown.tsx
index f99fb285..42e8ff54 100644
--- a/frontend/src/components/shared/markdown.tsx
+++ b/frontend/src/components/shared/markdown.tsx
@@ -19,7 +19,7 @@ import xml from 'highlight.js/lib/languages/xml';
import yaml from 'highlight.js/lib/languages/yaml';
import 'highlight.js/styles/atom-one-dark.css';
import { common, createLowlight } from 'lowlight';
-import { isValidElement, type ReactNode, useCallback, useMemo } from 'react';
+import { isValidElement, type ReactElement, type ReactNode, useCallback, useMemo } from 'react';
import ReactMarkdown, { type Components } from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import rehypeSlug from 'rehype-slug';
@@ -141,9 +141,7 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {
);
const processTextNode = useMemo(() => {
- const hasChildrenProp = (
- node: unknown,
- ): node is { key?: null | React.Key; props: { children: ReactNode } } =>
+ const hasChildrenProp = (node: unknown): node is ReactElement<{ children?: ReactNode }> =>
isValidElement(node) && (node.props as { children?: ReactNode }).children !== undefined;
const fn = (nodeChildren: ReactNode): ReactNode => {
@@ -196,7 +194,10 @@ function Markdown({ children, className, searchValue }: MarkdownProps) {
(ComponentName: string) => {
const Component = ComponentName as React.ElementType;
- const Renderer = ({ children: nodeChildren, ...props }: Record<string, unknown>) => {
+ const Renderer = ({
+ children: nodeChildren,
+ ...props
+ }: React.PropsWithChildren<Record<string, unknown>>) => {
const processedChildren = processTextNode(nodeChildren);
return <Component {...props}>{processedChildren}</Component>;
diff --git a/frontend/src/components/ui/calendar.tsx b/frontend/src/components/ui/calendar.tsx
index 7d1be806..03695397 100644
--- a/frontend/src/components/ui/calendar.tsx
+++ b/frontend/src/components/ui/calendar.tsx
@@ -19,7 +19,6 @@ function Calendar({ className, classNames, showOutsideDays = true, ...props }: C
buttonVariants({ variant: 'outline' }),
'absolute top-3 left-3 z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100',
),
- caption: 'flex justify-center pt-1 pb-2 relative items-center select-none',
caption_label: 'text-sm font-medium select-none',
day: cn(
buttonVariants({ variant: 'ghost' }),
diff --git a/frontend/src/components/ui/data-table.test.tsx b/frontend/src/components/ui/data-table.test.tsx
index dd2219d5..ba12e737 100644
--- a/frontend/src/components/ui/data-table.test.tsx
+++ b/frontend/src/components/ui/data-table.test.tsx
@@ -218,7 +218,7 @@ describe('DataTable — controlled filter projection', () => {
render(<FilterHost emitted={emitted} />, { wrapper: Wrapper });
const input = screen.getByPlaceholderText('Filter...');
- await user.type(input, 'bravo', { delay: 5 });
+ await user.type(input, 'bravo');
// No `waitFor` here — we want the X click to happen mid-debounce,
// before any emit has reached the parent.
expect(emitted).toEqual([]);
@@ -258,7 +258,7 @@ describe('DataTable — controlled filter projection', () => {
);
const input = screen.getByPlaceholderText('Filter...');
- await user.type(input, 'cha', { delay: 5 });
+ await user.type(input, 'cha');
// While the debounce is still pending, simulate an external write
// (e.g. back-button popping to a different `?q=`).
@@ -352,7 +352,7 @@ describe('DataTable — controlled filter projection', () => {
const { unmount } = render(<FilterHost emitted={emitted} />, { wrapper: Wrapper });
- await user.type(screen.getByPlaceholderText('Filter...'), 'gone', { delay: 5 });
+ await user.type(screen.getByPlaceholderText('Filter...'), 'gone');
// Unmount before the debounce settles.
unmount();
@@ -1139,6 +1139,11 @@ describe('DataTable — virtualization', () => {
// index so the check is independent of which window the virtualizer renders.
expect(document.querySelector('thead tr')).toHaveAttribute('aria-rowindex', '1');
const firstDataRow = dataRows()[0];
+
+ if (!firstDataRow) {
+ throw new Error('no row');
+ }
+
const dataIndex = Number(firstDataRow.getAttribute('data-index'));
expect(firstDataRow).toHaveAttribute('aria-rowindex', String(dataIndex + 2));
});
diff --git a/frontend/src/components/ui/data-table.tsx b/frontend/src/components/ui/data-table.tsx
index ddce6007..7d80ce28 100644
--- a/frontend/src/components/ui/data-table.tsx
+++ b/frontend/src/components/ui/data-table.tsx
@@ -1172,7 +1172,7 @@ function VirtualizedTableBody<TData>({
// follows row identity once the table opts into `getRowId` (today's default
// ids are positional, making this equivalent to the index). Recreated on
// every `rows` change so the cache tracks the current row set.
- const getItemKey = useCallback((index: number) => rows[index].id, [rows]);
+ const getItemKey = useCallback((index: number) => rows[index]?.id ?? index, [rows]);
const { anchorRef, measureItem, paddingEnd, paddingStart, virtualItems } =
useWindowVirtualList<HTMLTableSectionElement>({
@@ -1192,6 +1192,10 @@ function VirtualizedTableBody<TData>({
{virtualItems.map((virtualItem) => {
const row = rows[virtualItem.index];
+ if (!row) {
+ return null;
+ }
+
return (
<DataTableRow
isRowInteractive={isRowInteractive}
diff --git a/frontend/src/features/authentication/password-change-form.test.tsx b/frontend/src/features/authentication/password-change-form.test.tsx
index 4789fa35..25628da3 100644
--- a/frontend/src/features/authentication/password-change-form.test.tsx
+++ b/frontend/src/features/authentication/password-change-form.test.tsx
@@ -29,7 +29,13 @@ describe('PasswordChangeForm', () => {
const current = screen.getByPlaceholderText('Enter your current password') as HTMLInputElement;
expect(current.type).toBe('password');
- await user.click(screen.getAllByRole('button', { name: 'Show password' })[0]);
+ const [showButton] = screen.getAllByRole('button', { name: 'Show password' });
+
+ if (!showButton) {
+ throw new Error('expected a Show password toggle');
+ }
+
+ await user.click(showButton);
expect(current.type).toBe('text');
});
diff --git a/frontend/src/features/flows/files/use-flow-files-delete.ts b/frontend/src/features/flows/files/use-flow-files-delete.ts
index d482ab1d..7cd895ff 100644
--- a/frontend/src/features/flows/files/use-flow-files-delete.ts
+++ b/frontend/src/features/flows/files/use-flow-files-delete.ts
@@ -78,8 +78,8 @@ export function useFlowFilesDelete({ flowId, onAfterDelete }: UseFlowFilesDelete
);
if (filesToDelete.length === 1) {
- const single = filesToDelete[0];
- toast.success(single.isDir ? 'Directory deleted' : 'File deleted');
+ const [single] = filesToDelete;
+ toast.success(single?.isDir ? 'Directory deleted' : 'File deleted');
} else {
toast.success(`${filesToDelete.length} ${pluralizeItems(filesToDelete.length)} deleted`);
}
diff --git a/frontend/src/features/knowledges/knowledge-form-layout.tsx b/frontend/src/features/knowledges/knowledge-form-layout.tsx
index f241c8a1..9c18307c 100644
--- a/frontend/src/features/knowledges/knowledge-form-layout.tsx
+++ b/frontend/src/features/knowledges/knowledge-form-layout.tsx
@@ -29,7 +29,7 @@ export function KnowledgeFormLayoutDesktop({ control, isNew, isSaving, knowledge
<div className="flex min-h-0 w-full max-w-full flex-1 overflow-hidden">
<ResizablePanelGroup
className="w-full"
- direction="horizontal"
+ orientation="horizontal"
>
<ResizablePanel
defaultSize={45}
diff --git a/frontend/src/features/resources/use-resources-delete.ts b/frontend/src/features/resources/use-resources-delete.ts
index aa9bb231..ef3f0fd6 100644
--- a/frontend/src/features/resources/use-resources-delete.ts
+++ b/frontend/src/features/resources/use-resources-delete.ts
@@ -66,8 +66,8 @@ export function useResourcesDelete({ onAfterDelete }: UseResourcesDeleteParams =
await deleteResourcesRequest(filesToDelete.map((file) => file.path));
if (filesToDelete.length === 1) {
- const single = filesToDelete[0];
- toast.success(single.isDir ? 'Directory deleted' : 'Resource deleted');
+ const [single] = filesToDelete;
+ toast.success(single?.isDir ? 'Directory deleted' : 'Resource deleted');
} else {
toast.success(`${filesToDelete.length} ${pluralizeItems(filesToDelete.length)} deleted`);
}
diff --git a/frontend/src/hooks/use-table-query-filter.test.tsx b/frontend/src/hooks/use-table-query-filter.test.tsx
index 32466a60..8bebccd0 100644
--- a/frontend/src/hooks/use-table-query-filter.test.tsx
+++ b/frontend/src/hooks/use-table-query-filter.test.tsx
@@ -22,10 +22,9 @@ describe('useTableQueryFilterReader', () => {
const Wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter initialEntries={['/flows/abc?q=alpha']}>{children}</MemoryRouter>
);
- const { result } = renderHook(
- () => useTableQueryFilterReader({ debounceMs: SHORT_DEBOUNCE_MS, storageKey: STORAGE_KEY }),
- { wrapper: Wrapper },
- );
+ const { result } = renderHook(() => useTableQueryFilterReader({ debounceMs: SHORT_DEBOUNCE_MS }), {
+ wrapper: Wrapper,
+ });
expect(result.current.filter).toBe('alpha');
expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
@@ -40,7 +39,6 @@ describe('useTableQueryFilterReader', () => {
() => {
const reader = useTableQueryFilterReader({
debounceMs: SHORT_DEBOUNCE_MS,
- storageKey: STORAGE_KEY,
});
const { search } = useLocation();
diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts
index 9e1d0e5d..088c0390 100644
--- a/frontend/src/lib/apollo.ts
+++ b/frontend/src/lib/apollo.ts
@@ -1,6 +1,7 @@
import type { FetchResult, Operation, Reference, StoreObject } from '@apollo/client';
import { ApolloClient, ApolloLink, createHttpLink, InMemoryCache, Observable, split } from '@apollo/client';
+import { CombinedGraphQLErrors, ServerError } from '@apollo/client/errors';
import { onError } from '@apollo/client/link/error';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
@@ -420,9 +421,9 @@ const createApolloClient = () => {
const transportLink = split(isSubscriptionOperation, wsLink, httpLink);
- const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
- if (graphQLErrors) {
- for (const { extensions, locations, message, path } of graphQLErrors) {
+ const errorLink = onError(({ error, operation }) => {
+ if (CombinedGraphQLErrors.is(error)) {
+ for (const { extensions, locations, message, path } of error.errors) {
Log.error(`[GraphQL Error] ${message}`, {
locations,
operation: operation.operationName,
@@ -442,18 +443,12 @@ const createApolloClient = () => {
window.dispatchEvent(new Event('auth:refresh'));
}
}
- }
-
- if (networkError) {
- Log.error(`[Network Error] ${networkError.message}`, networkError);
-
- if ('statusCode' in networkError) {
- const statusCode = (networkError as { statusCode?: number }).statusCode;
+ } else if (error) {
+ Log.error(`[Network Error] ${error.message}`, error);
- if (statusCode === 401 || statusCode === 403) {
- Log.warn('Network authorization error detected, refreshing auth info');
- window.dispatchEvent(new Event('auth:refresh'));
- }
+ if (ServerError.is(error) && (error.statusCode === 401 || error.statusCode === 403)) {
+ Log.warn('Network authorization error detected, refreshing auth info');
+ window.dispatchEvent(new Event('auth:refresh'));
}
}
});
diff --git a/frontend/src/lib/clipboard.ts b/frontend/src/lib/clipboard.ts
index de0bc934..3e041570 100644
--- a/frontend/src/lib/clipboard.ts
+++ b/frontend/src/lib/clipboard.ts
@@ -21,8 +21,8 @@ export const getCleanTerminalText = (terminalContent: string): Promise<string> =
return new Promise((resolve) => {
let hiddenTerminal: null | XTerminal = null;
let hiddenDiv: HTMLDivElement | null = null;
- let timeoutId: NodeJS.Timeout | null = null;
- let safetyTimeoutId: NodeJS.Timeout | null = null;
+ let timeoutId: null | ReturnType<typeof setTimeout> = null;
+ let safetyTimeoutId: null | ReturnType<typeof setTimeout> = null;
let isResolved = false;
const cleanup = () => {
diff --git a/frontend/src/models/info.ts b/frontend/src/models/info.ts
index e6274ec3..43571828 100644
--- a/frontend/src/models/info.ts
+++ b/frontend/src/models/info.ts
@@ -1,4 +1,4 @@
-import type { User } from './User';
+import type { User } from './user';
export interface AuthInfo {
develop?: boolean;
diff --git a/frontend/src/pages/flows/flow.tsx b/frontend/src/pages/flows/flow.tsx
index f2725bbf..a03dc18b 100644
--- a/frontend/src/pages/flows/flow.tsx
+++ b/frontend/src/pages/flows/flow.tsx
@@ -398,7 +398,7 @@ function Flow() {
{isDesktop ? (
<ResizablePanelGroup
className="w-full"
- direction="horizontal"
+ orientation="horizontal"
>
<ResizablePanel
defaultSize={50}
diff --git a/frontend/src/pages/oauth-result.tsx b/frontend/src/pages/oauth-result.tsx
index f41386cd..7d6ef90b 100644
--- a/frontend/src/pages/oauth-result.tsx
+++ b/frontend/src/pages/oauth-result.tsx
@@ -23,9 +23,9 @@ function OAuthResult() {
const status = params.get('status');
const error = params.get('error');
- let redirectTimer: NodeJS.Timeout | null = null;
- let cleanupTimer: NodeJS.Timeout | null = null;
- let closeTimer: NodeJS.Timeout | null = null;
+ let redirectTimer: null | ReturnType<typeof setTimeout> = null;
+ let cleanupTimer: null | ReturnType<typeof setTimeout> = null;
+ let closeTimer: null | ReturnType<typeof setTimeout> = null;
const updateMessage = (message: string) => {
messageRef.current = message;
diff --git a/frontend/src/pages/settings/settings-account.test.tsx b/frontend/src/pages/settings/settings-account.test.tsx
index 39c09b48..c0356b5e 100644
--- a/frontend/src/pages/settings/settings-account.test.tsx
+++ b/frontend/src/pages/settings/settings-account.test.tsx
@@ -80,12 +80,24 @@ describe('SettingsAccount gating', () => {
authState.value = { user: localUser };
render(<SettingsAccount />);
- await user.click(screen.getAllByRole('button', { name: 'Change' })[0]);
+ const [firstChangeButton] = screen.getAllByRole('button', { name: 'Change' });
+
+ if (!firstChangeButton) {
+ throw new Error('expected a Change button');
+ }
+
+ await user.click(firstChangeButton);
const nameInput = screen.getByPlaceholderText('Enter your display name');
await user.clear(nameInput);
await user.type(nameInput, 'Draft Name');
- await user.click(screen.getAllByRole('button', { name: 'Change' })[0]);
+ const [reopenChangeButton] = screen.getAllByRole('button', { name: 'Change' });
+
+ if (!reopenChangeButton) {
+ throw new Error('expected a Change button');
+ }
+
+ await user.click(reopenChangeButton);
expect(screen.getByRole('button', { name: 'Update Email' })).toBeInTheDocument();
expect(screen.getByPlaceholderText('Enter your display name')).toHaveValue('Draft Name');
diff --git a/frontend/src/pages/settings/settings-api-tokens.tsx b/frontend/src/pages/settings/settings-api-tokens.tsx
index 6f0dc030..0c16cc70 100644
--- a/frontend/src/pages/settings/settings-api-tokens.tsx
+++ b/frontend/src/pages/settings/settings-api-tokens.tsx
@@ -64,10 +64,8 @@ type APIToken = ApiTokenFragmentFragment;
const tokenNameSchema = z.string().trim().max(255, 'Token name must be 255 characters or less').default('');
const createTokenFormSchema = z.object({
- // Nullable in the form state (the date picker starts empty) but required
- // for submission — the refine drives `formState.isValid`, which gates the
- // Create button without manual checks. Kept as `Date | null` in the
- // inferred type so `defaultValues` can be `null` without a cast.
+ // Nullable in form input (the date picker starts empty); the refine gates
+ // `formState.isValid` so the Create button stays disabled until a date is set.
expiresAt: z
.date()
.nullable()
@@ -80,11 +78,13 @@ const editTokenFormSchema = z.object({
status: z.nativeEnum(TokenStatusEnum),
});
-type CreateTokenFormValues = z.infer<typeof createTokenFormSchema>;
-type EditTokenFormValues = z.infer<typeof editTokenFormSchema>;
+type CreateTokenFormInput = z.input<typeof createTokenFormSchema>;
+type CreateTokenFormValues = z.output<typeof createTokenFormSchema>;
+type EditTokenFormInput = z.input<typeof editTokenFormSchema>;
+type EditTokenFormValues = z.output<typeof editTokenFormSchema>;
-const CREATE_TOKEN_DEFAULTS: CreateTokenFormValues = { expiresAt: null, name: '' };
-const EDIT_TOKEN_DEFAULTS: EditTokenFormValues = { name: '', status: TokenStatusEnum.Active };
+const CREATE_TOKEN_DEFAULTS: CreateTokenFormInput = { expiresAt: null, name: '' };
+const EDIT_TOKEN_DEFAULTS: EditTokenFormInput = { name: '', status: TokenStatusEnum.Active };
const isTokenExpired = (token: APIToken): boolean => {
const expiresAt = new Date(token.createdAt);
@@ -202,7 +202,7 @@ function CreateRowActions({
onCancel,
onSubmit,
}: {
- control: Control<CreateTokenFormValues>;
+ control: Control<CreateTokenFormInput>;
isLoading: boolean;
onCancel: () => void;
onSubmit: () => void;
@@ -240,7 +240,7 @@ function EditRowActions({
onCancel,
onSubmit,
}: {
- control: Control<EditTokenFormValues>;
+ control: Control<EditTokenFormInput>;
isLoading: boolean;
onCancel: () => void;
onSubmit: () => void;
@@ -294,12 +294,12 @@ function SettingsAPITokens() {
// Form state lives in the parent so that subscription-driven DataTable
// re-renders and row remounts cannot drop user input. <Controller> in each
// cell re-subscribes to this state on remount — no values are lost.
- const createForm = useForm<CreateTokenFormValues>({
+ const createForm = useForm<CreateTokenFormInput, unknown, CreateTokenFormValues>({
defaultValues: CREATE_TOKEN_DEFAULTS,
mode: 'onChange',
resolver: zodResolver(createTokenFormSchema),
});
- const editForm = useForm<EditTokenFormValues>({
+ const editForm = useForm<EditTokenFormInput, unknown, EditTokenFormValues>({
defaultValues: EDIT_TOKEN_DEFAULTS,
mode: 'onChange',
resolver: zodResolver(editTokenFormSchema),
@@ -353,7 +353,7 @@ function SettingsAPITokens() {
refetchQueries: ['apiTokens'],
variables: {
input: {
- name: values.name.trim() || null,
+ name: values.name?.trim() || null,
status: values.status,
},
tokenId,
@@ -398,7 +398,7 @@ function SettingsAPITokens() {
refetchQueries: ['apiTokens'],
variables: {
input: {
- name: values.name.trim() || null,
+ name: values.name?.trim() || null,
ttl,
},
},
diff --git a/frontend/src/pages/settings/settings-prompt.tsx b/frontend/src/pages/settings/settings-prompt.tsx
index 9baea6f4..57ffcb0d 100644
--- a/frontend/src/pages/settings/settings-prompt.tsx
+++ b/frontend/src/pages/settings/settings-prompt.tsx
@@ -17,7 +17,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import ReactDiffViewer from 'react-diff-viewer-continued';
import {
type Control,
- type ControllerRenderProps,
+ type FieldPathByValue,
type FieldValues,
useController,
useForm,
@@ -26,7 +26,14 @@ import {
import { useNavigate, useParams } from 'react-router-dom';
import { z } from 'zod';
-import type { AgentPrompt, AgentPrompts, DefaultPrompt, PromptType, ValidatePromptMutation } from '@/graphql/types';
+import type {
+ DefaultPromptFragmentFragment as DefaultPrompt,
+ PromptType,
+ ValidatePromptMutation,
+} from '@/graphql/types';
+
+type AgentPrompt = AgentPrompts;
+type AgentPrompts = { human?: DefaultPrompt; system: DefaultPrompt };
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
@@ -56,7 +63,7 @@ const humanFormSchema = z.object({
template: z.string().min(1, 'Human template is required'),
});
-interface BaseFieldProps extends ControllerProps {
+interface BaseFieldProps<T extends FieldValues> extends ControllerProps<T> {
label?: string;
}
interface BaseTextareaProps {
@@ -64,13 +71,13 @@ interface BaseTextareaProps {
placeholder?: string;
}
-interface ControllerProps {
- control: Control<FieldValues>;
+interface ControllerProps<T extends FieldValues> {
+ control: Control<T>;
disabled?: boolean;
- name: string;
+ name: FieldPathByValue<T, string>;
}
-interface FormTextareaItemProps extends BaseFieldProps, BaseTextareaProps {
+interface FormTextareaItemProps<T extends FieldValues> extends BaseFieldProps<T>, BaseTextareaProps {
description?: string;
}
@@ -78,10 +85,16 @@ type HumanFormData = z.infer<typeof humanFormSchema>;
type SystemFormData = z.infer<typeof systemFormSchema>;
-function FormTextareaItem({ className, control, disabled, label, name, placeholder }: FormTextareaItemProps) {
+function FormTextareaItem<T extends FieldValues>({
+ className,
+ control,
+ disabled,
+ label,
+ name,
+ placeholder,
+}: FormTextareaItemProps<T>) {
const { field, fieldState } = useController({
control,
- defaultValue: '',
disabled,
name,
});
@@ -154,7 +167,7 @@ function SettingsPrompt() {
const handleVariableClick = (
variable: string,
- field: ControllerRenderProps<FieldValues, string>,
+ field: { onChange: (value: string) => void; value: string },
formId: string,
) => {
const textarea = document.querySelector(`#${formId} textarea`) as HTMLTextAreaElement;
@@ -262,7 +275,7 @@ function SettingsPrompt() {
},
});
- setValidationResult(result.data?.validatePrompt);
+ setValidationResult(result.data?.validatePrompt ?? null);
setValidationDialogOpen(true);
} catch (error) {
console.error('Validation error:', error);
@@ -743,7 +756,7 @@ function SettingsPrompt() {
<AlertCircle className="size-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>
- {mutationError instanceof Error ? (
+ {typeof mutationError !== 'string' ? (
mutationError.message
) : (
<div className="whitespace-pre-line">{mutationError}</div>
@@ -784,7 +797,7 @@ function SettingsPrompt() {
<AlertCircle className="size-4" />
<AlertTitle>Error</AlertTitle>
<AlertDescription>
- {mutationError instanceof Error ? (
+ {typeof mutationError !== 'string' ? (
mutationError.message
) : (
<div className="whitespace-pre-line">{mutationError}</div>
diff --git a/frontend/src/pages/settings/settings-prompts.tsx b/frontend/src/pages/settings/settings-prompts.tsx
index dabde325..5b4e3362 100644
--- a/frontend/src/pages/settings/settings-prompts.tsx
+++ b/frontend/src/pages/settings/settings-prompts.tsx
@@ -19,7 +19,10 @@ import {
import { Fragment, useState } from 'react';
import { useNavigate } from 'react-router-dom';
-import type { AgentPrompt, AgentPrompts, DefaultPrompt, PromptType } from '@/graphql/types';
+import type { DefaultPromptFragmentFragment as DefaultPrompt, PromptType } from '@/graphql/types';
+
+type AgentPrompt = AgentPrompts;
+type AgentPrompts = { human?: DefaultPrompt; system: DefaultPrompt };
import ConfirmationDialog from '@/components/shared/confirmation-dialog';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
index ffe29ae4..dd64c17e 100644
--- a/frontend/tsconfig.app.json
+++ b/frontend/tsconfig.app.json
@@ -20,7 +20,7 @@
"noEmit": true,
/* If your code runs in the DOM: */
- "lib": ["es2022", "dom", "dom.iterable"],
+ "lib": ["es2023", "dom", "dom.iterable"],
"jsx": "react-jsx",
"paths": {