Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
additional cleanup
x0322056a0a7821e765
diff --git a/frontend/src/hooks/api/pam/maps.ts b/frontend/src/hooks/api/pam/maps.tsindex e432baf249..d4d3128524 100644--- a/frontend/src/hooks/api/pam/maps.ts+++ b/frontend/src/hooks/api/pam/maps.ts@@ -1,38 +1,11 @@-import { PamAccountType, PamResourceType } from "./enums";+import { PamAccountType } from "./enums";-export const PAM_RESOURCE_TYPE_MAP: Record<- PamResourceType,- { name: string; image: string; size?: number }-> = {- [PamResourceType.Postgres]: { name: "PostgreSQL", image: "Postgres.png" },- [PamResourceType.MySQL]: { name: "MySQL", image: "MySql.png" },- [PamResourceType.SSH]: { name: "SSH", image: "SSH.png" },- [PamResourceType.Kubernetes]: { name: "Kubernetes", image: "Kubernetes.png" },- [PamResourceType.OracleDB]: { name: "OracleDB", image: "Oracle.png", size: 55 },- [PamResourceType.SQLite]: { name: "SQLite", image: "SQLite.png" },- [PamResourceType.MsSQL]: { name: "Microsoft SQL Server", image: "MsSql.png" },- [PamResourceType.MCP]: { name: "MCP", image: "MCP.png" },- [PamResourceType.Redis]: { name: "Redis", image: "Redis.png" },- [PamResourceType.MongoDB]: { name: "MongoDB", image: "MongoDB.png" },- [PamResourceType.WebApp]: { name: "Web Application", image: "Web.png" },- [PamResourceType.Cassandra]: { name: "Cassandra", image: "Cassandra.png", size: 55 },- [PamResourceType.CockroachDB]: { name: "CockroachDB", image: "CockroachDB.png" },- [PamResourceType.Elasticsearch]: { name: "Elasticsearch", image: "Elastic.png" },- [PamResourceType.Snowflake]: { name: "Snowflake", image: "Snowflake.png" },- [PamResourceType.DynamoDB]: { name: "DynamoDB", image: "DynamoDB.png", size: 55 },- [PamResourceType.AwsIam]: { name: "AWS IAM", image: "Amazon Web Services.png" },- [PamResourceType.Windows]: { name: "Windows Server", image: "Windows.png" }-};--export const PAM_ACCOUNT_TYPE_MAP: Record<- PamAccountType,- { name: string; image: string; size?: number }-> = {+export const PAM_ACCOUNT_TYPE_MAP: Record<PamAccountType, { name: string; image: string }> = {[PamAccountType.Postgres]: { name: "PostgreSQL", image: "Postgres.png" },[PamAccountType.MySQL]: { name: "MySQL", image: "MySql.png" },[PamAccountType.SSH]: { name: "SSH", image: "SSH.png" },[PamAccountType.Kubernetes]: { name: "Kubernetes", image: "Kubernetes.png" },- [PamAccountType.OracleDB]: { name: "OracleDB", image: "Oracle.png", size: 55 },+ [PamAccountType.OracleDB]: { name: "OracleDB", image: "Oracle.png" },[PamAccountType.MsSQL]: { name: "Microsoft SQL Server", image: "MsSql.png" },[PamAccountType.Redis]: { name: "Redis", image: "Redis.png" },[PamAccountType.MongoDB]: { name: "MongoDB", image: "MongoDB.png" },diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxdeleted file mode 100644index 9c44bef4bb..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx+++ /dev/null@@ -1,555 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";-import { useParams } from "@tanstack/react-router";-import {- AlertTriangleIcon,- DatabaseIcon,- PlusIcon,- ShieldCheckIcon,- TableIcon,- TerminalSquareIcon,- UnplugIcon,- XIcon-} from "lucide-react";--import { Spinner } from "@app/components/v2";-import { Button } from "@app/components/v3/generic/Button";-import { cn } from "@app/components/v3/utils";-import { useGetPamAccountById } from "@app/hooks/api/pam";--import { DataExplorerGrid } from "./components/DataExplorerGrid";-import { DataExplorerSidebar } from "./components/DataExplorerSidebar";-import { QueryPanel } from "./components/QueryPanel";-import type { SchemaInfo, TableInfo } from "./data-explorer-types";-import { useDataExplorerSession } from "./use-data-explorer-session";-import { useQueryTabs } from "./use-query-tabs";--type Props = {- reason?: string;-};--export const PamDataExplorerPage = ({ reason }: Props = {}) => {- const { accountId, orgId } = useParams({- strict: false- }) as {- accountId: string;- orgId: string;- accountType: string;- };-- const { data: account } = useGetPamAccountById(accountId);-- // Sidebar-only view state. Switching schemas in the sidebar does not alter- // open tabs — tabs are bound to their own (schema, table) at open time.- const [schemas, setSchemas] = useState<SchemaInfo[]>([]);- const [selectedSchema, setSelectedSchema] = useState("public");- const [tables, setTables] = useState<TableInfo[]>([]);- const [isLoadingSchemas, setIsLoadingSchemas] = useState(false);- const [isLoadingTables, setIsLoadingTables] = useState(false);- const [hasDisconnected, setHasDisconnected] = useState(false);- const [disconnectReason, setDisconnectReason] = useState<string | null>(null);- const latestSchemaRequestRef = useRef(0);- const tabElRefs = useRef<Map<string, HTMLDivElement | null>>(new Map());-- const [approvalJustification, setApprovalJustification] = useState("");-- // Forward refs for tab-state handlers that useDataExplorerSession calls- // before useQueryTabs has been called. Assigned after useQueryTabs below.- const markConnectionDeadRef = useRef<((connId: string) => void) | null>(null);- const resetTabsRef = useRef<(() => void) | null>(null);- const openFirstQueryTabRef = useRef<(() => Promise<string | null>) | null>(null);- // Shared guard so the first-connect effect and onReconnected don't both- // end up opening a default tab.- const defaultTabOpenedRef = useRef(false);-- const {- isConnected,- isConnecting,- errorMessage,- mfaState,- approvalState,- connect,- disconnect,- reconnect,- handleMfaVerification,- submitApprovalRequest,- approvalRequestUrl,- openConnection,- closeConnection,- fetchSchemas,- fetchTables,- fetchTableDetail,- executeQuery,- cancelQuery- } = useDataExplorerSession({- accountId,- orgId,- accountName: account?.name ?? "",- reason,- onSessionEnd: (endReason?: string) => {- setHasDisconnected(true);- setDisconnectReason(endReason ?? null);- },- onConnectionClosed: (connId: string) => {- markConnectionDeadRef.current?.(connId);- },- onReconnected: () => {- // Drop all tabs on reconnect — all connectionIds are invalid.- resetTabsRef.current?.();- // Claim the default-tab slot so the first-connect effect skips it.- defaultTabOpenedRef.current = true;- const opener = openFirstQueryTabRef.current;- if (opener) opener().catch(() => {});- }- });-- const {- tabs,- activeTabId,- atTabLimit,- isOpeningTab,- openQueryTab,- openBrowseTab,- closeTab,- setActiveTab,- updateTabSql,- setTabTransactionOpen,- markConnectionDead,- resetTabs,- refreshBrowseTab,- MAX_TABS- } = useQueryTabs({- openConnection,- closeConnection,- fetchTableDetail- });-- markConnectionDeadRef.current = markConnectionDead;- resetTabsRef.current = resetTabs;- openFirstQueryTabRef.current = openQueryTab;-- // Drive connection from the page, not the hook.- // Use a ref callback as the gate (same approach as useWebAccessSession's containerEl).- // The ref callback fires once after the real DOM mount — StrictMode's simulated- // unmount/remount does NOT re-fire ref callbacks, so we get exactly one connect.- const connectedOnceRef = useRef(false);- const mountRef = useCallback(- (node: HTMLDivElement | null) => {- if (node && !connectedOnceRef.current) {- connectedOnceRef.current = true;- connect();- }- },- [connect]- );-- // Cleanup on real unmount- useEffect(() => {- return () => {- disconnect();- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const loadTables = useCallback(- async (schema: string) => {- // Guard against stale responses when the user switches schemas quickly.- // Only apply results if this is still the latest request.- latestSchemaRequestRef.current += 1;- const requestId = latestSchemaRequestRef.current;- setIsLoadingTables(true);- try {- const result = await fetchTables(schema);- if (latestSchemaRequestRef.current !== requestId) return;- setTables(result);- } catch {- // Error handled by the hook- } finally {- if (latestSchemaRequestRef.current === requestId) {- setIsLoadingTables(false);- }- }- },- [fetchTables]- );-- const loadSchemas = useCallback(- async (keepSelected = false) => {- setIsLoadingSchemas(true);- try {- const result = await fetchSchemas();- setSchemas(result);- const hasSelected = result.find((s) => s.name === selectedSchema);- const activeSchema = hasSelected ? selectedSchema : (result[0]?.name ?? "public");- if (!hasSelected && result.length > 0 && !keepSelected) {- setSelectedSchema(activeSchema);- }- if (result.length > 0) {- await loadTables(activeSchema);- }- } catch {- // Error handled by the hook- } finally {- setIsLoadingSchemas(false);- }- },- [fetchSchemas, loadTables, selectedSchema]- );-- // Keep the active tab visible in the tab bar whenever activation changes- // (tab switch, new tab opened, sidebar table opened, etc.). Only scrolls the- // tab bar itself — not ancestor containers — so the rest of the page layout- // stays put.- useEffect(() => {- if (!activeTabId) return;- const el = tabElRefs.current.get(activeTabId);- const container = el?.parentElement;- if (!el || !container) return;- const elRect = el.getBoundingClientRect();- const cRect = container.getBoundingClientRect();- if (elRect.left < cRect.left) {- container.scrollBy({ left: elRect.left - cRect.left, behavior: "smooth" });- } else if (elRect.right > cRect.right) {- container.scrollBy({ left: elRect.right - cRect.right, behavior: "smooth" });- }- }, [activeTabId, tabs.length]);-- // Auto-load schemas when we transition to connected- const wasConnectedRef = useRef(false);- useEffect(() => {- if (isConnected && !wasConnectedRef.current) {- wasConnectedRef.current = true;- setHasDisconnected(false);- (async () => {- await loadSchemas();- // Open a default query tab once — onReconnected handles subsequent- // reconnects via defaultTabOpenedRef, so we don't double-open.- if (!defaultTabOpenedRef.current) {- defaultTabOpenedRef.current = true;- await openQueryTab();- }- })().catch(() => {});- }- if (!isConnected) {- wasConnectedRef.current = false;- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [isConnected]);-- const handleSchemaChange = useCallback(- (schema: string) => {- setSelectedSchema(schema);- loadTables(schema);- },- [loadTables]- );-- const handleTableOpen = useCallback(- (tableName: string, opts: { forceNew: boolean }) => {- openBrowseTab(selectedSchema, tableName, opts).catch(() => {});- },- [selectedSchema, openBrowseTab]- );-- const handleReconnect = useCallback(() => {- setHasDisconnected(false);- setDisconnectReason(null);- setSchemas([]);- setTables([]);- resetTabs();- reconnect();- }, [reconnect, resetTabs]);-- // Tab-scoped refresh: re-fetches tableDetail + schemas + sidebar tables.- // The grid also re-runs its own SELECT after this completes.- const handleTabRefresh = useCallback(- async (tabId: string) => {- await Promise.all([refreshBrowseTab(tabId), loadSchemas(true), loadTables(selectedSchema)]);- },- [refreshBrowseTab, loadSchemas, loadTables, selectedSchema]- );-- const activeBrowseTarget = (() => {- const active = tabs.find((t) => t.id === activeTabId);- if (active?.kind === "browse") return { schema: active.schema, table: active.table };- return null;- })();-- // --- Overlay states (shown instead of the main layout) ----- if (isConnecting && !isConnected) {- return (- <div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-bunker-800">- <Spinner className="h-8 w-8" />- <p className="text-sm text-mineshaft-300">Connecting to database...</p>- </div>- );- }-- if (mfaState?.required) {- return (- <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">- <ShieldCheckIcon className="size-8 text-mineshaft-400" />- <h2 className="text-sm font-medium text-mineshaft-100">MFA Verification Required</h2>- <p className="max-w-sm text-center text-xs text-mineshaft-400">- Multi-factor authentication is required to access this database account.- </p>- {mfaState.verifying ? (- <div className="flex items-center gap-2 text-xs text-mineshaft-400">- <Spinner className="h-4 w-4" />- Waiting for verification...- </div>- ) : (- <Button variant="outline" size="xs" onClick={handleMfaVerification}>- Verify MFA- </Button>- )}- </div>- );- }-- if (approvalState?.required) {- return (- <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">- <AlertTriangleIcon className="size-8 text-mineshaft-400" />- <h2 className="text-sm font-medium text-mineshaft-100">Approval Required</h2>- <p className="max-w-sm text-center text-xs text-mineshaft-400">- This account is protected by policy: {approvalState.policyName ?? "Unknown"}- </p>- {approvalState.submitted ? (- <div className="flex flex-col items-center gap-2">- <p className="text-xs text-mineshaft-300">Approval request created successfully.</p>- {approvalRequestUrl && (- <a- href={approvalRequestUrl}- target="_blank"- rel="noopener noreferrer"- className="text-xs text-primary-500 underline hover:text-primary-400"- >- View approval request- </a>- )}- <Button variant="outline" size="xs" onClick={handleReconnect}>- Reconnect- </Button>- </div>- ) : (- <div className="flex w-full max-w-sm flex-col gap-2">- <textarea- className="w-full rounded border border-mineshaft-600 bg-bunker-700 px-3 py-2 text-xs text-mineshaft-200 placeholder:text-mineshaft-500 focus:border-mineshaft-400 focus:outline-none"- placeholder="Justification (optional)"- rows={2}- value={approvalJustification}- onChange={(e) => setApprovalJustification(e.target.value)}- />- {approvalState.errorMessage && (- <p className="text-xs text-red-400">{approvalState.errorMessage}</p>- )}- <div className="flex justify-center gap-2">- <Button- variant="outline"- size="xs"- isPending={approvalState.creating}- onClick={() => submitApprovalRequest(approvalJustification)}- >- Create Approval Request- </Button>- </div>- </div>- )}- </div>- );- }-- if (errorMessage && !isConnected) {- return (- <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">- <AlertTriangleIcon className="size-8 text-mineshaft-400" />- <h2 className="text-sm font-medium text-mineshaft-100">Connection Error</h2>- <p className="max-w-sm text-center text-xs text-mineshaft-400">{errorMessage}</p>- <Button variant="outline" size="xs" onClick={handleReconnect}>- Try Again- </Button>- </div>- );- }-- if (hasDisconnected && !isConnected && !isConnecting) {- return (- <div className="flex h-screen w-screen flex-col items-center justify-center gap-3 bg-bunker-800">- <UnplugIcon className="size-8 text-mineshaft-400" />- <h2 className="text-sm font-medium text-mineshaft-100">Disconnected</h2>- <p className="text-xs text-mineshaft-400">- {disconnectReason ?? "The database connection was closed."}- </p>- <Button variant="outline" size="xs" onClick={handleReconnect}>- Reconnect- </Button>- </div>- );- }-- // --- Main layout ----- const tabOpeningDisabled = isOpeningTab || atTabLimit;-- return (- <div ref={mountRef} className="flex h-screen w-screen flex-col bg-bunker-800">- <div className="flex flex-1 overflow-hidden">- <DataExplorerSidebar- schemas={schemas}- selectedSchema={selectedSchema}- onSchemaChange={handleSchemaChange}- tables={tables}- activeBrowseTarget={activeBrowseTarget}- onTableOpen={handleTableOpen}- isLoadingSchemas={isLoadingSchemas}- isLoadingTables={isLoadingTables}- disabled={isOpeningTab}- />-- <div className="flex flex-1 flex-col overflow-hidden">- <div className="flex min-h-[34px] shrink-0 items-center overflow-x-auto border-b border-mineshaft-600 bg-mineshaft-800 px-2 [scrollbar-color:transparent_transparent] [scrollbar-width:thin] hover:[scrollbar-color:#4a4b4e_transparent] [&::-webkit-scrollbar]:h-1 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-transparent hover:[&::-webkit-scrollbar-thumb]:bg-mineshaft-600 [&::-webkit-scrollbar-track]:bg-transparent">- {tabs.map((tab) => {- const isActive = activeTabId === tab.id;- const Icon = tab.kind === "browse" ? TableIcon : TerminalSquareIcon;- return (- <div- key={tab.id}- ref={(el) => {- if (el) tabElRefs.current.set(tab.id, el);- else tabElRefs.current.delete(tab.id);- }}- role="button"- tabIndex={0}- onClick={() => setActiveTab(tab.id)}- onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && setActiveTab(tab.id)}- className={cn(- "group flex shrink-0 cursor-pointer items-center gap-1 border-b-2 px-3 py-2 text-xs font-medium transition-colors",- isActive- ? "border-info text-mineshaft-100"- : "border-transparent text-mineshaft-400 hover:text-mineshaft-200",- tab.isDead && "text-red-400"- )}- >- <span className="flex items-center gap-1.5">- <Icon className="size-3.5" />- {tab.title}- </span>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- closeTab(tab.id);- }}- className="ml-1 rounded p-0.5 text-mineshaft-300 transition-colors hover:text-mineshaft-100"- aria-label={`Close ${tab.title}`}- >- <XIcon className="size-3" />- </button>- </div>- );- })}-- <button- type="button"- onClick={() => {- openQueryTab().catch(() => {});- }}- disabled={tabOpeningDisabled}- className="ml-1 flex shrink-0 items-center gap-1.5 rounded border border-mineshaft-600 px-2 py-1 text-xs text-mineshaft-300 transition-colors first:ml-0 hover:border-mineshaft-500 hover:text-mineshaft-100 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-mineshaft-600 disabled:hover:text-mineshaft-300"- aria-label="New query tab"- title={atTabLimit ? `Tab limit (${MAX_TABS}) reached` : "New query tab"}- >- <PlusIcon className="size-3" />- New query- </button>- </div>-- {/* All tabs are mounted; inactive tabs are CSS-hidden so their- component instance state (filters, pagination, SQL, results)- survives tab switches. */}- {tabs.map((tab) => {- const deadTabView = (- <div className="flex flex-1 flex-col items-center justify-center gap-3 text-center">- <AlertTriangleIcon className="size-8 text-red-400" />- <p className="text-sm text-mineshaft-300">- This connection was closed and cannot be reused.- </p>- <Button variant="outline" size="xs" onClick={() => closeTab(tab.id)}>- Close tab- </Button>- </div>- );- let content;- if (tab.isDead) {- content = deadTabView;- } else if (tab.kind === "browse") {- content = (- <DataExplorerGrid- key={tab.id}- tableDetail={tab.tableDetail}- tableType={tables.find((t) => t.name === tab.table)?.tableType}- schema={tab.schema}- table={tab.table}- connectionId={tab.connectionId}- executeQuery={executeQuery}- isLoading={tab.isLoadingDetail}- onRefresh={() => handleTabRefresh(tab.id)}- />- );- } else {- content = (- <QueryPanel- key={tab.id}- tab={tab}- executeQuery={executeQuery}- cancelQuery={cancelQuery}- onSqlChange={(sql) => updateTabSql(tab.id, sql)}- onTransactionStateChange={(open) => setTabTransactionOpen(tab.id, open)}- />- );- }- return (- <div- key={tab.id}- className={cn("flex flex-1 overflow-hidden", activeTabId !== tab.id && "hidden")}- >- {content}- </div>- );- })}-- {tabs.length === 0 && (- <div className="flex flex-1 flex-col items-center justify-center gap-3 text-center">- <DatabaseIcon className="size-12 text-mineshaft-600" />- <p className="text-sm text-mineshaft-400">No tabs open</p>- <Button- variant="outline"- size="xs"- onClick={() => {- openQueryTab().catch(() => {});- }}- isPending={isOpeningTab}- >- New query tab- </Button>- </div>- )}- </div>- </div>-- {/* Status bar */}- <div className="flex items-center justify-between border-t border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5 text-xs">- <span className="text-mineshaft-400">- {tables.length} table{tables.length !== 1 ? "s" : ""}- </span>- <div className="flex items-center gap-4">- <span>- <span className="text-mineshaft-400">Account:</span>{" "}- <span className="text-mineshaft-300">{account?.name ?? "Account"}</span>- </span>- </div>- </div>- </div>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsxdeleted file mode 100644index d58af64525..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx+++ /dev/null@@ -1,763 +0,0 @@-import { useCallback, useMemo, useRef, useState } from "react";-import type { CellContext, ColumnDef, HeaderContext } from "@tanstack/react-table";-import { EyeIcon } from "lucide-react";--import { createNotification } from "@app/components/notifications";-import { ContentLoader } from "@app/components/v2";-import { Alert, AlertDescription } from "@app/components/v3/generic/Alert";-import { Checkbox } from "@app/components/v3/generic/Checkbox";-import type { CellOpts } from "@app/components/v3/generic/DataGrid";-import { DataGrid, useDataGrid } from "@app/components/v3/generic/DataGrid";-import { Skeleton } from "@app/components/v3/generic/Skeleton";--import type { ColumnInfo, FieldInfo, ForeignKeyInfo, TableDetail } from "../data-explorer-types";-import { getColumnIndicator } from "../data-explorer-utils";-import { copyData, exportData } from "../data-export";-import type { FilterCondition, SortCondition } from "../sql-generation";-import {- buildCountQuery,- buildDeleteQuery,- buildInsertQuery,- buildSelectQuery,- buildUpdateQuery,- wrapInTransaction-} from "../sql-generation";-import { DataExplorerToolbar } from "./DataExplorerToolbar";--type DataExplorerGridProps = {- tableDetail: TableDetail | null;- tableType?: string;- schema: string;- table: string;- connectionId: string;- executeQuery: (- connectionId: string,- sql: string- ) => Promise<{- rows: Record<string, unknown>[];- fields: FieldInfo[];- rowCount: number | null;- command: string;- executionTimeMs: number;- }>;- isLoading: boolean;- onRefresh?: () => Promise<void>;-};--const ROW_KEY_PREFIX = "__new_";--function cellValuesEqual(a: unknown, b: unknown): boolean {- if (a === null && b === null) return true;- if (a === null || b === null) return false;- if (a === undefined && b === undefined) return true;- if (a === undefined || b === undefined) return false;- return String(a) === String(b);-}--function pgTypeToCellOpts(): CellOpts {- return { variant: "short-text" };-}--function getColumnSize(col: ColumnInfo, hasIndicator: boolean): number {- // Extra width for PK/FK icon + badge + type label in header- const indicatorExtra = hasIndicator ? 40 : 0;- const t = col.type.toLowerCase();- if (t === "boolean" || t === "bool" || t === "smallint" || t === "int2")- return 100 + indicatorExtra;- if (t === "integer" || t === "int4" || t === "serial") return 120 + indicatorExtra;- if (t === "uuid") return 280 + indicatorExtra;- if (t === "json" || t === "jsonb") return 250 + indicatorExtra;- if (t === "text" || t === "xml") return 220 + indicatorExtra;- // Scale with column name length as a rough heuristic- return Math.max(180, Math.min(350, col.name.length * 10 + 120)) + indicatorExtra;-}--type RowData = Record<string, unknown>;--type SelectionMeta = {- onRowSelect?: (rowIndex: number, checked: boolean, shiftKey: boolean) => void;-};--function SelectHeader({ table: t }: HeaderContext<RowData, unknown>) {- const isAllSelected = t.getIsAllRowsSelected();- const isSomeSelected = t.getIsSomeRowsSelected();- return (- <Checkbox- isChecked={isAllSelected || isSomeSelected}- isIndeterminate={isSomeSelected && !isAllSelected}- onCheckedChange={() => {- t.toggleAllRowsSelected(!isAllSelected);- }}- />- );-}--function SelectCell({ row, table: t }: CellContext<RowData, unknown>) {- const meta = t.options.meta as SelectionMeta | undefined;- const isSelected = row.getIsSelected();- return (- <Checkbox- isChecked={isSelected}- onCheckedChange={(checked) => {- if (meta?.onRowSelect) {- meta.onRowSelect(row.index, Boolean(checked), false);- } else {- row.toggleSelected(Boolean(checked));- }- }}- />- );-}--const SELECT_COLUMN: ColumnDef<RowData> = {- id: "select",- header: SelectHeader,- cell: SelectCell,- size: 40,- minSize: 40,- maxSize: 40,- enableSorting: false,- enableHiding: false,- enablePinning: false,- enableResizing: false-};--function buildColumnDefs(- cols: ColumnInfo[],- primaryKeys: string[],- foreignKeys: ForeignKeyInfo[]-): ColumnDef<Record<string, unknown>>[] {- // Build a map from column name → FK info for O(1) lookup- const fkMap = new Map<string, ForeignKeyInfo>();- foreignKeys.forEach((fk) => {- fk.columns.forEach((c) => {- if (!fkMap.has(c)) fkMap.set(c, fk);- });- });-- return cols.map((col) => {- const columnIndicator = getColumnIndicator(col.name, primaryKeys, fkMap);- return {- id: col.name,- accessorKey: col.name,- header: col.name,- meta: {- label: col.name,- typeLabel: col.type,- cell: pgTypeToCellOpts(),- columnIndicator- },- size: getColumnSize(col, Boolean(columnIndicator)),- minSize: 80,- maxSize: 600,- enableSorting: true,- enablePinning: true,- enableHiding: true- };- });-}--function getRowKey(row: Record<string, unknown>, primaryKeys: string[]): string {- if (primaryKeys.length === 0) return "";- const keyObj: Record<string, unknown> = {};- primaryKeys.forEach((pk) => {- keyObj[pk] = row[pk];- });- return JSON.stringify(keyObj);-}--function getPkMatch(row: Record<string, unknown>, primaryKeys: string[]): Record<string, unknown> {- const match: Record<string, unknown> = {};- primaryKeys.forEach((pk) => {- match[pk] = row[pk];- });- return match;-}--export const DataExplorerGrid = ({- tableDetail,- tableType,- schema,- table,- connectionId,- executeQuery,- isLoading,- onRefresh-}: DataExplorerGridProps) => {- const [originalData, setOriginalData] = useState<Record<string, unknown>[]>([]);- const [currentData, setCurrentData] = useState<Record<string, unknown>[]>([]);- const [totalCount, setTotalCount] = useState(0);- const [offset, setOffset] = useState(0);- const [pageSize, setPageSize] = useState(50);- const [filters, setFilters] = useState<FilterCondition[]>([]);- const [sorts, setSorts] = useState<SortCondition[]>([]);- const [executionTimeMs, setExecutionTimeMs] = useState<number | null>(null);- const [isSaving, setIsSaving] = useState(false);- const [isDataLoading, setIsDataLoading] = useState(true);- const [newRowTempIds, setNewRowTempIds] = useState<Set<string>>(new Set());- const newRowCounterRef = useRef(0);- const [hasLoaded, setHasLoaded] = useState(false);- const isFetchingRef = useRef(false);-- const primaryKeys = tableDetail?.primaryKeys ?? [];- const foreignKeys = tableDetail?.foreignKeys ?? [];- const tableColumns = tableDetail?.columns ?? [];- const hasPrimaryKey = primaryKeys.length > 0;- const primaryKeysRef = useRef(primaryKeys);- primaryKeysRef.current = primaryKeys;-- const [selectedRowCount, setSelectedRowCount] = useState(0);- const gridRef = useRef<ReturnType<typeof useDataGrid<Record<string, unknown>>>["table"] | null>(- null- );- const selectedRowsRef = useRef<Record<string, unknown>[]>([]);-- // Build TanStack Table column definitions from PG metadata- const columnDefs = useMemo(- () =>- hasPrimaryKey- ? [SELECT_COLUMN, ...buildColumnDefs(tableColumns, primaryKeys, foreignKeys)]- : buildColumnDefs(tableColumns, primaryKeys, foreignKeys),- [hasPrimaryKey, tableColumns, primaryKeys, foreignKeys]- );-- const fetchData = useCallback(- async (o: number, ps: number, f: FilterCondition[], s: SortCondition[]): Promise<number> => {- if (!tableDetail) return 0;- isFetchingRef.current = true;- setIsDataLoading(true);- try {- const selectSql = buildSelectQuery({- schema,- table,- filters: f,- sorts: s,- limit: ps,- offset: o,- primaryKeys- });- const countSql = buildCountQuery({ schema, table, filters: f });-- // These two queries don't share a database snapshot (the backend processes them- // sequentially, not in a single transaction), so the count could be off by 1 if- // another session modifies data between them. Acceptable for a data explorer.- const [dataResult, countResult] = await Promise.all([- executeQuery(connectionId, selectSql),- executeQuery(connectionId, countSql)- ]);-- const taggedRows = dataResult.rows.map((row: Record<string, unknown>) => ({- ...row,- originalPkKey: getRowKey(row, primaryKeys)- }));- setOriginalData(taggedRows);- setCurrentData(taggedRows);- setExecutionTimeMs(dataResult.executionTimeMs);- setTotalCount(Number(countResult.rows[0]?.count ?? 0));- setNewRowTempIds(new Set());- setSelectedRowCount(0);- selectedRowsRef.current = [];- setHasLoaded(true);- return dataResult.rows.length;- } catch (err) {- createNotification({- title: "Failed to load data",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- return -1;- } finally {- isFetchingRef.current = false;- setIsDataLoading(false);- }- },- [tableDetail, schema, table, primaryKeys, executeQuery, connectionId]- );-- // Fetch data when filters/sorts/pagination change.- // Table switches are handled by the parent via key={schema.table} which- // remounts this component with fresh state — no manual reset needed.- const prevFetchKeyRef = useRef("");- const fetchKey = `${schema}.${table}.${offset}.${pageSize}.${JSON.stringify(filters)}.${JSON.stringify(sorts)}`;- if (fetchKey !== prevFetchKeyRef.current && tableDetail && !isLoading) {- prevFetchKeyRef.current = fetchKey;- fetchData(offset, pageSize, filters, sorts);- } else if (isDataLoading && hasLoaded && !isFetchingRef.current) {- // Handlers eagerly set isDataLoading so the overlay appears immediately.- // If the fetchKey didn't actually change (e.g. applying empty filters when- // none were active), no fetch runs — reset loading to avoid getting stuck.- setIsDataLoading(false);- }-- const pageSizeRef = useRef(pageSize);- pageSizeRef.current = pageSize;- const sortsRef = useRef(sorts);- sortsRef.current = sorts;-- const handleFiltersChange = useCallback(- async (newFilters: FilterCondition[]): Promise<boolean> => {- setFilters(newFilters);- setOffset(0);- // Update prevFetchKeyRef so the render-time pattern doesn't double-fire- prevFetchKeyRef.current = `${schema}.${table}.${0}.${pageSizeRef.current}.${JSON.stringify(newFilters)}.${JSON.stringify(sortsRef.current)}`;- const result = await fetchData(0, pageSizeRef.current, newFilters, sortsRef.current);- return result >= 0;- },- [schema, table, fetchData]- );-- const handleSortsChange = useCallback((newSorts: SortCondition[]) => {- setIsDataLoading(true);- setSorts(newSorts);- setOffset(0);- }, []);-- const handleOffsetChange = useCallback((newOffset: number) => {- setIsDataLoading(true);- setOffset(Math.max(0, newOffset));- }, []);-- const handlePageSizeChange = useCallback((newSize: number) => {- setIsDataLoading(true);- setPageSize(newSize);- setOffset(0);- }, []);-- // PK-based lookup map for O(1) original row matching (avoids index misalignment after prepend)- const originalDataByPk = useMemo(() => {- if (primaryKeys.length === 0) return null;- const map = new Map<string, Record<string, unknown>>();- originalData.forEach((row) => {- map.set(getRowKey(row, primaryKeys), row);- });- return map;- }, [originalData, primaryKeys]);-- const originalDataByPkRef = useRef(originalDataByPk);- originalDataByPkRef.current = originalDataByPk;-- // Change tracking — use PK-based lookup so new row prepends don't misalign indices- const changeCount = useMemo(() => {- let count = newRowTempIds.size;- if (!originalDataByPk) return count;- currentData.forEach((row) => {- if (row.tempRowId && newRowTempIds.has(String(row.tempRowId))) return;- const key = row.originalPkKey as string;- if (!key) return;- const original = originalDataByPk.get(key);- if (!original) return;- const hasChanges = tableColumns.some(- (col) => !cellValuesEqual(row[col.name], original[col.name])- );- if (hasChanges) count += 1;- });- return count;- }, [currentData, originalDataByPk, primaryKeys, newRowTempIds, tableColumns]);-- const handleAddRecord = useCallback(() => {- newRowCounterRef.current += 1;- const tempId = `${ROW_KEY_PREFIX}${newRowCounterRef.current}`;- const newRow: Record<string, unknown> = { tempRowId: tempId };- tableColumns.forEach((col) => {- newRow[col.name] = null;- });- setCurrentData((prev) => [newRow, ...prev]);- setNewRowTempIds((prev) => new Set(prev).add(tempId));- return null;- }, [tableColumns]);-- const handleRowsDelete = useCallback(- async (_rows: Record<string, unknown>[], rowIndices: number[]) => {- const tempIdsToRemove: string[] = [];- const deleteStatements: string[] = [];-- rowIndices.forEach((idx) => {- const row = currentData[idx];- if (!row) return;- const tempId = row.tempRowId ? String(row.tempRowId) : null;- if (tempId) {- tempIdsToRemove.push(tempId);- } else {- deleteStatements.push(- buildDeleteQuery({ schema, table, primaryKeyMatch: getPkMatch(row, primaryKeys) })- );- }- });-- // Remove unsaved new rows from local state immediately- if (tempIdsToRemove.length > 0) {- const tempIdSet = new Set(tempIdsToRemove);- setCurrentData((prev) =>- prev.filter((r) => !r.tempRowId || !tempIdSet.has(String(r.tempRowId)))- );- setNewRowTempIds((prev) => {- const next = new Set(prev);- tempIdsToRemove.forEach((id) => next.delete(id));- return next;- });- }-- // Execute DELETE SQL for persisted rows immediately- if (deleteStatements.length > 0) {- try {- const sql = wrapInTransaction(deleteStatements);- await executeQuery(connectionId, sql);- createNotification({- text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,- type: "success"- });- const rowCount = await fetchData(offset, pageSize, filters, sorts);- if (rowCount === 0 && offset > 0) {- setOffset(Math.max(0, offset - pageSize));- }- } catch (err) {- createNotification({- title: "Delete failed",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- }- }- },- [- currentData,- primaryKeys,- schema,- table,- connectionId,- executeQuery,- fetchData,- offset,- pageSize,- filters,- sorts- ]- );-- const handleDiscard = useCallback(() => {- setCurrentData(originalData);- setNewRowTempIds(new Set());- }, [originalData]);-- const handleSave = useCallback(async () => {- setIsSaving(true);- try {- const statements: string[] = [];-- // Inserts (new rows)- currentData.forEach((row) => {- const tempId = row.tempRowId ? String(row.tempRowId) : null;- if (!tempId || !newRowTempIds.has(tempId)) return;- const values: Record<string, unknown> = {};- tableColumns.forEach((col) => {- if (- row[col.name] !== null &&- row[col.name] !== undefined &&- String(row[col.name]) !== ""- ) {- values[col.name] = row[col.name];- }- });- statements.push(buildInsertQuery({ schema, table, row: values }));- });-- // Updates (changed rows) — use PK-based lookup so prepends don't misalign- const pkMap = originalDataByPk;- currentData.forEach((row) => {- if (row.tempRowId) return;- const key = row.originalPkKey as string;- const original = key && pkMap ? pkMap.get(key) : undefined;- if (!original) return;- const changes: Record<string, unknown> = {};- tableColumns.forEach((col) => {- if (!cellValuesEqual(row[col.name], original[col.name])) {- changes[col.name] = row[col.name];- }- });- if (Object.keys(changes).length > 0) {- statements.push(- buildUpdateQuery({- schema,- table,- changes,- primaryKeyMatch: getPkMatch(original, primaryKeys)- })- );- }- });-- if (statements.length === 0) {- createNotification({ text: "No changes to save", type: "info" });- setIsSaving(false);- return;- }-- const sql = wrapInTransaction(statements);-- // The WebSocket maxPayload is 64 KB. Guard against sending a query- // that would exceed the limit and silently kill the connection.- const MAX_QUERY_SIZE = 50 * 1024;- if (sql.length > MAX_QUERY_SIZE) {- createNotification({- title: "Save failed",- text: "Changes are too large to save at once. Try saving fewer or smaller changes.",- type: "error"- });- setIsSaving(false);- return;- }-- await executeQuery(connectionId, sql);- createNotification({- text: `Saved ${statements.length} change${statements.length !== 1 ? "s" : ""}`,- type: "success"- });-- await fetchData(offset, pageSize, filters, sorts);- } catch (err) {- createNotification({- title: "Save failed",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- } finally {- setIsSaving(false);- }- }, [- currentData,- originalDataByPk,- newRowTempIds,- tableColumns,- primaryKeys,- schema,- table,- connectionId,- executeQuery,- fetchData,- offset,- pageSize,- filters,- sorts- ]);-- const handleDataChange = useCallback((newData: Record<string, unknown>[]) => {- setCurrentData(newData);- }, []);-- // Use refs so the callback identity is stable (survives tableMeta useMemo)- // while always reading the latest data.- const currentDataRef = useRef(currentData);- currentDataRef.current = currentData;- const newRowTempIdsRef = useRef(newRowTempIds);- newRowTempIdsRef.current = newRowTempIds;-- const getIsCellDirty = useCallback((rowIndex: number, columnId: string) => {- const row = currentDataRef.current[rowIndex];- if (!row) return false;- if (row.tempRowId && newRowTempIdsRef.current.has(String(row.tempRowId))) return true;- const pkMap = originalDataByPkRef.current;- if (!pkMap) return false;- const key = row.originalPkKey as string;- if (!key) return false;- const original = pkMap.get(key);- if (!original) return false;- return !cellValuesEqual(row[columnId], original[columnId]);- }, []);-- const getIsRowNew = useCallback((rowIndex: number) => {- const row = currentDataRef.current[rowIndex];- if (!row) return false;- return Boolean(row.tempRowId && newRowTempIdsRef.current.has(String(row.tempRowId)));- }, []);-- // Stable row identity for TanStack Table- const getRowId = useCallback(- (row: Record<string, unknown>, index: number) => {- if (row.tempRowId) return String(row.tempRowId);- if (row.originalPkKey) return row.originalPkKey as string;- if (primaryKeys.length > 0) return getRowKey(row, primaryKeys);- return String(index);- },- [primaryKeys]- );-- // Dice UI DataGrid- const gridProps = useDataGrid<Record<string, unknown>>({- data: currentData,- columns: columnDefs,- onDataChange: handleDataChange,- getRowId,- readOnly: !hasPrimaryKey,- rowHeight: "short",- enableSearch: true,- enablePaste: hasPrimaryKey,- onRowsDelete: hasPrimaryKey ? handleRowsDelete : undefined,- onRowSelectionChange: (rowSelection) => {- const selectedIds = new Set(Object.keys(rowSelection).filter((k) => rowSelection[k]));- setSelectedRowCount(selectedIds.size);- if (selectedIds.size > 0) {- selectedRowsRef.current = currentData.filter((_row, idx) =>- selectedIds.has(getRowId(_row, idx))- );- } else {- selectedRowsRef.current = [];- }- },- meta: { getIsCellDirty, getIsRowNew } as Record<string, unknown>- });- gridRef.current = gridProps.table;-- const handleDeleteSelected = useCallback(async () => {- // Use the snapshot captured at selection time — by the time this click handler- // fires, the DataGrid's outside-click listener has already cleared rowSelection.- const rows = selectedRowsRef.current;- if (rows.length === 0) return;-- const tempIdsToRemove: string[] = [];- const deleteStatements: string[] = [];-- rows.forEach((row) => {- const tempId = row.tempRowId ? String(row.tempRowId) : null;- if (tempId) {- tempIdsToRemove.push(tempId);- } else {- deleteStatements.push(- buildDeleteQuery({ schema, table, primaryKeyMatch: getPkMatch(row, primaryKeys) })- );- }- });-- // Remove unsaved new rows from local state immediately- if (tempIdsToRemove.length > 0) {- const tempIdSet = new Set(tempIdsToRemove);- setCurrentData((prev) =>- prev.filter((r) => !r.tempRowId || !tempIdSet.has(String(r.tempRowId)))- );- setNewRowTempIds((prev) => {- const next = new Set(prev);- tempIdsToRemove.forEach((id) => next.delete(id));- return next;- });- }-- // Execute DELETE SQL for persisted rows- if (deleteStatements.length > 0) {- try {- const sql = wrapInTransaction(deleteStatements);- await executeQuery(connectionId, sql);- createNotification({- text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,- type: "success"- });- const rowCount = await fetchData(offset, pageSize, filters, sorts);- if (rowCount === 0 && offset > 0) {- setOffset(Math.max(0, offset - pageSize));- }- } catch (err) {- createNotification({- title: "Delete failed",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- }- }-- gridRef.current?.resetRowSelection();- selectedRowsRef.current = [];- setSelectedRowCount(0);- }, [- schema,- table,- primaryKeys,- connectionId,- executeQuery,- fetchData,- offset,- pageSize,- filters,- sorts- ]);-- if (!tableDetail) {- return (- <div className="flex flex-1 items-center justify-center">- <Skeleton className="h-64 w-96" />- </div>- );- }-- return (- <div className="flex flex-1 flex-col overflow-hidden">- <DataExplorerToolbar- columns={tableColumns}- filters={filters}- onFiltersChange={handleFiltersChange}- sorts={sorts}- onSortsChange={handleSortsChange}- changeCount={changeCount}- onSave={handleSave}- onDiscard={handleDiscard}- isSaving={isSaving}- onAddRecord={handleAddRecord}- selectedRowCount={selectedRowCount}- onDeleteSelected={handleDeleteSelected}- totalCount={totalCount}- offset={offset}- pageSize={pageSize}- onOffsetChange={handleOffsetChange}- onPageSizeChange={handlePageSizeChange}- executionTimeMs={executionTimeMs}- hasPrimaryKey={hasPrimaryKey}- isDataLoading={isDataLoading}- onRefresh={async () => {- if (onRefresh) await onRefresh();- await fetchData(offset, pageSize, filters, sorts);- }}- isRefreshing={isDataLoading && hasLoaded}- onExport={(fmt) =>- exportData(- currentData,- tableColumns.map((c) => c.name),- fmt- )- }- onCopy={(fmt) =>- copyData(- currentData,- tableColumns.map((c) => c.name),- fmt- )- }- hasData={currentData.length > 0}- />-- {!hasPrimaryKey && (- <div className="shrink-0 px-3 py-3">- <Alert variant="info" className="py-2">- <EyeIcon />- <AlertDescription>- {tableType === "view" || tableType === "materialized_view"- ? "This view is read-only."- : "This table has no primary key. Browsing is read-only — editing requires a primary key."}- </AlertDescription>- </Alert>- </div>- )}-- {/* Dice UI DataGrid */}- <div className="data-explorer-grid relative flex min-h-0 flex-1 flex-col overflow-hidden font-mono text-foreground [--color-gray-200:var(--color-border)] [&_[data-slot=grid-footer]]:hidden [&_[data-slot=grid-header]]:bg-container [&_[data-slot=grid]]:thin-scrollbar [&_[data-slot=grid]]:rounded-none [&_[data-slot=grid]]:border-0 [&_[data-slot=grid]]:bg-bunker-800">- {isDataLoading && !hasLoaded && <ContentLoader className="h-full" />}- <DataGrid- {...gridProps}- className={`min-h-0 flex-1 ${isDataLoading && !hasLoaded ? "hidden" : ""}`}- stretchColumns- />- {isDataLoading && hasLoaded && (- <div className="absolute inset-0 z-20 flex items-center justify-center bg-bunker-800/60">- <ContentLoader className="h-auto" lottieClassName="h-24 w-24" />- </div>- )}- </div>- </div>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsxdeleted file mode 100644index 1144f5e9bd..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerRowEditor.tsx+++ /dev/null@@ -1,143 +0,0 @@-// NOTE: This component is not currently wired up but is kept for future use-// as a side-sheet row editor for the data explorer grid.-import { useEffect, useState } from "react";--import { Badge } from "@app/components/v3/generic/Badge";-import { Button } from "@app/components/v3/generic/Button";-import { Input } from "@app/components/v3/generic/Input";-import {- Sheet,- SheetContent,- SheetFooter,- SheetHeader,- SheetTitle-} from "@app/components/v3/generic/Sheet";-import { TextArea } from "@app/components/v3/generic/TextArea";--import type { ColumnInfo } from "../data-explorer-types";--type DataExplorerRowEditorProps = {- isOpen: boolean;- onOpenChange: (open: boolean) => void;- row: Record<string, unknown> | null;- columns: ColumnInfo[];- primaryKeys: string[];- onApply: (updates: Record<string, unknown>) => void;-};--const JSON_TYPES = new Set(["json", "jsonb", "xml"]);--export const DataExplorerRowEditor = ({- isOpen,- onOpenChange,- row,- columns,- primaryKeys,- onApply-}: DataExplorerRowEditorProps) => {- const [formValues, setFormValues] = useState<Record<string, string>>({});-- useEffect(() => {- if (row) {- const values: Record<string, string> = {};- columns.forEach((col) => {- const val = row[col.name];- values[col.name] = val === null || val === undefined ? "" : String(val);- });- setFormValues(values);- }- }, [row, columns]);-- const handleApply = () => {- const updates: Record<string, unknown> = {};- columns.forEach((col) => {- const newVal = formValues[col.name] ?? "";- const oldVal = row?.[col.name];- const oldStr = oldVal === null || oldVal === undefined ? "" : String(oldVal);- if (newVal !== oldStr) {- // If field is empty and column is nullable, set to null- updates[col.name] = newVal === "" && col.nullable ? null : newVal;- }- });- onApply(updates);- onOpenChange(false);- };-- const isPk = (colName: string) => primaryKeys.includes(colName);- const isReadOnly = (col: ColumnInfo) => isPk(col.name) || col.identityGeneration === "ALWAYS";-- return (- <Sheet open={isOpen} onOpenChange={onOpenChange}>- <SheetContent className="overflow-y-auto sm:max-w-lg">- <SheetHeader>- <SheetTitle>Edit Row</SheetTitle>- </SheetHeader>- <div className="space-y-3 py-4">- {columns.map((col) => {- const readOnly = isReadOnly(col);- const value = formValues[col.name] ?? "";- const isNull = row?.[col.name] === null;- const isJsonType = JSON_TYPES.has(col.type.replace("[]", ""));-- return (- <div key={col.name}>- <div className="mb-1 flex items-center gap-2">- {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}- <label- htmlFor={`row-editor-${col.name}`}- className="text-xs font-medium text-mineshaft-200"- >- {col.name}- </label>- <Badge variant="outline" className="text-[10px]">- {col.type}- </Badge>- {isPk(col.name) && <Badge className="text-[10px]">PK</Badge>}- {col.nullable && (- <Badge variant="outline" className="text-[10px]">- nullable- </Badge>- )}- {isNull && (- <Badge variant="outline" className="text-[10px] text-yellow-500">- NULL- </Badge>- )}- </div>- {isJsonType ? (- <TextArea- value={value}- onChange={(e) =>- setFormValues((prev) => ({ ...prev, [col.name]: e.target.value }))- }- disabled={readOnly}- className="font-mono text-xs"- rows={4}- />- ) : (- <Input- value={value}- onChange={(e) =>- setFormValues((prev) => ({ ...prev, [col.name]: e.target.value }))- }- disabled={readOnly}- className="text-xs"- placeholder={isNull ? "NULL" : undefined}- />- )}- </div>- );- })}- </div>- <SheetFooter className="gap-2">- <Button variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button variant="info" onClick={handleApply}>- Apply- </Button>- </SheetFooter>- </SheetContent>- </Sheet>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsxdeleted file mode 100644index 66920b1b05..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx+++ /dev/null@@ -1,198 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";-import { DatabaseIcon, SearchIcon, TableIcon, ViewIcon } from "lucide-react";--import { Input } from "@app/components/v3/generic/Input";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue-} from "@app/components/v3/generic/Select/Select";-import { Skeleton } from "@app/components/v3/generic/Skeleton";-import { cn } from "@app/components/v3/utils";--import type { SchemaInfo, TableInfo } from "../data-explorer-types";--type SelectedTab = { schema: string; table: string };--type DataExplorerSidebarProps = {- schemas: SchemaInfo[];- selectedSchema: string;- onSchemaChange: (schema: string) => void;- tables: TableInfo[];- activeBrowseTarget: SelectedTab | null;- onTableOpen: (table: string, opts: { forceNew: boolean }) => void;- isLoadingSchemas: boolean;- isLoadingTables: boolean;- disabled?: boolean;-};--type ContextMenuState = {- tableName: string;- x: number;- y: number;-};--export const DataExplorerSidebar = ({- schemas,- selectedSchema,- onSchemaChange,- tables,- activeBrowseTarget,- onTableOpen,- isLoadingSchemas,- isLoadingTables,- disabled = false-}: DataExplorerSidebarProps) => {- const [search, setSearch] = useState("");- const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);- const menuRef = useRef<HTMLDivElement>(null);-- // Reset search when schema changes- useEffect(() => {- setSearch("");- }, [selectedSchema]);-- // Close context menu on outside click / Escape- useEffect(() => {- if (!contextMenu) return undefined;- const handleDown = (e: MouseEvent) => {- if (menuRef.current && !menuRef.current.contains(e.target as Node)) {- setContextMenu(null);- }- };- const handleKey = (e: KeyboardEvent) => {- if (e.key === "Escape") setContextMenu(null);- };- window.addEventListener("mousedown", handleDown);- window.addEventListener("keydown", handleKey);- return () => {- window.removeEventListener("mousedown", handleDown);- window.removeEventListener("keydown", handleKey);- };- }, [contextMenu]);-- const filteredTables = tables.filter((t) => t.name.toLowerCase().includes(search.toLowerCase()));-- const getTableIcon = useCallback((tableType: string) => {- if (tableType === "view" || tableType === "materialized_view") {- return <ViewIcon className="size-3.5 shrink-0 text-accent" />;- }- return <TableIcon className="size-3.5 shrink-0 text-accent" />;- }, []);-- const handleClick = (name: string, e: React.MouseEvent) => {- if (disabled) return;- const forceNew = e.metaKey || e.ctrlKey;- onTableOpen(name, { forceNew });- };-- const handleContextMenu = (name: string, e: React.MouseEvent) => {- if (disabled) return;- e.preventDefault();- setContextMenu({ tableName: name, x: e.clientX, y: e.clientY });- };-- const handleOpenInNewTab = () => {- if (!contextMenu) return;- onTableOpen(contextMenu.tableName, { forceNew: true });- setContextMenu(null);- };-- return (- <div className="flex h-full w-64 shrink-0 flex-col border-r border-border bg-container">- {/* Schema selector + Search */}- <div className="space-y-2 border-b border-border p-3">- {isLoadingSchemas ? (- <Skeleton className="h-8 w-full" />- ) : (- <Select value={selectedSchema} onValueChange={onSchemaChange} disabled={disabled}>- <SelectTrigger className="h-9 w-full text-xs text-foreground">- <span className="flex items-center gap-1.5">- <DatabaseIcon className="size-3.5 text-accent" />- <SelectValue />- </span>- </SelectTrigger>- <SelectContent position="popper">- {schemas.map((s) => (- <SelectItem key={s.name} value={s.name}>- {s.name}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- <div className="relative">- <SearchIcon className="absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-accent" />- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search tables..."- className="pl-7 text-xs text-foreground"- />- </div>- </div>-- {/* Table list */}- <div className="thin-scrollbar flex-1 overflow-y-auto">- {isLoadingTables && tables.length === 0 && (- <div className="space-y-1 p-2">- {Array.from({ length: 8 }).map((_, i) => (- // eslint-disable-next-line react/no-array-index-key- <Skeleton key={i} className="h-7 w-full" />- ))}- </div>- )}- {!isLoadingTables && filteredTables.length === 0 && (- <div className="p-4 text-center text-xs text-accent">- {search ? "No matching tables" : "No tables in this schema"}- </div>- )}- {!isLoadingTables && filteredTables.length > 0 && (- <div className="p-1">- {filteredTables.map((t) => {- const isActive =- activeBrowseTarget?.schema === selectedSchema &&- activeBrowseTarget.table === t.name;- return (- <button- key={t.name}- type="button"- disabled={disabled}- onClick={(e) => handleClick(t.name, e)}- onContextMenu={(e) => handleContextMenu(t.name, e)}- className={cn(- "flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-xs text-muted transition-colors hover:bg-container-hover disabled:cursor-not-allowed disabled:opacity-50",- isActive && "bg-container-hover text-foreground"- )}- >- {getTableIcon(t.tableType)}- <span className="truncate" title={t.name}>- {t.name}- </span>- </button>- );- })}- </div>- )}- </div>-- {contextMenu && (- <div- ref={menuRef}- style={{ position: "fixed", top: contextMenu.y, left: contextMenu.x, zIndex: 50 }}- className="min-w-[160px] rounded-md border border-border bg-popover p-1 text-xs text-foreground shadow-md"- >- <button- type="button"- onClick={handleOpenInNewTab}- className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left hover:bg-container-hover"- >- Open in new tab- </button>- </div>- )}- </div>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsxdeleted file mode 100644index 54d225036b..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx+++ /dev/null@@ -1,307 +0,0 @@-import { useState } from "react";-import {- ChevronLeftIcon,- ChevronRightIcon,- ClockIcon,- PlusIcon,- RefreshCwIcon,- SaveIcon,- Trash2Icon,- UndoIcon-} from "lucide-react";--import { Button } from "@app/components/v3/generic/Button";-import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";--import type { ColumnInfo } from "../data-explorer-types";-import type { ExportFormat } from "../data-export";-import type { FilterCondition, SortCondition } from "../sql-generation";-import { ExportDropdown } from "./ExportDropdown";-import { FilterPopover } from "./FilterPopover";-import { SortPopover } from "./SortPopover";--type DataExplorerToolbarProps = {- columns: ColumnInfo[];- filters: FilterCondition[];- onFiltersChange: (filters: FilterCondition[]) => Promise<boolean>;- sorts: SortCondition[];- onSortsChange: (sorts: SortCondition[]) => void;- changeCount: number;- onSave: () => void;- onDiscard: () => void;- isSaving: boolean;- onAddRecord: () => void;- selectedRowCount: number;- onDeleteSelected: () => void;- totalCount: number;- offset: number;- pageSize: number;- onOffsetChange: (offset: number) => void;- onPageSizeChange: (size: number) => void;- executionTimeMs: number | null;- hasPrimaryKey: boolean;- isDataLoading?: boolean;- onRefresh: () => void;- isRefreshing?: boolean;- onExport: (format: ExportFormat) => void;- onCopy: (format: ExportFormat) => void;- hasData: boolean;-};--export const DataExplorerToolbar = ({- columns,- filters,- onFiltersChange,- sorts,- onSortsChange,- changeCount,- onSave,- onDiscard,- isSaving,- onAddRecord,- selectedRowCount,- onDeleteSelected,- totalCount,- offset,- pageSize,- onOffsetChange,- onPageSizeChange,- executionTimeMs,- hasPrimaryKey,- isDataLoading = false,- onRefresh,- isRefreshing = false,- onExport,- onCopy,- hasData-}: DataExplorerToolbarProps) => {- const rangeStart = totalCount === 0 ? 0 : offset + 1;- const rangeEnd = Math.min(offset + pageSize, totalCount);-- return (- <div- role="toolbar"- data-grid-popover=""- className="flex items-center justify-between border-b border-border px-3 py-1.5"- onMouseDown={(e) => e.stopPropagation()}- >- <div className="flex items-center gap-2">- <FilterPopover columns={columns} filters={filters} onFiltersChange={onFiltersChange} />- <SortPopover- columns={columns}- sorts={sorts}- onSortsChange={onSortsChange}- disabled={isDataLoading}- />-- {hasPrimaryKey && (- <>- <div className="h-4 w-px bg-border" />- <Button variant="outline" size="xs" onClick={onAddRecord} className="gap-1">- <PlusIcon className="size-3" />- Add record- </Button>- </>- )}-- {selectedRowCount > 0 && hasPrimaryKey && (- <Button variant="danger" size="xs" onClick={onDeleteSelected} className="gap-1">- <Trash2Icon className="size-3" />- Delete {selectedRowCount} record{selectedRowCount !== 1 ? "s" : ""}- </Button>- )}-- {changeCount > 0 && (- <>- <div className="h-4 w-px bg-border" />- <Button- variant="success"- size="xs"- onClick={onSave}- isPending={isSaving}- className="gap-1"- >- <SaveIcon className="size-3" />- Save {changeCount} change{changeCount !== 1 ? "s" : ""}- </Button>- <Button variant="ghost" size="xs" onClick={onDiscard} className="gap-1 underline">- <UndoIcon className="size-3" />- Discard changes- </Button>- </>- )}- </div>-- <div className="flex items-center gap-2">- {executionTimeMs !== null && (- <span className="flex items-center gap-1 text-xs text-accent">- <ClockIcon className="size-3" />- {executionTimeMs}ms- </span>- )}-- {/* Pagination */}- <Button- variant="ghost"- size="xs"- disabled={offset <= 0}- onClick={() => onOffsetChange(Math.max(0, offset - pageSize))}- className="size-7 p-0"- >- <ChevronLeftIcon className="size-3.5" />- </Button>- {/* eslint-disable-next-line @typescript-eslint/no-use-before-define */}- <LimitOffsetPopover- totalCount={totalCount}- rangeStart={rangeStart}- rangeEnd={rangeEnd}- pageSize={pageSize}- offset={offset}- onPageSizeChange={onPageSizeChange}- onOffsetChange={onOffsetChange}- />- <Button- variant="ghost"- size="xs"- disabled={offset + pageSize >= totalCount}- onClick={() => onOffsetChange(offset + pageSize)}- className="size-7 p-0"- >- <ChevronRightIcon className="size-3.5" />- </Button>-- {/* Export */}- <ExportDropdown onExport={onExport} onCopy={onCopy} disabled={!hasData} />-- {/* Refresh */}- <Button- variant="ghost"- size="xs"- onClick={onRefresh}- disabled={isRefreshing}- className="size-7 p-0"- >- <RefreshCwIcon className={`size-3.5 ${isRefreshing ? "animate-spin" : ""}`} />- </Button>- </div>- </div>- );-};--// --- Limit / Offset popover -----type LimitOffsetPopoverProps = {- totalCount: number;- rangeStart: number;- rangeEnd: number;- pageSize: number;- offset: number;- onPageSizeChange: (size: number) => void;- onOffsetChange: (offset: number) => void;-};--const LimitOffsetPopover = ({- totalCount,- rangeStart,- rangeEnd,- pageSize,- offset,- onPageSizeChange,- onOffsetChange-}: LimitOffsetPopoverProps) => {- const [open, setOpen] = useState(false);- const [limitInput, setLimitInput] = useState(String(pageSize));- const [offsetInput, setOffsetInput] = useState(String(offset));-- const handleOpen = (isOpen: boolean) => {- if (isOpen) {- setLimitInput(String(pageSize));- setOffsetInput(String(offset));- }- setOpen(isOpen);- };-- const limitNum = Number(limitInput);- const getLimitError = (): string | null => {- if (limitInput === "" || Number.isNaN(limitNum)) return "Must be a number";- if (limitNum < 1) return "Minimum is 1";- if (limitNum > 1000) return "Maximum is 1000";- return null;- };- const limitError = getLimitError();-- const offsetNum = Number(offsetInput);- const getOffsetError = (): string | null => {- if (offsetInput === "" || Number.isNaN(offsetNum)) return "Must be a number";- if (offsetNum < 0) return "Must be 0 or greater";- return null;- };- const offsetError = getOffsetError();-- const applyChanges = () => {- if (limitError || offsetError) return;- const newLimit = Math.max(1, Math.min(1000, limitNum || 50));- const newOffset = Math.max(0, offsetNum || 0);- onPageSizeChange(newLimit);- onOffsetChange(newOffset);- setOpen(false);- };-- return (- <Popover open={open} onOpenChange={handleOpen}>- <PopoverTrigger asChild>- <Button variant="ghost" size="xs" className="text-muted">- {rangeStart} - {rangeEnd} of {totalCount}- </Button>- </PopoverTrigger>- <PopoverContent className="w-auto p-3" align="center">- <div className="flex flex-col gap-2">- <div className="flex items-center gap-3">- <div className="flex flex-col items-center gap-1">- <span className="text-[10px] font-medium text-accent">Limit</span>- <input- type="number"- value={limitInput}- onChange={(e) => setLimitInput(e.target.value)}- onKeyDown={(e) => e.key === "Enter" && applyChanges()}- className={`h-8 w-16 rounded border bg-transparent text-center text-sm text-mineshaft-200 outline-none ${- limitError- ? "border-red-500 focus:border-red-500"- : "border-border focus:border-ring"- }`}- min={1}- />- </div>- <div className="flex flex-col items-center gap-1">- <span className="text-[10px] font-medium text-accent">Offset</span>- <input- type="number"- value={offsetInput}- onChange={(e) => setOffsetInput(e.target.value)}- onKeyDown={(e) => e.key === "Enter" && applyChanges()}- className={`h-8 w-16 rounded border bg-transparent text-center text-sm text-mineshaft-200 outline-none ${- offsetError- ? "border-red-500 focus:border-red-500"- : "border-border focus:border-ring"- }`}- min={0}- />- </div>- </div>- {(limitError || offsetError) && (- <p className="text-center text-[10px] text-red-400">{limitError || offsetError}</p>- )}- <Button- variant="outline"- size="xs"- onClick={applyChanges}- disabled={Boolean(limitError || offsetError)}- className="w-full"- >- Apply- </Button>- </div>- </PopoverContent>- </Popover>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/ExportDropdown.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/ExportDropdown.tsxdeleted file mode 100644index e1d55aec01..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/ExportDropdown.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { ClipboardCopyIcon, DownloadIcon } from "lucide-react";--import { Button } from "@app/components/v3/generic/Button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger-} from "@app/components/v3/generic/Dropdown";--import type { ExportFormat } from "../data-export";--type Props = {- onExport: (format: ExportFormat) => void;- onCopy: (format: ExportFormat) => void;- disabled?: boolean;-};--export function ExportDropdown({ onExport, onCopy, disabled }: Props) {- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="xs" disabled={disabled} title="Export">- <DownloadIcon />- Export- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => onExport("csv")}>- <DownloadIcon className="size-3.5" />- Download as CSV- </DropdownMenuItem>- <DropdownMenuItem onClick={() => onExport("json")}>- <DownloadIcon className="size-3.5" />- Download as JSON- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={() => onCopy("csv")}>- <ClipboardCopyIcon className="size-3.5" />- Copy as CSV- </DropdownMenuItem>- <DropdownMenuItem onClick={() => onCopy("json")}>- <ClipboardCopyIcon className="size-3.5" />- Copy as JSON- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsxdeleted file mode 100644index f1dd4c18b6..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/FilterPopover.tsx+++ /dev/null@@ -1,264 +0,0 @@-import { useEffect, useState } from "react";-import { CheckIcon, FilterIcon, PlusIcon, XIcon } from "lucide-react";--import { Button } from "@app/components/v3/generic/Button";-import { Input } from "@app/components/v3/generic/Input";-import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue-} from "@app/components/v3/generic/Select";--import type { ColumnInfo } from "../data-explorer-types";-import type { FilterCondition, FilterOperator } from "../sql-generation";--function getFilterPlaceholder(columnType: string, operator: FilterOperator): string {- switch (operator) {- case "LIKE":- return "%pattern%";- case "ILIKE":- return "%pattern% (case-insensitive)";- case "IN":- return "a, b, c";- case "IS NULL":- case "IS NOT NULL":- return "";- default:- break;- }-- const t = columnType.toLowerCase().replace("[]", "");- switch (t) {- case "int2":- case "int4":- case "int8":- case "serial":- case "bigserial":- case "smallserial":- case "integer":- case "bigint":- case "smallint":- return "42";- case "float4":- case "float8":- case "numeric":- case "decimal":- case "real":- case "double precision":- case "money":- return "3.14";- case "bool":- case "boolean":- return "true";- case "uuid":- return "550e8400-e29b-41d4-a716-...";- case "date":- return "2024-01-15";- case "timestamp":- case "timestamptz":- return "2024-01-15 09:30:00";- case "time":- case "timetz":- return "09:30:00";- case "json":- case "jsonb":- return '{"key": "value"}';- case "inet":- case "cidr":- return "192.168.1.0/24";- case "text":- case "varchar":- case "char":- case "bpchar":- case "name":- case "citext":- return "some text";- default:- return "Value";- }-}--const OPERATORS: { value: FilterOperator; label: string; needsValue: boolean }[] = [- { value: "=", label: "equals", needsValue: true },- { value: "<>", label: "not equals", needsValue: true },- { value: ">", label: "greater than", needsValue: true },- { value: "<", label: "less than", needsValue: true },- { value: ">=", label: "greater or equal", needsValue: true },- { value: "<=", label: "less or equal", needsValue: true },- { value: "LIKE", label: "like", needsValue: true },- { value: "ILIKE", label: "ilike", needsValue: true },- { value: "IS NULL", label: "is null", needsValue: false },- { value: "IS NOT NULL", label: "is not null", needsValue: false },- { value: "IN", label: "in", needsValue: true }-];--type FilterPopoverProps = {- columns: ColumnInfo[];- filters: FilterCondition[];- onFiltersChange: (filters: FilterCondition[]) => Promise<boolean>;-};--export const FilterPopover = ({ columns, filters, onFiltersChange }: FilterPopoverProps) => {- const [open, setOpen] = useState(false);- const [draft, setDraft] = useState<FilterCondition[]>(filters);- const [isApplying, setIsApplying] = useState(false);-- // Sync draft when external filters change (e.g. cleared from outside)- useEffect(() => {- if (!open) {- setDraft(filters);- }- }, [filters, open]);-- // Reset draft when popover opens; prevent close while applying- const handleOpenChange = (isOpen: boolean) => {- if (!isOpen && isApplying) return;- if (isOpen) {- setDraft(filters);- }- setOpen(isOpen);- };-- const addFilter = () => {- if (columns.length === 0) return;- setDraft((prev) => [...prev, { column: columns[0].name, operator: "=", value: "" }]);- };-- const removeFilter = (index: number) => {- setDraft((prev) => prev.filter((_, i) => i !== index));- };-- const updateFilter = (index: number, update: Partial<FilterCondition>) => {- setDraft((prev) => prev.map((f, i) => (i === index ? { ...f, ...update } : f)));- };-- const clearAll = async () => {- setIsApplying(true);- await onFiltersChange([]);- setIsApplying(false);- setOpen(false);- };-- const applyFilters = async () => {- setIsApplying(true);- const success = await onFiltersChange(draft);- setIsApplying(false);- if (success) setOpen(false);- };-- return (- <Popover open={open} onOpenChange={handleOpenChange}>- <PopoverTrigger asChild>- <Button variant="outline" size="xs" className="gap-1.5">- <FilterIcon className="size-3" />- Filter- {filters.length > 0 && (- <span className="rounded-full bg-primary/20 px-1.5 text-[10px] font-medium text-primary">- {filters.length}- </span>- )}- </Button>- </PopoverTrigger>- <PopoverContent className="w-[580px] p-3" align="start">- <div className="mb-2 flex items-center justify-between">- <span className="text-sm font-medium text-mineshaft-200">Filters</span>- {draft.length > 0 && (- <Button variant="ghost" size="xs" onClick={clearAll} className="h-auto p-0 text-xs">- Clear all- </Button>- )}- </div>-- {draft.length === 0 ? (- <p className="py-3 text-center text-xs text-mineshaft-400">No filters applied</p>- ) : (- <div className="space-y-2">- {draft.map((filter, index) => {- const opConfig = OPERATORS.find((o) => o.value === filter.operator);- const colInfo = columns.find((c) => c.name === filter.column);- return (- // eslint-disable-next-line react/no-array-index-key- <div key={index} className="flex items-center gap-1.5">- <Select- value={filter.column}- onValueChange={(val) => updateFilter(index, { column: val })}- >- <SelectTrigger- size="sm"- className="w-40 text-xs text-mineshaft-200"- title={filter.column}- >- <SelectValue />- </SelectTrigger>- <SelectContent>- {columns.map((col) => (- <SelectItem key={col.name} value={col.name}>- {col.name}- </SelectItem>- ))}- </SelectContent>- </Select>-- <Select- value={filter.operator}- onValueChange={(val) =>- updateFilter(index, { operator: val as FilterOperator })- }- >- <SelectTrigger size="sm" className="w-28 text-xs text-mineshaft-200">- <SelectValue />- </SelectTrigger>- <SelectContent>- {OPERATORS.map((op) => (- <SelectItem key={op.value} value={op.value}>- {op.label}- </SelectItem>- ))}- </SelectContent>- </Select>-- {opConfig?.needsValue !== false && (- <Input- value={filter.value}- onChange={(e) => updateFilter(index, { value: e.target.value })}- placeholder={getFilterPlaceholder(colInfo?.type ?? "", filter.operator)}- className="h-7 flex-1 text-xs text-mineshaft-200"- />- )}-- <button- type="button"- onClick={() => removeFilter(index)}- className="rounded p-1 text-mineshaft-400 hover:bg-mineshaft-700 hover:text-mineshaft-200"- >- <XIcon className="size-3" />- </button>- </div>- );- })}- </div>- )}-- <div className="mt-3 flex items-center justify-between">- <Button variant="outline" size="xs" onClick={addFilter} className="gap-1">- <PlusIcon className="size-3" />- Add filter- </Button>- <Button- variant="info"- size="xs"- onClick={applyFilters}- isPending={isApplying}- className="gap-1"- >- <CheckIcon className="size-3" />- Apply- </Button>- </div>- </PopoverContent>- </Popover>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsxdeleted file mode 100644index b546e14af0..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx+++ /dev/null@@ -1,209 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { GripHorizontalIcon } from "lucide-react";--import { cn } from "@app/components/v3/utils";--import type { FieldInfo } from "../data-explorer-types";-import { copyData, exportData } from "../data-export";-import type { QueryTab } from "../use-query-tabs";-import { ExportDropdown } from "./ExportDropdown";-import { QueryResultsTable } from "./QueryResultsTable";-import { QueryToolbar } from "./QueryToolbar";-import { SqlEditor } from "./SqlEditor";--function getRowLabel(rowCount: number, isTruncated: boolean): string {- if (isTruncated) return `Showing 1,000 of ${rowCount.toLocaleString()} rows`;- return `${rowCount} row${rowCount !== 1 ? "s" : ""}`;-}--type QueryResult = {- rows: Record<string, unknown>[];- fields: FieldInfo[];- rowCount: number | null;- isTruncated: boolean;- transactionOpen: boolean;- command: string;- executionTimeMs: number;-};--type Props = {- tab: QueryTab;- executeQuery: (connectionId: string, sql: string) => Promise<QueryResult>;- cancelQuery: (connectionId: string) => void;- onSqlChange: (sql: string) => void;- onTransactionStateChange: (open: boolean) => void;-};--export function QueryPanel({- tab,- executeQuery,- cancelQuery,- onSqlChange,- onTransactionStateChange-}: Props) {- const [isRunning, setIsRunning] = useState(false);- const [result, setResult] = useState<QueryResult | null>(null);- const [error, setError] = useState<string | null>(null);- const [isDragging, setIsDragging] = useState(false);- const [hasSelection, setHasSelection] = useState(false);- const sqlToRunRef = useRef<string>(tab.sql);-- const containerRef = useRef<HTMLDivElement>(null);- const editorPaneRef = useRef<HTMLDivElement>(null);- const splitPctRef = useRef(40);-- useEffect(() => {- if (editorPaneRef.current) {- editorPaneRef.current.style.height = `${splitPctRef.current}%`;- }- }, []);-- const runSql = async (sqlToRun: string) => {- setIsRunning(true);- setError(null);- try {- const res = await executeQuery(tab.connectionId, sqlToRun);- onTransactionStateChange(res.transactionOpen);- setResult(res);- } catch (err) {- // BE is the source of truth via transactionOpen on error responses, but- // when the pending promise rejects without a transactionOpen (e.g. WS- // drop, timeout) we fall back to assuming the txn is gone.- onTransactionStateChange(false);- setError(err instanceof Error ? err.message : String(err));- setResult(null);- } finally {- setIsRunning(false);- }- };-- const handleRun = async (sqlToRun?: string) => {- const query = sqlToRun ?? sqlToRunRef.current;- if (!query.trim() || isRunning) return;- await runSql(query);- };-- const handleCommit = async () => {- await runSql("COMMIT");- };-- const handleRollback = async () => {- await runSql("ROLLBACK");- };-- useEffect(() => {- if (!isDragging) return undefined;-- const onMouseMove = (e: MouseEvent) => {- const container = containerRef.current;- const editorPane = editorPaneRef.current;- if (!container || !editorPane) return;- const rect = container.getBoundingClientRect();- const pct = Math.min(85, Math.max(10, ((e.clientY - rect.top) / rect.height) * 100));- splitPctRef.current = pct;- editorPane.style.height = `${pct}%`;- };-- const onMouseUp = () => setIsDragging(false);-- window.addEventListener("mousemove", onMouseMove);- window.addEventListener("mouseup", onMouseUp);- return () => {- window.removeEventListener("mousemove", onMouseMove);- window.removeEventListener("mouseup", onMouseUp);- };- }, [isDragging]);-- return (- <div className="flex h-full w-full flex-col overflow-hidden">- <QueryToolbar- isRunning={isRunning}- isInTransaction={tab.isInTransaction}- hasSelection={hasSelection}- onRun={handleRun}- onCommit={handleCommit}- onRollback={handleRollback}- onCancel={() => cancelQuery(tab.connectionId)}- />- <div- ref={containerRef}- className={cn("flex flex-1 flex-col overflow-hidden", isDragging && "select-none")}- >- <div- ref={editorPaneRef}- className="min-h-0 overflow-hidden"- style={{ backgroundColor: "#16181a" }}- >- <SqlEditor- value={tab.sql}- onChange={onSqlChange}- onExecute={(s) => handleRun(s)}- onSelectionChange={setHasSelection}- onSqlToRunChange={(s) => {- sqlToRunRef.current = s;- }}- />- </div>-- {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}- <div- className="group relative z-10 h-0 shrink-0 cursor-row-resize"- onMouseDown={(e) => {- e.preventDefault();- setIsDragging(true);- }}- >- <div- className={cn(- "absolute inset-x-0 top-0 h-px bg-mineshaft-600 transition-colors group-hover:bg-mineshaft-400",- isDragging && "bg-mineshaft-400"- )}- />- <div- className={cn(- "absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-sm bg-mineshaft-600 px-2 text-mineshaft-300 transition-colors group-hover:bg-mineshaft-500 group-hover:text-mineshaft-100",- isDragging && "bg-mineshaft-500 text-mineshaft-100"- )}- >- <GripHorizontalIcon className="size-3" />- </div>- </div>-- <div className="relative z-0 flex min-h-0 flex-1 flex-col overflow-hidden bg-bunker-800">- <div className="min-h-0 flex-1 overflow-hidden">- <QueryResultsTable result={result} error={error} isRunning={isRunning} />- </div>- {!isRunning && result && !error && (- <div className="flex shrink-0 items-center justify-between border-t border-mineshaft-600 px-3 py-1">- <span className="text-xs text-mineshaft-400">- {result.rowCount != null- ? getRowLabel(result.rowCount, result.isTruncated)- : result.command}- {" · "}- {result.executionTimeMs}ms- </span>- {result.rows.length > 0 && (- <ExportDropdown- onExport={(fmt) =>- exportData(- result.rows,- result.fields.map((f) => f.name),- fmt- )- }- onCopy={(fmt) =>- copyData(- result.rows,- result.fields.map((f) => f.name),- fmt- )- }- />- )}- </div>- )}- </div>- </div>- </div>- );-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsxdeleted file mode 100644index 6b7c29e063..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryResultsTable.tsx+++ /dev/null@@ -1,134 +0,0 @@-import { useCallback, useMemo } from "react";-import type { ColumnDef } from "@tanstack/react-table";--import { Spinner } from "@app/components/v2";-import { DataGrid, useDataGrid } from "@app/components/v3/generic/DataGrid";--import type { FieldInfo } from "../data-explorer-types";--type QueryResult = {- rows: Record<string, unknown>[];- fields: FieldInfo[];- rowCount: number | null;- isTruncated: boolean;- command: string;- executionTimeMs: number;-};--type Props = {- result: QueryResult | null;- error: string | null;- isRunning: boolean;-};--type RowData = Record<string, unknown>;--function buildColumns(fields: FieldInfo[]): ColumnDef<RowData>[] {- return fields.map((f) => ({- id: f.name,- accessorKey: f.name,- header: f.name,- meta: {- label: f.name,- cell: { variant: "short-text" as const }- },- enableSorting: true,- enablePinning: true,- enableHiding: true- }));-}--function ResultsGrid({ result }: { result: QueryResult }) {- const { isTruncated } = result;-- const columns = useMemo(() => buildColumns(result.fields), [result.fields]);-- const getRowId = useCallback((_row: RowData, index: number) => String(index), []);-- const gridProps = useDataGrid<RowData>({- data: result.rows,- columns,- getRowId,- readOnly: true,- rowHeight: "short",- enableSearch: true- });-- return (- <div className="flex h-full flex-col overflow-hidden">- <div className="data-explorer-grid relative flex min-h-0 flex-1 flex-col overflow-hidden font-mono text-foreground [--color-gray-200:var(--color-border)] [&_[data-slot=grid-footer]]:hidden [&_[data-slot=grid-header]]:bg-container [&_[data-slot=grid]]:thin-scrollbar [&_[data-slot=grid]]:rounded-none [&_[data-slot=grid]]:border-0 [&_[data-slot=grid]]:bg-bunker-800">- <DataGrid {...gridProps} className="min-h-0 flex-1" stretchColumns />- </div>- {isTruncated && (- <div className="shrink-0 border-t border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5 text-xs text-yellow-500/80">- Showing first {result.rows.length.toLocaleString()} rows (results truncated)- </div>- )}- </div>- );-}--export function QueryResultsTable({ result, error, isRunning }: Props) {- if (isRunning) {- return (- <div className="flex h-full items-center justify-center">- <Spinner className="size-5" />- </div>- );- }-- if (error) {- return (- <div className="p-4">- <div className="rounded-md border border-red-500/30 bg-red-500/10 px-4 py-3 font-mono text-xs whitespace-pre-wrap text-red-400">- {error}- </div>- </div>- );- }-- if (!result) {- return (- <div className="flex h-full items-center justify-center">- <p className="text-sm text-mineshaft-300">Run a query to see results</p>- </div>- );- }-- if (result.rows.length === 0) {- const cmdUpper = result.command.toUpperCase();- const count = result.rowCount ?? 0;- const verb: Record<string, string> = {- INSERT: "inserted",- UPDATE: "updated",- DELETE: "deleted"- };- const staticMessage: Record<string, string> = {- BEGIN: "Transaction started",- COMMIT: "Transaction committed",- ROLLBACK: "Transaction rolled back"- };-- const isMutation = verb[cmdUpper] !== undefined && result.fields.length === 0;-- let message: string;- if (staticMessage[cmdUpper]) {- message = staticMessage[cmdUpper];- } else if (isMutation) {- message = `${count} row${count !== 1 ? "s" : ""} ${verb[cmdUpper]}`;- } else {- message = "No rows returned";- }-- return (- <div className="flex h-full flex-col items-center justify-center gap-2">- <span className="rounded border-2 border-mineshaft-500 bg-mineshaft-700 px-3 py-1.5 font-mono text-sm text-mineshaft-200">- {message}- {isMutation && <span className="ml-2 text-mineshaft-400">· No rows returned</span>}- </span>- </div>- );- }-- return <ResultsGrid result={result} />;-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsxdeleted file mode 100644index edb5ae893e..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryToolbar.tsx+++ /dev/null@@ -1,73 +0,0 @@-import { CheckIcon, PlayIcon, RotateCcwIcon, SquareIcon } from "lucide-react";--import { Button } from "@app/components/v3/generic/Button";--const isMac = typeof navigator !== "undefined" && navigator.userAgent.includes("Mac");--type Props = {- isRunning: boolean;- isInTransaction: boolean;- hasSelection: boolean;- onRun: () => void;- onCommit: () => void;- onRollback: () => void;- onCancel: () => void;-};--export function QueryToolbar({- isRunning,- isInTransaction,- hasSelection,- onRun,- onCommit,- onRollback,- onCancel-}: Props) {- return (- <div className="flex shrink-0 items-center justify-between border-b border-mineshaft-600 bg-bunker-800 px-3 py-1.5">- <div className="flex items-center gap-3">- {isRunning ? (- <Button size="xs" variant="outline" onClick={onCancel} className="gap-1.5">- <SquareIcon className="size-3 text-red-400" />- Cancel- </Button>- ) : (- <Button size="xs" onClick={() => onRun()} className="gap-1.5">- <PlayIcon className="size-3" />- {hasSelection ? "Run Selection" : "Run"}- <span className="opacity-60">{isMac ? "⌘" : "Ctrl"} ↵</span>- </Button>- )}- {isInTransaction && (- <>- <Button- size="xs"- variant="success"- onClick={onCommit}- isDisabled={isRunning}- className="gap-1.5"- >- <CheckIcon className="size-3" />- Commit- </Button>- <Button- size="xs"- variant="danger"- onClick={onRollback}- isDisabled={isRunning}- className="gap-1.5"- >- <RotateCcwIcon className="size-3" />- Rollback- </Button>- </>- )}- </div>- {isInTransaction && (- <span className="rounded bg-yellow-500/15 px-2 py-0.5 text-xs font-medium text-yellow-400">- Transaction open- </span>- )}- </div>- );-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsxdeleted file mode 100644index aa912071e9..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/SortPopover.tsx+++ /dev/null@@ -1,102 +0,0 @@-import { ArrowUpDownIcon, CheckIcon } from "lucide-react";--import { Button } from "@app/components/v3/generic/Button";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList-} from "@app/components/v3/generic/Command";-import { Popover, PopoverContent, PopoverTrigger } from "@app/components/v3/generic/Popover";-import { cn } from "@app/components/v3/utils";--import type { ColumnInfo } from "../data-explorer-types";-import type { SortCondition } from "../sql-generation";--type SortPopoverProps = {- columns: ColumnInfo[];- sorts: SortCondition[];- onSortsChange: (sorts: SortCondition[]) => void;- disabled?: boolean;-};--export const SortPopover = ({- columns,- sorts,- onSortsChange,- disabled = false-}: SortPopoverProps) => {- const activeSort = sorts[0] ?? null;- const isAscending = activeSort?.direction !== "DESC";-- const handleColumnSelect = (colName: string) => {- if (activeSort?.column === colName) {- onSortsChange([]);- } else {- onSortsChange([{ column: colName, direction: isAscending ? "ASC" : "DESC" }]);- }- };-- const handleDirectionToggle = () => {- if (!activeSort) return;- onSortsChange([- { column: activeSort.column, direction: activeSort.direction === "ASC" ? "DESC" : "ASC" }- ]);- };-- return (- <Popover>- <PopoverTrigger asChild>- <Button variant="outline" size="xs" className="gap-1.5" disabled={disabled}>- <ArrowUpDownIcon className="size-3" />- Sort- {activeSort && (- <span className="rounded-full bg-primary/20 px-1.5 text-[10px] font-medium text-primary">- {activeSort.column}- </span>- )}- </Button>- </PopoverTrigger>- <PopoverContent className="w-[300px] p-0" align="start">- <div className="flex items-center justify-between border-b border-border px-3 py-2">- <span className="text-sm font-medium text-foreground">Sort by</span>- <button- type="button"- onClick={handleDirectionToggle}- disabled={!activeSort || disabled}- className="flex items-center gap-1.5 rounded px-2 py-0.5 text-xs text-muted transition-colors hover:bg-foreground/5 disabled:opacity-40"- >- {isAscending ? "Ascending" : "Descending"}- <ArrowUpDownIcon className="size-3" />- </button>- </div>- <Command>- <CommandInput placeholder="Search columns..." />- <CommandList>- <CommandEmpty>No matching columns</CommandEmpty>- <CommandGroup>- {columns.map((col) => (- <CommandItem- key={col.name}- value={col.name}- onSelect={() => handleColumnSelect(col.name)}- disabled={disabled}- >- <CheckIcon- className={cn(- "size-3.5",- activeSort?.column === col.name ? "opacity-100" : "opacity-0"- )}- />- <span className="truncate">{col.name}</span>- </CommandItem>- ))}- </CommandGroup>- </CommandList>- </Command>- </PopoverContent>- </Popover>- );-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsxdeleted file mode 100644index 87b36729cd..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx+++ /dev/null@@ -1,155 +0,0 @@-import { useEffect, useRef } from "react";-import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";-import { PostgreSQL, sql } from "@codemirror/lang-sql";-import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";-import { EditorState, type Transaction } from "@codemirror/state";-import { EditorView, keymap, placeholder, type ViewUpdate } from "@codemirror/view";-import { tags } from "@lezer/highlight";--const infisicalTheme = EditorView.theme({- "&": { height: "100%", fontSize: "13px", backgroundColor: "#16181a" },- "&.cm-editor": { backgroundColor: "#16181a" },- ".cm-scroller": {- overflow: "auto",- fontFamily: "ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, monospace",- backgroundColor: "#16181a",- scrollbarWidth: "thin",- scrollbarColor: "#39393d transparent"- },- ".cm-scroller::-webkit-scrollbar": { width: "4px", height: "4px" },- ".cm-scroller::-webkit-scrollbar-track": { background: "transparent" },- ".cm-scroller::-webkit-scrollbar-thumb": { background: "#39393d", borderRadius: "2px" },- ".cm-content": { padding: "8px 0", caretColor: "#e0ed34", backgroundColor: "#16181a" },- ".cm-line": { backgroundColor: "transparent" },- ".cm-gutters": {- backgroundColor: "#16181a",- borderRight: "1px solid #2b2c30",- color: "#707174"- },- ".cm-lineNumbers .cm-gutterElement": { padding: "0 12px 0 8px" },- ".cm-activeLine": { backgroundColor: "rgba(45, 47, 51, 0.5)" },- ".cm-activeLineGutter": { backgroundColor: "rgba(45, 47, 51, 0.5)" },- ".cm-cursor": { borderLeftColor: "#e0ed34" },- ".cm-selectionBackground": { backgroundColor: "#2d2f33 !important" },- "&.cm-focused .cm-selectionBackground": { backgroundColor: "#2d2f33 !important" },- ".cm-matchingBracket": { backgroundColor: "#323439", color: "#e0ed34 !important" }-});--const infisicalHighlight = HighlightStyle.define(- [- { tag: tags.keyword, color: "#63b0bd", fontWeight: "600" },- { tag: tags.string, color: "#29b866" },- { tag: tags.number, color: "#f39c12" },- { tag: tags.comment, color: "#707174", fontStyle: "italic" },- { tag: tags.operator, color: "#adaeb0" },- { tag: tags.punctuation, color: "#adaeb0" },- { tag: tags.separator, color: "#adaeb0" },- { tag: tags.bracket, color: "#adaeb0" },- { tag: tags.name, color: "#ebebeb" },- { tag: tags.function(tags.name), color: "#63b0bd" },- { tag: tags.typeName, color: "#f39c12" },- { tag: tags.bool, color: "#63b0bd" },- { tag: tags.null, color: "#707174" },- { tag: tags.special(tags.string), color: "#29b866" },- { tag: tags.invalid, color: "#e74c3c" }- ],- { all: { color: "#ebebeb" } }-);--const MAX_SQL_BYTES = 50 * 1024; // 50KB — matches backend Zod limit--const maxSqlLength = EditorState.transactionFilter.of((tr: Transaction) => {- if (tr.docChanged && tr.newDoc.length > MAX_SQL_BYTES) return [];- return tr;-});--type Props = {- value: string;- onChange: (value: string) => void;- onExecute: (sql: string) => void;- onSelectionChange: (hasSelection: boolean) => void;- onSqlToRunChange: (sql: string) => void;-};--export function SqlEditor({- value,- onChange,- onExecute,- onSelectionChange,- onSqlToRunChange-}: Props) {- const containerRef = useRef<HTMLDivElement>(null);- const viewRef = useRef<EditorView | null>(null);- const onExecuteRef = useRef(onExecute);- const onChangeRef = useRef(onChange);- const onSelectionChangeRef = useRef(onSelectionChange);- const onSqlToRunChangeRef = useRef(onSqlToRunChange);- onExecuteRef.current = onExecute;- onChangeRef.current = onChange;- onSelectionChangeRef.current = onSelectionChange;- onSqlToRunChangeRef.current = onSqlToRunChange;-- useEffect(() => {- if (!containerRef.current) return undefined;-- const view = new EditorView({- state: EditorState.create({- doc: value,- extensions: [- history(),- keymap.of([- {- key: "Mod-Enter",- run: (v) => {- const selection = v.state.selection.main;- const selectedText = selection.empty- ? v.state.doc.toString()- : v.state.sliceDoc(selection.from, selection.to);- onExecuteRef.current(selectedText);- return true;- }- },- ...historyKeymap,- ...defaultKeymap- ]),- maxSqlLength,- placeholder("Start writing SQL..."),- sql({ dialect: PostgreSQL }),- infisicalTheme,- syntaxHighlighting(infisicalHighlight),- EditorView.updateListener.of((update: ViewUpdate) => {- if (update.docChanged) {- const doc = update.state.doc.toString();- onChangeRef.current(doc);- if (update.state.selection.main.empty) {- onSqlToRunChangeRef.current(doc);- }- }- if (update.selectionSet) {- const selection = update.state.selection.main;- if (selection.empty) {- onSqlToRunChangeRef.current(update.state.doc.toString());- onSelectionChangeRef.current(false);- } else {- onSqlToRunChangeRef.current(update.state.sliceDoc(selection.from, selection.to));- onSelectionChangeRef.current(true);- }- }- })- ]- }),- parent: containerRef.current- });-- viewRef.current = view;- onSqlToRunChangeRef.current(value);-- return () => {- view.destroy();- viewRef.current = null;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- return <div ref={containerRef} className="h-full w-full" />;-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.tsdeleted file mode 100644index 0c423f56a5..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts+++ /dev/null@@ -1,87 +0,0 @@-// WebSocket message types for the Postgres Data Explorer--export type DataExplorerClientMessage =- // Metadata (no connectionId) — served by short-lived BE pg.Clients- | { type: "get-schemas"; id: string }- | { type: "get-tables"; id: string; schema: string }- // Tab-scoped — routed to a specific BE controller- | { type: "get-table-detail"; id: string; connectionId: string; schema: string; table: string }- | { type: "query"; id: string; connectionId: string; sql: string }- // Cancel is fire-and-forget; gains connectionId for routing but not id- | { type: "cancel"; connectionId: string }- // Lifecycle- | { type: "open-connection"; id: string }- | { type: "close-connection"; connectionId: string }- // Keepalive sent while the browser tab is visible; resets the BE idle timer- | { type: "activity" };--export type DataExplorerServerMessage =- | { type: "schemas"; id: string; data: SchemaInfo[] }- | { type: "tables"; id: string; data: TableInfo[] }- | {- type: "table-detail";- id: string;- connectionId: string;- transactionOpen: boolean;- data: TableDetail;- }- | {- type: "query-result";- id: string;- connectionId: string;- rows: Record<string, unknown>[];- fields: FieldInfo[];- rowCount: number | null;- isTruncated: boolean;- transactionOpen: boolean;- command: string;- executionTimeMs: number;- }- | {- type: "error";- id: string;- connectionId?: string;- transactionOpen?: boolean;- error: string;- detail?: string;- hint?: string;- }- | { type: "connection-opened"; id: string; connectionId: string; backendPid: number | null }- | { type: "connection-open-failed"; id: string; error: string }- | { type: "connection-closed"; connectionId: string; reason: string }- | { type: "ready" }- | { type: "session_end"; reason: string };--export type SchemaInfo = {- name: string;-};--export type TableInfo = {- name: string;- tableType: string;-};--export type ColumnInfo = {- name: string;- type: string;- nullable: boolean;- identityGeneration: string | null;-};--export type ForeignKeyInfo = {- constraintName: string;- columns: string[];- targetSchema: string;- targetTable: string;- targetColumns: string[];-};--export type TableDetail = {- columns: ColumnInfo[];- primaryKeys: string[];- foreignKeys: ForeignKeyInfo[];-};--export type FieldInfo = {- name: string;-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-utils.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-utils.tsdeleted file mode 100644index a00fc9540a..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-utils.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { ForeignKeyInfo } from "./data-explorer-types";--export function getColumnIndicator(- colName: string,- primaryKeys: string[],- fkMap: Map<string, ForeignKeyInfo>-): { type: "pk" | "fk"; tooltip?: string } | undefined {- if (primaryKeys.includes(colName)) return { type: "pk" };- const fk = fkMap.get(colName);- if (fk) {- const targetCol = fk.targetColumns[fk.columns.indexOf(colName)] ?? fk.targetColumns[0];- return { type: "fk", tooltip: `\u2192 ${fk.targetSchema}.${fk.targetTable}(${targetCol})` };- }- return undefined;-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-export.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-export.tsdeleted file mode 100644index 4e52a457a8..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/data-export.ts+++ /dev/null@@ -1,75 +0,0 @@-export type ExportFormat = "csv" | "json";--const FORMULA_PREFIXES = new Set(["=", "+", "-", "@"]);--function escapeCsvField(value: unknown): string {- if (value === null || value === undefined) return "";- let str = typeof value === "object" ? JSON.stringify(value) : String(value);- if (FORMULA_PREFIXES.has(str.charAt(0))) {- str = `'${str}`;- }- if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {- return `"${str.replace(/"/g, '""')}"`;- }- return str;-}--function buildTimestamp(): string {- return new Date()- .toISOString()- .replace(/[:]/g, "-")- .replace(/\.\d+Z$/, "Z");-}--function buildCsv(rows: Record<string, unknown>[], columns: string[]): string {- const header = columns.map(escapeCsvField).join(",");- const body = rows- .map((row) => columns.map((col) => escapeCsvField(row[col])).join(","))- .join("\n");- return `${header}\n${body}`;-}--function buildJson(rows: Record<string, unknown>[], columns: string[]): string {- const filtered = rows.map((row) => {- const obj: Record<string, unknown> = {};- columns.forEach((col) => {- obj[col] = row[col] ?? null;- });- return obj;- });- return JSON.stringify(filtered, null, 2);-}--function serialize(- rows: Record<string, unknown>[],- columns: string[],- format: ExportFormat-): string {- return format === "json" ? buildJson(rows, columns) : buildCsv(rows, columns);-}--export function exportData(- rows: Record<string, unknown>[],- columns: string[],- format: ExportFormat-): void {- if (rows.length === 0) return;- const content = serialize(rows, columns, format);- const mime = format === "json" ? "application/json;charset=utf-8;" : "text/csv;charset=utf-8;";- const blob = new Blob([content], { type: mime });- const url = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = url;- a.download = `infisical_data_${buildTimestamp()}.${format}`;- a.click();- URL.revokeObjectURL(url);-}--export async function copyData(- rows: Record<string, unknown>[],- columns: string[],- format: ExportFormat-): Promise<void> {- if (rows.length === 0) return;- await navigator.clipboard.writeText(serialize(rows, columns, format));-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.tsdeleted file mode 100644index 8790880a93..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts+++ /dev/null@@ -1,175 +0,0 @@-// Client-side SQL generation for the Postgres Data Explorer.-// All identifiers are properly quoted to prevent SQL injection.--export function quoteIdent(name: string): string {- return `"${name.replace(/"/g, '""')}"`;-}--export function quoteLiteral(value: unknown): string {- if (value === null || value === undefined) return "NULL";- if (typeof value === "number") {- if (!Number.isFinite(value)) return "NULL";- return String(value);- }- if (typeof value === "boolean") return value ? "TRUE" : "FALSE";- const str = String(value);- // Use dollar-quoting if the string contains single quotes and no dollar signs- if (str.includes("'") && !str.includes("$")) {- return `$$${str}$$`;- }- return `'${str.replace(/'/g, "''")}'`;-}--export type FilterCondition = {- column: string;- operator: FilterOperator;- value: string;-};--export type FilterOperator =- | "="- | "<>"- | ">"- | "<"- | ">="- | "<="- | "LIKE"- | "ILIKE"- | "IS NULL"- | "IS NOT NULL"- | "IN";--export type SortCondition = {- column: string;- direction: "ASC" | "DESC";-};--function buildWhereClause(filters: FilterCondition[]): string {- if (filters.length === 0) return "";- const conditions = filters.map((f) => {- const col = quoteIdent(f.column);- switch (f.operator) {- case "IS NULL":- return `${col} IS NULL`;- case "IS NOT NULL":- return `${col} IS NOT NULL`;- case "IN": {- const values = f.value- .split(",")- .map((v) => quoteLiteral(v.trim()))- .join(", ");- return `${col} IN (${values})`;- }- case "LIKE":- case "ILIKE":- return `${col} ${f.operator} ${quoteLiteral(f.value)}`;- default:- return `${col} ${f.operator} ${quoteLiteral(f.value)}`;- }- });- return ` WHERE ${conditions.join(" AND ")}`;-}--function buildOrderByClause(sorts: SortCondition[]): string {- if (sorts.length === 0) return "";- const parts = sorts.map((s) => `${quoteIdent(s.column)} ${s.direction}`);- return ` ORDER BY ${parts.join(", ")}`;-}--export function buildSelectQuery(params: {- schema: string;- table: string;- filters: FilterCondition[];- sorts: SortCondition[];- limit: number;- offset: number;- primaryKeys?: string[];-}): string {- const { schema, table, filters, sorts, limit, offset, primaryKeys } = params;- const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;- const where = buildWhereClause(filters);-- // Default sort by PK for stable pagination- let orderBy: string;- if (sorts.length > 0) {- orderBy = buildOrderByClause(sorts);- } else if (primaryKeys && primaryKeys.length > 0) {- orderBy = buildOrderByClause(- primaryKeys.map((pk) => ({ column: pk, direction: "ASC" as const }))- );- } else {- orderBy = "";- }-- return `SELECT * FROM ${tableName}${where}${orderBy} LIMIT ${limit} OFFSET ${offset}`;-}--export function buildCountQuery(params: {- schema: string;- table: string;- filters: FilterCondition[];-}): string {- const { schema, table, filters } = params;- const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;- const where = buildWhereClause(filters);- return `SELECT COUNT(*) AS count FROM ${tableName}${where}`;-}--export function buildInsertQuery(params: {- schema: string;- table: string;- row: Record<string, unknown>;-}): string {- const { schema, table, row } = params;- const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;- const entries = Object.entries(row).filter(([, v]) => v !== undefined && v !== "");- if (entries.length === 0) {- return `INSERT INTO ${tableName} DEFAULT VALUES RETURNING *`;- }- const columns = entries.map(([k]) => quoteIdent(k)).join(", ");- const values = entries.map(([, v]) => quoteLiteral(v)).join(", ");- return `INSERT INTO ${tableName} (${columns}) VALUES (${values}) RETURNING *`;-}--export function buildUpdateQuery(params: {- schema: string;- table: string;- changes: Record<string, unknown>;- primaryKeyMatch: Record<string, unknown>;-}): string {- const { schema, table, changes, primaryKeyMatch } = params;- if (Object.keys(primaryKeyMatch).length === 0) {- throw new Error("UPDATE requires at least one primary key condition");- }- const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;- const setClauses = Object.entries(changes)- .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)- .join(", ");- const whereClauses = Object.entries(primaryKeyMatch)- .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)- .join(" AND ");- return `UPDATE ${tableName} SET ${setClauses} WHERE ${whereClauses} RETURNING *`;-}--export function buildDeleteQuery(params: {- schema: string;- table: string;- primaryKeyMatch: Record<string, unknown>;-}): string {- const { schema, table, primaryKeyMatch } = params;- if (Object.keys(primaryKeyMatch).length === 0) {- throw new Error("DELETE requires at least one primary key condition");- }- const tableName = `${quoteIdent(schema)}.${quoteIdent(table)}`;- const whereClauses = Object.entries(primaryKeyMatch)- .map(([col, val]) => `${quoteIdent(col)} = ${quoteLiteral(val)}`)- .join(" AND ");- return `DELETE FROM ${tableName} WHERE ${whereClauses}`;-}--// Note: RETURNING * in individual INSERT/UPDATE statements is harmless but unused when-// wrapped here — pgClient.query() returns only the last statement's result (COMMIT).-// The frontend re-fetches data after save anyway.-export function wrapInTransaction(statements: string[]): string {- return `BEGIN;\n${statements.join(";\n")};\nCOMMIT;`;-}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.tsdeleted file mode 100644index 3d529c4428..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts+++ /dev/null@@ -1,576 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";-import ms from "ms";--import { apiRequest } from "@app/config/request";-import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";--import { DEFAULT_ACCESS_DURATION } from "../constants";-import type {- DataExplorerClientMessage,- DataExplorerServerMessage,- FieldInfo,- SchemaInfo,- TableDetail,- TableInfo-} from "./data-explorer-types";--type PendingRequest = {- resolve: (msg: DataExplorerServerMessage) => void;- reject: (err: Error) => void;- timer: ReturnType<typeof setTimeout>;- // Present on tab-scoped requests so we can reject all pending when a tab closes.- connectionId?: string;-};--type MfaState = {- required: boolean;- sessionId?: string;- method?: string;- verifying: boolean;-};--type ApprovalState = {- required: boolean;- policyName?: string;- policyId?: string;- accessDurationMax?: string;- creating: boolean;- submitted: boolean;- approvalRequestId?: string;- errorMessage?: string;-};--type UseDataExplorerSessionOptions = {- accountId: string;- orgId: string;- accountName: string;- reason?: string;- onSessionEnd?: (reason?: string) => void;- // Server pushes connection-closed when a BE controller dies unexpectedly.- onConnectionClosed?: (connectionId: string, reason: string) => void;- // Called after a reconnect so the page can drop tabs + land on a fresh query tab.- onReconnected?: () => void;-};--const REQUEST_TIMEOUT_MS = 30_000;--// Cadence for the visibility-driven keepalive. The BE idle timer is 10 min;-// 60s leaves plenty of headroom if a heartbeat drops on flaky networks.-const ACTIVITY_PING_INTERVAL_MS = 60_000;--type QueryResult = {- rows: Record<string, unknown>[];- fields: FieldInfo[];- rowCount: number | null;- isTruncated: boolean;- transactionOpen: boolean;- command: string;- executionTimeMs: number;-};--export const useDataExplorerSession = ({- accountId,- orgId,- accountName,- reason: accessReason,- onSessionEnd,- onConnectionClosed,- onReconnected-}: UseDataExplorerSessionOptions) => {- const [isConnected, setIsConnected] = useState(false);- const [isConnecting, setIsConnecting] = useState(false);- const [errorMessage, setErrorMessage] = useState<string | null>(null);- const [mfaState, setMfaState] = useState<MfaState | null>(null);- const [approvalState, setApprovalState] = useState<ApprovalState | null>(null);-- const wsRef = useRef<WebSocket | null>(null);- const pendingRequestsRef = useRef<Map<string, PendingRequest>>(new Map());- const readyResolveRef = useRef<(() => void) | null>(null);- const readyRejectRef = useRef<((err: Error) => void) | null>(null);- const readyPromiseRef = useRef<Promise<void> | null>(null);- const onSessionEndRef = useRef(onSessionEnd);- const onConnectionClosedRef = useRef(onConnectionClosed);- const onReconnectedRef = useRef(onReconnected);- const hasConnectedBeforeRef = useRef(false);-- useEffect(() => {- onSessionEndRef.current = onSessionEnd;- }, [onSessionEnd]);- useEffect(() => {- onConnectionClosedRef.current = onConnectionClosed;- }, [onConnectionClosed]);- useEffect(() => {- onReconnectedRef.current = onReconnected;- }, [onReconnected]);-- const rejectAllPending = useCallback((reason: string) => {- const pending = pendingRequestsRef.current;- pending.forEach(({ reject: rej, timer }) => {- clearTimeout(timer);- rej(new Error(reason));- });- pending.clear();- }, []);-- // --- WebSocket lifecycle (imperative, mirrors useWebAccessSession) ----- const openWebSocket = useCallback(- (ticket: string) => {- const { protocol, host } = window.location;- const wsProtocol = protocol === "https:" ? "wss:" : "ws:";- const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;- const ws = new WebSocket(wsUrl);- wsRef.current = ws;-- ws.onmessage = (event) => {- let serverMsg: DataExplorerServerMessage;- try {- serverMsg = JSON.parse(event.data as string) as DataExplorerServerMessage;- } catch {- return;- }-- if (serverMsg.type === "ready") {- setIsConnected(true);- setIsConnecting(false);- readyResolveRef.current?.();- if (hasConnectedBeforeRef.current) {- onReconnectedRef.current?.();- }- hasConnectedBeforeRef.current = true;- return;- }-- if (serverMsg.type === "session_end") {- wsRef.current = null;- setIsConnected(false);- setIsConnecting(false);- rejectAllPending("Session ended");- readyRejectRef.current?.(new Error("Session ended"));- onSessionEndRef.current?.(serverMsg.reason);- return;- }-- if (serverMsg.type === "connection-closed") {- // Informational only — the FE has no pending-request id to resolve.- // Reject any pending requests tied to this connectionId.- const pending = pendingRequestsRef.current;- pending.forEach((p, id) => {- if (p.connectionId === serverMsg.connectionId) {- clearTimeout(p.timer);- p.reject(new Error(serverMsg.reason || "Connection closed"));- pending.delete(id);- }- });- onConnectionClosedRef.current?.(serverMsg.connectionId, serverMsg.reason);- return;- }-- // Request-response correlation (all remaining typed messages carry `id`).- if ("id" in serverMsg && serverMsg.id) {- const pending = pendingRequestsRef.current.get(serverMsg.id);- if (pending) {- pendingRequestsRef.current.delete(serverMsg.id);- clearTimeout(pending.timer);-- if (serverMsg.type === "error") {- const errMsg = [serverMsg.error, serverMsg.detail, serverMsg.hint]- .filter(Boolean)- .join("\n");- pending.reject(new Error(errMsg));- } else if (serverMsg.type === "connection-open-failed") {- pending.reject(new Error(serverMsg.error));- } else {- pending.resolve(serverMsg);- }- }- }- };-- ws.onclose = () => {- // If wsRef was already cleared (by disconnect/cleanup or session_end handler), skip.- if (wsRef.current !== ws) return;-- wsRef.current = null;- setIsConnected(false);- setIsConnecting(false);- rejectAllPending("Connection closed");- readyRejectRef.current?.(new Error("Connection closed"));- onSessionEndRef.current?.();- };-- ws.onerror = () => {- // onclose always fires after onerror- };- },- [accountId, rejectAllPending]- );-- const connect = useCallback(- async (mfaSessionId?: string) => {- setIsConnecting(true);- setErrorMessage(null);- setMfaState(null);- setApprovalState(null);-- readyPromiseRef.current = new Promise<void>((resolve, reject) => {- readyResolveRef.current = resolve;- readyRejectRef.current = reject;- });- // Prevent unhandled rejection — callers of sendRequest will see the error- // when they await readyPromiseRef.current.- readyPromiseRef.current.catch(() => {});-- try {- const { data } = await apiRequest.post<{ ticket: string }>(- `/api/v1/pam/accounts/${accountId}/web-access-ticket`,- { mfaSessionId, reason: accessReason }- );- openWebSocket(data.ticket);- } catch (err: unknown) {- const axiosErr = err as {- response?: {- data?: {- error?: string;- message?: string;- details?: {- mfaSessionId?: string;- mfaMethod?: string;- policyId?: string;- policyName?: string;- constraints?: { accessDuration: { max: string } };- };- };- };- };-- if (axiosErr?.response?.data?.error === "SESSION_MFA_REQUIRED") {- const { details } = axiosErr.response!.data!;- setMfaState({- required: true,- sessionId: details?.mfaSessionId,- method: details?.mfaMethod,- verifying: false- });- setIsConnecting(false);- return;- }-- if (axiosErr?.response?.data?.error === "PolicyViolationError") {- const { details } = axiosErr.response!.data!;- setApprovalState({- required: true,- policyName: details?.policyName,- policyId: details?.policyId,- accessDurationMax: details?.constraints?.accessDuration.max,- creating: false,- submitted: false- });- setIsConnecting(false);- return;- }-- setErrorMessage(axiosErr?.response?.data?.message ?? "Failed to connect to database");- setIsConnecting(false);- readyRejectRef.current?.(new Error("Failed to connect"));- }- },- [accountId, accessReason, openWebSocket]- );-- const disconnect = useCallback(() => {- const ws = wsRef.current;- // Clear ref BEFORE close — so onclose sees wsRef.current !== ws and skips.- wsRef.current = null;- if (ws) ws.close();- rejectAllPending("Disconnected");- }, [rejectAllPending]);-- const reconnect = useCallback(() => {- disconnect();- connect();- }, [disconnect, connect]);-- // MFA flow- const handleMfaVerification = useCallback(async () => {- if (!mfaState?.sessionId) return;-- const mfaUrl = `${window.location.origin}/mfa-session/${mfaState.sessionId}`;- window.open(mfaUrl, "_blank");-- setMfaState((prev) => (prev ? { ...prev, verifying: true } : null));-- const MFA_POLL_INTERVAL = 2000;- const MFA_TIMEOUT = 5 * 60 * 1000;- const startTime = Date.now();-- const verified = await new Promise<boolean>((resolve) => {- const interval = setInterval(async () => {- if (Date.now() - startTime > MFA_TIMEOUT) {- clearInterval(interval);- resolve(false);- return;- }- try {- const resp = await apiRequest.get<TMfaSessionStatusResponse>(- `/api/v2/mfa-sessions/${mfaState.sessionId}/status`- );- if (resp.data.status === MfaSessionStatus.ACTIVE) {- clearInterval(interval);- resolve(true);- }- } catch {- clearInterval(interval);- resolve(false);- }- }, MFA_POLL_INTERVAL);- });-- if (verified) {- connect(mfaState.sessionId);- } else {- setMfaState((prev) => (prev ? { ...prev, verifying: false } : null));- setErrorMessage("MFA verification timed out or failed");- }- }, [mfaState, connect]);-- // Approval request flow- const submitApprovalRequest = useCallback(- async (justification?: string) => {- if (!approvalState?.required) return;- setApprovalState((prev) =>- prev ? { ...prev, creating: true, errorMessage: undefined } : null- );-- try {- const { data: approvalData } = await apiRequest.post<{ request: { id: string } }>(- "/api/v1/approval-policies/pam-access/requests",- {- requestData: {- accessDuration:- approvalState.accessDurationMax &&- ms(approvalState.accessDurationMax) < ms(DEFAULT_ACCESS_DURATION)- ? approvalState.accessDurationMax- : DEFAULT_ACCESS_DURATION,- accountName- },- justification: justification?.trim() || undefined- }- );- setApprovalState((prev) =>- prev- ? {- ...prev,- creating: false,- submitted: true,- approvalRequestId: approvalData.request.id- }- : null- );- } catch {- setApprovalState((prev) =>- prev- ? { ...prev, creating: false, errorMessage: "Failed to create approval request" }- : null- );- }- },- [approvalState, accountName]- );-- const approvalRequestUrl = approvalState?.approvalRequestId- ? `${window.location.origin}/organizations/${orgId}/approvals/${approvalState.approvalRequestId}`- : undefined;-- // --- Request helpers ----- const sendRequest = useCallback(- async <T extends DataExplorerServerMessage>(- msg: Record<string, unknown>,- opts?: { connectionId?: string }- ): Promise<T> => {- if (readyPromiseRef.current) {- await readyPromiseRef.current;- }-- const id = crypto.randomUUID();- const fullMsg = { ...msg, id } as DataExplorerClientMessage;-- return new Promise<T>((resolve, reject) => {- const timer = setTimeout(() => {- pendingRequestsRef.current.delete(id);- reject(new Error("Request timed out"));- }, REQUEST_TIMEOUT_MS);-- pendingRequestsRef.current.set(id, {- resolve: resolve as (m: DataExplorerServerMessage) => void,- reject,- timer,- connectionId: opts?.connectionId- });-- const ws = wsRef.current;- if (ws && ws.readyState === WebSocket.OPEN) {- ws.send(JSON.stringify(fullMsg));- } else {- pendingRequestsRef.current.delete(id);- clearTimeout(timer);- reject(new Error("WebSocket not connected"));- }- });- },- []- );-- const openConnection = useCallback(async (): Promise<{- connectionId: string;- backendPid: number | null;- }> => {- const resp = await sendRequest<- Extract<DataExplorerServerMessage, { type: "connection-opened" }>- >({- type: "open-connection"- });- return { connectionId: resp.connectionId, backendPid: resp.backendPid };- }, [sendRequest]);-- const closeConnection = useCallback((connectionId: string): void => {- const ws = wsRef.current;- // Reject any pending requests tied to this connection immediately so the- // caller doesn't have a dangling promise when the tab is gone.- const pending = pendingRequestsRef.current;- pending.forEach((p, id) => {- if (p.connectionId === connectionId) {- clearTimeout(p.timer);- p.reject(new Error("Connection closed"));- pending.delete(id);- }- });- if (ws && ws.readyState === WebSocket.OPEN) {- ws.send(JSON.stringify({ type: "close-connection", connectionId }));- }- }, []);-- const fetchSchemas = useCallback(async (): Promise<SchemaInfo[]> => {- const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "schemas" }>>({- type: "get-schemas"- });- return resp.data;- }, [sendRequest]);-- const fetchTables = useCallback(- async (schema: string): Promise<TableInfo[]> => {- const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "tables" }>>({- type: "get-tables",- schema- });- return resp.data;- },- [sendRequest]- );-- const fetchTableDetail = useCallback(- async (- connectionId: string,- schema: string,- table: string- ): Promise<{ detail: TableDetail; transactionOpen: boolean }> => {- const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "table-detail" }>>(- { type: "get-table-detail", connectionId, schema, table },- { connectionId }- );- return { detail: resp.data, transactionOpen: resp.transactionOpen };- },- [sendRequest]- );-- const cancelQuery = useCallback((connectionId: string) => {- const ws = wsRef.current;- if (ws && ws.readyState === WebSocket.OPEN) {- ws.send(JSON.stringify({ type: "cancel", connectionId }));- }- }, []);-- const executeQuery = useCallback(- async (connectionId: string, sql: string): Promise<QueryResult> => {- const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "query-result" }>>(- { type: "query", connectionId, sql },- { connectionId }- );- return {- rows: resp.rows,- fields: resp.fields,- rowCount: resp.rowCount,- isTruncated: resp.isTruncated,- transactionOpen: resp.transactionOpen,- command: resp.command,- executionTimeMs: resp.executionTimeMs- };- },- [sendRequest]- );-- // Visibility-driven keepalive. While the browser tab is visible and the WS- // is open, send a fire-and-forget { type: "activity" } every minute so the- // BE idle timer doesn't fire on read-only sessions (filter/paginate/browse).- // When the tab goes hidden we stop sending, and the BE idle timer takes over.- useEffect(() => {- if (!isConnected) return undefined;-- let interval: ReturnType<typeof setInterval> | null = null;-- const sendActivity = () => {- const ws = wsRef.current;- if (ws && ws.readyState === WebSocket.OPEN) {- ws.send(JSON.stringify({ type: "activity" } satisfies DataExplorerClientMessage));- }- };-- const start = () => {- if (interval) return;- sendActivity();- interval = setInterval(sendActivity, ACTIVITY_PING_INTERVAL_MS);- };-- const stop = () => {- if (interval) {- clearInterval(interval);- interval = null;- }- };-- const onVisibilityChange = () => {- if (document.visibilityState === "visible") start();- else stop();- };-- if (document.visibilityState === "visible") start();- document.addEventListener("visibilitychange", onVisibilityChange);-- return () => {- document.removeEventListener("visibilitychange", onVisibilityChange);- stop();- };- }, [isConnected]);-- return {- isConnected,- isConnecting,- errorMessage,- mfaState,- approvalState,- connect,- disconnect,- reconnect,- handleMfaVerification,- submitApprovalRequest,- approvalRequestUrl,- openConnection,- closeConnection,- fetchSchemas,- fetchTables,- fetchTableDetail,- executeQuery,- cancelQuery- };-};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.tsdeleted file mode 100644index 5d488a827a..0000000000--- a/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts+++ /dev/null@@ -1,308 +0,0 @@-import { useCallback, useRef, useState } from "react";--import { createNotification } from "@app/components/notifications";--import type { TableDetail } from "./data-explorer-types";--type TabBase = {- id: string;- connectionId: string;- backendPid: number | null;- isInTransaction: boolean;- lastFocusedAt: number;- isDead?: boolean;-};--type BrowseTab = TabBase & {- kind: "browse";- title: string;- schema: string;- table: string;- tableDetail: TableDetail | null;- isLoadingDetail: boolean;-};--export type QueryTab = TabBase & {- kind: "query";- title: string;- sql: string;-};--type Tab = BrowseTab | QueryTab;--const MAX_TABS = 20;--type UseQueryTabsOptions = {- openConnection: () => Promise<{ connectionId: string; backendPid: number | null }>;- closeConnection: (connectionId: string) => void;- fetchTableDetail: (- connectionId: string,- schema: string,- table: string- ) => Promise<{ detail: TableDetail; transactionOpen: boolean }>;-};--export const useQueryTabs = ({- openConnection,- closeConnection,- fetchTableDetail-}: UseQueryTabsOptions) => {- const [tabs, setTabs] = useState<Tab[]>([]);- const [activeTabId, setActiveTabId] = useState<string | null>(null);- const [isOpeningTab, setIsOpeningTab] = useState(false);- const nextQueryNumberRef = useRef(1);-- const atTabLimit = tabs.length >= MAX_TABS;-- const guardLimit = useCallback((): boolean => {- if (tabs.length >= MAX_TABS) {- createNotification({- title: "Tab limit reached",- text: `Maximum ${MAX_TABS} tabs open. Close one to open another.`,- type: "warning"- });- return false;- }- return true;- }, [tabs.length]);-- // Shared shell for openQueryTab / openBrowseTab: enforces the tab-count cap,- // toggles the spinner, asks the BE for a new connection, and surfaces any- // failure as a toast. Returns null if the caller should bail out.- const acquireTabConnection = useCallback(async (): Promise<{- connectionId: string;- backendPid: number | null;- } | null> => {- if (!guardLimit()) return null;- setIsOpeningTab(true);- try {- return await openConnection();- } catch (err) {- createNotification({- title: "Failed to open tab",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- return null;- } finally {- setIsOpeningTab(false);- }- }, [openConnection, guardLimit]);-- const openQueryTab = useCallback(async (): Promise<string | null> => {- const conn = await acquireTabConnection();- if (!conn) return null;- const id = crypto.randomUUID();- const title = `Query ${nextQueryNumberRef.current}`;- nextQueryNumberRef.current += 1;- setTabs((prev) => [- ...prev,- {- kind: "query",- id,- connectionId: conn.connectionId,- backendPid: conn.backendPid,- isInTransaction: false,- lastFocusedAt: Date.now(),- title,- sql: ""- }- ]);- setActiveTabId(id);- return id;- }, [acquireTabConnection]);-- const openBrowseTab = useCallback(- async (- schema: string,- table: string,- { forceNew }: { forceNew: boolean }- ): Promise<string | null> => {- if (!forceNew) {- const matches = tabs.filter(- (t): t is BrowseTab =>- t.kind === "browse" && t.schema === schema && t.table === table && !t.isDead- );- if (matches.length > 0) {- const focus = matches.reduce((a, b) => (a.lastFocusedAt >= b.lastFocusedAt ? a : b));- setActiveTabId(focus.id);- setTabs((prev) =>- prev.map((t) => (t.id === focus.id ? { ...t, lastFocusedAt: Date.now() } : t))- );- return focus.id;- }- }-- const conn = await acquireTabConnection();- if (!conn) return null;- const id = crypto.randomUUID();-- // Optimistic push with isLoadingDetail: true — the grid shows a skeleton- // until fetchTableDetail resolves.- setTabs((prev) => [- ...prev,- {- kind: "browse",- id,- connectionId: conn.connectionId,- backendPid: conn.backendPid,- isInTransaction: false,- lastFocusedAt: Date.now(),- title: `${schema}.${table}`,- schema,- table,- tableDetail: null,- isLoadingDetail: true- }- ]);- setActiveTabId(id);-- // Fire the detail fetch off the critical open path.- (async () => {- try {- const { detail, transactionOpen } = await fetchTableDetail(- conn.connectionId,- schema,- table- );- setTabs((prev) =>- prev.map((t) =>- t.id === id && t.kind === "browse"- ? {- ...t,- tableDetail: detail,- isLoadingDetail: false,- isInTransaction: transactionOpen- }- : t- )- );- } catch (err) {- setTabs((prev) =>- prev.map((t) =>- t.id === id && t.kind === "browse"- ? { ...t, isLoadingDetail: false, isDead: true }- : t- )- );- createNotification({- title: "Failed to load table",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- }- })().catch(() => {});-- return id;- },- [acquireTabConnection, fetchTableDetail, tabs]- );-- const closeTab = useCallback(- (id: string) => {- // Side effects (closeConnection + setActiveTabId) are hoisted OUT of- // the setTabs updater so StrictMode's double-invoke can't fire the WS- // close frame twice. React requires updaters to be pure.- const target = tabs.find((t) => t.id === id);- if (!target) return;- closeConnection(target.connectionId);- const remaining = tabs.filter((t) => t.id !== id);- if (activeTabId === id) {- // Activate the most recently focused remaining tab, if any.- const nextActive =- remaining.length > 0- ? remaining.reduce((a, b) => (a.lastFocusedAt >= b.lastFocusedAt ? a : b)).id- : null;- setActiveTabId(nextActive);- }- setTabs(remaining);- },- [tabs, activeTabId, closeConnection]- );-- const setActiveTab = useCallback((id: string) => {- setActiveTabId(id);- setTabs((prev) => prev.map((t) => (t.id === id ? { ...t, lastFocusedAt: Date.now() } : t)));- }, []);-- const updateTabSql = useCallback((id: string, sql: string) => {- setTabs((prev) => prev.map((t) => (t.id === id && t.kind === "query" ? { ...t, sql } : t)));- }, []);-- const setTabTransactionOpen = useCallback((id: string, open: boolean) => {- setTabs((prev) => prev.map((t) => (t.id === id ? { ...t, isInTransaction: open } : t)));- }, []);-- // Server pushed connection-closed for this tab's connection — mark it dead- // but don't auto-remove. The user sees an error state and can close manually.- const markConnectionDead = useCallback((connectionId: string) => {- setTabs((prev) =>- prev.map((t) => (t.connectionId === connectionId ? { ...t, isDead: true } : t))- );- }, []);-- // Reconnect flow — drop all tabs, reset next-query counter.- const resetTabs = useCallback(() => {- setTabs([]);- setActiveTabId(null);- nextQueryNumberRef.current = 1;- }, []);-- const refreshBrowseTab = useCallback(- async (id: string) => {- const target = tabs.find((t) => t.id === id);- if (!target || target.kind !== "browse") return;- setTabs((prev) =>- prev.map((t) => (t.id === id && t.kind === "browse" ? { ...t, isLoadingDetail: true } : t))- );- try {- const { detail, transactionOpen } = await fetchTableDetail(- target.connectionId,- target.schema,- target.table- );- setTabs((prev) =>- prev.map((t) =>- t.id === id && t.kind === "browse"- ? {- ...t,- tableDetail: detail,- isLoadingDetail: false,- isInTransaction: transactionOpen- }- : t- )- );- } catch (err) {- setTabs((prev) =>- prev.map((t) =>- t.id === id && t.kind === "browse" ? { ...t, isLoadingDetail: false } : t- )- );- createNotification({- title: "Failed to refresh table",- text: err instanceof Error ? err.message : "Unknown error",- type: "error"- });- }- },- [tabs, fetchTableDetail]- );-- return {- tabs,- activeTabId,- atTabLimit,- isOpeningTab,- openQueryTab,- openBrowseTab,- closeTab,- setActiveTab,- updateTabSql,- setTabTransactionOpen,- markConnectionDead,- resetTabs,- refreshBrowseTab,- MAX_TABS- };-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsxdeleted file mode 100644index 51b3252c75..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/PamSessionByIDPage.tsx+++ /dev/null@@ -1,163 +0,0 @@-import { useState } from "react";-import { Helmet } from "react-helmet";-import { faChevronLeft, faEllipsisV } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { Link, useParams } from "@tanstack/react-router";-import { GavelIcon } from "lucide-react";--import { ProjectPermissionCan } from "@app/components/permissions";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- IconButton,- PageHeader-} from "@app/components/v2";-import { ROUTE_PATHS } from "@app/const/routes";-import { ProjectPermissionSub, useOrganization, useProject } from "@app/context";-import { ProjectPermissionPamSessionActions } from "@app/context/ProjectPermissionContext/types";-import { usePopUp } from "@app/hooks";-import { PamSessionStatus, useGetPamSessionById } from "@app/hooks/api/pam";-import { useGetPamSessionPlaybackBundle } from "@app/hooks/api/pam/session-playback";-import { ProjectType } from "@app/hooks/api/projects/types";--import { PamTerminateSessionModal } from "../components/PamTerminateSessionModal";-import { PamSessionAiInsightsSection } from "./components/PamSessionAiInsightsSection";-import { PamSessionDetailsSection } from "./components/PamSessionDetailsSection";-import { PamSessionLogsSection } from "./components/PamSessionLogsSection";--const Page = () => {- const sessionId = useParams({- from: ROUTE_PATHS.Pam.PamSessionByIDPage.id,- select: (el) => el.sessionId- });- const { data: session } = useGetPamSessionById(sessionId, {- refetchInterval: (query) => {- const { data } = query.state;- if (!data) return false;- if (data.aiInsightsStatus === "pending") return 3000;- // Also poll briefly after a session ends to catch the null → pending transition,- // since queueAiSummary runs asynchronously after the session status is written.- const isEnded =- data.status === PamSessionStatus.Ended || data.status === PamSessionStatus.Terminated;- const isRecentlyEnded =- data.endedAt && Date.now() - new Date(data.endedAt).getTime() < 30_000;- if (isEnded && data.aiInsightsStatus === null && isRecentlyEnded) return 3000;- return false;- }- });- const { currentOrg } = useOrganization();- const { currentProject } = useProject();- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["terminateSession"] as const);- const [scrollToLogIndex, setScrollToLogIndex] = useState<number | undefined>();-- const handleWarningClick = (logIndex: number) => {- // Reset to undefined first so clicking the same warning twice triggers a new scroll- setScrollToLogIndex(undefined);- requestAnimationFrame(() => setScrollToLogIndex(logIndex));- };-- const bundleQuery = useGetPamSessionPlaybackBundle(sessionId, !!session);- const sessionComplete = bundleQuery.data?.sessionComplete ?? false;-- const activeOrStarting =- session?.status === PamSessionStatus.Active || session?.status === PamSessionStatus.Starting;- const isActive = activeOrStarting && !sessionComplete;- const isGatewaySession = !!session?.gatewayIdentityId || !!session?.gatewayId;- return (- <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">- {session && (- <div className="mx-auto mb-6 flex w-full max-w-8xl flex-col">- <Link- to="/organizations/$orgId/projects/pam/$projectId/sessions"- params={{- orgId: currentOrg.id,- projectId: currentProject.id- }}- className="mb-4 flex items-center gap-x-2 text-sm text-mineshaft-400"- >- <FontAwesomeIcon icon={faChevronLeft} />- Sessions- </Link>- <PageHeader- scope={ProjectType.PAM}- title={`${session.accountName} Session`}- description={`View details for this ${session.accountName} session.`}- >- {isGatewaySession && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- ariaLabel="Options"- colorSchema="secondary"- className="w-6"- variant="plain"- >- <FontAwesomeIcon icon={faEllipsisV} />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent sideOffset={2} align="end">- <ProjectPermissionCan- I={ProjectPermissionPamSessionActions.Terminate}- a={ProjectPermissionSub.PamSessions}- >- {(isAllowed: boolean) => (- <DropdownMenuItem- isDisabled={!isAllowed || !isActive}- className="text-red-600"- icon={<GavelIcon size={14} />}- onClick={() => handlePopUpOpen("terminateSession")}- >- Terminate Session- </DropdownMenuItem>- )}- </ProjectPermissionCan>- </DropdownMenuContent>- </DropdownMenu>- )}- </PageHeader>- <div className="flex">- <div className="mr-4 flex h-fit w-96 shrink-0">- <PamSessionDetailsSection- session={session}- statusOverride={- activeOrStarting && sessionComplete ? PamSessionStatus.Ended : undefined- }- />- </div>- <div className="flex min-w-0 flex-1 flex-col gap-4">- <PamSessionAiInsightsSection session={session} onWarningClick={handleWarningClick} />- <PamSessionLogsSection session={session} scrollToLogIndex={scrollToLogIndex} />- </div>- </div>-- <PamTerminateSessionModal- sessionId={session.id}- projectId={currentProject.id}- isOpen={popUp.terminateSession.isOpen}- onOpenChange={(isOpen) => handlePopUpToggle("terminateSession", isOpen)}- />- </div>- )}- </div>- );-};--export const PamSessionByIDPage = () => {- return (- <>- <Helmet>- <title>PAM Session</title>- </Helmet>- <ProjectPermissionCan- I={ProjectPermissionPamSessionActions.Read}- a={ProjectPermissionSub.PamSessions}- passThrough={false}- renderGuardBanner- >- <Page />- </ProjectPermissionCan>- </>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsxdeleted file mode 100644index 00c03c3d4f..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/CommandLogView.tsx+++ /dev/null@@ -1,178 +0,0 @@-import { useEffect, useMemo, useRef, useState } from "react";-import { faChevronRight, faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { twMerge } from "tailwind-merge";--import { createNotification } from "@app/components/notifications";-import { Input } from "@app/components/v2";-import { HighlightText } from "@app/components/v2/HighlightText";-import { TPamCommandLog } from "@app/hooks/api/pam";-import { isBrokenChunkMarker, TBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";--import { formatLogContent } from "./PamSessionLogsSection.utils";--type Props = {- logs: (TPamCommandLog | TBrokenChunkMarker)[];- scrollToLogIndex?: number;-};--export const CommandLogView = ({ logs, scrollToLogIndex }: Props) => {- const [expandedLogTimestamps, setExpandedLogTimestamps] = useState<Set<string>>(new Set());- const [search, setSearch] = useState("");- const handledScrollIndexRef = useRef<number | undefined>(undefined);- const toastShownRef = useRef<number | undefined>(undefined);-- useEffect(() => {- if (scrollToLogIndex == null) {- handledScrollIndexRef.current = undefined;- toastShownRef.current = undefined;- return;- }- if (scrollToLogIndex === handledScrollIndexRef.current) return;- const target = logs[scrollToLogIndex - 1];- if (!target) {- if (toastShownRef.current !== scrollToLogIndex) {- toastShownRef.current = scrollToLogIndex;- createNotification({- type: "info",- text: "Log entry not yet loaded. Load more logs to jump to this entry."- });- }- return;- }- handledScrollIndexRef.current = scrollToLogIndex;- setSearch("");- if (!isBrokenChunkMarker(target)) {- setExpandedLogTimestamps(new Set([target.timestamp]));- }- setTimeout(() => {- document- .getElementById(`log-${scrollToLogIndex}`)- ?.scrollIntoView({ behavior: "smooth", block: "center" });- }, 50);- }, [scrollToLogIndex, logs]);-- const toggleExpand = (timestamp: string) => {- setExpandedLogTimestamps((prev) => {- if (prev.has(timestamp)) {- return new Set();- }- return new Set([timestamp]);- });- };-- const filteredLogs = useMemo(- () =>- logs.filter((log) => {- if (isBrokenChunkMarker(log)) return true;- const searchValue = search.trim().toLowerCase();- return (- log.input.toLowerCase().includes(searchValue) ||- log.output.toLowerCase().includes(searchValue)- );- }),- [logs, search]- );-- return (- <>- <div className="flex gap-2">- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}- placeholder="Search logs..."- className="flex-1 bg-mineshaft-800"- containerClassName="bg-transparent"- />- </div>-- <div className="flex grow flex-col gap-2 overflow-y-auto text-xs">- {filteredLogs.length > 0 ? (- filteredLogs.map((log, idx) => {- if (isBrokenChunkMarker(log)) {- return (- <div- key={`broken-${log.chunkIndex}`}- className="rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-xs text-warning"- >- Chunk {log.chunkIndex} unavailable: {log.message}- </div>- );- }-- const originalIndex = logs.indexOf(log) + 1;- const isExpanded = search.length || expandedLogTimestamps.has(log.timestamp);- const formattedInput = formatLogContent(log.input);- const logKey = `${log.timestamp}-${idx}`;-- return (- <button- type="button"- id={`log-${originalIndex}`}- key={logKey}- className={`flex w-full flex-col rounded-md border border-mineshaft-700 p-3 text-left focus:inset-ring-2 focus:inset-ring-mineshaft-400 focus:outline-hidden ${- isExpanded ? "bg-mineshaft-700" : "bg-mineshaft-800 hover:bg-mineshaft-700"- }`}- onClick={() => toggleExpand(log.timestamp)}- >- <div className="flex items-center justify-between text-bunker-400">- <div className="flex items-center gap-2 select-none">- <FontAwesomeIcon- icon={faChevronRight}- className={twMerge(- "size-3 transition-transform duration-100 ease-in-out",- isExpanded && "rotate-90"- )}- />- <span>{new Date(log.timestamp).toLocaleString()}</span>- </div>- </div>-- <div- className={`mt-2 font-mono ${- isExpanded ? "break-all whitespace-pre-wrap" : "truncate"- }`}- >- <HighlightText text={formattedInput} highlight={search} />- </div>-- <div- className={twMerge(- "grid transition-all duration-100 ease-in-out",- isExpanded && log.output ? "grid-rows-[1fr]" : "grid-rows-[0fr]"- )}- >- <div className="overflow-hidden">- {log.output && (- <div className="pt-2 text-bunker-300">- <HighlightText text={log.output} highlight={search} />- </div>- )}- </div>- </div>- </button>- );- })- ) : (- <div className="flex grow items-center justify-center text-bunker-300">- {search.length ? (- <div className="text-center">- <div className="mb-2">No logs match search criteria</div>- </div>- ) : (- <div className="text-center">- <div className="mb-2">Session logs are not yet available</div>- <div className="text-xs text-bunker-400">- Logs will be uploaded after the session duration has elapsed.- <br />- If logs do not appear after some time, please contact your Gateway administrators.- </div>- </div>- )}- </div>- )}- </div>- </>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsxdeleted file mode 100644index e46529018d..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/HttpEventView.tsx+++ /dev/null@@ -1,323 +0,0 @@-import { useMemo, useState } from "react";-import { faChevronDown, faChevronUp, faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";--import { Input } from "@app/components/v2";-import { HighlightText } from "@app/components/v2/HighlightText";-import { THttpEvent } from "@app/hooks/api/pam";-import { isBrokenChunkMarker, TBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";--type Props = {- events: (THttpEvent | TBrokenChunkMarker)[];-};--export const HttpEventView = ({ events }: Props) => {- const [search, setSearch] = useState("");- const [expandedEvents, setExpandedEvents] = useState<Record<string, boolean>>({});- const [expandedSections, setExpandedSections] = useState<- Record<string, { headers: boolean; body: boolean }>- >({});-- const getContentType = (headers: Record<string, string[]>): string | undefined => {- const contentTypeKey = Object.keys(headers).find((key) => key.toLowerCase() === "content-type");- return contentTypeKey ? headers[contentTypeKey]?.[0] : undefined;- };-- const decodeBase64Body = (body: string): string => {- try {- return atob(body);- } catch {- // If base64 decoding fails, return original body- return body;- }- };-- const parseBodyForSearch = (- body: string | undefined,- headers: Record<string, string[]>- ): string => {- if (!body) return "";-- // Decode base64 first- const decodedBody = decodeBase64Body(body);-- const contentType = getContentType(headers);- const isJson = contentType?.toLowerCase().includes("application/json");-- if (isJson) {- try {- const parsed = JSON.parse(decodedBody);- return JSON.stringify(parsed);- } catch {- // If JSON parsing fails, fall back to decoded body- return decodedBody;- }- }-- return decodedBody;- };-- const filteredEvents = useMemo(- () =>- events.filter((event) => {- if (isBrokenChunkMarker(event)) return true;- const searchValue = search.trim().toLowerCase();- if (!searchValue) return true;-- if (event.eventType === "request") {- const bodyForSearch = parseBodyForSearch(event.body, event.headers);- return (- event.method.toLowerCase().includes(searchValue) ||- event.url.toLowerCase().includes(searchValue) ||- event.requestId.toLowerCase().includes(searchValue) ||- Object.keys(event.headers).some((key) => key.toLowerCase().includes(searchValue)) ||- Object.values(event.headers).some((values) =>- values.some((value) => value.toLowerCase().includes(searchValue))- ) ||- bodyForSearch.toLowerCase().includes(searchValue)- );- }- return (- event.status.toLowerCase().includes(searchValue) ||- event.requestId.toLowerCase().includes(searchValue) ||- Object.keys(event.headers).some((key) => key.toLowerCase().includes(searchValue)) ||- Object.values(event.headers).some((values) =>- values.some((value) => value.toLowerCase().includes(searchValue))- )- );- }),- [events, search]- );-- const formatHeaders = (headers: Record<string, string[]>) => {- return Object.entries(headers)- .map(([key, values]) => `${key}: ${values.join(", ")}`)- .join("\n");- };-- const formatBody = (body: string | undefined, headers: Record<string, string[]>): string => {- if (!body) {- return "";- }-- // Decode base64 first- const decodedBody = decodeBase64Body(body);-- const contentType = getContentType(headers);- const isJson = contentType?.toLowerCase().includes("application/json");-- if (isJson) {- try {- const parsed = JSON.parse(decodedBody);- return JSON.stringify(parsed, null, 2);- } catch {- // If JSON parsing fails, return decoded body- return decodedBody;- }- }-- // For non-JSON content, return decoded body- return decodedBody;- };-- const getKubectlCommand = (headers: Record<string, string[]>) => {- const headerKey = Object.keys(headers).find((key) => key.toLowerCase() === "kubectl-command");- return headerKey ? headers[headerKey]?.[0] : undefined;- };-- const toggleEvent = (eventKey: string) => {- const willBeExpanded = !expandedEvents[eventKey];- setExpandedEvents((prev) => ({- ...prev,- [eventKey]: willBeExpanded- }));- // When expanding, show headers by default (but keep body collapsed)- if (willBeExpanded) {- setExpandedSections((prev) => ({- ...prev,- [eventKey]: {- headers: true,- body: prev[eventKey]?.body ?? false- }- }));- }- };-- const toggleSection = (eventKey: string, section: "headers" | "body") => {- setExpandedSections((prev) => ({- ...prev,- [eventKey]: {- ...prev[eventKey],- [section]: !prev[eventKey]?.[section]- }- }));- };-- const isEventExpanded = (eventKey: string) => {- return expandedEvents[eventKey] ?? false;- };-- const isSectionExpanded = (eventKey: string, section: "headers" | "body") => {- return expandedSections[eventKey]?.[section] ?? false;- };-- return (- <>- <div className="flex gap-2">- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}- placeholder="Search HTTP events..."- className="flex-1 bg-mineshaft-800"- containerClassName="bg-transparent"- />- </div>-- <div className="flex grow flex-col gap-2 overflow-y-auto text-xs">- {filteredEvents.length > 0 ? (- filteredEvents.map((event, index) => {- if (isBrokenChunkMarker(event)) {- return (- <div- key={`broken-${event.chunkIndex}`}- className="rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-xs text-warning"- >- Chunk {event.chunkIndex} unavailable: {event.message}- </div>- );- }-- const eventKey = `${event.timestamp}-${event.requestId}-${index}`;- const isRequest = event.eventType === "request";- const kubectlCommand = getKubectlCommand(event.headers);-- const isExpanded = isEventExpanded(eventKey);-- return (- <div- key={eventKey}- className="flex w-full flex-col rounded-md border border-mineshaft-700 bg-mineshaft-800 p-3"- >- <button- type="button"- onClick={() => toggleEvent(eventKey)}- className="flex items-center justify-between text-bunker-400 transition-colors hover:text-bunker-300"- >- <div className="flex items-center gap-2 text-xs">- <FontAwesomeIcon- icon={isExpanded ? faChevronUp : faChevronDown}- className="text-xs"- />- <span- className={`rounded px-2 py-0.5 ${- isRequest- ? "bg-blue-500/20 text-blue-400"- : "bg-green-500/20 text-green-400"- }`}- >- {isRequest ? "REQUEST" : "RESPONSE"}- </span>- {kubectlCommand && (- <span- className="rounded bg-purple-500/20 px-2 py-0.5 text-purple-400"- title="Kubectl Command"- >- kubectl: {kubectlCommand}- </span>- )}- <span>{new Date(event.timestamp).toLocaleString()}</span>- <span className="text-bunker-500">•</span>- <span className="font-mono text-xs">{event.requestId}</span>- </div>- </button>-- <div className="mt-2">- {isRequest ? (- <div className="font-mono text-bunker-100">- <span className="font-semibold text-bunker-200">{event.method}</span>{" "}- <HighlightText text={event.url} highlight={search} />- </div>- ) : (- <div className="font-mono text-bunker-100">- <span className="font-semibold text-bunker-200">Status:</span>{" "}- <HighlightText text={event.status} highlight={search} />- </div>- )}- </div>-- {isExpanded && (- <div className="mt-2 ml-4 space-y-2 border-l-2 border-mineshaft-600 pl-3">- {Object.keys(event.headers).length > 0 && (- <div className="mt-2 border-t border-mineshaft-700 pt-2">- <button- type="button"- onClick={() => toggleSection(eventKey, "headers")}- className="mb-1 flex w-full items-center gap-2 text-left text-xs text-bunker-400 transition-colors hover:text-bunker-300"- >- <FontAwesomeIcon- icon={- isSectionExpanded(eventKey, "headers") ? faChevronUp : faChevronDown- }- className="text-xs"- />- <span>Headers:</span>- </button>- {isSectionExpanded(eventKey, "headers") && (- <div className="font-mono text-xs whitespace-pre-wrap text-bunker-300">- <HighlightText text={formatHeaders(event.headers)} highlight={search} />- </div>- )}- </div>- )}-- {event.body && (- <div className="mt-2 border-t border-mineshaft-700 pt-2">- <button- type="button"- onClick={() => toggleSection(eventKey, "body")}- className="mb-1 flex w-full items-center gap-2 text-left text-xs text-bunker-400 transition-colors hover:text-bunker-300"- >- <FontAwesomeIcon- icon={isSectionExpanded(eventKey, "body") ? faChevronUp : faChevronDown}- className="text-xs"- />- <span>Body:</span>- </button>- {isSectionExpanded(eventKey, "body") && (- <div className="font-mono text-xs whitespace-pre-wrap text-bunker-300">- <HighlightText- text={formatBody(event.body, event.headers)}- highlight={search}- />- </div>- )}- </div>- )}- </div>- )}- </div>- );- })- ) : (- <div className="flex grow items-center justify-center text-bunker-300">- {search.length ? (- <div className="text-center">- <div className="mb-2">No HTTP events match search criteria</div>- </div>- ) : (- <div className="text-center">- <div className="mb-2">HTTP session logs are not yet available</div>- <div className="text-xs text-bunker-400">- Logs will be uploaded after the session duration has elapsed.- <br />- If logs do not appear after some time, please contact your Gateway administrators.- </div>- </div>- )}- </div>- )}- </div>- </>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionAiInsightsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionAiInsightsSection.tsxdeleted file mode 100644index 89c15e1dad..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionAiInsightsSection.tsx+++ /dev/null@@ -1,108 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck -- old PAM page, pending deletion in frontend cleanup-import {- AlertTriangleIcon,- ClockIcon,- CornerDownRightIcon,- SparklesIcon,- XCircleIcon-} from "lucide-react";--import { Spinner } from "@app/components/v2";-import { PamResourceType, PamSessionStatus, TPamSession } from "@app/hooks/api/pam";--type Props = {- session: TPamSession;- onWarningClick?: (logIndex: number) => void;-};--export const PamSessionAiInsightsSection = ({ session, onWarningClick }: Props) => {- const { aiInsightsStatus, aiInsightsError, aiInsights } = session;-- const isEnded =- session.status === PamSessionStatus.Ended || session.status === PamSessionStatus.Terminated;-- // Only show for ended sessions that have an aiInsightsStatus- if (!isEnded || !aiInsightsStatus) return null;-- return (- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">- <div className="flex items-center gap-2 border-b border-mineshaft-400 pb-3">- <SparklesIcon className="size-4 text-purple-400" />- <h3 className="text-base font-medium text-mineshaft-100">AI Insights</h3>- </div>-- <div className="pt-3">- {aiInsightsStatus === "pending" && (- <div className="flex items-center gap-2 text-sm text-mineshaft-300">- <Spinner size="xs" />- <span>Generating summary...</span>- </div>- )}-- {aiInsightsStatus === "failed" && (- <div className="flex flex-col gap-2">- <div className="flex items-center gap-2 text-red-400">- <XCircleIcon className="size-4 shrink-0" />- <span className="text-sm font-medium">Summarization failed</span>- </div>- {aiInsightsError && <p className="text-xs text-mineshaft-400">{aiInsightsError}</p>}- </div>- )}-- {aiInsightsStatus === "completed" && aiInsights && (- <div className="flex flex-col gap-3">- <p className="text-sm leading-relaxed text-mineshaft-200">{aiInsights.summary}</p>-- {aiInsights.warnings.length > 0 && (- <div className="flex flex-col gap-2">- <div className="flex items-center gap-1.5 text-amber-400">- <AlertTriangleIcon className="size-3.5" />- <span className="text-xs font-semibold tracking-wide uppercase">Warnings</span>- </div>- <ul className="flex list-disc flex-col gap-1 pl-4">- {aiInsights.warnings.map((warning, i) => (- // eslint-disable-next-line react/no-array-index-key- <li key={i} className="text-xs text-amber-300">- {warning.logIndex != null &&- onWarningClick &&- session.resourceType !== PamResourceType.SSH ? (- <button- type="button"- className="inline-flex items-center gap-1.5 text-left underline decoration-dotted underline-offset-2 hover:decoration-solid"- onClick={() => onWarningClick(warning.logIndex!)}- >- {warning.text}- <CornerDownRightIcon className="size-3 shrink-0 opacity-70" />- </button>- ) : (- warning.text- )}- </li>- ))}- </ul>- </div>- )}-- {aiInsights.warnings.length === 0 && (- <p className="text-xs text-mineshaft-500">No security concerns detected.</p>- )}- </div>- )}-- {aiInsightsStatus === "completed" && !aiInsights && (- <div className="flex items-center gap-2 text-sm text-mineshaft-400">- <ClockIcon className="size-4" />- <span>No summary available</span>- </div>- )}- </div>-- <div className="mt-4 border-t border-mineshaft-600 pt-3">- <p className="text-center text-xs text-mineshaft-400 italic">- Results are produced by a language model and may not be fully accurate.- </p>- </div>- </div>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsxdeleted file mode 100644index d81efcf35f..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionDetailsSection.tsx+++ /dev/null@@ -1,139 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck -- old PAM page, pending deletion in frontend cleanup-import { faCheck, faCopy, faUser } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { PackageOpenIcon } from "lucide-react";--import { IconButton, Tooltip } from "@app/components/v2";-import { Badge } from "@app/components/v3";-import { useTimedReset } from "@app/hooks";-import { PAM_RESOURCE_TYPE_MAP, PamSessionStatus, TPamSession } from "@app/hooks/api/pam";--import { PamSessionStatusBadge } from "../../PamSessionsPage/components/PamSessionStatusBadge";--type Props = {- session: TPamSession;- statusOverride?: PamSessionStatus;-};--const DetailItem = ({ label, children }: { label: string; children: React.ReactNode }) => (- <div className="mb-4">- <p className="font-medium">{label}</p>- {children}- </div>-);--export const PamSessionDetailsSection = ({- session: {- id,- accountName,- resourceType,- resourceName,- status,- actorName,- actorEmail,- createdAt,- endedAt,- actorIp,- actorUserAgent,- startedAt,- expiresAt,- reason- },- statusOverride-}: Props) => {- const displayStatus = statusOverride ?? status;- const [copyTextId, isCopyingId, setCopyTextId] = useTimedReset<string>({- initialState: "Copy ID to clipboard"- });-- const details = PAM_RESOURCE_TYPE_MAP[resourceType];-- return (- <div className="max-w-[350px] rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">- <div className="flex items-center border-b border-mineshaft-400 pb-4">- <h3 className="text-lg font-medium text-mineshaft-100">Session Details</h3>- </div>- <div className="pt-4 text-sm text-mineshaft-300">- <DetailItem label="Session ID">- <div className="group flex align-top">- <p className="truncate">{id}</p>- <div className="opacity-0 transition-opacity duration-300 group-hover:opacity-100">- <Tooltip content={copyTextId}>- <IconButton- ariaLabel="copy icon"- variant="plain"- className="group relative ml-2"- onClick={() => {- navigator.clipboard.writeText(id);- setCopyTextId("Copied");- }}- >- <FontAwesomeIcon icon={isCopyingId ? faCheck : faCopy} />- </IconButton>- </Tooltip>- </div>- </div>- </DetailItem>-- <DetailItem label="Account">- <div className="flex items-center gap-2">- <img- alt={`${details.name} logo`}- src={`/images/integrations/${details.image}`}- className="size-4"- />- <p>{accountName}</p>- <Badge variant="neutral">- <PackageOpenIcon />- {resourceName}- </Badge>- </div>- </DetailItem>-- <DetailItem label="Actor">- <div className="flex items-center gap-2">- <FontAwesomeIcon icon={faUser} className="-translate-y-px" />- <p>- <strong>{actorName}</strong> ({actorEmail})- </p>- </div>- </DetailItem>-- <DetailItem label="Status">- <PamSessionStatusBadge status={displayStatus} />- </DetailItem>-- <DetailItem label="IP Address">- <p>{actorIp}</p>- </DetailItem>-- <DetailItem label="User Agent">- <p className="truncate">{actorUserAgent}</p>- </DetailItem>-- <DetailItem label="Reason">- <div className="max-h-32 overflow-y-auto">- <p className="break-words whitespace-pre-wrap">{reason || "—"}</p>- </div>- </DetailItem>-- <DetailItem label="Created At">- <p>{new Date(createdAt).toLocaleString()}</p>- </DetailItem>-- <DetailItem label="Expires At">- <p>{expiresAt ? new Date(expiresAt).toLocaleString() : "Never"}</p>- </DetailItem>-- <DetailItem label="Started At">- <p>{startedAt ? new Date(startedAt).toLocaleString() : "Not Started"}</p>- </DetailItem>-- <DetailItem label="Ended At">- <p>{endedAt ? new Date(endedAt).toLocaleString() : "Ongoing"}</p>- </DetailItem>- </div>- </div>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsxdeleted file mode 100644index 73358ec4bd..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx+++ /dev/null@@ -1,166 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck -- old PAM page, pending deletion in frontend cleanup-import { lazy, Suspense, useEffect } from "react";-import { ExternalLinkIcon, Loader2Icon } from "lucide-react";--import { Lottie } from "@app/components/v2";-import { Button } from "@app/components/v3";-import {- PamResourceType,- PamSessionStatus,- THttpEvent,- TPamCommandLog,- TPamSession,- TSessionEvent,- useGetPamSessionLogs-} from "@app/hooks/api/pam";-import { useDecryptedSessionLogs } from "@app/hooks/api/pam/session-playback";--import { CommandLogView } from "./CommandLogView";-import { HttpEventView } from "./HttpEventView";-import { TerminalEventView } from "./TerminalEventView";--// Lazy-load to keep the WASM decoder out of the main bundle.-const importRdpReplayView = () => import("./RdpReplayView/RdpReplayView");-const RdpReplayView = lazy(importRdpReplayView);--type Props = {- session: TPamSession;- scrollToLogIndex?: number;-};--export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {- const isActive =- session.status === PamSessionStatus.Active || session.status === PamSessionStatus.Starting;-- const playback = useDecryptedSessionLogs(session.id, true, isActive);-- const isLive = isActive && !playback.sessionComplete;- const isLegacyOrNoChunks = playback.legacy || (!playback.loading && playback.totalChunks === 0);-- const legacy = useGetPamSessionLogs(session.id, isLive, isLegacyOrNoChunks);-- const hasChunkEvents = !playback.legacy && playback.events.length > 0;- const logs = hasChunkEvents ? (playback.events as typeof legacy.logs) : legacy.logs;- const isLoading = hasChunkEvents ? false : legacy.isLoading || (isLive && logs.length === 0);- const hasMore = hasChunkEvents ? false : legacy.hasMore;- const loadMore = hasChunkEvents ? () => {} : legacy.loadMore;- const isLoadingMore = hasChunkEvents ? false : legacy.isLoadingMore;-- const isSSHSession = session.resourceType === PamResourceType.SSH;- const isDatabaseSession =- session.resourceType === PamResourceType.Postgres ||- session.resourceType === PamResourceType.MySQL ||- session.resourceType === PamResourceType.MsSQL ||- session.resourceType === PamResourceType.MongoDB ||- session.resourceType === PamResourceType.Redis ||- session.resourceType === PamResourceType.OracleDB;- const isHttpSession = session.resourceType === PamResourceType.Kubernetes;- const isAwsIamSession = session.resourceType === PamResourceType.AwsIam;- const isRdpSession = session.resourceType === PamResourceType.Windows;- const hasLogs = logs.length > 0;-- // Warm the lazy chunk so Suspense doesn't fall back on first mount.- useEffect(() => {- if (isRdpSession) {- importRdpReplayView().catch(() => undefined);- }- }, [isRdpSession]);-- return (- <div- className={`flex w-full flex-col gap-4 rounded-lg border border-border bg-container p-4 ${- isRdpSession ? "" : "h-full"- }`}- >- <div className="flex items-center gap-3 border-b border-border pb-4">- <h3 className="text-lg font-medium text-foreground">- {isRdpSession ? "Session Recording" : "Session Logs"}- </h3>- {isLive && (- <span className="flex animate-pulse items-center gap-1.5 rounded-full bg-success/10 px-2.5 py-1 text-xs font-medium text-success">- <span className="size-1.5 animate-pulse rounded-full bg-success" />- LIVE- </span>- )}- </div>-- {isLoading && !hasLogs && !isRdpSession && (- <div className="flex grow items-center justify-center">- <div className="flex items-center gap-2 text-sm text-muted">- <Loader2Icon className="size-4 animate-spin" />- <span>Fetching and decrypting logs...</span>- </div>- </div>- )}-- {isDatabaseSession && hasLogs && (- <CommandLogView logs={logs as TPamCommandLog[]} scrollToLogIndex={scrollToLogIndex} />- )}- {isSSHSession && hasLogs && <TerminalEventView events={logs as TSessionEvent[]} />}- {isHttpSession && hasLogs && <HttpEventView events={logs as THttpEvent[]} />}- {isRdpSession && hasLogs && (- <Suspense- fallback={- <div className="flex grow flex-col items-center justify-center gap-2">- <Lottie isAutoPlay icon="infisical_loading" className="pointer-events-none size-12" />- <span className="text-sm text-muted">Loading session recording</span>- </div>- }- >- <RdpReplayView- events={logs as TSessionEvent[]}- isStreaming={isLive}- totalDurationMs={isLegacyOrNoChunks ? undefined : playback.totalDurationMs}- />- </Suspense>- )}- {isRdpSession && !hasLogs && isLoading && (- <div className="flex grow flex-col items-center justify-center gap-2">- <Lottie isAutoPlay icon="infisical_loading" className="pointer-events-none size-12" />- <span className="text-sm text-muted">Loading session recording</span>- </div>- )}- {isAwsIamSession && (- <div className="flex grow items-center justify-center text-muted">- <div className="text-center">- <div className="mb-2">AWS Console session activity is logged in AWS CloudTrail</div>- <div className="text-xs text-muted">- View detailed activity logs for this session in your AWS CloudTrail console.- <br />- <a- href="https://console.aws.amazon.com/cloudtrail"- target="_blank"- rel="noopener noreferrer"- className="mt-2 inline-flex items-center gap-1 text-info hover:text-info/80"- >- Open AWS CloudTrail- <ExternalLinkIcon className="size-3" />- </a>- </div>- </div>- </div>- )}- {!hasLogs && !isAwsIamSession && !isLoading && (- <div className="flex grow items-center justify-center text-muted">- <div className="text-center">- <div className="mb-2">Session logs are not yet available</div>- <div className="text-xs text-muted">- Logs will be uploaded after the session duration has elapsed.- <br />- If logs do not appear after some time, please contact your Gateway administrators.- </div>- </div>- </div>- )}-- {!isLive && hasMore && !isAwsIamSession && (- <div className="flex justify-center pt-2">- <Button variant="outline" size="xs" isPending={isLoadingMore} onClick={loadMore}>- Load more- </Button>- </div>- )}- </div>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.tsdeleted file mode 100644index d761456558..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.utils.ts+++ /dev/null@@ -1,46 +0,0 @@-// This function trims top and bottom empty padding, as well as moves all relative text to the left while still respecting indentation-export const formatLogContent = (text: string | null | undefined): string => {- if (!text) return "";-- let lines = text.split("\n");-- // Find the first and last non-empty lines to trim vertical padding- let firstLineIndex = -1;- for (let i = 0; i < lines.length; i += 1) {- if (lines[i].trim() !== "") {- firstLineIndex = i;- break;- }- }-- if (firstLineIndex === -1) {- return "";- }-- let lastLineIndex = -1;- for (let i = lines.length - 1; i >= 0; i -= 1) {- if (lines[i].trim() !== "") {- lastLineIndex = i;- break;- }- }-- lines = lines.slice(firstLineIndex, lastLineIndex + 1);-- // Determine the minimum indentation of non-empty lines- const indentations = lines- .filter((line) => line.trim() !== "")- .map((line) => {- const match = line.match(/^\s*/);- return match ? match[0].length : 0;- });-- const minIndentation = indentations.length > 0 ? Math.min(...indentations) : 0;-- // Remove the common indentation from all lines- if (minIndentation > 0) {- lines = lines.map((line) => line.substring(minIndentation));- }-- return lines.join("\n");-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsxdeleted file mode 100644index aec491b35a..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsx+++ /dev/null@@ -1,309 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { AnimatePresence, motion } from "framer-motion";-import { Loader2Icon, PauseIcon, PlayIcon, RotateCcwIcon } from "lucide-react";--import { IconButton } from "@app/components/v3";-import { TSessionEvent } from "@app/hooks/api/pam";-import { isBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";--import { parseRdpLogEntry, RdpEvent, RdpReplayPlayer } from "./rdpReplayPlayer";--const CANVAS_W = 1920;-const CANVAS_H = 1080;-// Locks the player footprint so it doesn't reshape on first frame.-const OUTER_ASPECT_W = 16;-const OUTER_ASPECT_H = 9;-const OUTER_ASPECT = OUTER_ASPECT_W / OUTER_ASPECT_H;--const formatMs = (ms: number) => {- const s = Math.floor(ms / 1000);- const h = Math.floor(s / 3600);- const m = Math.floor((s % 3600) / 60);- const r = s % 60;- const mm = m.toString().padStart(2, "0");- const ss = r.toString().padStart(2, "0");- return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;-};--const parseRange = (events: TSessionEvent[], start: number, end: number): RdpEvent[] => {- const out: RdpEvent[] = [];- for (let i = start; i < end; i += 1) {- const ev = parseRdpLogEntry(events[i]);- if (ev) out.push(ev);- }- return out;-};--type Props = {- events: TSessionEvent[];- isStreaming?: boolean;- totalDurationMs?: number;-};--export const RdpReplayView = ({ events, isStreaming = false, totalDurationMs }: Props) => {- const canvasRef = useRef<HTMLCanvasElement | null>(null);- const playerRef = useRef<RdpReplayPlayer | null>(null);- const lastParsedIndexRef = useRef(0);- // raf-frequency updates: write progress fill + time text via refs to- // avoid re-rendering the player subtree at 60fps.- const progressFillRef = useRef<HTMLDivElement | null>(null);- const timeTextRef = useRef<HTMLSpanElement | null>(null);- const currentMsRef = useRef(0);- const [isPlaying, setIsPlaying] = useState(false);- const [isBuffering, setIsBuffering] = useState(false);- const [lastSeenEventMs, setLastSeenEventMs] = useState(0);- const [error, setError] = useState<string | null>(null);- // Re-triggers the events / isStreaming effects once the async WASM init- // resolves; ref assignment alone wouldn't schedule a render.- const [playerReady, setPlayerReady] = useState(false);- // nonce remounts AnimatePresence on rapid toggles so the pulse restarts.- const [feedback, setFeedback] = useState<{- icon: "play" | "pause";- nonce: number;- } | null>(null);- const totalMs = totalDurationMs && totalDurationMs > 0 ? totalDurationMs : lastSeenEventMs;- const [contentBounds, setContentBounds] = useState({- width: CANVAS_W,- height: CANVAS_H- });-- const totalMsRef = useRef(totalMs);- totalMsRef.current = totalMs;-- const writeProgress = (ms: number) => {- currentMsRef.current = ms;- const total = totalMsRef.current;- if (progressFillRef.current) {- const pct = total > 0 ? Math.min(1, ms / total) * 100 : 0;- progressFillRef.current.style.width = `${pct}%`;- }- if (timeTextRef.current) {- timeTextRef.current.textContent = `${formatMs(ms)} / ${formatMs(total)}`;- }- };-- // Player lifetime is mount-scoped; later chunks land via appendEvents.- useEffect(() => {- let cancelled = false;- const canvas = canvasRef.current;- if (!canvas) return undefined;-- // RDP frames are deltas; bail before creating the player if the initial- // event range already includes a corrupt-chunk marker (the events effect- // below only checks events past lastParsedIndexRef).- for (let i = 0; i < events.length; i += 1) {- const ev = events[i];- if (isBrokenChunkMarker(ev)) {- setError(`Chunk ${ev.chunkIndex}: ${ev.message}`);- return undefined;- }- }-- const initial = parseRange(events, 0, events.length);- lastParsedIndexRef.current = events.length;- if (initial.length > 0) setLastSeenEventMs(initial[initial.length - 1].elapsedMs);-- RdpReplayPlayer.create(initial, canvas, {- onTick: writeProgress,- onEnded: () => {- setIsPlaying(false);- setIsBuffering(false);- },- onContentBoundsChange: (width, height) => setContentBounds({ width, height }),- onBuffering: (b) => setIsBuffering(b)- })- .then((player) => {- if (cancelled) {- player.dispose();- return;- }- playerRef.current = player;- // Trigger the events / isStreaming effects to handle any state that- // accumulated during the async init (events that arrived, isStreaming- // that flipped to false).- setPlayerReady(true);- })- .catch((e: unknown) => {- setError(e instanceof Error ? e.message : "Failed to initialize RDP replay player");- });-- return () => {- cancelled = true;- if (playerRef.current) {- playerRef.current.dispose();- playerRef.current = null;- }- lastParsedIndexRef.current = 0;- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- useEffect(() => {- const player = playerRef.current;- if (!player) return;- if (events.length <= lastParsedIndexRef.current) return;- // RDP frames are deltas; one corrupt/missing chunk desyncs everything- // after it. Halt playback and surface the failure rather than rendering- // garbage frames.- for (let i = lastParsedIndexRef.current; i < events.length; i += 1) {- const ev = events[i];- if (isBrokenChunkMarker(ev)) {- player.pause();- setError(`Chunk ${ev.chunkIndex}: ${ev.message}`);- return;- }- }- const more = parseRange(events, lastParsedIndexRef.current, events.length);- lastParsedIndexRef.current = events.length;- if (more.length > 0) {- player.appendEvents(more);- setLastSeenEventMs(more[more.length - 1].elapsedMs);- }- }, [events, playerReady]);-- useEffect(() => {- if (!isStreaming && playerRef.current) {- playerRef.current.markStreamComplete();- }- }, [isStreaming, playerReady]);-- useEffect(() => {- writeProgress(currentMsRef.current);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [totalMs]);-- const onPlayPause = () => {- const p = playerRef.current;- if (!p) return;- if (p.isPlaying) {- p.pause();- setIsPlaying(false);- setFeedback({ icon: "pause", nonce: Date.now() });- return;- }- // play() auto-replays from t=0 when at end-of-stream; reset bounds too.- const willAutoReplay = p.currentMs >= p.totalMs && p.totalMs > 0;- p.play();- if (willAutoReplay) {- setContentBounds({ width: CANVAS_W, height: CANVAS_H });- }- setIsPlaying(true);- setFeedback({ icon: "play", nonce: Date.now() });- };-- useEffect(() => {- if (!feedback) return undefined;- const t = setTimeout(() => setFeedback(null), 400);- return () => clearTimeout(t);- }, [feedback]);-- const onRestart = () => {- const p = playerRef.current;- if (!p) return;- p.restart();- setIsPlaying(false);- setIsBuffering(false);- setContentBounds({ width: CANVAS_W, height: CANVAS_H });- };-- if (error) {- return (- <div className="flex flex-col gap-1 rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-xs text-danger">- <span>Playback halted: recording chunks are unavailable or corrupted.</span>- <span className="text-danger/70">{error}</span>- </div>- );- }-- return (- <div className="flex flex-col gap-3">- <button- type="button"- onClick={onPlayPause}- aria-label={isPlaying ? "Pause" : "Play"}- className="group relative flex cursor-pointer items-center justify-center overflow-hidden rounded-md border border-border bg-black focus-visible:ring-2 focus-visible:ring-foreground/30 focus-visible:outline-none"- style={{ aspectRatio: `${OUTER_ASPECT_W} / ${OUTER_ASPECT_H}` }}- >- <div- className="relative overflow-hidden"- style={{- aspectRatio: `${contentBounds.width} / ${contentBounds.height}`,- ...(contentBounds.width / contentBounds.height <= OUTER_ASPECT- ? { height: "100%" }- : { width: "100%" })- }}- >- <canvas- ref={canvasRef}- width={CANVAS_W}- height={CANVAS_H}- style={{- width: `${(CANVAS_W / contentBounds.width) * 100}%`,- height: `${(CANVAS_H / contentBounds.height) * 100}%`,- display: "block"- }}- aria-label="RDP session replay"- />- </div>- <AnimatePresence>- {feedback && (- <motion.div- key={feedback.nonce}- initial={{ opacity: 0, scale: 0.6 }}- animate={{ opacity: 1, scale: 1 }}- exit={{ opacity: 0, scale: 1.4 }}- transition={{ duration: 0.35, ease: "easeOut" }}- className="pointer-events-none absolute inset-0 flex items-center justify-center"- >- <div className="flex size-16 items-center justify-center rounded-full bg-black/60 backdrop-blur-sm">- {feedback.icon === "play" ? (- <PlayIcon className="size-8 text-white" />- ) : (- <PauseIcon className="size-8 text-white" />- )}- </div>- </motion.div>- )}- </AnimatePresence>- {isBuffering && (- <div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/40">- <div className="flex items-center gap-2 rounded-md bg-black/70 px-3 py-1.5 text-xs text-foreground">- <Loader2Icon className="size-3.5 animate-spin" />- <span>Buffering...</span>- </div>- </div>- )}- </button>- <div className="flex items-center gap-3">- <IconButton- variant="project"- size="sm"- onClick={onPlayPause}- aria-label={isPlaying ? "Pause" : "Play"}- >- {isPlaying ? <PauseIcon /> : <PlayIcon />}- </IconButton>- <div className="relative h-1 flex-1 overflow-hidden rounded-full bg-foreground/10">- <div- ref={progressFillRef}- className="absolute inset-y-0 left-0 rounded-full bg-foreground/70"- style={{ width: "0%" }}- />- </div>- <span ref={timeTextRef} className="font-mono text-xs text-muted tabular-nums">- {formatMs(0)} / {formatMs(totalMs)}- </span>- <IconButton- variant="ghost-muted"- size="sm"- onClick={onRestart}- aria-label="Restart from beginning"- >- <RotateCcwIcon />- </IconButton>- </div>- </div>- );-};--export default RdpReplayView;diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/index.ts b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/index.tsdeleted file mode 100644index d868ea6193..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/index.ts+++ /dev/null@@ -1 +0,0 @@-export { RdpReplayView } from "./RdpReplayView";diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.ts b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.tsdeleted file mode 100644index b0d37c9689..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.ts+++ /dev/null@@ -1,347 +0,0 @@-import wasmInit, { InitOutput, RdpDecoder } from "@app/lib/ironrdp-decoder/infisical_rdp_decoder";--export type RdpEventType = "keyboard" | "unicode" | "mouse" | "target_frame";--export type RdpEvent = {- type: RdpEventType;- elapsedMs: number;- scancode?: number;- codePoint?: number;- x?: number;- y?: number;- wheelDelta?: number;- flags?: number;- action?: "x224" | "fastpath";- payload?: Uint8Array;-};--type PlayerCallbacks = {- onTick: (currentMs: number) => void;- onEnded: () => void;- onContentBoundsChange: (width: number, height: number) => void;- onBuffering: (buffering: boolean) => void;-};--let wasmReady: Promise<InitOutput> | null = null;-const ensureWasm = (): Promise<InitOutput> => {- if (!wasmReady) wasmReady = wasmInit();- return wasmReady;-};--export class RdpReplayPlayer {- private events: RdpEvent[];-- private canvas: HTMLCanvasElement;-- private ctx: CanvasRenderingContext2D;-- private callbacks: PlayerCallbacks;-- private decoder: RdpDecoder;-- private wasm: InitOutput;-- private index = 0;-- private clockMs = 0;-- private wallStart: number | null = null;-- private raf: number | null = null;-- // Stays true while buffering so an append can auto-resume playback.- private wantPlay = false;-- private streamComplete = false;-- private buffering = false;-- // Running max of blitted rects; discovers the real desktop size.- private contentMaxX = 0;-- private contentMaxY = 0;-- private constructor(- events: RdpEvent[],- canvas: HTMLCanvasElement,- callbacks: PlayerCallbacks,- decoder: RdpDecoder,- wasm: InitOutput- ) {- this.events = events;- this.canvas = canvas;- const c = canvas.getContext("2d");- if (!c) throw new Error("2d context unavailable");- this.ctx = c;- this.callbacks = callbacks;- this.decoder = decoder;- this.wasm = wasm;- }-- static async create(- events: RdpEvent[],- canvas: HTMLCanvasElement,- callbacks: PlayerCallbacks- ): Promise<RdpReplayPlayer> {- const wasm = await ensureWasm();- const decoder = new RdpDecoder(canvas.width, canvas.height);- // Prime pointer position off-screen so the first server-emitted pointer- // bitmap doesn't paint at (0,0) before the first recorded mouse event.- decoder.move_pointer(0xffff, 0xffff);- return new RdpReplayPlayer(events, canvas, callbacks, decoder, wasm);- }-- get totalMs(): number {- const last = this.events[this.events.length - 1];- return last ? last.elapsedMs : 0;- }-- get currentMs(): number {- return this.clockMs;- }-- get isPlaying(): boolean {- return this.wantPlay;- }-- get isBuffering(): boolean {- return this.buffering;- }-- play = () => {- if (this.wantPlay) return;- // Play after end-of-stream replays from t=0.- if (this.streamComplete && this.index >= this.events.length) {- this.resetForReplay();- }- this.wantPlay = true;- if (this.index >= this.events.length) {- this.setBuffering(true);- return;- }- this.startRaf();- };-- pause = () => {- this.wantPlay = false;- this.stopRaf();- this.setBuffering(false);- };-- restart = () => {- this.resetForReplay();- this.wantPlay = false;- };-- // Shared between restart() and the play()-after-end auto-replay path.- private resetForReplay = () => {- this.stopRaf();- this.setBuffering(false);- this.index = 0;- this.clockMs = 0;- this.contentMaxX = 0;- this.contentMaxY = 0;- // Frames are deltas, so replaying needs a fresh decoder state.- this.decoder.free();- this.decoder = new RdpDecoder(this.canvas.width, this.canvas.height);- this.decoder.move_pointer(0xffff, 0xffff);- this.ctx.fillStyle = "#000";- this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);- this.callbacks.onTick(0);- };-- // Caller must preserve global elapsedMs ordering across calls.- appendEvents = (more: RdpEvent[]) => {- if (more.length === 0) return;- this.events.push(...more);- if (this.buffering && this.wantPlay) {- this.setBuffering(false);- this.startRaf();- }- };-- markStreamComplete = () => {- if (this.streamComplete) return;- this.streamComplete = true;- if (this.buffering) {- this.setBuffering(false);- this.wantPlay = false;- this.callbacks.onEnded();- }- };-- dispose = () => {- this.stopRaf();- this.wantPlay = false;- this.buffering = false;- try {- this.decoder.free();- } catch {- /* ignore */- }- };-- private startRaf = () => {- if (this.raf !== null) return;- this.wallStart = performance.now() - this.clockMs;- this.tick();- };-- private stopRaf = () => {- if (this.raf === null) return;- cancelAnimationFrame(this.raf);- this.raf = null;- this.wallStart = null;- };-- private setBuffering = (value: boolean) => {- if (this.buffering === value) return;- this.buffering = value;- this.callbacks.onBuffering(value);- };-- private tick = () => {- if (this.wallStart === null) return;- const now = performance.now();- this.clockMs = now - this.wallStart;-- while (this.index < this.events.length && this.events[this.index].elapsedMs <= this.clockMs) {- // One bad event shouldn't halt the raf loop.- try {- this.apply(this.events[this.index]);- } catch (err) {- // eslint-disable-next-line no-console- console.warn("RDP replay: apply failed, skipping event", err);- }- this.index += 1;- }-- this.callbacks.onTick(this.clockMs);-- if (this.index >= this.events.length) {- this.raf = null;- this.wallStart = null;- if (this.streamComplete) {- this.wantPlay = false;- this.callbacks.onEnded();- } else {- this.setBuffering(true);- }- return;- }-- this.raf = requestAnimationFrame(this.tick);- };-- private apply = (ev: RdpEvent) => {- switch (ev.type) {- case "target_frame":- if (ev.payload) this.feedFrame(ev);- break;- case "mouse":- // Server only sends PositionPointer for its own moves; drive cursor from input.- if (ev.x !== undefined && ev.y !== undefined) {- const count = this.decoder.move_pointer(ev.x, ev.y);- // expandBounds=false: cursor composite rects can extend slightly- // past the framebuffer (sprite at the desktop edge). Cursor- // position shouldn't define the recording's desktop bounds.- if (count > 0) this.blitDirtyRects(count, false);- }- break;- case "keyboard":- case "unicode":- break;- default:- break;- }- };-- private blitDirtyRects = (count: number, expandBounds = true) => {- // Re-view: wasm-bindgen may reallocate linear memory between calls.- const ptr = this.decoder.buffer_ptr();- const len = this.decoder.buffer_len();- const width = this.decoder.width();- const height = this.decoder.height();- const fb = new Uint8ClampedArray(this.wasm.memory.buffer, ptr, len);- const fullImage = new ImageData(fb, width, height);-- let boundsExpanded = false;- for (let i = 0; i < count; i += 1) {- const r = this.decoder.dirty_rect(i);- if (r) {- this.ctx.putImageData(fullImage, 0, 0, r.x, r.y, r.w, r.h);- if (expandBounds) {- const right = r.x + r.w;- const bottom = r.y + r.h;- if (right > this.contentMaxX) {- this.contentMaxX = right;- boundsExpanded = true;- }- if (bottom > this.contentMaxY) {- this.contentMaxY = bottom;- boundsExpanded = true;- }- }- r.free();- }- }- if (boundsExpanded) {- this.callbacks.onContentBoundsChange(this.contentMaxX, this.contentMaxY);- }- };-- private feedFrame = (ev: RdpEvent) => {- if (!ev.payload) return;- // X.224 activation PDUs corrupt ActiveStage state; FastPath alone is enough.- if (ev.action === "x224") return;- let count: number;- try {- count = this.decoder.feed(1, ev.payload);- } catch {- return;- }- if (count === 0) return;- this.blitDirtyRects(count);- };-}--const decodeBase64ToUint8 = (b64: string): Uint8Array => {- const bin = atob(b64);- const out = new Uint8Array(bin.length);- for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);- return out;-};--// Wire shape: base64 JSON. See rdp*Envelope in cli/.../rdp/proxy.go.-export const parseRdpLogEntry = (entry: unknown): RdpEvent | null => {- const e = entry as { data?: string; channelType?: string };- if (e?.channelType !== "rdp" || typeof e.data !== "string") return null;- let rec: Record<string, unknown>;- try {- rec = JSON.parse(atob(e.data));- } catch {- return null;- }- const type = rec.type as RdpEventType | undefined;- if (!type) return null;- const elapsedMs = Number(rec.elapsedNs ?? 0) / 1e6;-- const ev: RdpEvent = { type, elapsedMs };- if (type === "keyboard") {- ev.scancode = Number(rec.scancode ?? 0);- ev.flags = Number(rec.flags ?? 0);- } else if (type === "unicode") {- ev.codePoint = Number(rec.codePoint ?? 0);- ev.flags = Number(rec.flags ?? 0);- } else if (type === "mouse") {- ev.x = Number(rec.x ?? 0);- ev.y = Number(rec.y ?? 0);- ev.flags = Number(rec.flags ?? 0);- ev.wheelDelta = Number(rec.wheelDelta ?? 0);- } else if (type === "target_frame") {- ev.action = rec.action as "x224" | "fastpath";- const payloadB64 = rec.payload as string | undefined;- if (payloadB64) ev.payload = decodeBase64ToUint8(payloadB64);- }- return ev;-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsxdeleted file mode 100644index d7247097b7..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/TerminalEventView.tsx+++ /dev/null@@ -1,121 +0,0 @@-import { useMemo, useState } from "react";-import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";--import { Input } from "@app/components/v2";-import { HighlightText } from "@app/components/v2/HighlightText";-import { SessionChannelType, TSessionEvent } from "@app/hooks/api/pam";-import { isBrokenChunkMarker, TBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";--import { aggregateTerminalEvents } from "./terminal-utils";--const CHANNEL_LABEL_MAP: Record<string, string> = {- [SessionChannelType.Exec]: "Exec",- [SessionChannelType.Sftp]: "SFTP"-};--type Props = {- events: (TSessionEvent | TBrokenChunkMarker)[];-};--export const TerminalEventView = ({ events }: Props) => {- const [search, setSearch] = useState("");-- const markers = useMemo(() => events.filter(isBrokenChunkMarker), [events]);-- const realEvents = useMemo(- () => events.filter((e): e is TSessionEvent => !isBrokenChunkMarker(e)),- [events]- );-- const aggregatedEvents = useMemo(() => aggregateTerminalEvents(realEvents), [realEvents]);-- const filteredEvents = useMemo(- () =>- aggregatedEvents.filter((event) => {- const searchValue = search.trim().toLowerCase();- if (!searchValue) return true;- return event.data.toLowerCase().includes(searchValue);- }),- [aggregatedEvents, search]- );-- return (- <>- <div className="flex gap-2">- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}- placeholder="Search terminal output..."- className="flex-1 bg-mineshaft-800"- containerClassName="bg-transparent"- />- </div>-- <div className="flex grow flex-col gap-2 overflow-y-auto text-xs">- {markers.length > 0 && (- <div className="flex flex-col gap-1 rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-xs text-warning">- <span>Some terminal output may be missing due to unavailable chunks.</span>- {markers.map((m) => (- <span key={m.chunkIndex} className="text-warning/70">- Chunk {m.chunkIndex}: {m.message}- </span>- ))}- </div>- )}- {filteredEvents.length > 0 ? (- filteredEvents.map((event, index) => {- const eventKey = `${event.timestamp}-${index}`;-- const channelLabel = event.channelType ? CHANNEL_LABEL_MAP[event.channelType] : null;-- return (- <div- key={eventKey}- className="flex w-full flex-col rounded-md border border-border bg-card p-3"- >- <div className="flex items-center justify-between text-muted">- <div className="flex items-center gap-2 text-xs">- <span>{new Date(event.timestamp).toLocaleString()}</span>- {channelLabel && (- <span className="rounded bg-card px-1.5 py-0.5 text-label">- {channelLabel}- </span>- )}- {event.eventType === "input" && (- <span className="rounded bg-primary-900/30 px-1.5 py-0.5 text-primary-400">- Command- </span>- )}- </div>- </div>-- <div className="mt-2 font-mono whitespace-pre-wrap text-foreground">- <HighlightText text={event.data} highlight={search} />- </div>- </div>- );- })- ) : (- <div className="flex grow items-center justify-center text-label">- {search.length ? (- <div className="text-center">- <div className="mb-2">No terminal output matches search criteria</div>- </div>- ) : (- <div className="text-center">- <div className="mb-2">Terminal session logs are not yet available</div>- <div className="text-xs text-muted">- Logs will be uploaded after the session duration has elapsed.- <br />- If logs do not appear after some time, please contact your Gateway administrators.- </div>- </div>- )}- </div>- )}- </div>- </>- );-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/terminal-utils.ts b/frontend/src/pages/pam/PamSessionsByIDPage/components/terminal-utils.tsdeleted file mode 100644index 683d27aa2c..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/terminal-utils.ts+++ /dev/null@@ -1,211 +0,0 @@-import { SessionChannelType, TSessionEvent } from "@app/hooks/api/pam";--// Strip ANSI escape codes from terminal output-export const stripAnsiCodes = (text: string): string => {- // eslint-disable-next-line no-control-regex- return text.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").replace(/\x1b\][0-9];[^\x07]*\x07/g, "");-};--// Check if a string contains mostly printable characters-const isPrintableText = (text: string): boolean => {- if (text.length === 0) return false;- let printableCount = 0;- for (let i = 0; i < text.length; i += 1) {- const code = text.charCodeAt(i);- if ((code >= 32 && code <= 126) || code === 10 || code === 13 || code === 9 || code > 127) {- printableCount += 1;- }- }- return printableCount / text.length >= 0.8;-};--// Decode a single event's base64 data, returning empty string on failure or binary data-const decodeEventData = (event: TSessionEvent): string => {- try {- const decoded = stripAnsiCodes(atob(event.data));- if (!isPrintableText(decoded)) {- return "";- }- return decoded;- } catch {- return "";- }-};--export type AggregatedTerminalEvent = {- timestamp: string;- eventType: string;- channelType?: string;- data: string;- elapsedTime: number;- eventCount: number;-};--// Aggregate consecutive output events using prompt-based segmentation-const aggregateOutputEvents = (- outputEvents: TSessionEvent[],- channelType?: string-): AggregatedTerminalEvent[] => {- if (outputEvents.length === 0) return [];-- const decodedEvents: { text: string; event: TSessionEvent }[] = outputEvents- .map((e) => ({ text: decodeEventData(e), event: e }))- .filter((e) => e.text.length > 0);-- if (decodedEvents.length === 0) return [];-- const charToEventIndex: number[] = [];- decodedEvents.forEach((decoded, eventIndex) => {- for (let i = 0; i < decoded.text.length; i += 1) {- charToEventIndex.push(eventIndex);- }- });-- const allText = decodedEvents.map((d) => d.text).join("");- const promptPattern = /^[\w-]+@[\w-]+[^\s]*[:#$]\s+/;-- const lines = allText.split("\n");- const segments: { text: string; startCharIndex: number }[] = [];- let currentSegmentLines: string[] = [];- let currentSegmentStartChar = 0;- let currentCharIndex = 0;-- lines.forEach((line, lineIndex) => {- const hasPrompt = promptPattern.test(line);-- if (hasPrompt && currentSegmentLines.length > 0) {- segments.push({- text: currentSegmentLines.join("\n"),- startCharIndex: currentSegmentStartChar- });- currentSegmentLines = [line];- currentSegmentStartChar = currentCharIndex;- } else {- currentSegmentLines.push(line);- }-- currentCharIndex += line.length + (lineIndex < lines.length - 1 ? 1 : 0);- });-- if (currentSegmentLines.length > 0) {- segments.push({- text: currentSegmentLines.join("\n"),- startCharIndex: currentSegmentStartChar- });- }-- const validSegments = segments.filter((seg) => seg.text.trim().length > 0);-- return validSegments.map((segment) => {- const eventIndex = charToEventIndex[segment.startCharIndex] ?? 0;- const originalEvent = decodedEvents[eventIndex]?.event ?? outputEvents[0];-- return {- timestamp: originalEvent.timestamp,- eventType: "output",- channelType,- data: segment.text,- elapsedTime: originalEvent.elapsedTime,- eventCount: 1- };- });-};--// Convert input events to aggregated format-const convertInputEvents = (- inputEvents: TSessionEvent[],- channelType?: string-): AggregatedTerminalEvent[] => {- const results: AggregatedTerminalEvent[] = [];-- inputEvents.forEach((event) => {- const text = decodeEventData(event);- if (text.trim()) {- results.push({- timestamp: event.timestamp,- eventType: "input",- channelType,- data: text,- elapsedTime: event.elapsedTime,- eventCount: 1- });- }- });-- return results;-};--// Process events that have channelType (new format)-const processEventsWithChannelType = (events: TSessionEvent[]): AggregatedTerminalEvent[] => {- const results: AggregatedTerminalEvent[] = [];-- // Group events by channelType- const terminalEvents = events.filter((e) => e.channelType === SessionChannelType.Terminal);- const execEvents = events.filter((e) => e.channelType === SessionChannelType.Exec);- const sftpEvents = events.filter((e) => e.channelType === SessionChannelType.Sftp);-- // Terminal: only show output (input is echoed)- const terminalOutputs = terminalEvents.filter((e) => e.eventType === "output");- results.push(...aggregateOutputEvents(terminalOutputs, SessionChannelType.Terminal));-- // Exec: show both input (command) and output (result)- const execInputs = execEvents.filter((e) => e.eventType === "input");- const execOutputs = execEvents.filter((e) => e.eventType === "output");- results.push(...convertInputEvents(execInputs, SessionChannelType.Exec));- results.push(...aggregateOutputEvents(execOutputs, SessionChannelType.Exec));-- // SFTP: show only input messages (no meaningful output)- const sftpInputs = sftpEvents.filter((e) => e.eventType === "input");- results.push(...convertInputEvents(sftpInputs, SessionChannelType.Sftp));-- // Sort by timestamp to maintain chronological order- results.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());-- return results;-};--// Backwards compatibility: process legacy events without channelType-// Uses heuristic - only show output events (assumes interactive terminal)-const processLegacyEvents = (events: TSessionEvent[]): AggregatedTerminalEvent[] => {- const outputEvents = events.filter((e) => e.eventType === "output");-- // If there are output events, aggregate them (interactive terminal behavior)- if (outputEvents.length > 0) {- return aggregateOutputEvents(outputEvents);- }-- // Fallback: if no output events, show input events (might be SFTP-like)- const inputEvents = events.filter((e) => e.eventType === "input");- return convertInputEvents(inputEvents);-};--// Main aggregation function-export const aggregateTerminalEvents = (events: TSessionEvent[]): AggregatedTerminalEvent[] => {- if (events.length === 0) return [];-- // Check if any events have channelType (new format)- const hasChannelType = events.some((e) => e.channelType !== undefined);-- if (hasChannelType) {- // New format: use explicit channelType for routing- // Handle mixed case: events with channelType + legacy events without- const eventsWithChannelType = events.filter((e) => e.channelType !== undefined);- const eventsWithoutChannelType = events.filter((e) => e.channelType === undefined);-- const results: AggregatedTerminalEvent[] = [];- results.push(...processEventsWithChannelType(eventsWithChannelType));-- // Process legacy events (if any) separately- if (eventsWithoutChannelType.length > 0) {- results.push(...processLegacyEvents(eventsWithoutChannelType));- }-- // Re-sort after merging- results.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());-- return results;- }-- // Legacy format: use heuristic approach- return processLegacyEvents(events);-};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/route.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/route.tsxdeleted file mode 100644index 1230c65b11..0000000000--- a/frontend/src/pages/pam/PamSessionsByIDPage/route.tsx+++ /dev/null@@ -1,26 +0,0 @@-import { createFileRoute, linkOptions } from "@tanstack/react-router";--import { PamSessionByIDPage } from "./PamSessionByIDPage";--export const Route = createFileRoute(- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions/$sessionId"-)({- component: PamSessionByIDPage,- beforeLoad: ({ context, params }) => {- return {- breadcrumbs: [- ...context.breadcrumbs,- {- label: "Sessions",- link: linkOptions({- to: "/organizations/$orgId/projects/pam/$projectId/sessions",- params- })- },- {- label: "Details"- }- ]- };- }-});diff --git a/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsx b/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsxdeleted file mode 100644index 18a6d05ef5..0000000000--- a/frontend/src/pages/pam/PamSessionsPage/PamSessionsPage.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { Helmet } from "react-helmet";-import { useTranslation } from "react-i18next";--import { ProjectPermissionCan } from "@app/components/permissions";-import { PageHeader } from "@app/components/v2";-import { ProjectPermissionSub } from "@app/context";-import { ProjectPermissionPamSessionActions } from "@app/context/ProjectPermissionContext/types";-import { ProjectType } from "@app/hooks/api/projects/types";--import { PamSessionSection } from "./components/PamSessionSection";--export const PamSessionPage = () => {- const { t } = useTranslation();- return (- <>- <Helmet>- <title>{t("common.head-title", { title: "PAM" })}</title>- </Helmet>- <ProjectPermissionCan- renderGuardBanner- I={ProjectPermissionPamSessionActions.Read}- a={ProjectPermissionSub.PamSessions}- >- <div className="h-full bg-bunker-800">- <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">- <div className="mx-auto mb-6 w-full max-w-8xl">- <PageHeader- scope={ProjectType.PAM}- title="Sessions"- description="View and filter account sessions."- />- <PamSessionSection />- </div>- </div>- </div>- </ProjectPermissionCan>- </>- );-};diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsxdeleted file mode 100644index 4166af7da0..0000000000--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionRow.tsx+++ /dev/null@@ -1,188 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck -- old PAM page, pending deletion in frontend cleanup-import { useState } from "react";-import { faBoxOpen, faEdit, faEllipsisV } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { useNavigate } from "@tanstack/react-router";-import { GavelIcon } from "lucide-react";-import { twMerge } from "tailwind-merge";--import { ProjectPermissionCan } from "@app/components/permissions";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- IconButton,- Td,- Tooltip,- Tr-} from "@app/components/v2";-import {- ProjectPermissionActions,- ProjectPermissionPamSessionActions,- ProjectPermissionSub,- useOrganization-} from "@app/context";-import { PAM_RESOURCE_TYPE_MAP, PamSessionStatus, TPamSession } from "@app/hooks/api/pam";--import { PamTerminateSessionModal } from "../../components/PamTerminateSessionModal";-import { PamSessionStatusBadge } from "./PamSessionStatusBadge";--type Props = {- session: TPamSession;-};--export const PamSessionRow = ({ session }: Props) => {- const navigate = useNavigate();- const { currentOrg } = useOrganization();- const [isTerminateDialogOpen, setIsTerminateDialogOpen] = useState(false);-- const {- id,- accountName,- resourceType,- resourceName,- projectId,- status,- actorName,- actorEmail,- createdAt,- endedAt,- gatewayIdentityId,- gatewayId- } = session;-- const isActive = status === PamSessionStatus.Active || status === PamSessionStatus.Starting;- const isGatewaySession = !!gatewayIdentityId || !!gatewayId;-- const { image, name: resourceTypeName } = PAM_RESOURCE_TYPE_MAP[resourceType];-- return (- <>- <Tr- className={twMerge("group h-10 cursor-pointer hover:bg-bunker-400/20")}- onClick={() =>- navigate({- to: "/organizations/$orgId/projects/pam/$projectId/sessions/$sessionId",- params: { orgId: currentOrg.id, projectId, sessionId: id }- })- }- >- <Td>- <div className="flex items-center gap-4">- <div className="relative">- <img- alt={resourceTypeName}- src={`/images/integrations/${image}`}- className="size-6"- />- </div>- <div className="flex items-center gap-2">- <div className="flex flex-col">- <span>{accountName}</span>- <div className="flex items-center gap-1 text-xs text-bunker-300">- <FontAwesomeIcon icon={faBoxOpen} className="size-3" />- <span>{resourceName}</span>- </div>- </div>- </div>- </div>- </Td>- <Td>- <div className="flex flex-col">- <span>{actorName}</span>- <span className="text-xs text-bunker-300">{actorEmail}</span>- </div>- </Td>- <Td>- <div className="flex flex-col">- <span>{new Date(createdAt).toLocaleTimeString()}</span>- <span className="text-xs text-bunker-300">- {new Date(createdAt).toLocaleDateString()}- </span>- </div>- </Td>- <Td>- {endedAt ? (- <div className="flex flex-col">- <span>{new Date(endedAt).toLocaleTimeString()}</span>- <span className="text-xs text-bunker-300">- {new Date(endedAt).toLocaleDateString()}- </span>- </div>- ) : (- <span className="text-bunker-400">Ongoing</span>- )}- </Td>- <Td>- <div className="flex items-center justify-end gap-2">- <PamSessionStatusBadge status={status} />- <Tooltip className="max-w-sm text-center" content="Options">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- ariaLabel="Options"- colorSchema="secondary"- className="w-6"- variant="plain"- >- <FontAwesomeIcon icon={faEllipsisV} />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuContent sideOffset={2} align="end">- <ProjectPermissionCan- I={ProjectPermissionActions.Read}- a={ProjectPermissionSub.PamSessions}- >- {(isAllowed: boolean) => (- <DropdownMenuItem- isDisabled={!isAllowed}- icon={<FontAwesomeIcon icon={faEdit} />}- onClick={() =>- navigate({- to: "/organizations/$orgId/projects/pam/$projectId/sessions/$sessionId",- params: { orgId: currentOrg.id, projectId, sessionId: id }- })- }- >- View Session- </DropdownMenuItem>- )}- </ProjectPermissionCan>- {isGatewaySession && (- <ProjectPermissionCan- I={ProjectPermissionPamSessionActions.Terminate}- a={ProjectPermissionSub.PamSessions}- >- {(isAllowed: boolean) => (- <DropdownMenuItem- isDisabled={!isAllowed || !isActive}- className="text-red-600"- icon={<GavelIcon size={14} />}- onClick={(e) => {- e.stopPropagation();- setIsTerminateDialogOpen(true);- }}- >- Terminate Session- </DropdownMenuItem>- )}- </ProjectPermissionCan>- )}- </DropdownMenuContent>- </DropdownMenu>- </Tooltip>- </div>- </Td>- </Tr>-- <PamTerminateSessionModal- sessionId={id}- projectId={projectId}- isOpen={isTerminateDialogOpen}- onOpenChange={setIsTerminateDialogOpen}- />- </>- );-};diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionSection.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionSection.tsxdeleted file mode 100644index 6a3c786cb3..0000000000--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionSection.tsx+++ /dev/null@@ -1,17 +0,0 @@-import { ContentLoader } from "@app/components/v2";-import { useProject } from "@app/context";-import { useListPamSessions } from "@app/hooks/api/pam";--import { PamSessionsTable } from "./PamSessionsTable";--export const PamSessionSection = () => {- const { currentProject } = useProject();-- const { data: sessions = [], isPending } = useListPamSessions(currentProject.id, {- refetchInterval: 30000- });-- if (isPending) return <ContentLoader />;-- return <PamSessionsTable sessions={sessions} />;-};diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionStatusBadge.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionStatusBadge.tsxdeleted file mode 100644index 1b347210e8..0000000000--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionStatusBadge.tsx+++ /dev/null@@ -1,52 +0,0 @@-import {- ActivityIcon,- BanIcon,- ChevronsLeftRightEllipsisIcon,- GavelIcon,- LucideIcon-} from "lucide-react";--import { Badge, TBadgeProps } from "@app/components/v3";-import { PamSessionStatus } from "@app/hooks/api/pam";--interface StatusConfig {- variant: TBadgeProps["variant"];- icon: LucideIcon;- className?: string;-}--const PAM_SESSION_STATUS_CONFIG: Record<PamSessionStatus, StatusConfig> = {- [PamSessionStatus.Active]: {- variant: "success",- icon: ActivityIcon,- className: "animate-pulse"- },- [PamSessionStatus.Terminated]: {- variant: "danger",- icon: GavelIcon- },- [PamSessionStatus.Starting]: {- variant: "info",- icon: ChevronsLeftRightEllipsisIcon,- className: "animate-pulse"- },- [PamSessionStatus.Ended]: {- variant: "neutral",- icon: BanIcon- }-};--export const PamSessionStatusBadge = ({ status }: { status: PamSessionStatus }) => {- const config = PAM_SESSION_STATUS_CONFIG[status];-- const displayName = status[0].toUpperCase() + status.slice(1);-- const Icon = config.icon;-- return (- <Badge variant={config.variant} className={config.className}>- <Icon />- {displayName}- </Badge>- );-};diff --git a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsx b/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsxdeleted file mode 100644index 59bb471322..0000000000--- a/frontend/src/pages/pam/PamSessionsPage/components/PamSessionsTable.tsx+++ /dev/null@@ -1,314 +0,0 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheck -- old PAM page, pending deletion in frontend cleanup-import { useEffect, useMemo, useState } from "react";-import { faCircleXmark } from "@fortawesome/free-regular-svg-icons";-import { faArrowDown, faArrowUp, faSearch } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { FilterIcon } from "lucide-react";-import { twMerge } from "tailwind-merge";--import {- EmptyState,- IconButton as IconButtonV2,- Pagination,- Table,- TableContainer,- TBody,- Th,- THead,- Tr-} from "@app/components/v2";-import {- DropdownMenu,- DropdownMenuCheckboxItem,- DropdownMenuContent,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,- IconButton,- Tooltip,- TooltipContent,- TooltipTrigger-} from "@app/components/v3";-import { usePagination, useResetPageHelper } from "@app/hooks";-import { OrderByDirection } from "@app/hooks/api/generic/types";-import {- PAM_RESOURCE_TYPE_MAP,- PamResourceType,- PamSessionStatus,- TPamSession-} from "@app/hooks/api/pam";--import { PamSessionRow } from "./PamSessionRow";--enum OrderBy {- Account = "account",- Actor = "actor",- CreatedAt = "createdAt",- EndedAt = "endedAt"-}--type Filters = {- resourceType: PamResourceType[];- status: PamSessionStatus[];-};--type Props = {- sessions: TPamSession[];-};--export const PamSessionsTable = ({ sessions }: Props) => {- const [filters, setFilters] = useState<Filters>({- resourceType: [],- status: []- });-- const {- setPage,- page,- perPage,- setPerPage,- offset,- orderDirection,- toggleOrderDirection,- orderBy,- setOrderDirection,- setOrderBy- } = usePagination<OrderBy>(OrderBy.CreatedAt, {- initPerPage: 20- });-- useEffect(() => {- setOrderDirection(OrderByDirection.DESC);- }, []);-- const filteredSessions = useMemo(- () =>- sessions- .filter((session) => {- const { resourceType, status } = session;- if (- (filters.resourceType.length && !filters.resourceType.includes(resourceType)) ||- (filters.status.length && !filters.status.includes(status))- ) {- return false;- }- return true;- })- .sort((a, b) => {- const [one, two] = orderDirection === OrderByDirection.ASC ? [a, b] : [b, a];-- switch (orderBy) {- case OrderBy.Account:- return one.accountName.toLowerCase().localeCompare(two.accountName.toLowerCase());- case OrderBy.Actor:- return one.actorName.toLowerCase().localeCompare(two.actorName.toLowerCase());- case OrderBy.EndedAt: {- const dateOne = one.endedAt || one.createdAt;- const dateTwo = two.endedAt || two.createdAt;- return new Date(dateOne).getTime() - new Date(dateTwo).getTime();- }- case OrderBy.CreatedAt:- default: {- const dateOne = one.createdAt;- const dateTwo = two.createdAt;- return new Date(dateOne).getTime() - new Date(dateTwo).getTime();- }- }- }),- [sessions, orderDirection, orderBy, filters]- );-- useResetPageHelper({- totalCount: filteredSessions.length,- offset,- setPage- });-- const currentPageData = useMemo(- () => filteredSessions.slice(offset, perPage * page),- [filteredSessions, offset, perPage, page]- );-- const handleSort = (column: OrderBy) => {- if (column === orderBy) {- toggleOrderDirection();- return;- }-- setOrderBy(column);- setOrderDirection(OrderByDirection.ASC);- };-- const getClassName = (col: OrderBy) => twMerge("ml-2", orderBy === col ? "" : "opacity-30");-- const getColSortIcon = (col: OrderBy) =>- orderDirection === OrderByDirection.DESC && orderBy === col ? faArrowUp : faArrowDown;-- const isTableFiltered = Boolean(filters.resourceType.length || filters.status.length);- const isContentEmpty = !filteredSessions.length;- const isFilteredEmpty = isContentEmpty && isTableFiltered;-- const availableStatuses = [...new Set(sessions.map(({ status }) => status))];- const availableResourceTypes = [...new Set(sessions.map(({ resourceType }) => resourceType))];-- return (- <div>- <div className="flex justify-end">- <DropdownMenu>- <DropdownMenuTrigger className="outline-0">- <Tooltip>- <TooltipTrigger asChild>- <IconButton- className="relative"- size="md"- variant={isTableFiltered ? "project" : "outline"}- >- <FilterIcon />- </IconButton>- </TooltipTrigger>- <TooltipContent>Filter sessions</TooltipContent>- </Tooltip>- </DropdownMenuTrigger>- <DropdownMenuContent className="max-h-[70vh] thin-scrollbar overflow-y-auto" align="end">- <DropdownMenuLabel>Status</DropdownMenuLabel>- {availableStatuses.length ? (- availableStatuses.map((status) => (- <DropdownMenuCheckboxItem- key={status}- checked={filters.status.includes(status)}- onClick={(e) => {- e.preventDefault();- setFilters((prev) => ({- ...prev,- status: prev.status.includes(status)- ? prev.status.filter((a) => a !== status)- : [...prev.status, status]- }));- }}- >- {status[0].toUpperCase() + status.slice(1)}- </DropdownMenuCheckboxItem>- ))- ) : (- <p className="px-2 py-1.5 text-sm text-muted">No sessions</p>- )}- <DropdownMenuSeparator />- <DropdownMenuLabel>Resource Type</DropdownMenuLabel>- {availableResourceTypes.length ? (- availableResourceTypes.map((type) => {- const { name, image } = PAM_RESOURCE_TYPE_MAP[type];-- return (- <DropdownMenuCheckboxItem- key={type}- checked={filters.resourceType.includes(type)}- onClick={(e) => {- e.preventDefault();- setFilters((prev) => ({- ...prev,- resourceType: prev.resourceType.includes(type)- ? prev.resourceType.filter((a) => a !== type)- : [...prev.resourceType, type]- }));- }}- >- <img- alt={`${name} resource type`}- src={`/images/integrations/${image}`}- className="h-4 w-4"- />- {name}- </DropdownMenuCheckboxItem>- );- })- ) : (- <p className="px-2 py-1.5 text-sm text-muted">No sessions</p>- )}- </DropdownMenuContent>- </DropdownMenu>- </div>- <TableContainer className="mt-4">- <Table>- <THead>- <Tr>- <Th>- <div className="flex items-center">- Account- <IconButtonV2- variant="plain"- className={getClassName(OrderBy.Account)}- ariaLabel="Sort"- onClick={() => handleSort(OrderBy.Account)}- >- <FontAwesomeIcon icon={getColSortIcon(OrderBy.Account)} />- </IconButtonV2>- </div>- </Th>- <Th>- <div className="flex items-center">- Actor- <IconButtonV2- variant="plain"- className={getClassName(OrderBy.Actor)}- ariaLabel="Sort"- onClick={() => handleSort(OrderBy.Actor)}- >- <FontAwesomeIcon icon={getColSortIcon(OrderBy.Actor)} />- </IconButtonV2>- </div>- </Th>- <Th>- <div className="flex items-center">- Created At- <IconButtonV2- variant="plain"- className={getClassName(OrderBy.CreatedAt)}- ariaLabel="Sort"- onClick={() => handleSort(OrderBy.CreatedAt)}- >- <FontAwesomeIcon icon={getColSortIcon(OrderBy.CreatedAt)} />- </IconButtonV2>- </div>- </Th>- <Th>- <div className="flex items-center">- Ended At- <IconButtonV2- variant="plain"- className={getClassName(OrderBy.EndedAt)}- ariaLabel="Sort"- onClick={() => handleSort(OrderBy.EndedAt)}- >- <FontAwesomeIcon icon={getColSortIcon(OrderBy.EndedAt)} />- </IconButtonV2>- </div>- </Th>- <Th className="w-5" />- </Tr>- </THead>- <TBody>- {currentPageData.map((session) => (- <PamSessionRow key={session.id} session={session} />- ))}- </TBody>- </Table>- {Boolean(filteredSessions.length) && (- <Pagination- count={filteredSessions.length}- page={page}- perPage={perPage}- onChangePage={setPage}- onChangePerPage={setPerPage}- />- )}- {isContentEmpty && (- <EmptyState- title={isFilteredEmpty ? "No sessions match filters" : "No sessions"}- icon={isFilteredEmpty ? faSearch : faCircleXmark}- />- )}- </TableContainer>- </div>- );-};diff --git a/frontend/src/pages/pam/PamSessionsPage/route.tsx b/frontend/src/pages/pam/PamSessionsPage/route.tsxdeleted file mode 100644index 52d5c7d153..0000000000--- a/frontend/src/pages/pam/PamSessionsPage/route.tsx+++ /dev/null@@ -1,19 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { PamSessionPage } from "./PamSessionsPage";--export const Route = createFileRoute(- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/sessions/"-)({- beforeLoad: ({ context }) => {- return {- breadcrumbs: [- ...context.breadcrumbs,- {- label: "Sessions"- }- ]- };- },- component: PamSessionPage-});diff --git a/frontend/src/pages/pam/components/PamTerminateSessionModal.tsx b/frontend/src/pages/pam/components/PamTerminateSessionModal.tsxdeleted file mode 100644index 29aa4d589e..0000000000--- a/frontend/src/pages/pam/components/PamTerminateSessionModal.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { createNotification } from "@app/components/notifications";-import { Button, Modal, ModalClose, ModalContent } from "@app/components/v2";-import { useTerminatePamSession } from "@app/hooks/api/pam";--type Props = {- sessionId: string;- projectId: string;- isOpen: boolean;- onOpenChange: (isOpen: boolean) => void;-};--export const PamTerminateSessionModal = ({ sessionId, projectId, isOpen, onOpenChange }: Props) => {- const terminateSession = useTerminatePamSession();-- const handleTerminate = async () => {- await terminateSession.mutateAsync(- { sessionId, projectId },- {- onSuccess: () => {- createNotification({- text: "Session terminated successfully",- type: "success"- });- onOpenChange(false);- }- }- );- };-- return (- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>- <ModalContent- title="Terminate Session"- subTitle="Are you sure you want to terminate this session?"- footerContent={- <div className="mx-2 flex items-center">- <Button- className="mr-4"- colorSchema="danger"- isLoading={terminateSession.isPending}- onClick={handleTerminate}- >- Terminate- </Button>- <ModalClose asChild>- <Button variant="plain" colorSchema="secondary">- Cancel- </Button>- </ModalClose>- </div>- }- />- </Modal>- );-};diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex f0a3c03657..2d59f230c9 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -95,11 +95,9 @@ import { Route as projectIdentityDetailsByIDPageRoutePamImport } from './pages/pimport { Route as projectGroupDetailsByIDPageRoutePamImport } from './pages/project/GroupDetailsByIDPage/route-pam'import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'import { Route as organizationKmipServersPageKmipServerDetailsByIDPageRouteImport } from './pages/organization/KmipServersPage/KmipServerDetailsByIDPage/route'-import { Route as pamPamSessionsByIDPageRouteImport } from './pages/pam/PamSessionsByIDPage/route'import { Route as organizationAppConnectionsGitHubManifestCallbackPageRouteImport } from './pages/organization/AppConnections/GitHubManifestCallbackPage/route'import { Route as organizationAppConnectionsOauthCallbackPageRouteImport } from './pages/organization/AppConnections/OauthCallbackPage/route'import { Route as organizationKmipServersPageRouteImport } from './pages/organization/KmipServersPage/route'-import { Route as pamPamSessionsPageRouteImport } from './pages/pam/PamSessionsPage/route'import { Route as pamPamAccessPageRouteImport } from './pages/pam/PamAccessPage/route'import { Route as projectAuditLogsPageRouteSshImport } from './pages/project/AuditLogsPage/route-ssh'import { Route as projectAccessControlPageRouteSshImport } from './pages/project/AccessControlPage/route-ssh'@@ -345,10 +343,6 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsAiProjectIdcreateFileRoute('/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId',)()-const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsImport =- createFileRoute(- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions',- )()const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessImport =createFileRoute('/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access',@@ -1017,15 +1011,6 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsAiProjectId} as any,)-const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRoute =- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsImport.update(- {- id: '/sessions',- path: '/sessions',- getParentRoute: () => pamLayoutRoute,- } as any,- )-const projectAuditLogsPageRoutePamRoute =projectAuditLogsPageRoutePamImport.update({id: '/audit-logs',@@ -1152,14 +1137,6 @@ const organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute =AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsKmipServersRoute,} as any)-const pamPamSessionsByIDPageRouteRoute =- pamPamSessionsByIDPageRouteImport.update({- id: '/$sessionId',- path: '/$sessionId',- getParentRoute: () =>- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRoute,- } as any)-const organizationAppConnectionsGitHubManifestCallbackPageRouteRoute =organizationAppConnectionsGitHubManifestCallbackPageRouteImport.update({id: '/github/manifest/callback',@@ -1184,13 +1161,6 @@ const organizationKmipServersPageRouteRoute =AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsKmipServersRoute,} as any)-const pamPamSessionsPageRouteRoute = pamPamSessionsPageRouteImport.update({- id: '/',- path: '/',- getParentRoute: () =>- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRoute,-} as any)-const pamPamAccessPageRouteRoute = pamPamAccessPageRouteImport.update({id: '/',path: '/',@@ -3162,13 +3132,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof projectAuditLogsPageRoutePamImportparentRoute: typeof pamLayoutImport}- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions': {- id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions'- path: '/sessions'- fullPath: '/organizations/$orgId/pam/sessions'- preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsImport- parentRoute: typeof pamLayoutImport- }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId'path: '/ai/$projectId'@@ -3232,13 +3195,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof pamPamAccessPageRouteImportparentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessImport}- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/': {- id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/'- path: '/'- fullPath: '/organizations/$orgId/pam/sessions/'- preLoaderRoute: typeof pamPamSessionsPageRouteImport- parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsImport- }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/'path: '/'@@ -3260,13 +3216,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof organizationAppConnectionsGitHubManifestCallbackPageRouteImportparentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAppConnectionsImport}- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/$sessionId': {- id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/$sessionId'- path: '/$sessionId'- fullPath: '/organizations/$orgId/pam/sessions/$sessionId'- preLoaderRoute: typeof pamPamSessionsByIDPageRouteImport- parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsImport- }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'path: '/$kmipServerId'@@ -5555,27 +5504,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRAuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteChildren,)-interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteChildren {- pamPamSessionsPageRouteRoute: typeof pamPamSessionsPageRouteRoute- pamPamSessionsByIDPageRouteRoute: typeof pamPamSessionsByIDPageRouteRoute-}--const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteChildren =- {- pamPamSessionsPageRouteRoute: pamPamSessionsPageRouteRoute,- pamPamSessionsByIDPageRouteRoute: pamPamSessionsByIDPageRouteRoute,- }--const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteWithChildren =- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRoute._addFileChildren(- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteChildren,- )-interface pamLayoutRouteChildren {AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildrenprojectAccessControlPageRoutePamRoute: typeof projectAccessControlPageRoutePamRouteprojectAuditLogsPageRoutePamRoute: typeof projectAuditLogsPageRoutePamRoute- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteWithChildrenprojectGroupDetailsByIDPageRoutePamRoute: typeof projectGroupDetailsByIDPageRoutePamRouteprojectIdentityDetailsByIDPageRoutePamRoute: typeof projectIdentityDetailsByIDPageRoutePamRouteprojectMemberDetailsByIDPageRoutePamRoute: typeof projectMemberDetailsByIDPageRoutePamRoute@@ -5587,8 +5519,6 @@ const pamLayoutRouteChildren: pamLayoutRouteChildren = {AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildren,projectAccessControlPageRoutePamRoute: projectAccessControlPageRoutePamRoute,projectAuditLogsPageRoutePamRoute: projectAuditLogsPageRoutePamRoute,- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRoute:- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteWithChildren,projectGroupDetailsByIDPageRoutePamRoute:projectGroupDetailsByIDPageRoutePamRoute,projectIdentityDetailsByIDPageRoutePamRoute:@@ -5998,7 +5928,6 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/pam/access': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildren'/organizations/$orgId/pam/access-management': typeof projectAccessControlPageRoutePamRoute'/organizations/$orgId/pam/audit-logs': typeof projectAuditLogsPageRoutePamRoute- '/organizations/$orgId/pam/sessions': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteWithChildren'/organizations/$orgId/projects/ai/$projectId': typeof aiLayoutRouteWithChildren'/organizations/$orgId/projects/cert-manager/$projectId': typeof certManagerLayoutRouteWithChildren'/organizations/$orgId/projects/kms/$projectId': typeof kmsLayoutRouteWithChildren@@ -6008,11 +5937,9 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/projects/ssh/$projectId': typeof sshLayoutRouteWithChildren'/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute'/organizations/$orgId/pam/access/': typeof pamPamAccessPageRouteRoute- '/organizations/$orgId/pam/sessions/': typeof pamPamSessionsPageRouteRoute'/organizations/$orgId/projects/kms/kmip-servers/': typeof organizationKmipServersPageRouteRoute'/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute'/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute- '/organizations/$orgId/pam/sessions/$sessionId': typeof pamPamSessionsByIDPageRouteRoute'/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': typeof organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute'/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/organizations/$orgId/pam/groups/$groupId': typeof projectGroupDetailsByIDPageRoutePamRoute@@ -6278,11 +6205,9 @@ export interface FileRoutesByTo {'/organizations/$orgId/projects/ssh/$projectId': typeof sshLayoutRouteWithChildren'/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute'/organizations/$orgId/pam/access': typeof pamPamAccessPageRouteRoute- '/organizations/$orgId/pam/sessions': typeof pamPamSessionsPageRouteRoute'/organizations/$orgId/projects/kms/kmip-servers': typeof organizationKmipServersPageRouteRoute'/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute'/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute- '/organizations/$orgId/pam/sessions/$sessionId': typeof pamPamSessionsByIDPageRouteRoute'/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': typeof organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute'/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/organizations/$orgId/pam/groups/$groupId': typeof projectGroupDetailsByIDPageRoutePamRoute@@ -6544,7 +6469,6 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutAccessRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access-management': typeof projectAccessControlPageRoutePamRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/audit-logs': typeof projectAuditLogsPageRoutePamRoute- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdPamPamLayoutSessionsRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsAiProjectIdRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsCertManagerProjectIdRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsProjectIdRouteWithChildren@@ -6554,11 +6478,9 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSshProjectIdRouteWithChildren'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId/approval': typeof secretManagerRedirectsRedirectApprovalPageRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access/': typeof pamPamAccessPageRouteRoute- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/': typeof pamPamSessionsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/': typeof organizationKmipServersPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback': typeof organizationAppConnectionsOauthCallbackPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback': typeof organizationAppConnectionsGitHubManifestCallbackPageRouteRoute- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/$sessionId': typeof pamPamSessionsByIDPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId': typeof organizationKmipServersPageKmipServerDetailsByIDPageRouteRoute'/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access': typeof pamPamAccountAccessPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId': typeof projectGroupDetailsByIDPageRoutePamRoute@@ -6833,7 +6755,6 @@ export interface FileRouteTypes {| '/organizations/$orgId/pam/access'| '/organizations/$orgId/pam/access-management'| '/organizations/$orgId/pam/audit-logs'- | '/organizations/$orgId/pam/sessions'| '/organizations/$orgId/projects/ai/$projectId'| '/organizations/$orgId/projects/cert-manager/$projectId'| '/organizations/$orgId/projects/kms/$projectId'@@ -6843,11 +6764,9 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/ssh/$projectId'| '/organizations/$orgId/secret-manager/$projectId/approval'| '/organizations/$orgId/pam/access/'- | '/organizations/$orgId/pam/sessions/'| '/organizations/$orgId/projects/kms/kmip-servers/'| '/organizations/$orgId/app-connections/$appConnection/oauth/callback'| '/organizations/$orgId/app-connections/github/manifest/callback'- | '/organizations/$orgId/pam/sessions/$sessionId'| '/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'| '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'| '/organizations/$orgId/pam/groups/$groupId'@@ -7112,11 +7031,9 @@ export interface FileRouteTypes {| '/organizations/$orgId/projects/ssh/$projectId'| '/organizations/$orgId/secret-manager/$projectId/approval'| '/organizations/$orgId/pam/access'- | '/organizations/$orgId/pam/sessions'| '/organizations/$orgId/projects/kms/kmip-servers'| '/organizations/$orgId/app-connections/$appConnection/oauth/callback'| '/organizations/$orgId/app-connections/github/manifest/callback'- | '/organizations/$orgId/pam/sessions/$sessionId'| '/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'| '/organizations/$orgId/pam/accounts/$accountType/$accountId/access'| '/organizations/$orgId/pam/groups/$groupId'@@ -7376,7 +7293,6 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access-management'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/audit-logs'- | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/$projectId'@@ -7386,11 +7302,9 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ssh/$projectId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/secret-manager/$projectId/approval'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access/'- | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/$appConnection/oauth/callback'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections/github/manifest/callback'- | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/$sessionId'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId'| '/_authenticate/_inject-org-details/organizations/$orgId/pam/accounts/$accountType/$accountId/access'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId'@@ -8035,7 +7949,6 @@ export const routeTree = rootRoute"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access-management","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/audit-logs",- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/groups/$groupId","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/identities/$identityId","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/members/$membershipId",@@ -8084,14 +7997,6 @@ export const routeTree = rootRoute"filePath": "project/AuditLogsPage/route-pam.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout"},- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions": {- "filePath": "",- "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout",- "children": [- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/",- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/$sessionId"- ]- },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/ai/$projectId": {"filePath": "","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects",@@ -8150,10 +8055,6 @@ export const routeTree = rootRoute"filePath": "pam/PamAccessPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/access"},- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/": {- "filePath": "pam/PamSessionsPage/route.tsx",- "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions"- },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/": {"filePath": "organization/KmipServersPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers"@@ -8166,10 +8067,6 @@ export const routeTree = rootRoute"filePath": "organization/AppConnections/GitHubManifestCallbackPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/app-connections"},- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions/$sessionId": {- "filePath": "pam/PamSessionsByIDPage/route.tsx",- "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/pam/_pam-layout/sessions"- },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers/$kmipServerId": {"filePath": "organization/KmipServersPage/KmipServerDetailsByIDPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/kms/kmip-servers"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 0971add96f..a157a546fc 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -396,10 +396,6 @@ const secretScanningRoutes = route("/organizations/$orgId/projects/secret-scanniconst pamRoutes = route("/organizations/$orgId/pam", [layout("pam-layout", "pam/layout.tsx", [route("/access", [index("pam/PamAccessPage/route.tsx")]),- route("/sessions", [- index("pam/PamSessionsPage/route.tsx"),- route("/$sessionId", "pam/PamSessionsByIDPage/route.tsx")- ]),route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),// Access Management