Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Migrate api key table to design-system components (#17791)

Ben Bachemfcdccf61324c
diff --git a/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx b/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx
index d2737f87c1..91075fb82a 100644
--- a/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx
+++ b/web/src/components/design-system/table/columns/createTextTableColumn.stories.tsx
@@ -1,3 +1,6 @@
+import { Pencil } from "lucide-react";
+import { fn } from "storybook/test";
+
import preview from "../../../../../.storybook/preview";
import {
@@ -16,15 +19,23 @@ const columns = [
createTextTableColumn<Row>({
id: "name",
accessorFn: (row) => row.name,
- header: "Text",
+ header: "Copyable text",
+ trailingAction: { type: "copy-to-clipboard" },
}),
createTextTableColumn<Row, number>({
accessorKey: "count",
- header: "Mapped text",
+ header: "Mapped text with action",
mapValue: (value, { row }) =>
row.original.isCountLoading
? { type: "loading" }
: value?.toLocaleString(),
+ nullValue: "—",
+ trailingAction: {
+ type: "custom",
+ icon: Pencil,
+ label: "Edit value",
+ onClick: fn(),
+ },
}),
];
diff --git a/web/src/components/design-system/table/columns/createTextTableColumn.tsx b/web/src/components/design-system/table/columns/createTextTableColumn.tsx
index bdfff2df81..c8d2b95a94 100644
--- a/web/src/components/design-system/table/columns/createTextTableColumn.tsx
+++ b/web/src/components/design-system/table/columns/createTextTableColumn.tsx
@@ -1,7 +1,11 @@
/* eslint-disable boundaries/dependencies */
import { type CellContext, type RowData } from "@tanstack/react-table";
+import { Check, Copy, type LucideIcon } from "lucide-react";
+import { type ReactNode } from "react";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
import { Skeleton } from "@/src/components/ui/skeleton";
+import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";
import {
createTableColumn,
type TableColumnOptions,
@@ -20,11 +24,26 @@ type TextTableColumnOptions<TData extends RowData, TValue> = TableColumnOptions<
? { mapValue?: TextValueMapper<TData, TValue> }
: { mapValue: TextValueMapper<TData, TValue> });
+type TextTableColumnTrailingAction<TData extends RowData, TValue> =
+ | {
+ type: "copy-to-clipboard";
+ }
+ | {
+ type: "custom";
+ icon: LucideIcon;
+ label: string;
+ onClick: (context: CellContext<TData, TValue>) => void;
+ };
+
export function createTextTableColumn<TData extends RowData, TValue = string>({
mapValue,
nullValue,
+ trailingAction,
...options
-}: TextTableColumnOptions<TData, TValue> & { nullValue?: string }) {
+}: TextTableColumnOptions<TData, TValue> & {
+ nullValue?: string;
+ trailingAction?: TextTableColumnTrailingAction<TData, TValue>;
+}) {
const loadingCell = <Skeleton className="h-4 w-1/2" />;
return createTableColumn<TData, TValue>({
@@ -34,19 +53,118 @@ export function createTextTableColumn<TData extends RowData, TValue = string>({
const text = mapValue ? mapValue(value, context) : value;
if (text === null || text === undefined) {
- return nullValue ? (
- <span className="block w-full truncate" title={nullValue}>
- {nullValue}
- </span>
- ) : null;
+ if (!trailingAction)
+ return nullValue ? <Text value={nullValue} /> : null;
+ if (trailingAction.type === "copy-to-clipboard") {
+ return nullValue ? <CopyableText value={nullValue} /> : null;
+ }
+
+ return (
+ <TextWithTrailingAction
+ value={nullValue}
+ action={trailingAction}
+ context={context}
+ />
+ );
}
if (typeof text !== "string") return loadingCell;
- return (
- <span className="block w-full truncate" title={text}>
- {text}
- </span>
- );
+ if (trailingAction?.type === "copy-to-clipboard") {
+ return <CopyableText value={text} />;
+ }
+ if (trailingAction?.type === "custom") {
+ return (
+ <TextWithTrailingAction
+ value={text}
+ action={trailingAction}
+ context={context}
+ />
+ );
+ }
+
+ return <Text value={text} />;
},
});
}
+
+function TextWithTrailingAction<TData extends RowData, TValue>({
+ action,
+ context,
+ value,
+}: {
+ action: Extract<
+ TextTableColumnTrailingAction<TData, TValue>,
+ { type: "custom" }
+ >;
+ context: CellContext<TData, TValue>;
+ value?: string;
+}) {
+ return (
+ <TextWithAction
+ value={value}
+ action={
+ <IconButton
+ icon={action.icon}
+ label={action.label}
+ size="xs"
+ onClick={() => action.onClick(context)}
+ />
+ }
+ />
+ );
+}
+
+function TextWithAction({
+ action,
+ value,
+}: {
+ action: ReactNode;
+ value?: string;
+}) {
+ return (
+ <div className="flex w-full min-w-0 items-center gap-1">
+ {value ? (
+ <span className="min-w-0 truncate" title={value}>
+ {value}
+ </span>
+ ) : null}
+ <span className="shrink-0 p-1">{action}</span>
+ </div>
+ );
+}
+
+function Text({ value }: { value: string }) {
+ return (
+ <span className="block w-full truncate" title={value}>
+ {value}
+ </span>
+ );
+}
+
+function CopyableText({ value }: { value: string }) {
+ const { copy, isCopied } = useCopyToClipboard();
+
+ return (
+ <TextWithAction
+ value={value}
+ action={
+ <IconButton
+ icon={isCopied ? Check : Copy}
+ label={isCopied ? "Copied" : "Copy to clipboard"}
+ size="xs"
+ title="Copy to clipboard"
+ onClick={async (event) => {
+ const button = event.currentTarget;
+ try {
+ await copy(value);
+ } catch {
+ // Clipboard failures are intentionally silent.
+ } finally {
+ button.focus();
+ }
+ }}
+ />
+ }
+ />
+ );
+}
diff --git a/web/src/components/design-system/table/columns/createUserTableColumn.stories.tsx b/web/src/components/design-system/table/columns/createUserTableColumn.stories.tsx
index 7d35dcc154..a46b0abbad 100644
--- a/web/src/components/design-system/table/columns/createUserTableColumn.stories.tsx
+++ b/web/src/components/design-system/table/columns/createUserTableColumn.stories.tsx
@@ -21,6 +21,7 @@ const avatarColumns = [
header: "User",
variant: "avatar",
emptyValue: "Unknown",
+ nullValue: "—",
getUser: (user, { row }) => {
if (row.original.isUserLoading) return { type: "loading" };
if (!user) return undefined;
diff --git a/web/src/components/design-system/table/columns/createUserTableColumn.tsx b/web/src/components/design-system/table/columns/createUserTableColumn.tsx
index 5f5506c5ce..82c153e61b 100644
--- a/web/src/components/design-system/table/columns/createUserTableColumn.tsx
+++ b/web/src/components/design-system/table/columns/createUserTableColumn.tsx
@@ -79,7 +79,14 @@ export function createUserTableColumn<
cell = { type: "user", user: value };
}
- if (!cell) return null;
+ if (!cell) {
+ const placeholder = nullValue ?? emptyValue;
+ return placeholder ? (
+ <span className="block w-full truncate" title={placeholder}>
+ {placeholder}
+ </span>
+ ) : null;
+ }
if (cell.type === "loading") return loadingCell;
const { name, email, image, id } = cell.user;
@@ -94,9 +101,14 @@ export function createUserTableColumn<
}
return (
- <div className="flex items-center space-x-2">
+ <div
+ className="flex min-w-0 items-center space-x-2"
+ title={email ?? label}
+ >
<Avatar size="md" src={image ?? undefined} displayName={label} />
- <span>{label}</span>
+ <span className="truncate" title={email ?? label}>
+ {label}
+ </span>
</div>
);
},
diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsx
index 6ca92cc5bd..b154a9c5f4 100644
--- a/web/src/features/public-api/components/ApiKeyList.tsx
+++ b/web/src/features/public-api/components/ApiKeyList.tsx
@@ -1,41 +1,17 @@
-/* eslint-disable @repo/no-null-render */
+import startCase from "lodash/startCase";
+
+import { Alert } from "@/src/components/design-system/Alert/Alert";
import Header from "@/src/components/layouts/header";
-import { Button } from "@/src/components/ui/button";
-import { Card } from "@/src/components/ui/card";
import { CodeView } from "@/src/components/ui/CodeJsonViewer";
-import { Input } from "@/src/components/ui/input";
-import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";
-import { SimpleDataTable } from "@/src/components/table/simple-data-table";
-import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { CreateApiKeyButton } from "@/src/features/public-api/components/CreateApiKeyButton";
+import { ConnectedApiKeySettingsTable } from "@/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable";
+import { useLangfuseEnvCode } from "@/src/features/public-api/hooks/useLangfuseEnvCode";
import {
useHasOrganizationAccess,
useHasProjectAccess,
} from "@/src/features/rbac";
-import { api, reportNonTrpcError } from "@/src/utils/api";
-import { Check, Copy, TrashIcon } from "lucide-react";
-import { useMemo, useState } from "react";
-import { Alert } from "@/src/components/design-system/Alert/Alert";
-import startCase from "lodash/startCase";
-import { useLangfuseEnvCode } from "@/src/features/public-api/hooks/useLangfuseEnvCode";
-import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";
-import { type RouterOutput } from "@/src/utils/types";
type ApiKeyScope = "project" | "organization";
-type ApiKeyRow =
- | RouterOutput["projectApiKeys"]["byProjectId"][number]
- | RouterOutput["organizationApiKeys"]["byOrganizationId"][number];
-type ApiKeyEntity = { id: string; note: string | null };
-type ApiKeyCreator = {
- createdByUser: {
- id: string;
- name: string | null;
- email: string | null;
- } | null;
- createdByApiKey: { id: string; publicKey: string } | null;
-};
export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {
const { entityId, scope } = props;
@@ -47,85 +23,23 @@ export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {
);
}
- // Viewing the list only needs apiKeys:read, which project MEMBERs hold.
- // Create, delete, and note editing stay behind apiKeys:CUD.
const hasProjectReadAccess = useHasProjectAccess({
- projectId: props.entityId,
+ projectId: entityId,
scope: "apiKeys:read",
});
const hasProjectWriteAccess = useHasProjectAccess({
- projectId: props.entityId,
+ projectId: entityId,
scope: "apiKeys:CUD",
});
const hasOrganizationAccess = useHasOrganizationAccess({
- organizationId: props.entityId,
+ organizationId: entityId,
scope: "organization:CRUD_apiKeys",
});
const hasAccess =
- props.scope === "project" ? hasProjectReadAccess : hasOrganizationAccess;
- const hasCreateAccess =
- props.scope === "project" ? hasProjectWriteAccess : hasOrganizationAccess;
-
- const projectApiKeysQuery = api.projectApiKeys.byProjectId.useQuery(
- { projectId: entityId },
- { enabled: hasProjectReadAccess && props.scope === "project" },
- );
- const organizationApiKeysQuery =
- api.organizationApiKeys.byOrganizationId.useQuery(
- { orgId: entityId },
- { enabled: hasOrganizationAccess && props.scope === "organization" },
- );
- const apiKeysQuery =
- props.scope === "project" ? projectApiKeysQuery : organizationApiKeysQuery;
-
- const columns = useMemo<LangfuseColumnDef<ApiKeyRow>[]>(
- () => [
- createTextTableColumn<ApiKeyRow, Date>({
- accessorKey: "createdAt",
- header: "Created",
- mapValue: (value) => value?.toLocaleDateString(),
- hideBelowMd: true,
- }),
- {
- accessorKey: "createdByUser",
- header: "Created By",
- hideBelowMd: true,
- cell: ({ row }) => <ApiKeyCreatedBy apiKey={row.original} />,
- },
- {
- accessorKey: "note",
- header: "Note",
- cell: ({ row }) => (
- <ApiKeyNote apiKey={row.original} entityId={entityId} scope={scope} />
- ),
- },
- {
- accessorKey: "publicKey",
- header: "Public Key",
- cell: ({ row }) => <PublicKeyCell publicKey={row.original.publicKey} />,
- },
- {
- accessorKey: "displaySecretKey",
- header: "Secret Key",
- cell: ({ getValue }) => (
- <span className="font-mono">{getValue<string>()}</span>
- ),
- },
- {
- accessorKey: "id",
- header: "",
- cell: ({ row }) => (
- <DeleteApiKeyButton
- entityId={entityId}
- apiKeyId={row.original.id}
- scope={scope}
- />
- ),
- },
- ],
- [entityId, scope],
- );
+ scope === "project" ? hasProjectReadAccess : hasOrganizationAccess;
+ const hasWriteAccess =
+ scope === "project" ? hasProjectWriteAccess : hasOrganizationAccess;
if (!hasAccess) {
return (
@@ -153,7 +67,7 @@ export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {
: "https://langfuse.com/docs/api#org-scoped-routes",
}}
actionButtons={
- hasCreateAccess ? (
+ hasWriteAccess ? (
<CreateApiKeyButton entityId={entityId} scope={scope} />
) : undefined
}
@@ -163,232 +77,11 @@ export function ApiKeyList(props: { entityId: string; scope: ApiKeyScope }) {
title=".env"
copiedToClipboardMessage="Secrets are not included, create a new key to copy them."
/>
- <Card className="mb-4 overflow-hidden">
- <SimpleDataTable
- columns={columns}
- data={apiKeysQuery.data ?? []}
- isLoading={apiKeysQuery.isLoading}
- noResults={
- apiKeysQuery.isError ? (
- <span className="text-destructive">
- Failed to load API keys. Please try again.
- </span>
- ) : (
- "None"
- )
- }
- bodyTone="muted"
- rowVariant="primary-hover"
- />
- </Card>
- </div>
- );
-}
-
-function PublicKeyCell({ publicKey }: { publicKey: string }) {
- const { copy, isCopied } = useCopyToClipboard();
-
- return (
- <div className="relative min-w-0 truncate pr-8 font-mono" title={publicKey}>
- <span>{publicKey}</span>
- <Button
- variant="ghost"
- size="icon-xs"
- className="absolute top-1/2 right-2 -translate-y-1/2"
- title="Copy to clipboard"
- aria-label="Copy to clipboard"
- onClick={async (event) => {
- event.preventDefault();
- const button = event.currentTarget;
- try {
- await copy(publicKey);
- } catch {
- // Clipboard failures are intentionally silent.
- }
- button.focus();
- }}
- >
- {isCopied ? (
- <Check className="h-3 w-3" />
- ) : (
- <Copy className="h-3 w-3" />
- )}
- </Button>
- </div>
- );
-}
-
-// show dialog to let user confirm that this is a destructive action
-function DeleteApiKeyButton(props: {
- entityId: string;
- apiKeyId: string;
- scope: ApiKeyScope;
-}) {
- const { entityId, apiKeyId, scope } = props;
- const capture = usePostHogClientCapture();
-
- const hasProjectAccess = useHasProjectAccess({
- projectId: props.entityId,
- scope: "apiKeys:CUD",
- });
- const hasOrganizationAccess = useHasOrganizationAccess({
- organizationId: props.entityId,
- scope: "organization:CRUD_apiKeys",
- });
-
- const hasAccess =
- props.scope === "project" ? hasProjectAccess : hasOrganizationAccess;
-
- const utils = api.useUtils();
-
- const mutDeleteProjectApiKey = api.projectApiKeys.delete.useMutation({
- onSuccess: () => utils.projectApiKeys.invalidate(),
- });
- const mutDeleteOrgApiKey = api.organizationApiKeys.delete.useMutation({
- onSuccess: () => utils.organizationApiKeys.invalidate(),
- });
-
- const [open, setOpen] = useState(false);
-
- if (!hasAccess) return null;
-
- const handleDelete = () => {
- if (scope === "project") {
- mutDeleteProjectApiKey
- .mutateAsync({
- projectId: entityId,
- id: apiKeyId,
- })
- .then(() => {
- capture(`${scope}_settings:api_key_delete`);
- setOpen(false);
- })
- .catch((error) => reportNonTrpcError(error, "api-keys"));
- } else {
- mutDeleteOrgApiKey
- .mutateAsync({
- orgId: entityId,
- id: apiKeyId,
- })
- .then(() => {
- capture(`${scope}_settings:api_key_delete`);
- setOpen(false);
- })
- .catch((error) => reportNonTrpcError(error, "api-keys"));
- }
- };
-
- return (
- <ConfirmDialog
- open={open}
- onOpenChange={setOpen}
- trigger={
- <Button variant="ghost" size="icon">
- <TrashIcon className="h-4 w-4" />
- </Button>
- }
- title="Delete API key"
- description="Are you sure you want to delete this API key? This action cannot be undone."
- confirmLabel="Permanently delete"
- loading={mutDeleteOrgApiKey.isPending || mutDeleteProjectApiKey.isPending}
- onConfirm={handleDelete}
- />
- );
-}
-
-function ApiKeyCreatedBy({ apiKey }: { apiKey: ApiKeyCreator }) {
- if (apiKey.createdByUser) {
- const { name, email } = apiKey.createdByUser;
- return (
- <span className="truncate" title={email ?? undefined}>
- {name ?? email ?? "Unknown user"}
- </span>
- );
- }
- if (apiKey.createdByApiKey) {
- return (
- <span
- className="truncate font-mono"
- title={`Created via API by key ${apiKey.createdByApiKey.publicKey}`}
- >
- {apiKey.createdByApiKey.publicKey}
- </span>
- );
- }
- return <span>—</span>;
-}
-
-function ApiKeyNote({
- apiKey,
- entityId,
- scope,
-}: {
- apiKey: ApiKeyEntity;
- entityId: string;
- scope: ApiKeyScope;
-}) {
- const utils = api.useUtils();
-
- const hasProjectAccess = useHasProjectAccess({
- projectId: entityId,
- scope: "apiKeys:CUD",
- });
- const hasOrganizationAccess = useHasOrganizationAccess({
- organizationId: entityId,
- scope: "organization:CRUD_apiKeys",
- });
- const hasEditAccess =
- scope === "project" ? hasProjectAccess : hasOrganizationAccess;
-
- const mutUpdateProjectApiKey = api.projectApiKeys.updateNote.useMutation({
- onSuccess: () => utils.projectApiKeys.invalidate(),
- });
- const mutUpdateOrgApiKey = api.organizationApiKeys.updateNote.useMutation({
- onSuccess: () => utils.organizationApiKeys.invalidate(),
- });
-
- const [note, setNote] = useState(apiKey.note ?? "");
- const [isEditing, setIsEditing] = useState(false);
-
- const handleBlur = () => {
- setIsEditing(false);
- if (note !== apiKey.note) {
- if (scope === "project") {
- mutUpdateProjectApiKey.mutate({
- projectId: entityId,
- keyId: apiKey.id,
- note,
- });
- } else {
- mutUpdateOrgApiKey.mutate({
- orgId: entityId,
- keyId: apiKey.id,
- note,
- });
- }
- }
- };
-
- if (!hasEditAccess) return note ?? "";
-
- if (isEditing) {
- return (
- <Input
- value={note}
- onChange={(e) => setNote(e.target.value)}
- onBlur={handleBlur}
- autoFocus
- className="h-8"
+ <ConnectedApiKeySettingsTable
+ entityId={entityId}
+ scope={scope}
+ hasWriteAccess={hasWriteAccess}
/>
- );
- }
-
- return (
- <div
- onClick={() => setIsEditing(true)}
- className="hover:bg-secondary/50 -mx-2 cursor-pointer rounded px-2 py-1"
- >
- {note || "Click to add note"}
</div>
);
}
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx
new file mode 100644
index 0000000000..b2d679954d
--- /dev/null
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.stories.tsx
@@ -0,0 +1,45 @@
+import { fn } from "storybook/test";
+
+import preview from "../../../../../.storybook/preview";
+import { ApiKeySettingsTable } from "./ApiKeySettingsTable";
+
+const meta = preview.meta({ component: ApiKeySettingsTable });
+
+export const Default = meta.story({
+ args: {
+ editNoteAction: { hasAccess: true, onClick: fn() },
+ hasWriteAccess: true,
+ onDelete: fn(),
+ data: {
+ status: "success",
+ data: [
+ {
+ id: "key-1",
+ createdAt: new Date("2026-09-01"),
+ expiresAt: null,
+ lastUsedAt: null,
+ note: "Production key",
+ publicKey: "pk-lf-1234",
+ displaySecretKey: "sk-lf-...5678",
+ createdByUser: {
+ id: "user-1",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ image: "https://i.pravatar.cc/[email protected]",
+ },
+ createdByApiKey: null,
+ },
+ ],
+ },
+ },
+});
+
+export const Loading = meta.story({
+ args: {
+ editNoteAction: { hasAccess: true, onClick: fn() },
+ hasWriteAccess: true,
+ onDelete: fn(),
+ data: { status: "loading" },
+ loadingRowCount: 5,
+ },
+});
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
new file mode 100644
index 0000000000..a6ae4b317d
--- /dev/null
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ApiKeySettingsTable.tsx
@@ -0,0 +1,121 @@
+import { useCallback, useMemo } from "react";
+import { Pencil, Trash } from "lucide-react";
+
+import { type TableProps } from "@/src/components/design-system/table/Table";
+import { createDateTableColumn } from "@/src/components/design-system/table/columns/createDateTableColumn";
+import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";
+import { createUserTableColumn } from "@/src/components/design-system/table/columns/createUserTableColumn";
+import { SettingsTable } from "@/src/components/SettingsTable/SettingsTable";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { type RouterOutput } from "@/src/utils/types";
+
+export type ApiKeySettingsTableRow =
+ | RouterOutput["projectApiKeys"]["byProjectId"][number]
+ | RouterOutput["organizationApiKeys"]["byOrganizationId"][number];
+
+export function ApiKeySettingsTable({
+ editNoteAction,
+ hasWriteAccess,
+ onDelete,
+ ...tableProps
+}: Pick<
+ TableProps<ApiKeySettingsTableRow>,
+ "data" | "loadingRowCount" | "noResultsMessage"
+> & {
+ editNoteAction: {
+ hasAccess: boolean;
+ onClick: (apiKey: ApiKeySettingsTableRow) => void;
+ };
+ hasWriteAccess: boolean;
+ onDelete: (apiKey: ApiKeySettingsTableRow) => void;
+}) {
+ const columns = useMemo<LangfuseColumnDef<ApiKeySettingsTableRow>[]>(
+ () => [
+ createDateTableColumn<ApiKeySettingsTableRow>({
+ accessorKey: "createdAt",
+ header: "Created",
+ hideBelowMd: true,
+ enableResizing: false,
+ }),
+ createUserTableColumn<ApiKeySettingsTableRow>({
+ accessorKey: "createdByUser",
+ header: "Created By",
+ variant: "avatar",
+ nullValue: "—",
+ hideBelowMd: true,
+ enableResizing: false,
+ getUser: (user, { row }) => {
+ if (user?.name || user?.email) return { type: "user", user };
+ if (user) {
+ return {
+ type: "user",
+ user: { name: "Unknown user", image: user.image },
+ };
+ }
+ if (row.original.createdByApiKey) {
+ return {
+ type: "user",
+ user: { name: row.original.createdByApiKey.publicKey },
+ };
+ }
+ return undefined;
+ },
+ }),
+ createTextTableColumn<ApiKeySettingsTableRow>({
+ id: "note",
+ accessorFn: (apiKey) => apiKey.note || null,
+ header: "Note",
+ enableResizing: false,
+ nullValue: "—",
+ trailingAction: editNoteAction.hasAccess
+ ? {
+ type: "custom",
+ icon: Pencil,
+ label: "Edit note",
+ onClick: ({ row }) => editNoteAction.onClick(row.original),
+ }
+ : undefined,
+ }),
+ createTextTableColumn<ApiKeySettingsTableRow>({
+ accessorKey: "publicKey",
+ header: "Public Key",
+ trailingAction: { type: "copy-to-clipboard" },
+ enableResizing: false,
+ }),
+ createTextTableColumn<ApiKeySettingsTableRow>({
+ accessorKey: "displaySecretKey",
+ header: "Secret Key",
+ enableResizing: false,
+ }),
+ ],
+ [editNoteAction],
+ );
+
+ const actions = useCallback<
+ NonNullable<TableProps<ApiKeySettingsTableRow>["actions"]>
+ >(
+ (apiKey) => [
+ {
+ id: "delete",
+ type: "item",
+ title: "Delete API key",
+ icon: Trash,
+ variant: "destructive",
+ disabled: hasWriteAccess
+ ? undefined
+ : { reason: "You do not have permission to delete this API key" },
+ onClick: () => onDelete(apiKey),
+ },
+ ],
+ [hasWriteAccess, onDelete],
+ );
+
+ return (
+ <SettingsTable
+ tableName="API keys"
+ columns={columns}
+ actions={actions}
+ {...tableProps}
+ />
+ );
+}
diff --git a/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx b/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx
new file mode 100644
index 0000000000..71c247f1cb
--- /dev/null
+++ b/web/src/features/public-api/components/ApiKeySettingsTable/ConnectedApiKeySettingsTable.tsx
@@ -0,0 +1,215 @@
+import { useId, useMemo, useRef, useState, type ReactNode } from "react";
+
+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";
+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { type AsyncTableData } from "@/src/components/design-system/table/Table";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
+import { api, reportNonTrpcError } from "@/src/utils/api";
+import {
+ ApiKeySettingsTable,
+ type ApiKeySettingsTableRow,
+} from "./ApiKeySettingsTable";
+
+type ApiKeyScope = "project" | "organization";
+
+export function ConnectedApiKeySettingsTable({
+ entityId,
+ scope,
+ hasWriteAccess,
+}: {
+ entityId: string;
+ scope: ApiKeyScope;
+ hasWriteAccess: boolean;
+}) {
+ const capture = usePostHogClientCapture();
+ const utils = api.useUtils();
+
+ const projectApiKeys = api.projectApiKeys.byProjectId.useQuery(
+ { projectId: entityId },
+ { enabled: scope === "project" },
+ );
+ const organizationApiKeys = api.organizationApiKeys.byOrganizationId.useQuery(
+ { orgId: entityId },
+ { enabled: scope === "organization" },
+ );
+ const apiKeys = scope === "project" ? projectApiKeys : organizationApiKeys;
+
+ const deleteProjectApiKey = api.projectApiKeys.delete.useMutation({
+ onSuccess: () => utils.projectApiKeys.invalidate(),
+ });
+ const deleteOrganizationApiKey = api.organizationApiKeys.delete.useMutation({
+ onSuccess: () => utils.organizationApiKeys.invalidate(),
+ });
+ const tableData = useMemo<AsyncTableData<ApiKeySettingsTableRow[]>>(() => {
+ if (apiKeys.isLoading) return { status: "loading" };
+ if (apiKeys.isError) {
+ return { status: "error", error: "Failed to load API keys" };
+ }
+ return { status: "success", data: apiKeys.data ?? [] };
+ }, [apiKeys.data, apiKeys.isError, apiKeys.isLoading]);
+
+ const deleteApiKey =
+ scope === "project" ? deleteProjectApiKey : deleteOrganizationApiKey;
+
+ return (
+ <ConnectedApiKeyNoteDialogController entityId={entityId} scope={scope}>
+ {({ openDialog: openEditNoteDialog }) => (
+ <ConfirmationDialogController<{ id: string }>
+ title="Delete API key"
+ text="Are you sure you want to delete this API key? This action cannot be undone."
+ confirmLabel="Permanently delete"
+ variant="destructive"
+ loading={deleteApiKey.isPending}
+ error={deleteApiKey.error?.message}
+ onAfterDismiss={deleteApiKey.reset}
+ onConfirm={async (apiKey) => {
+ try {
+ if (scope === "project") {
+ await deleteProjectApiKey.mutateAsync({
+ projectId: entityId,
+ id: apiKey.id,
+ });
+ } else {
+ await deleteOrganizationApiKey.mutateAsync({
+ orgId: entityId,
+ id: apiKey.id,
+ });
+ }
+ capture(`${scope}_settings:api_key_delete`);
+ } catch (error) {
+ reportNonTrpcError(error, "api-keys");
+ throw error;
+ }
+ }}
+ >
+ {({ openDialog: openDeleteDialog }) => (
+ <ApiKeySettingsTable
+ data={tableData}
+ editNoteAction={{
+ hasAccess: hasWriteAccess,
+ onClick: openEditNoteDialog,
+ }}
+ hasWriteAccess={hasWriteAccess}
+ onDelete={openDeleteDialog}
+ noResultsMessage="None"
+ />
+ )}
+ </ConfirmationDialogController>
+ )}
+ </ConnectedApiKeyNoteDialogController>
+ );
+}
+
+function ConnectedApiKeyNoteDialogController({
+ children,
+ entityId,
+ scope,
+}: {
+ children: (control: {
+ openDialog: (apiKey: ApiKeySettingsTableRow) => void;
+ }) => ReactNode;
+ entityId: string;
+ scope: ApiKeyScope;
+}) {
+ const utils = api.useUtils();
+ const instance = useRef(0);
+ const updateProjectApiKey = api.projectApiKeys.updateNote.useMutation({
+ onSuccess: () => utils.projectApiKeys.invalidate(),
+ });
+ const updateOrganizationApiKey =
+ api.organizationApiKeys.updateNote.useMutation({
+ onSuccess: () => utils.organizationApiKeys.invalidate(),
+ });
+ const updateApiKey =
+ scope === "project" ? updateProjectApiKey : updateOrganizationApiKey;
+
+ return (
+ <DialogController<ApiKeySettingsTableRow & { instance: number }>
+ onBeforeClose={() => !updateApiKey.isPending}
+ onDismiss={updateApiKey.reset}
+ renderDialog={({ state, closeDialog }) => (
+ <ApiKeyNoteDialog
+ key={state.instance}
+ apiKey={state}
+ error={updateApiKey.error?.message}
+ isPending={updateApiKey.isPending}
+ onSave={async (note) => {
+ try {
+ if (scope === "project") {
+ await updateProjectApiKey.mutateAsync({
+ projectId: entityId,
+ keyId: state.id,
+ note,
+ });
+ } else {
+ await updateOrganizationApiKey.mutateAsync({
+ orgId: entityId,
+ keyId: state.id,
+ note,
+ });
+ }
+ closeDialog();
+ } catch (error) {
+ reportNonTrpcError(error, "api-keys");
+ }
+ }}
+ />
+ )}
+ >
+ {({ openDialog }) =>
+ children({
+ openDialog: (apiKey) =>
+ openDialog({ ...apiKey, instance: ++instance.current }),
+ })
+ }
+ </DialogController>
+ );
+}
+
+function ApiKeyNoteDialog({
+ apiKey,
+ error,
+ isPending,
+ onSave,
+}: {
+ apiKey: ApiKeySettingsTableRow;
+ error?: string;
+ isPending: boolean;
+ onSave: (note: string) => Promise<void>;
+}) {
+ const inputId = useId();
+ const [note, setNote] = useState(apiKey.note ?? "");
+
+ return (
+ <Dialog
+ title="Edit API key note"
+ actions={[
+ {
+ label: "Save",
+ loading: isPending,
+ disabled: note === (apiKey.note ?? ""),
+ onClick: () => onSave(note),
+ },
+ ]}
+ >
+ <Dialog.Body>
+ <div className="grid gap-2">
+ <label htmlFor={inputId} className="text-sm leading-none font-bold">
+ Note
+ </label>
+ <Input
+ id={inputId}
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ disabled={isPending}
+ error={Boolean(error)}
+ autoFocus
+ />
+ </div>
+ {error ? <p className="text-destructive">{error}</p> : null}
+ </Dialog.Body>
+ </Dialog>
+ );
+}
diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.ts
index 2c099771b3..ef8b61b76b 100644
--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts
+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts
@@ -43,6 +43,7 @@ export const organizationApiKeysRouter = createTRPCRouter({
id: true,
name: true,
email: true,
+ image: true,
},
},
createdByApiKey: {
diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.ts
index 301059089c..d1fed03937 100644
--- a/web/src/features/public-api/server/projectApiKeyRouter.ts
+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts
@@ -43,6 +43,7 @@ export const projectApiKeysRouter = createTRPCRouter({
id: true,
name: true,
email: true,
+ image: true,
},
},
createdByApiKey: {