🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(web): Migrate gateway provider creds table to design system (#17985)
Ben Bachem687215e6497a
diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/GatewayProvidersPage.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/GatewayProvidersPage.tsxindex e88f647724..f22b157c5b 100644--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/GatewayProvidersPage.tsx+++ b/web/src/features/ai-gateway/components/GatewayProvidersPage/GatewayProvidersPage.tsx@@ -1,15 +1,16 @@-import { useState } from "react";-import { Pencil, Plus } from "lucide-react";+import { useRef, useState } from "react";+import { Plus } from "lucide-react";import Header from "@/src/components/layouts/header";import { Alert } from "@/src/components/design-system/Alert/Alert";+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { PaginationBar } from "@/src/components/design-system/PaginationBar/PaginationBar";import { Button } from "@/src/components/ui/button";import { Skeleton } from "@/src/components/ui/skeleton";-import { DeleteProviderDialog } from "@/src/features/ai-gateway/components/GatewayProvidersPage/components/DeleteProviderDialog";import { ProviderDialogController } from "@/src/features/ai-gateway/components/GatewayProvidersPage/components/ProviderDialogController/ProviderDialogController";-import { GatewayProvidersView } from "@/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView";-import { RetryProviderButton } from "@/src/features/ai-gateway/components/GatewayProvidersPage/components/RetryProviderButton";+import { ConnectedGatewayProvidersTable } from "@/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/ConnectedGatewayProvidersTable";import { buildGatewayModelsUrl } from "@/src/features/ai-gateway/fns/gatewayUrls/buildGatewayModelsUrl";+import type { GatewayConnection } from "@/src/features/ai-gateway/types/gatewayProvider";import { api, reportNonTrpcError } from "@/src/utils/api";export function GatewayProvidersPage({@@ -28,8 +29,48 @@ export function GatewayProvidersPage({const [retriedModelCounts, setRetriedModelCounts] = useState<Record<string, number>>({});+ const [pageIndex, setPageIndex] = useState(0);+ const [isReordering, setIsReordering] = useState(false);+ const reorderLock = useRef(false);const utils = api.useUtils();const reorder = api.aiGateway.reorderConnections.useMutation();+ const retry = api.aiGateway.retryConnection.useMutation();+ const remove = api.aiGateway.deleteConnection.useMutation();++ const retryConnection = async (connection: GatewayConnection) => {+ try {+ const result = await retry.mutateAsync({+ orgId: organizationId,+ id: connection.id,+ });+ if (result.success) {+ setRetriedModelCounts((current) => ({+ ...current,+ [connection.id]: result.models.length,+ }));+ }+ await utils.aiGateway.listConnections.invalidate({+ orgId: organizationId,+ });+ } catch (error) {+ reportNonTrpcError(error, "ai-gateway-providers");+ }+ };++ const deleteConnection = async (connection: GatewayConnection) => {+ try {+ await remove.mutateAsync({+ orgId: organizationId,+ id: connection.id,+ });+ await utils.aiGateway.listConnections.invalidate({+ orgId: organizationId,+ });+ } catch (error) {+ reportNonTrpcError(error, "ai-gateway-providers");+ throw error;+ }+ };if (connectionsQuery.isPending) {return <ProvidersSkeleton />;@@ -56,11 +97,16 @@ export function GatewayProvidersPage({);}- const connections =- connectionsQuery.data?.pages.flatMap((page) => page.data) ?? [];+ const pages = connectionsQuery.data?.pages ?? [];+ const visiblePageIndex = Math.min(pageIndex, Math.max(0, pages.length - 1));+ const allConnections = pages.flatMap((page) => page.data);+ const connections = pages[visiblePageIndex]?.data ?? [];+ const pageOffset = pages+ .slice(0, visiblePageIndex)+ .reduce((count, page) => count + page.data.length, 0);const modelCounts: Record<string, number | "loading"> = modelsQuery.isPending? Object.fromEntries(- connections+ allConnections.filter((connection) => connection.status === "ENABLED").map((connection) => [connection.id, "loading"]),)@@ -72,86 +118,126 @@ export function GatewayProvidersPage({Object.assign(modelCounts, retriedModelCounts);return (- <GatewayProvidersView- connections={connections}- modelCounts={modelCounts}- getModelsUrl={(connection) =>- buildGatewayModelsUrl(organizationId, connection.id)- }- hasMore={Boolean(connectionsQuery.hasNextPage)}- isLoadingMore={connectionsQuery.isFetchingNextPage}- onLoadMore={() => connectionsQuery.fetchNextPage()}- canReorder={!connectionsQuery.hasNextPage && !reorder.isPending}- onReorder={async (sourceId, targetId) => {- const sourceIndex = connections.findIndex(- (connection) => connection.id === sourceId,- );- const targetIndex = connections.findIndex(- (connection) => connection.id === targetId,- );- if (sourceIndex < 0 || targetIndex < 0) return false;- const connectionIds = connections.map((connection) => connection.id);- const [movedId] = connectionIds.splice(sourceIndex, 1);- if (!movedId) return false;- connectionIds.splice(targetIndex, 0, movedId);- try {- await reorder.mutateAsync({ orgId: organizationId, connectionIds });- await utils.aiGateway.listConnections.invalidate({- orgId: organizationId,- });- return true;- } catch (error) {- reportNonTrpcError(error, "ai-gateway-providers");- return false;+ <div className="flex flex-col gap-4">+ <Header+ title="Provider credentials"+ actionButtons={+ <ProviderDialogController organizationId={organizationId}>+ {({ openAddDialog }) => (+ <Button onClick={openAddDialog}>+ <Plus className="mr-1.5 size-4" />+ Add credential+ </Button>+ )}+ </ProviderDialogController>}- }}- createAction={- <ProviderDialogController organizationId={organizationId}>- {({ openDialog }) => (- <Button onClick={openDialog}>- <Plus className="mr-1.5 size-4" />- Add credential- </Button>- )}- </ProviderDialogController>- }- renderCredentialActions={(connection) => {- return (- <>- <RetryProviderButton- organizationId={organizationId}- connectionId={connection.id}- onModelsLoaded={(count) =>- setRetriedModelCounts((current) => ({- ...current,- [connection.id]: count,- }))- }- />- <ProviderDialogController- key={`${connection.id}:${connection.updatedAt.toISOString()}`}- organizationId={organizationId}- connection={connection}- >- {({ openDialog }) => (- <Button- size="icon-xs"- variant="ghost"- aria-label="Edit credential"- onClick={openDialog}- >- <Pencil className="size-4" />- </Button>- )}- </ProviderDialogController>- <DeleteProviderDialog- organizationId={organizationId}- connection={connection}- />- </>- );- }}- />+ />+ <p className="text-muted-foreground text-sm">+ Requests use the first compatible enabled credential in routing priority+ order. Credentials are validated against the provider when they are+ saved.+ </p>+ <ConfirmationDialogController<GatewayConnection>+ title="Delete provider credential"+ text={(connection) =>+ `Delete “${connection.name}”? Requests will immediately stop using it.`+ }+ confirmLabel="Delete credential"+ variant="destructive"+ loading={remove.isPending}+ onConfirm={deleteConnection}+ >+ {({ openDialog: openDeleteDialog }) => (+ <ProviderDialogController organizationId={organizationId}>+ {({ openEditDialog }) => (+ <div className="flex max-h-[60dvh] flex-col overflow-hidden">+ <ConnectedGatewayProvidersTable+ connections={connections}+ pageOffset={pageOffset}+ previousConnectionId={allConnections[pageOffset - 1]?.id}+ nextConnectionId={+ allConnections[pageOffset + connections.length]?.id+ }+ modelCounts={modelCounts}+ getModelsUrl={(connection) =>+ buildGatewayModelsUrl(organizationId, connection.id)+ }+ canReorder={!connectionsQuery.hasNextPage && !isReordering}+ onReorder={async (sourceId, targetId) => {+ if (reorderLock.current) return false;+ const sourceIndex = allConnections.findIndex(+ (connection) => connection.id === sourceId,+ );+ const targetIndex = allConnections.findIndex(+ (connection) => connection.id === targetId,+ );+ if (sourceIndex < 0 || targetIndex < 0) return false;+ reorderLock.current = true;+ setIsReordering(true);+ const connectionIds = allConnections.map(+ (connection) => connection.id,+ );+ const [movedId] = connectionIds.splice(sourceIndex, 1);+ if (!movedId) return false;+ connectionIds.splice(targetIndex, 0, movedId);+ try {+ await reorder.mutateAsync({+ orgId: organizationId,+ connectionIds,+ });+ await utils.aiGateway.listConnections.invalidate({+ orgId: organizationId,+ });+ if (+ Math.floor(sourceIndex / 50) !==+ Math.floor(targetIndex / 50)+ ) {+ setPageIndex(Math.floor(targetIndex / 50));+ }+ return true;+ } catch (error) {+ reportNonTrpcError(error, "ai-gateway-providers");+ return false;+ } finally {+ reorderLock.current = false;+ setIsReordering(false);+ }+ }}+ onRetry={retryConnection}+ retryDisabled={+ retry.isPending+ ? { reason: "Validation in progress" }+ : undefined+ }+ onEdit={openEditDialog}+ onDelete={openDeleteDialog}+ />+ </div>+ )}+ </ProviderDialogController>+ )}+ </ConfirmationDialogController>+ <PaginationBar+ mode="cursor"+ state={{ pageIndex: visiblePageIndex, pageSize: 50 }}+ hasNextPage={+ visiblePageIndex < pages.length - 1 ||+ Boolean(connectionsQuery.hasNextPage)+ }+ isLoadingNextPage={connectionsQuery.isFetchingNextPage}+ onChange={async (nextState) => {+ if (nextState.pageIndex < pages.length) {+ setPageIndex(nextState.pageIndex);+ return;+ }+ if (!connectionsQuery.hasNextPage) return;+ const result = await connectionsQuery.fetchNextPage();+ if (result.data?.pages[nextState.pageIndex]) {+ setPageIndex(nextState.pageIndex);+ }+ }}+ />+ </div>);}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/DeleteProviderDialog.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/DeleteProviderDialog.tsxdeleted file mode 100644index 7738219ca2..0000000000--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/DeleteProviderDialog.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { useState } from "react";-import { Trash2 } from "lucide-react";--import { Button } from "@/src/components/ui/button";-import { ConfirmDialog } from "@/src/components/ui/confirm-dialog";-import type { GatewayConnection } from "@/src/features/ai-gateway/types/gatewayProvider";-import { api, reportNonTrpcError } from "@/src/utils/api";--export function DeleteProviderDialog({- organizationId,- connection,-}: {- organizationId: string;- connection: GatewayConnection;-}) {- const [open, setOpen] = useState(false);- const utils = api.useUtils();- const remove = api.aiGateway.deleteConnection.useMutation();-- const deleteConnection = async () => {- try {- await remove.mutateAsync({- orgId: organizationId,- id: connection.id,- });- await utils.aiGateway.listConnections.invalidate({- orgId: organizationId,- });- setOpen(false);- } catch (error) {- reportNonTrpcError(error, "ai-gateway-providers");- }- };-- return (- <ConfirmDialog- open={open}- onOpenChange={setOpen}- trigger={- <Button size="icon-xs" variant="ghost" aria-label="Delete credential">- <Trash2 className="size-4" />- </Button>- }- title="Delete provider credential"- description={`Delete “${connection.name}”? Requests will immediately stop using it.`}- confirmLabel="Delete credential"- loading={remove.isPending}- onConfirm={deleteConnection}- />- );-}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/ConnectedGatewayProvidersTable.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/ConnectedGatewayProvidersTable.tsxnew file mode 100644index 0000000000..6dfc1a5b4c--- /dev/null+++ b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/ConnectedGatewayProvidersTable.tsx@@ -0,0 +1,59 @@+import { useState } from "react";++import { reorderProviderIds } from "@/src/features/ai-gateway/fns/providerReorder/reorderProviderIds";+import {+ GatewayProvidersTable,+ type GatewayProvidersTableProps,+} from "./GatewayProvidersTable";++type Props = Omit<GatewayProvidersTableProps, "onMove"> & {+ onReorder: (sourceId: string, targetId: string) => Promise<boolean>;+};++export function ConnectedGatewayProvidersTable(props: Props) {+ const { onReorder, ...tableProps } = props;+ const serverOrderKey = JSON.stringify(+ props.connections.map((connection) => connection.id),+ );+ const [optimisticOrder, setOptimisticOrder] = useState<{+ base: string;+ ids: string[];+ } | null>(null);+ const serverIds = props.connections.map((connection) => connection.id);+ const sameMembers =+ optimisticOrder &&+ JSON.stringify([...optimisticOrder.ids].sort()) ===+ JSON.stringify([...serverIds].sort());+ const orderedIds =+ optimisticOrder &&+ sameMembers &&+ (serverOrderKey === optimisticOrder.base ||+ serverOrderKey === JSON.stringify(optimisticOrder.ids))+ ? optimisticOrder.ids+ : serverIds;+ const connections = props.connections.toSorted(+ (left, right) => orderedIds.indexOf(left.id) - orderedIds.indexOf(right.id),+ );++ const onMove = async (sourceId: string, targetId: string) => {+ const previousIds = orderedIds;+ const nextIds = reorderProviderIds(previousIds, sourceId, targetId);+ if (nextIds === previousIds) {+ if (sourceId !== targetId) await onReorder(sourceId, targetId);+ return;+ }++ setOptimisticOrder({ base: serverOrderKey, ids: nextIds });+ if (!(await onReorder(sourceId, targetId))) {+ setOptimisticOrder(null);+ }+ };++ return (+ <GatewayProvidersTable+ {...tableProps}+ connections={connections}+ onMove={onMove}+ />+ );+}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.clienttest.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.clienttest.tsxnew file mode 100644index 0000000000..6e05482128--- /dev/null+++ b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.clienttest.tsx@@ -0,0 +1,147 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import type { GatewayConnection } from "@/src/features/ai-gateway/types/gatewayProvider";+import { ConnectedGatewayProvidersTable } from "./ConnectedGatewayProvidersTable";++const connections = ["Alpha", "Beta"].map((name, index) => ({+ id: name.toLowerCase(),+ name,+ provider: "OPENAI" as const,+ displaySecret: "sk-...test",+ status: "ENABLED" as const,+ organizationId: "org-1",+ createdById: "user-1",+ routingPriority: index,+ createdAt: new Date("2026-09-08T12:00:00.000Z"),+ updatedAt: new Date("2026-09-08T12:00:00.000Z"),+})) satisfies GatewayConnection[];++describe("gateway providers table", () => {+ it("renders priority first and exposes a table actions menu", () => {+ render(+ <ConnectedGatewayProvidersTable+ connections={connections}+ pageOffset={0}+ modelCounts={{}}+ getModelsUrl={(connection) => `/models/${connection.id}`}+ onRetry={() => {}}+ onEdit={() => {}}+ onDelete={() => {}}+ canReorder+ onReorder={async () => true}+ />,+ );++ expect(screen.getAllByRole("columnheader")[0]).toHaveTextContent(+ "Priority",+ );+ expect(+ screen.getAllByRole("button", { name: "Open actions menu" }),+ ).toHaveLength(2);+ });++ it("keeps a successful move through a stale refresh and shows absolute priorities", async () => {+ const onReorder = vi.fn(async () => true);+ const props = {+ connections,+ pageOffset: 50,+ modelCounts: {},+ getModelsUrl: (connection: GatewayConnection) =>+ `/models/${connection.id}`,+ onRetry: () => {},+ onEdit: () => {},+ onDelete: () => {},+ canReorder: true,+ onReorder,+ };+ const { rerender } = render(<ConnectedGatewayProvidersTable {...props} />);++ expect(screen.getAllByRole("row")[1]).toHaveTextContent("51");+ fireEvent.click(+ screen.getAllByRole("button", { name: "Move credential down" })[0]!,+ );+ await waitFor(() => expect(onReorder).toHaveBeenCalledOnce());+ rerender(+ <ConnectedGatewayProvidersTable+ {...props}+ connections={[...connections]}+ />,+ );+ expect(screen.getAllByRole("row")[1]).toHaveTextContent("Beta");+ expect(screen.getAllByRole("row")[1]).toHaveTextContent("51");++ rerender(+ <ConnectedGatewayProvidersTable+ {...props}+ connections={[...connections].reverse()}+ />,+ );+ expect(screen.getAllByRole("row")[1]).toHaveTextContent("Beta");+ });++ it("allows a boundary credential to move to the adjacent page", async () => {+ const onReorder = vi.fn(async () => true);+ render(+ <ConnectedGatewayProvidersTable+ connections={connections}+ pageOffset={50}+ previousConnectionId="previous-page"+ nextConnectionId="next-page"+ modelCounts={{}}+ getModelsUrl={(connection) => `/models/${connection.id}`}+ onRetry={() => {}}+ onEdit={() => {}}+ onDelete={() => {}}+ canReorder+ onReorder={onReorder}+ />,+ );++ fireEvent.click(+ screen.getAllByRole("button", { name: "Move credential up" })[0]!,+ );+ await waitFor(() =>+ expect(onReorder).toHaveBeenCalledWith("alpha", "previous-page"),+ );+ fireEvent.click(+ screen.getAllByRole("button", { name: "Move credential down" })[1]!,+ );+ await waitFor(() =>+ expect(onReorder).toHaveBeenCalledWith("beta", "next-page"),+ );+ });++ it("adopts a new server order that differs from an optimistic move", async () => {+ const gamma = { ...connections[0]!, id: "gamma", name: "Gamma" };+ const onReorder = vi.fn(async () => true);+ const props = {+ pageOffset: 0,+ modelCounts: {},+ getModelsUrl: (connection: GatewayConnection) =>+ `/models/${connection.id}`,+ onRetry: () => {},+ onEdit: () => {},+ onDelete: () => {},+ canReorder: true,+ onReorder,+ };+ const { rerender } = render(+ <ConnectedGatewayProvidersTable+ {...props}+ connections={[...connections, gamma]}+ />,+ );+ fireEvent.click(+ screen.getAllByRole("button", { name: "Move credential down" })[0]!,+ );+ await waitFor(() => expect(onReorder).toHaveBeenCalledOnce());+ rerender(+ <ConnectedGatewayProvidersTable+ {...props}+ connections={[gamma, ...connections]}+ />,+ );+ expect(screen.getAllByRole("row")[1]).toHaveTextContent("Gamma");+ });+});diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.stories.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.stories.tsxsimilarity index 56%rename from web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.stories.tsxrename to web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.stories.tsxindex a756f71b85..ba38edbecb 100644--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.stories.tsx+++ b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.stories.tsx@@ -1,15 +1,14 @@-import type { ComponentProps } from "react";+import { useState, type ComponentProps } from "react";import { Button } from "@/src/components/ui/button";import { expect, fn, userEvent } from "storybook/test";import preview from "@/.storybook/preview";-import { GatewayProvidersView } from "./GatewayProvidersView";+import { GatewayProvidersTable } from "./GatewayProvidersTable";+import { ConnectedGatewayProvidersTable } from "./ConnectedGatewayProvidersTable";-const meta = preview.meta({ component: GatewayProvidersView });+const meta = preview.meta({ component: GatewayProvidersTable });-const onCreate = fn();const onCredentialAction = fn();-const onLoadMore = fn();const onReorder = fn(async () => true);const connections = [@@ -37,7 +36,7 @@ const connections = [createdAt: new Date("2026-09-07T12:00:00.000Z"),updatedAt: new Date("2026-09-07T12:00:00.000Z"),},-] satisfies ComponentProps<typeof GatewayProvidersView>["connections"];+] satisfies ComponentProps<typeof GatewayProvidersTable>["connections"];const providers = ["OPENAI", "ANTHROPIC"] as const;const statuses = ["ENABLED", "ERROR", "DISABLED"] as const;@@ -52,7 +51,7 @@ const manyConnections = Array.from({ length: 30 }, (_, index) => ({routingPriority: index,createdAt: new Date(Date.UTC(2026, 8, 30 - index)),updatedAt: new Date("2026-09-30T12:00:00.000Z"),-})) satisfies ComponentProps<typeof GatewayProvidersView>["connections"];+})) satisfies ComponentProps<typeof GatewayProvidersTable>["connections"];const manyModelCounts = Object.fromEntries(manyConnections.map((connection, index) => [connection.id, index * 7 + 1]),@@ -61,31 +60,21 @@ const manyModelCounts = Object.fromEntries(const actions = {getModelsUrl: (connection) =>`/organization/org-1/settings/ai-gateway-models?connection=${connection.id}`,- createAction: <Button onClick={onCreate}>Add credential</Button>,- renderCredentialActions: (connection) => (- <Button- size="sm"- variant="ghost"- onClick={() => onCredentialAction(connection.id)}- >- Manage- </Button>- ),- hasMore: false,- isLoadingMore: false,- onLoadMore,+ onRetry: (connection) => onCredentialAction(connection.id),+ onEdit: (connection) => onCredentialAction(connection.id),+ onDelete: (connection) => onCredentialAction(connection.id),canReorder: true,- onReorder,+ pageOffset: 0,+ onMove: fn(),} satisfies Pick<- ComponentProps<typeof GatewayProvidersView>,+ ComponentProps<typeof GatewayProvidersTable>,| "getModelsUrl"- | "createAction"- | "renderCredentialActions"- | "hasMore"- | "isLoadingMore"- | "onLoadMore"+ | "onRetry"+ | "onEdit"+ | "onDelete"| "canReorder"- | "onReorder"+ | "onMove"+ | "pageOffset">;export const OrderedCredentials = meta.story({@@ -99,12 +88,11 @@ export const OrderedCredentials = meta.story({},});-export const ManyRowsWithMoreAvailable = meta.story({+export const ManyRows = meta.story({args: {connections: manyConnections,modelCounts: manyModelCounts,...actions,- hasMore: true,},});@@ -116,25 +104,6 @@ export const Empty = meta.story({},});-export const MoreAvailable = meta.story({- args: {- connections,- modelCounts: {},- ...actions,- hasMore: true,- },-});--export const LoadingMore = meta.story({- args: {- connections,- modelCounts: {},- ...actions,- hasMore: true,- isLoadingMore: true,- },-});-export const MovesImmediately = meta.story({name: "(Test) Moves Immediately",args: {@@ -142,6 +111,9 @@ export const MovesImmediately = meta.story({modelCounts: {},...actions,},+ render: (args) => (+ <ConnectedGatewayProvidersTable {...args} onReorder={onReorder} />+ ),play: async ({ canvas }) => {onReorder.mockClear();await userEvent.click(@@ -158,17 +130,52 @@ export const MovesImmediately = meta.story({},});-export const LoadsMore = meta.story({- name: "(Test) Loads More",+export const ResetsWhenServerOrderChanges = meta.story({+ name: "(Test) Resets When Server Order Changes",args: {- connections,+ connections: [+ ...connections,+ {+ ...connections[0]!,+ id: "connection-third",+ name: "Third",+ routingPriority: 2,+ },+ ],modelCounts: {},...actions,- hasMore: true,},+ render: (args) => <ServerOrderExample {...args} />,play: async ({ canvas }) => {- onLoadMore.mockClear();- await userEvent.click(canvas.getByRole("button", { name: "Load more" }));- await expect(onLoadMore).toHaveBeenCalledOnce();+ await userEvent.click(+ canvas.getAllByRole("button", { name: "Move credential down" })[0]!,+ );+ await expect(canvas.getAllByRole("row")[1]).toHaveTextContent("Fallback");+ await userEvent.click(+ canvas.getByRole("button", { name: "Update server order" }),+ );+ await expect(canvas.getAllByRole("row")[1]).toHaveTextContent("Third");+ await expect(canvas.getAllByRole("row")[2]).toHaveTextContent("Fallback");+ await expect(canvas.getAllByRole("row")[3]).toHaveTextContent("Primary");},});++function ServerOrderExample(+ args: ComponentProps<typeof GatewayProvidersTable>,+) {+ const [serverConnections, setServerConnections] = useState(args.connections);+ return (+ <div>+ <Button+ onClick={() => setServerConnections([...args.connections].reverse())}+ >+ Update server order+ </Button>+ <ConnectedGatewayProvidersTable+ {...args}+ connections={serverConnections}+ onReorder={async () => true}+ />+ </div>+ );+}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.tsxnew file mode 100644index 0000000000..00c15bdf2b--- /dev/null+++ b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersTable/GatewayProvidersTable.tsx@@ -0,0 +1,231 @@+/* eslint-disable no-nested-ternary */+import { useMemo } from "react";+import {+ ArrowDown,+ ArrowUp,+ Pencil,+ RefreshCw,+ Route,+ Trash2,+} from "lucide-react";+import Link from "next/link";+import { SiAnthropic, SiOpenai } from "react-icons/si";++import { SettingsTable } from "@/src/components/SettingsTable/SettingsTable";+import { createStatusTableColumn } from "@/src/components/design-system/table/columns/createStatusTableColumn";+import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";+import type { LangfuseColumnDef } from "@/src/components/table/types";+import { Button } from "@/src/components/ui/button";+import { providerLabels } from "@/src/features/ai-gateway/constants/providerLabels";+import type {+ GatewayConnection,+ GatewayProvider,+} from "@/src/features/ai-gateway/types/gatewayProvider";++export type GatewayProvidersTableProps = {+ connections: GatewayConnection[];+ pageOffset: number;+ previousConnectionId?: string;+ nextConnectionId?: string;+ modelCounts: Record<string, number | "loading">;+ getModelsUrl: (connection: GatewayConnection) => string;+ onRetry: (connection: GatewayConnection) => void;+ onEdit: (connection: GatewayConnection) => void;+ onDelete: (connection: GatewayConnection) => void;+ retryDisabled?: { reason: string };+ editDisabled?: { reason: string };+ deleteDisabled?: { reason: string };+ canReorder: boolean;+ onMove: (sourceId: string, targetId: string) => void;+};++const connectionStatus = {+ ENABLED: "active",+ ERROR: "error",+ DISABLED: "disabled",+} as const satisfies Record<GatewayConnection["status"], string>;++export function GatewayProvidersTable({+ connections,+ pageOffset,+ previousConnectionId,+ nextConnectionId,+ modelCounts,+ getModelsUrl,+ onRetry,+ onEdit,+ onDelete,+ retryDisabled,+ editDisabled,+ deleteDisabled,+ canReorder,+ onMove,+}: GatewayProvidersTableProps) {+ const columns = useMemo<LangfuseColumnDef<GatewayConnection>[]>(+ () => [+ {+ accessorKey: "routingPriority",+ header: "Priority",+ size: 110,+ cell: ({ row }) => (+ <div className="group flex items-center gap-1">+ <span className="flex size-6 shrink-0 items-center justify-center font-mono">+ {pageOffset + row.index + 1}+ </span>+ <div className="flex items-center opacity-40 transition-opacity group-hover:opacity-100 focus-within:opacity-100">+ <Button+ size="icon-xs"+ variant="ghost"+ disabled={+ !canReorder || (row.index === 0 && !previousConnectionId)+ }+ aria-label="Move credential up"+ onClick={() => {+ const targetId =+ connections[row.index - 1]?.id ?? previousConnectionId;+ if (targetId) onMove(row.original.id, targetId);+ }}+ >+ <ArrowUp className="size-3" />+ </Button>+ <Button+ size="icon-xs"+ variant="ghost"+ disabled={+ !canReorder ||+ (row.index === connections.length - 1 && !nextConnectionId)+ }+ aria-label="Move credential down"+ onClick={() => {+ const targetId =+ connections[row.index + 1]?.id ?? nextConnectionId;+ if (targetId) onMove(row.original.id, targetId);+ }}+ >+ <ArrowDown className="size-3" />+ </Button>+ </div>+ </div>+ ),+ },+ {+ accessorKey: "provider",+ header: "Provider",+ size: 170,+ cell: ({ row }) => <ProviderName provider={row.original.provider} />,+ },+ createTextTableColumn<GatewayConnection>({+ accessorKey: "name",+ header: "Name",+ size: 180,+ }),+ createTextTableColumn<GatewayConnection>({+ accessorKey: "displaySecret",+ header: "Credential",+ size: 180,+ sensitive: true,+ }),+ createStatusTableColumn<GatewayConnection, GatewayConnection["status"]>({+ accessorKey: "status",+ header: "Status",+ size: 110,+ getStatus: (status) => (status ? connectionStatus[status] : undefined),+ isLive: false,+ }),+ {+ accessorKey: "id",+ id: "models",+ header: "Models",+ size: 180,+ cell: ({ row }) => (+ <ModelCount+ value={modelCounts[row.original.id]}+ href={getModelsUrl(row.original)}+ />+ ),+ },+ ],+ [+ canReorder,+ connections,+ pageOffset,+ previousConnectionId,+ nextConnectionId,+ getModelsUrl,+ modelCounts,+ onMove,+ ],+ );++ return (+ <SettingsTable+ tableName="gateway-provider-credentials"+ columns={columns}+ actions={(connection) => [+ {+ id: "retry",+ type: "item",+ title: "Retry provider validation",+ icon: RefreshCw,+ disabled: retryDisabled,+ onClick: () => onRetry(connection),+ },+ {+ id: "edit",+ type: "item",+ title: "Edit credential",+ icon: Pencil,+ disabled: editDisabled,+ onClick: () => onEdit(connection),+ },+ {+ id: "delete",+ type: "item",+ title: "Delete credential",+ icon: Trash2,+ variant: "destructive",+ disabled: deleteDisabled,+ onClick: () => onDelete(connection),+ },+ ]}+ data={{ status: "success", data: connections }}+ noResultsMessage="No provider credentials configured."+ />+ );+}++function ModelCount({+ value,+ href,+}: {+ value: number | "loading" | undefined;+ href: string;+}) {+ if (value === "loading") return <>Loading…</>;+ if (value === undefined) return <>—</>;+ return (+ <Link className="text-primary hover:underline" href={href}>+ {value} {value === 1 ? "model" : "models"} available+ </Link>+ );+}++function ProviderName({ provider }: { provider: GatewayProvider }) {+ const icon =+ provider === "OPENAI" ? (+ <SiOpenai className="size-4" aria-hidden="true" />+ ) : provider === "ANTHROPIC" ? (+ <SiAnthropic className="size-4" aria-hidden="true" />+ ) : (+ <Route className="size-4" aria-hidden="true" />+ );++ return (+ <div className="flex items-center gap-2">+ <span className="bg-muted flex size-7 items-center justify-center rounded-md border">+ {icon}+ </span>+ <span>{providerLabels[provider]}</span>+ </div>+ );+}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.clienttest.ts b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.clienttest.tsdeleted file mode 100644index ef5408054a..0000000000--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.clienttest.ts+++ /dev/null@@ -1,99 +0,0 @@-import { createElement } from "react";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";--import { getProviderReorder } from "@/src/features/ai-gateway/fns/providerReorder/getProviderReorder";-import { reorderProviderIds } from "@/src/features/ai-gateway/fns/providerReorder/reorderProviderIds";-import type { GatewayConnection } from "@/src/features/ai-gateway/types/gatewayProvider";-import { GatewayProvidersView } from "./GatewayProvidersView";--const connection = (- id: string,- name: string,- routingPriority: number,-): GatewayConnection => ({- id,- name,- provider: "OPENAI",- displaySecret: "sk-...test",- status: "ENABLED",- organizationId: "org-1",- createdById: "user-1",- routingPriority,- createdAt: new Date("2026-09-08T12:00:00.000Z"),- updatedAt: new Date("2026-09-08T12:00:00.000Z"),-});--describe("provider credential reordering", () => {- it("moves credentials in both directions", () => {- expect(- reorderProviderIds(["openai", "anthropic"], "openai", "anthropic"),- ).toEqual(["anthropic", "openai"]);- expect(- reorderProviderIds(["anthropic", "openai"], "openai", "anthropic"),- ).toEqual(["openai", "anthropic"]);- });-- it("resets an optimistic order when the server order changes", async () => {- const alpha = connection("alpha", "Alpha", 0);- const beta = connection("beta", "Beta", 1);- const gamma = connection("gamma", "Gamma", 2);- const props = {- modelCounts: {},- getModelsUrl: (item: GatewayConnection) => `/models/${item.id}`,- createAction: null,- renderCredentialActions: () => null,- hasMore: false,- isLoadingMore: false,- onLoadMore: vi.fn(),- canReorder: true,- onReorder: vi.fn(async () => true),- };- const { rerender } = render(- createElement(GatewayProvidersView, {- ...props,- connections: [alpha, beta, gamma],- }),- );-- fireEvent.click(- screen.getAllByRole("button", { name: "Move credential down" })[0]!,- );- await waitFor(() => {- expect(screen.getAllByRole("row")[1]).toHaveTextContent("Beta");- });-- rerender(- createElement(GatewayProvidersView, {- ...props,- connections: [gamma, beta, alpha],- }),- );-- expect(screen.getAllByRole("row")[1]).toHaveTextContent("Gamma");- expect(screen.getAllByRole("row")[2]).toHaveTextContent("Beta");- expect(screen.getAllByRole("row")[3]).toHaveTextContent("Alpha");- });-- it("maps a completed drag to the source and target credentials", () => {- expect(- getProviderReorder(- {- active: { id: "openai" },- over: { id: "anthropic" },- } as Parameters<typeof getProviderReorder>[0],- true,- ),- ).toEqual({ sourceId: "openai", targetId: "anthropic" });- });-- it("ignores disabled and unchanged drags", () => {- const drag = {- active: { id: "openai" },- over: { id: "openai" },- } as Parameters<typeof getProviderReorder>[0];-- expect(getProviderReorder(drag, true)).toBeNull();- expect(getProviderReorder(drag, false)).toBeNull();- });-});diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.tsxdeleted file mode 100644index 188490f225..0000000000--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/GatewayProvidersView/GatewayProvidersView.tsx+++ /dev/null@@ -1,491 +0,0 @@-import {- createContext,- useCallback,- useContext,- useLayoutEffect,- useMemo,- useRef,- useState,- type CSSProperties,- type ReactNode,-} from "react";-import {- closestCenter,- DndContext,- KeyboardSensor,- MouseSensor,- TouchSensor,- type DragEndEvent,- useSensor,- useSensors,-} from "@dnd-kit/core";-import {- restrictToParentElement,- restrictToVerticalAxis,-} from "@dnd-kit/modifiers";-import {- SortableContext,- useSortable,- verticalListSortingStrategy,-} from "@dnd-kit/sortable";-import { CSS } from "@dnd-kit/utilities";-import { ArrowDown, ArrowUp, GripVertical, Route } from "lucide-react";-import Link from "next/link";-import { SiAnthropic, SiOpenai } from "react-icons/si";--import Header from "@/src/components/layouts/header";-import { DataTable } from "@/src/components/table/data-table";-import type { LangfuseColumnDef } from "@/src/components/table/types";-import { Badge } from "@/src/components/ui/badge";-import { Button } from "@/src/components/ui/button";-import { TableRow } from "@/src/components/ui/table";-import { providerLabels } from "@/src/features/ai-gateway/constants/providerLabels";-import { getProviderReorder } from "@/src/features/ai-gateway/fns/providerReorder/getProviderReorder";-import { reorderProviderIds } from "@/src/features/ai-gateway/fns/providerReorder/reorderProviderIds";-import type {- GatewayConnection,- GatewayProvider,-} from "@/src/features/ai-gateway/types/gatewayProvider";-import { cn } from "@/src/utils/tailwind";--const TABLE_NAME = "gateway-provider-credentials";--type SortableHandleContextValue = Pick<- ReturnType<typeof useSortable>,- "attributes" | "listeners"->;-const SortableHandleContext = createContext<SortableHandleContextValue | null>(- null,-);--type GatewayConnectionRow = GatewayConnection;--type GatewayProvidersViewProps = {- connections: GatewayConnectionRow[];- modelCounts: Record<string, number | "loading">;- getModelsUrl: (connection: GatewayConnectionRow) => string;- createAction: ReactNode;- renderCredentialActions: (- connection: GatewayConnectionRow,- index: number,- ) => ReactNode;- hasMore: boolean;- isLoadingMore: boolean;- onLoadMore: () => unknown;- canReorder: boolean;- onReorder: (sourceId: string, targetId: string) => Promise<boolean>;-};--export function GatewayProvidersView(props: GatewayProvidersViewProps) {- const serverOrderKey = JSON.stringify(- props.connections.map((connection) => connection.id),- );- return <SortableGatewayProvidersView key={serverOrderKey} {...props} />;-}--function SortableGatewayProvidersView({- connections,- modelCounts,- getModelsUrl,- createAction,- renderCredentialActions,- hasMore,- isLoadingMore,- onLoadMore,- canReorder,- onReorder,-}: GatewayProvidersViewProps) {- const sensors = useSensors(- useSensor(MouseSensor, { activationConstraint: { distance: 4 } }),- useSensor(TouchSensor, { activationConstraint: { distance: 4 } }),- useSensor(KeyboardSensor),- );- const [orderedIds, setOrderedIds] = useState(() =>- connections.map((connection) => connection.id),- );- const rowNodes = useRef(new Map<string, HTMLTableRowElement>());- const pendingRowPositions = useRef<Map<string, number> | null>(null);-- const captureRowPositions = useCallback(- () =>- new Map(- [...rowNodes.current].map(([id, node]) => [- id,- node.getBoundingClientRect().top,- ]),- ),- [],- );- const registerRowNode = useCallback(- (id: string, node: HTMLTableRowElement | null) => {- if (node) rowNodes.current.set(id, node);- else rowNodes.current.delete(id);- },- [],- );-- useLayoutEffect(() => {- const previousPositions = pendingRowPositions.current;- if (!previousPositions) return;- pendingRowPositions.current = null;-- for (const [id, node] of rowNodes.current) {- const previousTop = previousPositions.get(id);- if (previousTop === undefined) continue;- const offset = previousTop - node.getBoundingClientRect().top;- if (offset === 0) continue;-- node.animate(- [- { transform: `translateY(${offset}px)` },- { transform: "translateY(0)" },- ],- { duration: 200, easing: "ease" },- );- }- }, [orderedIds]);-- const orderedConnections = useMemo(() => {- const orderById = new Map(- orderedIds.map((connectionId, index) => [connectionId, index]),- );- return connections.toSorted(- (left, right) =>- (orderById.get(left.id) ?? Number.MAX_SAFE_INTEGER) -- (orderById.get(right.id) ?? Number.MAX_SAFE_INTEGER),- );- }, [connections, orderedIds]);-- const moveConnection = useCallback(- async (sourceId: string, targetId: string, animateRows = false) => {- const previousIds = orderedIds;- const nextIds = reorderProviderIds(previousIds, sourceId, targetId);- if (nextIds === previousIds) return;-- if (animateRows) pendingRowPositions.current = captureRowPositions();- setOrderedIds(nextIds);-- if (!(await onReorder(sourceId, targetId))) {- if (animateRows) pendingRowPositions.current = captureRowPositions();- setOrderedIds(previousIds);- }- },- [captureRowPositions, onReorder, orderedIds],- );- const columns = useMemo<LangfuseColumnDef<GatewayConnectionRow, unknown>[]>(- () => [- {- accessorKey: "priority",- id: "priority",- header: "Priority",- size: 180,- cell: ({ row }) => (- <ProviderPriorityCell- connection={row.original}- index={row.index}- connectionCount={orderedConnections.length}- canReorder={canReorder}- onMove={async (targetIndex) => {- const target = orderedConnections[targetIndex];- if (target)- await moveConnection(row.original.id, target.id, true);- }}- />- ),- },- {- accessorKey: "provider",- id: "provider",- header: "Provider",- size: 220,- cell: ({ row }) => <ProviderName provider={row.original.provider} />,- },- {- accessorKey: "name",- id: "name",- header: "Name",- size: 220,- isFlexWidth: true,- },- {- accessorKey: "displaySecret",- id: "displaySecret",- header: "Credential",- size: 220,- cell: ({ row }) => (- <span className="font-mono">{row.original.displaySecret}</span>- ),- },- {- accessorKey: "status",- id: "status",- header: "Status",- size: 120,- cell: ({ row }) => <ConnectionStatus status={row.original.status} />,- },- {- accessorKey: "models",- id: "models",- header: "Models",- size: 180,- cell: ({ row }) => (- <ModelCount- value={modelCounts[row.original.id]}- href={getModelsUrl(row.original)}- />- ),- },- {- accessorKey: "actions",- id: "actions",- header: "Actions",- size: 180,- enableResizing: false,- isFixedPosition: true,- cell: ({ row }) => (- <div className="flex justify-end gap-1">- {renderCredentialActions(row.original, row.index)}- </div>- ),- },- ],- [- canReorder,- getModelsUrl,- modelCounts,- moveConnection,- orderedConnections,- renderCredentialActions,- ],- );-- const handleDragEnd = async (event: DragEndEvent) => {- const reorder = getProviderReorder(event, canReorder);- if (reorder) await moveConnection(reorder.sourceId, reorder.targetId);- };-- return (- <div className="flex flex-col gap-4">- <Header title="Provider credentials" actionButtons={createAction} />- <p className="text-muted-foreground text-sm">- Requests use the first compatible enabled credential in routing priority- order. Credentials are validated against the provider when they are- saved.- </p>-- <DndContext- autoScroll={false}- collisionDetection={closestCenter}- modifiers={[restrictToVerticalAxis, restrictToParentElement]}- sensors={sensors}- onDragEnd={handleDragEnd}- >- <SortableContext- items={orderedConnections.map((connection) => connection.id)}- strategy={verticalListSortingStrategy}- >- <div className="flex max-h-[60dvh] flex-col overflow-hidden rounded-md border [&>:first-child>:first-child]:border-t-0">- <DataTable- tableName={TABLE_NAME}- columns={columns}- data={{- isLoading: false,- isError: false,- data: orderedConnections,- }}- hidePagination- footer={- hasMore ? (- <Button- variant="secondary"- loading={isLoadingMore}- disabled={isLoadingMore}- aria-label="Load more"- onClick={() => {- onLoadMore();- }}- >- Load more- </Button>- ) : undefined- }- cellPadding="comfortable"- noResultsMessage="No provider credentials configured."- renderRow={({ row, children }) => (- <SortableProviderRow- connection={row.original}- canReorder={canReorder}- registerRowNode={registerRowNode}- >- {children}- </SortableProviderRow>- )}- />- </div>- </SortableContext>- </DndContext>- </div>- );-}--function SortableProviderRow({- connection,- canReorder,- registerRowNode,- children,-}: {- connection: GatewayConnectionRow;- canReorder: boolean;- registerRowNode: (id: string, node: HTMLTableRowElement | null) => void;- children: ReactNode;-}) {- const {- attributes,- isDragging,- listeners,- setNodeRef,- transform,- transition,- } = useSortable({- id: connection.id,- disabled: !canReorder,- });- const handleNodeRef = useCallback(- (node: HTMLTableRowElement | null) => {- setNodeRef(node);- registerRowNode(connection.id, node);- },- [connection.id, registerRowNode, setNodeRef],- );- const style: CSSProperties = {- transform: CSS.Transform.toString(transform),- transition,- zIndex: isDragging ? 1 : undefined,- position: isDragging ? "relative" : undefined,- };-- return (- <SortableHandleContext.Provider value={{ attributes, listeners }}>- <TableRow- ref={handleNodeRef}- style={style}- className={cn(- "ph-no-capture group hover:bg-accent cursor-default",- isDragging && "bg-muted z-10 opacity-70 shadow-sm",- )}- >- {children}- </TableRow>- </SortableHandleContext.Provider>- );-}--function ProviderPriorityCell({- connection,- index,- connectionCount,- canReorder,- onMove,-}: {- connection: GatewayConnectionRow;- index: number;- connectionCount: number;- canReorder: boolean;- onMove: (targetIndex: number) => Promise<void>;-}) {- const sortableHandle = useContext(SortableHandleContext);-- return (- <div className="flex h-7 items-center gap-1">- <button- {...sortableHandle?.attributes}- {...sortableHandle?.listeners}- type="button"- disabled={!sortableHandle}- aria-label={`Drag ${connection.name} to reorder`}- className="text-muted-foreground flex size-6 shrink-0 cursor-grab touch-none items-center justify-center p-0 opacity-50 hover:opacity-100 active:cursor-grabbing disabled:cursor-not-allowed"- >- <GripVertical className="size-3.5" />- </button>- <span className="flex size-6 shrink-0 translate-y-px items-center justify-center font-mono leading-none">- {index + 1}- </span>- <div className="flex h-6 items-center opacity-40 transition-opacity group-hover:opacity-100">- <Button- size="icon-xs"- variant="ghost"- className="text-muted-foreground size-6 opacity-60 hover:opacity-100"- disabled={!canReorder || index === 0}- aria-label="Move credential up"- onClick={() => onMove(index - 1)}- >- <ArrowUp className="size-3" />- </Button>- <Button- size="icon-xs"- variant="ghost"- className="text-muted-foreground size-6 opacity-60 hover:opacity-100"- disabled={!canReorder || index === connectionCount - 1}- aria-label="Move credential down"- onClick={() => onMove(index + 1)}- >- <ArrowDown className="size-3" />- </Button>- </div>- </div>- );-}--function ModelCount({- value,- href,-}: {- value: number | "loading" | undefined;- href: string;-}) {- if (value === "loading") return <>Loading…</>;- if (value === undefined) return <>—</>;- return (- <Link className="text-primary hover:underline" href={href}>- {value} {value === 1 ? "model" : "models"} available- </Link>- );-}--function ProviderName({ provider }: { provider: GatewayProvider }) {- const icon = (() => {- if (provider === "OPENAI") {- return <SiOpenai className="size-4" aria-hidden="true" />;- }- if (provider === "ANTHROPIC") {- return <SiAnthropic className="size-4" aria-hidden="true" />;- }- return <Route className="size-4" aria-hidden="true" />;- })();-- return (- <div className="flex items-center gap-2">- <span className="bg-muted flex size-7 items-center justify-center rounded-md border">- {icon}- </span>- <span>{providerLabels[provider]}</span>- </div>- );-}--function ConnectionStatus({- status,-}: {- status: GatewayConnectionRow["status"];-}) {- const variant = (() => {- if (status === "ENABLED") {- return "success";- }- if (status === "ERROR") {- return "error";- }- return "secondary";- })();- return <Badge variant={variant}>{status.toLowerCase()}</Badge>;-}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/ProviderDialogController/ProviderDialogController.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/ProviderDialogController/ProviderDialogController.tsxindex 133fdaa4d1..46522ceefa 100644--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/ProviderDialogController/ProviderDialogController.tsx+++ b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/ProviderDialogController/ProviderDialogController.tsx@@ -32,7 +32,10 @@ export function ProviderDialogController({}: {organizationId: string;connection?: GatewayConnection;- children: (control: { openDialog: () => void }) => ReactNode;+ children: (control: {+ openAddDialog: () => void;+ openEditDialog: (connection: GatewayConnection) => void;+ }) => ReactNode;}) {const [provider, setProvider] = useState<GatewayProvider>(connection?.provider ?? "OPENAI",@@ -57,16 +60,18 @@ export function ProviderDialogController({const isError = test.isError || create.isError || update.isError;const reset = () => {- setProvider(connection?.provider ?? "OPENAI");- setName(connection?.name ?? "");+ setProvider("OPENAI");+ setName("");setCredential("");};- const testCredential = async () => {+ const testCredential = async (+ selectedConnection: GatewayConnection | null,+ ) => {try {await test.mutateAsync({orgId: organizationId,- provider: connection?.provider ?? provider,+ provider: selectedConnection?.provider ?? provider,credential,});} catch (error) {@@ -74,12 +79,15 @@ export function ProviderDialogController({}};- const submit = async (closeDialog: () => void) => {+ const submit = async (+ selectedConnection: GatewayConnection | null,+ closeDialog: () => void,+ ) => {try {- if (connection) {+ if (selectedConnection) {await update.mutateAsync({orgId: organizationId,- id: connection.id,+ id: selectedConnection.id,name,...(credential ? { credential } : {}),});@@ -104,27 +112,27 @@ export function ProviderDialogController({};return (- <DialogController+ <DialogController<GatewayConnection | null>size="default"closeOnInteractionOutside={false}onDismiss={reset}onBeforeClose={() => !isPending}- renderContent={({ closeDialog }) => (+ renderContent={({ state: selectedConnection, closeDialog }) => (<><DialogHeader><DialogTitle>- {connection+ {selectedConnection? "Edit provider credential": "Add provider credential"}</DialogTitle></DialogHeader><DialogBody>- {connection ? (+ {selectedConnection ? (<div><Label>Provider</Label><InputclassName="mt-1.5"- value={providerLabels[connection.provider]}+ value={providerLabels[selectedConnection.provider]}disabled/></div>@@ -135,7 +143,7 @@ export function ProviderDialogController({name={name}credential={credential}credentialPlaceholder={- connection+ selectedConnection? "Leave blank to keep current key": "Enter secret key"}@@ -164,16 +172,18 @@ export function ProviderDialogController({variant="secondary"disabled={!credential || isPending}loading={test.isPending}- onClick={testCredential}+ onClick={() => testCredential(selectedConnection)}>Test</Button><Buttondisabled={- !name.trim() || (!connection && !credential) || isPending+ !name.trim() ||+ (!selectedConnection && !credential) ||+ isPending}loading={isSaving}- onClick={() => submit(closeDialog)}+ onClick={() => submit(selectedConnection, closeDialog)}>Test and save</Button>@@ -181,7 +191,22 @@ export function ProviderDialogController({</>)}>- {({ openDialog }) => children({ openDialog })}+ {({ openDialog }) =>+ children({+ openAddDialog: () => {+ setProvider(connection?.provider ?? "OPENAI");+ setName(connection?.name ?? "");+ setCredential("");+ openDialog(connection ?? null);+ },+ openEditDialog: (selectedConnection) => {+ setProvider(selectedConnection.provider);+ setName(selectedConnection.name);+ setCredential("");+ openDialog(selectedConnection);+ },+ })+ }</DialogController>);}diff --git a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/RetryProviderButton.tsx b/web/src/features/ai-gateway/components/GatewayProvidersPage/components/RetryProviderButton.tsxdeleted file mode 100644index f166295312..0000000000--- a/web/src/features/ai-gateway/components/GatewayProvidersPage/components/RetryProviderButton.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { RefreshCw } from "lucide-react";--import { Button } from "@/src/components/ui/button";-import { api, reportNonTrpcError } from "@/src/utils/api";--export function RetryProviderButton({- organizationId,- connectionId,- onModelsLoaded,-}: {- organizationId: string;- connectionId: string;- onModelsLoaded: (count: number) => void;-}) {- const utils = api.useUtils();- const retry = api.aiGateway.retryConnection.useMutation();-- const retryConnection = async () => {- try {- const result = await retry.mutateAsync({- orgId: organizationId,- id: connectionId,- });- if (result.success) onModelsLoaded(result.models.length);- await utils.aiGateway.listConnections.invalidate({- orgId: organizationId,- });- } catch (error) {- reportNonTrpcError(error, "ai-gateway-providers");- }- };-- return (- <Button- size="icon-xs"- variant="ghost"- loading={retry.isPending}- aria-label="Retry provider validation"- onClick={retryConnection}- >- <RefreshCw className="size-4" />- </Button>- );-}diff --git a/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx b/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsxindex 2e0e700b5b..510a0c2579 100644--- a/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx+++ b/web/src/features/ai-gateway/components/gatewayMutationErrors.clienttest.tsx@@ -241,7 +241,9 @@ describe("gateway mutation local error handling", () => {it("tests a provider credential without saving", async () => {render(<ProviderDialogController organizationId="org-1">- {({ openDialog }) => <Button onClick={openDialog}>Add provider</Button>}+ {({ openAddDialog }) => (+ <Button onClick={openAddDialog}>Add provider</Button>+ )}</ProviderDialogController>,);@@ -266,7 +268,9 @@ describe("gateway mutation local error handling", () => {it("create provider dialog routes tRPC failures locally without a global toast", async () => {render(<ProviderDialogController organizationId="org-1">- {({ openDialog }) => <Button onClick={openDialog}>Add provider</Button>}+ {({ openAddDialog }) => (+ <Button onClick={openAddDialog}>Add provider</Button>+ )}</ProviderDialogController>,);@@ -295,14 +299,32 @@ describe("gateway mutation local error handling", () => {).toBeInTheDocument();});+ it("opens the selected credential through the dialog controller", () => {+ render(+ <ProviderDialogController organizationId="org-1">+ {({ openEditDialog }) => (+ <Button onClick={() => openEditDialog(testConnection)}>+ Edit provider+ </Button>+ )}+ </ProviderDialogController>,+ );++ fireEvent.click(screen.getByRole("button", { name: "Edit provider" }));+ expect(+ screen.getByRole("heading", { name: "Edit provider credential" }),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Name")).toHaveValue(testConnection.name);+ });+it("edit provider dialog routes tRPC failures locally without a global toast", async () => {render(<ProviderDialogControllerorganizationId="org-1"connection={testConnection}>- {({ openDialog }) => (- <Button onClick={openDialog}>Edit provider</Button>+ {({ openAddDialog }) => (+ <Button onClick={openAddDialog}>Edit provider</Button>)}</ProviderDialogController>,);diff --git a/web/src/features/ai-gateway/fns/providerReorder/getProviderReorder.ts b/web/src/features/ai-gateway/fns/providerReorder/getProviderReorder.tsdeleted file mode 100644index d4d7dcb50f..0000000000--- a/web/src/features/ai-gateway/fns/providerReorder/getProviderReorder.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { DragEndEvent } from "@dnd-kit/core";--export function getProviderReorder(- event: Pick<DragEndEvent, "active" | "over">,- canReorder: boolean,-) {- if (- !canReorder ||- !event.over ||- event.active.id === event.over.id ||- typeof event.active.id !== "string" ||- typeof event.over.id !== "string"- ) {- return null;- }-- return { sourceId: event.active.id, targetId: event.over.id };-}