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
feat(pam): per-tab Postgres connections with isolated transactions (#6154)
Saif Ur Rahmane7a3da3d012c
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts b/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.tsnew file mode 100644index 0000000000..88f3ce9c34--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-connection-controller.ts@@ -0,0 +1,309 @@+import { parse as parseSql } from "libpg-query";+import pg from "pg";+import Cursor from "pg-cursor";++import { logger } from "@app/lib/logger";++import { getTableDetailQuery } from "./pam-postgres-data-explorer-metadata";+import {+ PostgresClientMessageType,+ PostgresServerMessageType,+ type TPostgresClientMessage,+ type TPostgresCorrelatedServerMessage+} from "./pam-postgres-ws-types";++type ControllerParams = {+ relayPort: number;+ username: string;+ database: string;+ sessionId: string;+ connectionId: string;+ sendResponse: (msg: TPostgresCorrelatedServerMessage) => void;+ onUnexpectedTermination: (reason: string) => void;+};++// Tab-scoped messages the controller handles. Metadata (get-schemas, get-tables)+// and lifecycle messages are handled at the multiplexer layer.+type TTabScopedMessage = Extract<+ TPostgresClientMessage,+ {+ type: PostgresClientMessageType.GetTableDetail | PostgresClientMessageType.Query | PostgresClientMessageType.Cancel;+ }+>;++export type TPostgresConnectionController = {+ connectionId: string;+ backendPid: number | null;+ handleMessage: (msg: TTabScopedMessage) => void;+ dispose: () => void;+ isDisposing: () => boolean;+};++// Type parser shared between the pg.Client and pg-cursor instances so all+// results — whether fetched via the simple query path or cursor — apply the+// same normalisation rules.+const pgTypes = {+ getTypeParser: (oid: number) => {+ // Boolean (OID 16): Postgres wire protocol sends 't'/'f' — expand to 'true'/'false'+ // so the Data Explorer UI displays human-readable literals.+ if (oid === 16)+ return (val: string | Buffer) => {+ const raw = typeof val === "string" ? val : val.toString("utf8");+ return raw === "t" ? "true" : "false";+ };+ return (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"));+ }+};++export const createPostgresConnectionController = async (+ params: ControllerParams+): Promise<TPostgresConnectionController> => {+ const { relayPort, username, database, sessionId, connectionId, sendResponse, onUnexpectedTermination } = params;++ const pgClient = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: username,+ database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 30_000,+ statement_timeout: 30_000,+ types: pgTypes+ });++ await pgClient.connect();++ const { rows: pidRows } = await pgClient.query<{ pid: number }>("SELECT pg_backend_pid() AS pid");+ const backendPid = pidRows[0]?.pid ?? null;++ // Server-side transaction state — updated after every query so the client+ // always receives the authoritative value, including for multi-statement SQL.+ let isInTransaction = false;+ let disposing = false;++ const sendQueryError = async (id: string, err: unknown) => {+ const pgErr = err as { message?: string; detail?: string; hint?: string };++ // If the failed query was inside a transaction, roll back so the+ // connection is not stuck in an aborted transaction state.+ try {+ await pgClient.query("ROLLBACK");+ } catch {+ // ROLLBACK fails if there was no active transaction — safe to ignore.+ }++ isInTransaction = false;++ sendResponse({+ type: PostgresServerMessageType.Error,+ id,+ connectionId,+ transactionOpen: false,+ error: pgErr.message ?? "Query execution failed",+ detail: pgErr.detail,+ hint: pgErr.hint+ });+ };++ // Cancel the currently running query via pg_cancel_backend.+ // Runs on a separate connection so it is not blocked by the sequential queue.+ const cancelRunningQuery = async () => {+ if (!backendPid) return;+ const cancelClient = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: username,+ database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 5_000+ });+ // pg.Client is an EventEmitter; an unhandled 'error' would throw and+ // crash the Node process. Attach a no-op listener.+ cancelClient.on("error", (err) => {+ logger.debug(err, `Cancel client error [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ });+ try {+ await cancelClient.connect();+ await cancelClient.query("SELECT pg_cancel_backend($1)", [backendPid]);+ } catch (err) {+ logger.debug(err, `Failed to cancel backend query [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ } finally {+ await cancelClient.end().catch(() => {});+ }+ };++ // Sequential message processing to prevent concurrent query issues on the+ // same pg.Client. Each controller has its own queue.+ let processingPromise: Promise<void> = Promise.resolve();++ const handleMessage = (message: TTabScopedMessage) => {+ // Cancel is handled immediately outside the sequential queue so it can+ // interrupt a running query rather than waiting behind it.+ if (message.type === PostgresClientMessageType.Cancel) {+ if (disposing) return;+ void cancelRunningQuery();+ return;+ }++ processingPromise = processingPromise+ .then(async () => {+ if (disposing) return;++ switch (message.type) {+ case PostgresClientMessageType.GetTableDetail: {+ try {+ const query = getTableDetailQuery(message.schema, message.table);+ const result = await pgClient.query<{ result: string }>(query.text, query.values);+ const rawDetail = result.rows[0]?.result;+ if (!rawDetail) {+ sendResponse({+ type: PostgresServerMessageType.Error,+ id: message.id,+ connectionId,+ transactionOpen: isInTransaction,+ error: "Table not found or no metadata available"+ });+ break;+ }+ const detail =+ typeof rawDetail === "string"+ ? (JSON.parse(rawDetail) as Record<string, unknown>)+ : (rawDetail as unknown as Record<string, unknown>);+ sendResponse({+ type: PostgresServerMessageType.TableDetail,+ id: message.id,+ connectionId,+ transactionOpen: isInTransaction,+ data: detail as {+ columns: {+ name: string;+ type: string;+ nullable: boolean;+ identityGeneration: string | null;+ }[];+ primaryKeys: string[];+ foreignKeys: {+ constraintName: string;+ columns: string[];+ targetSchema: string;+ targetTable: string;+ targetColumns: string[];+ }[];+ }+ });+ } catch (err) {+ await sendQueryError(message.id, err);+ }+ break;+ }++ case PostgresClientMessageType.Query: {+ try {+ const startTime = performance.now();+ const MAX_ROWS = 1000;++ // Split the SQL into individual statements using the real PostgreSQL C parser+ // (via libpg-query WASM). Each statement is then run through a pg-cursor with+ // an explicit row cap — the server sends at most MAX_ROWS+1 rows at the wire+ // level regardless of result set size, so memory usage is bounded.+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const parsed = await parseSql(message.sql);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const stmtTexts = (parsed.stmts as Array<{ stmt_location?: number; stmt_len?: number }>).map((s) => {+ const location = s.stmt_location ?? 0;+ return s.stmt_len !== undefined+ ? message.sql.slice(location, location + s.stmt_len)+ : message.sql.slice(location).trim();+ });++ let lastRows: Record<string, unknown>[] = [];+ let lastFields: { name: string }[] = [];+ let lastRowCount: number | null = null;+ let lastCommand = "";+ let lastIsTruncated = false;++ for (const stmtSql of stmtTexts) {+ const cursor = pgClient.query(new Cursor(stmtSql.trim(), null, { types: pgTypes }));+ // eslint-disable-next-line no-await-in-loop+ const stmtRows = await cursor.read(MAX_ROWS + 1);+ const stmtIsTruncated = stmtRows.length > MAX_ROWS;+ if (stmtIsTruncated) stmtRows.splice(MAX_ROWS);+ // eslint-disable-next-line no-await-in-loop+ await cursor.close();++ // eslint-disable-next-line no-underscore-dangle+ const cursorResult = cursor._result;+ const cmd = (cursorResult.command ?? "").toUpperCase();+ if (cmd === "BEGIN" || cmd === "START") isInTransaction = true;+ if (cmd === "COMMIT" || cmd === "ROLLBACK") isInTransaction = false;++ lastRows = stmtRows;+ lastFields = (cursorResult.fields ?? []).map((f) => ({ name: f.name }));+ lastRowCount = cursorResult.rowCount;+ lastCommand = cursorResult.command ?? "";+ lastIsTruncated = stmtIsTruncated;+ }++ const executionTimeMs = Math.round(performance.now() - startTime);+ sendResponse({+ type: PostgresServerMessageType.QueryResult,+ id: message.id,+ connectionId,+ rows: lastRows,+ fields: lastFields,+ rowCount: lastRowCount,+ isTruncated: lastIsTruncated,+ transactionOpen: isInTransaction,+ command: lastCommand,+ executionTimeMs+ });+ } catch (err) {+ await sendQueryError(message.id, err);+ }+ break;+ }++ default:+ break;+ }+ })+ .catch((err) => {+ logger.error(err, `Error processing Postgres message [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ });+ };++ // Server-initiated termination — pg.Client errors outside clean dispose.+ pgClient.on("error", (err) => {+ if (disposing) return;+ logger.error(err, `Tab connection error [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ disposing = true;+ onUnexpectedTermination(err.message || "Database connection error");+ });++ pgClient.on("end", () => {+ if (disposing) return;+ disposing = true;+ onUnexpectedTermination("Database connection ended");+ });++ const dispose = () => {+ if (disposing) return;+ disposing = true;+ // Fire-and-forget: Postgres auto-rollbacks uncommitted txns on socket close+ // and cleans up backend PIDs when it next tries to write. No explicit+ // ROLLBACK needed — keeps dispose synchronous from the caller's view.+ void pgClient.end().catch((err) => {+ logger.debug(err, `Error closing pg client [sessionId=${sessionId}] [connectionId=${connectionId}]`);+ });+ };++ return {+ connectionId,+ backendPid,+ handleMessage,+ dispose,+ isDisposing: () => disposing+ };+};diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts b/backend/src/ee/services/pam-web-access/pam-postgres-metadata.tsnew file mode 100644index 0000000000..90ac171b82--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-postgres-metadata.ts@@ -0,0 +1,66 @@+import pg from "pg";++import { logger } from "@app/lib/logger";++import { getSchemasQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";++// Shared connection options for one-shot metadata queries. Each call opens a+// fresh pg.Client, runs one query, then disposes — no persistent BE state.+type OneShotOptions = {+ relayPort: number;+ username: string;+ database: string;+};++const buildClient = ({ relayPort, username, database }: OneShotOptions): pg.Client => {+ const client = new pg.Client({+ host: "localhost",+ port: relayPort,+ user: username,+ database,+ password: "",+ ssl: false,+ connectionTimeoutMillis: 10_000,+ statement_timeout: 30_000+ });+ // pg.Client is an EventEmitter; an unhandled 'error' (e.g. mid-query socket+ // reset) would throw and crash the Node process. Attach a no-op listener.+ client.on("error", (err) => {+ logger.debug(err, "one-shot pg client error");+ });+ return client;+};++const withClient = async <T>(opts: OneShotOptions, fn: (client: pg.Client) => Promise<T>): Promise<T> => {+ const client = buildClient(opts);+ await client.connect();+ try {+ return await fn(client);+ } finally {+ await client.end().catch(() => {});+ }+};++export const fetchSchemasOneShot = (opts: OneShotOptions): Promise<{ name: string }[]> =>+ withClient(opts, async (client) => {+ const query = getSchemasQuery();+ const result = await client.query<{ name: string }>(query.text, query.values);+ return result.rows;+ });++export const fetchTablesOneShot = (+ opts: OneShotOptions,+ schema: string+): Promise<{ name: string; tableType: string }[]> =>+ withClient(opts, async (client) => {+ const query = getTablesQuery(schema);+ const result = await client.query<{ name: string; tableType: string }>(query.text, query.values);+ return result.rows;+ });++// Called once at WS setup to fail fast if credentials or tunnel are broken —+// preserves the early "Connection error" UX we used to get from pgClient.connect().+export const verifyReachabilityOneShot = (opts: OneShotOptions): Promise<void> =>+ withClient(opts, async (client) => {+ await client.query("SELECT 1");+ });diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.tsindex 5a4bf5635e..8d724124e6 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts@@ -3,13 +3,18 @@/* eslint-disable @typescript-eslint/no-unsafe-call *//* eslint-disable @typescript-eslint/no-unsafe-argument *//* eslint-disable @typescript-eslint/unbound-method */+/* eslint-disable @typescript-eslint/no-explicit-any */import { beforeEach, describe, expect, test, vi } from "vitest";import type WebSocket from "ws";import { PostgresClientMessageType, PostgresServerMessageType } from "./pam-postgres-ws-types";-import { TerminalServerMessageType, type TSessionContext, type TWebSocketServerMessage } from "./pam-web-access-types";+import {+ SessionEndReason,+ TerminalServerMessageType,+ type TSessionContext,+ type TWebSocketServerMessage+} from "./pam-web-access-types";-// Mock loggervi.mock("@app/lib/logger", () => ({logger: {info: vi.fn(),@@ -19,30 +24,55 @@ vi.mock("@app/lib/logger", () => ({}}));-// Mock the REPL (terminal sessions create one eagerly)-vi.mock("./pam-web-access-repl", () => ({- createPamSqlRepl: vi.fn(() => ({- getPrompt: vi.fn().mockReturnValue("=> "),- clearBuffer: vi.fn(),- processInput: vi.fn().mockResolvedValue({ output: "", prompt: "=> ", shouldClose: false })- }))-}));+// Per-client script lets individual tests stub behaviour for the Nth pg.Client+// that gets constructed. Useful for simulating mid-life failures, differing+// backend PIDs across tab controllers, etc.+type ClientScript = {+ connect?: () => Promise<void>;+ query?: (text: string, values?: unknown[]) => Promise<any>;+ end?: () => Promise<void>;+};++const clientScripts: ClientScript[] = [];+const createdClients: MockPgClient[] = [];++type MockPgClient = {+ query: ReturnType<typeof vi.fn>;+ connect: ReturnType<typeof vi.fn>;+ end: ReturnType<typeof vi.fn>;+ on: ReturnType<typeof vi.fn>;+ emit: (event: string, ...args: unknown[]) => void;+ _listeners: Record<string, Array<(...args: unknown[]) => void>>;+};-// Mock pgvi.mock("pg", () => {- const mockQuery = vi.fn().mockResolvedValue({ rows: [] });- const mockConnect = vi.fn().mockResolvedValue(undefined);- const mockEnd = vi.fn().mockResolvedValue(undefined);- const mockOn = vi.fn();+ const makeClient = (): MockPgClient => {+ const script = clientScripts.shift() ?? {};+ const defaultQuery = vi.fn(async (text: string) => {+ if (text.includes("pg_backend_pid")) return { rows: [{ pid: 1000 + createdClients.length }] };+ return { rows: [] };+ });+ const listeners: Record<string, Array<(...args: unknown[]) => void>> = {};+ const client: MockPgClient = {+ query: vi.fn(script.query ?? defaultQuery),+ connect: vi.fn(script.connect ?? (async () => {})),+ end: vi.fn(script.end ?? (async () => {})),+ on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {+ listeners[event] = listeners[event] || [];+ listeners[event].push(cb);+ }),+ emit: (event: string, ...args: unknown[]) => {+ (listeners[event] || []).forEach((cb) => cb(...args));+ },+ _listeners: listeners+ };+ createdClients.push(client);+ return client;+ };return {default: {- Client: vi.fn(() => ({- query: mockQuery,- connect: mockConnect,- end: mockEnd,- on: mockOn- }))+ Client: vi.fn(() => makeClient())}};});@@ -53,12 +83,11 @@ import pg from "pg";// eslint-disable-next-line import/firstimport { handlePostgresSession } from "./pam-postgres-session-handler";-type MockPgClient = {- query: ReturnType<typeof vi.fn>;- connect: ReturnType<typeof vi.fn>;- end: ReturnType<typeof vi.fn>;- on: ReturnType<typeof vi.fn>;-};+function resetMockState() {+ clientScripts.length = 0;+ createdClients.length = 0;+ (pg.Client as unknown as { mockClear: () => void }).mockClear();+}function createMockContext(): TSessionContext & { sentMessages: TWebSocketServerMessage[] } {const sentMessages: TWebSocketServerMessage[] = [];@@ -88,81 +117,318 @@ const mockParams = {credentials: { username: "testuser" }} as Parameters<typeof handlePostgresSession>[1];-function getPgInstance(): MockPgClient {- const ClientMock = pg.Client as unknown as { mock: { results: { value: MockPgClient }[] } };- return ClientMock.mock.results[ClientMock.mock.results.length - 1].value;+function getMessageHandler(ctx: TSessionContext): (data: Buffer) => void {+ const messageCall = (ctx.socket.on as ReturnType<typeof vi.fn>).mock.calls.find(+ ([event]: string[]) => event === "message"+ );+ return messageCall![1] as (data: Buffer) => void;+}++function getSentResponses(ctx: TSessionContext): any[] {+ const send = ctx.socket.send as unknown as ReturnType<typeof vi.fn>;+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return+ return send.mock.calls.map(([raw]) => JSON.parse(raw as string));+}++async function openConnection(ctx: TSessionContext, id = "11111111-1111-1111-1111-111111111111"): Promise<string> {+ const onMessage = getMessageHandler(ctx);+ onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.OpenConnection, id })));+ // Let microtasks settle for the async open flow.+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 10);+ });+ const resp = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.ConnectionOpened && r.id === id);+ if (!resp) throw new Error("open-connection did not ack");+ return resp.connectionId as string;}describe("handlePostgresSession", () => {beforeEach(() => {vi.clearAllMocks();+ resetMockState();});- test("connects to database and sends ready message", async () => {+ test("sends ready after reachability check succeeds", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ expect(ctx.sendMessage).toHaveBeenCalledWith(expect.objectContaining({ type: TerminalServerMessageType.Ready }));+ // Reachability check — one short-lived client.+ expect(pg.Client).toHaveBeenCalledTimes(1);+ });++ test("tears down the WS when reachability check fails", async () => {+ clientScripts.push({+ connect: async () => {+ throw new Error("connection refused");+ }+ });const ctx = createMockContext();const result = await handlePostgresSession(ctx, mockParams);- expect(pg.Client).toHaveBeenCalledWith(- expect.objectContaining({- host: "localhost",- port: 5432,- user: "testuser",- database: "testdb"- })+ expect(ctx.sendSessionEnd).toHaveBeenCalledWith(SessionEndReason.SetupFailed);+ expect(ctx.sendMessage).not.toHaveBeenCalledWith(+ expect.objectContaining({ type: TerminalServerMessageType.Ready }));- expect(ctx.sendMessage).toHaveBeenCalledWith(- expect.objectContaining({- type: TerminalServerMessageType.Ready+ expect(result.cleanup).toBeDefined();+ });++ test("open-connection creates a controller and returns connectionId + backendPid", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ const connectionId = await openConnection(ctx);+ expect(connectionId).toMatch(/[0-9a-f-]{36}/i);+ const resp = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.ConnectionOpened);+ expect(resp.backendPid).toBeTypeOf("number");+ });++ test("get-schemas uses a short-lived client and works with no tab controllers", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ // Script a schemas query response on the next client created.+ clientScripts.push({+ query: vi.fn(async (text: string) => {+ if (text.includes("pg_namespace")) return { rows: [{ name: "public" }] };+ return { rows: [] };+ })+ });++ const onMessage = getMessageHandler(ctx);+ const reqId = "22222222-2222-2222-2222-222222222222";+ onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.GetSchemas, id: reqId })));++ await new Promise<void>((r) => {+ setTimeout(r, 20);+ });++ const responses = getSentResponses(ctx);+ const schemasResp = responses.find((r) => r.type === PostgresServerMessageType.Schemas && r.id === reqId);+ expect(schemasResp).toBeTruthy();+ expect(schemasResp.data).toEqual([{ name: "public" }]);+ });++ test("get-tables works while a tab controller is open", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);+ await openConnection(ctx);++ clientScripts.push({+ query: vi.fn(async (text: string) => {+ if (text.includes("pg_class")) return { rows: [{ name: "users", tableType: "table" }] };+ return { rows: [] };})+ });++ const onMessage = getMessageHandler(ctx);+ const reqId = "33333333-3333-3333-3333-333333333333";+ onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.GetTables, id: reqId, schema: "public" })));++ await new Promise<void>((r) => {+ setTimeout(r, 20);+ });+ const tablesResp = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.Tables && r.id === reqId);+ expect(tablesResp).toBeTruthy();+ expect(tablesResp.data).toEqual([{ name: "users", tableType: "table" }]);+ });++ test("unknown connectionId on tab-scoped message returns 'Connection not found'", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ const onMessage = getMessageHandler(ctx);+ const reqId = "44444444-4444-4444-4444-444444444444";+ onMessage(+ Buffer.from(+ JSON.stringify({+ type: PostgresClientMessageType.Query,+ id: reqId,+ connectionId: "99999999-9999-9999-9999-999999999999",+ sql: "SELECT 1"+ })+ ));- expect(result.cleanup).toBeDefined();++ await new Promise<void>((r) => {+ setTimeout(r, 10);+ });+ const err = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.Error && r.id === reqId);+ expect(err).toBeTruthy();+ expect(err.error).toContain("Connection not found");});- test("registers message handler on socket", async () => {+ test("close-connection on unknown id is a silent no-op", async () => {const ctx = createMockContext();await handlePostgresSession(ctx, mockParams);- expect(ctx.socket.on).toHaveBeenCalledWith("message", expect.any(Function));+ const onMessage = getMessageHandler(ctx);+ onMessage(+ Buffer.from(+ JSON.stringify({+ type: PostgresClientMessageType.CloseConnection,+ connectionId: "99999999-9999-9999-9999-999999999999"+ })+ )+ );++ await new Promise<void>((r) => {+ setTimeout(r, 10);+ });+ const responses = getSentResponses(ctx);+ // No response ever sent for close-connection.+ expect(responses.filter((r) => r.type === PostgresServerMessageType.ConnectionClosed)).toEqual([]);+ expect(responses.filter((r) => r.type === PostgresServerMessageType.Error)).toEqual([]);});- test("cleanup closes pg client", async () => {+ test("cancel on unknown connectionId is a silent no-op", async () => {const ctx = createMockContext();- const result = await handlePostgresSession(ctx, mockParams);- const pgInstance = getPgInstance();+ await handlePostgresSession(ctx, mockParams);- await result.cleanup();- expect(pgInstance.end).toHaveBeenCalled();+ const onMessage = getMessageHandler(ctx);+ onMessage(+ Buffer.from(+ JSON.stringify({+ type: PostgresClientMessageType.Cancel,+ connectionId: "99999999-9999-9999-9999-999999999999"+ })+ )+ );++ await new Promise<void>((r) => {+ setTimeout(r, 10);+ });+ expect(getSentResponses(ctx)).toEqual([]);});- test("handles get-schemas data explorer message", async () => {+ test("activity keepalive is accepted and emits no response", async () => {const ctx = createMockContext();await handlePostgresSession(ctx, mockParams);- const pgInstance = getPgInstance();- pgInstance.query.mockResolvedValue({- rows: [{ name: "public" }, { name: "auth" }]+ const onMessage = getMessageHandler(ctx);+ onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.Activity })));++ await new Promise<void>((r) => {+ setTimeout(r, 10);});+ expect(getSentResponses(ctx)).toEqual([]);+ expect(ctx.sendSessionEnd).not.toHaveBeenCalled();+ });++ test("server-initiated controller death removes entry and emits connection-closed", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);+ const connectionId = await openConnection(ctx);- // Get the message handler callback- const messageCall = (ctx.socket.on as ReturnType<typeof vi.fn>).mock.calls.find(- ([event]: string[]) => event === "message"+ // Grab the tab controller's pg.Client (created after reachability client).+ const tabClient = createdClients[1];+ tabClient.emit("error", new Error("peer reset"));++ await new Promise<void>((r) => {+ setTimeout(r, 10);+ });+ const closedEvt = getSentResponses(ctx).find(+ (r) => r.type === PostgresServerMessageType.ConnectionClosed && r.connectionId === connectionId);- const onMessage = messageCall?.[1] as ((data: Buffer) => void) | undefined;+ expect(closedEvt).toBeTruthy();+ expect(closedEvt.reason).toBe("peer reset");- if (onMessage) {- const msg = Buffer.from(- JSON.stringify({ type: PostgresClientMessageType.GetSchemas, id: "550e8400-e29b-41d4-a716-446655440000" })- );- onMessage(msg);+ // Subsequent tab-scoped message for the same id should now miss.+ const onMessage = getMessageHandler(ctx);+ const reqId = "55555555-5555-5555-5555-555555555555";+ onMessage(+ Buffer.from(+ JSON.stringify({+ type: PostgresClientMessageType.Query,+ id: reqId,+ connectionId,+ sql: "SELECT 1"+ })+ )+ );+ await new Promise<void>((r) => {+ setTimeout(r, 10);+ });+ const err = getSentResponses(ctx).find((r) => r.type === PostgresServerMessageType.Error && r.id === reqId);+ expect(err.error).toContain("Connection not found");+ });- // Wait for async processing- await new Promise<void>((resolve) => {- setTimeout(resolve, 50);- });+ test("exceeding MAX_CONNECTIONS_PER_WS returns connection-open-failed", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ for (let i = 0; i < 20; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ await openConnection(ctx, `aaaaaaaa-aaaa-aaaa-aaaa-${String(i).padStart(12, "0")}`);+ }++ const onMessage = getMessageHandler(ctx);+ const overflowId = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";+ onMessage(Buffer.from(JSON.stringify({ type: PostgresClientMessageType.OpenConnection, id: overflowId })));+ await new Promise<void>((r) => {+ setTimeout(r, 10);+ });+ const failed = getSentResponses(ctx).find(+ (r) => r.type === PostgresServerMessageType.ConnectionOpenFailed && r.id === overflowId+ );+ expect(failed).toBeTruthy();+ expect(failed.error).toContain("Maximum");+ });- expect((ctx.socket as unknown as { send: ReturnType<typeof vi.fn> }).send).toHaveBeenCalledWith(- expect.stringContaining(`"${PostgresServerMessageType.Schemas}"`)+ test("concurrent open-connection requests cannot bypass the cap", async () => {+ // Simulates a client firing 25 opens at once. Without the pendingOpens+ // counter, each check against controllers.size would see 0 before any+ // controller finished connecting, and all 25 would succeed.+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ const onMessage = getMessageHandler(ctx);+ const ATTEMPTS = 25;+ for (let i = 0; i < ATTEMPTS; i += 1) {+ onMessage(+ Buffer.from(+ JSON.stringify({+ type: PostgresClientMessageType.OpenConnection,+ id: `eeeeeeee-eeee-eeee-eeee-${String(i).padStart(12, "0")}`+ })+ ));}++ await new Promise<void>((r) => {+ setTimeout(r, 50);+ });++ const opened = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpened);+ const failed = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpenFailed);+ expect(opened.length).toBe(20);+ expect(failed.length).toBe(ATTEMPTS - 20);+ });++ test("cleanup disposes every controller", async () => {+ const ctx = createMockContext();+ const result = await handlePostgresSession(ctx, mockParams);+ await openConnection(ctx, "cccccccc-cccc-cccc-cccc-cccccccccccc");+ await openConnection(ctx, "dddddddd-dddd-dddd-dddd-dddddddddddd");++ const tabClients = createdClients.slice(1, 3);++ await result.cleanup();++ tabClients.forEach((c) => {+ expect(c.end).toHaveBeenCalled();+ });+ });++ test("two tab controllers have independent backendPids", async () => {+ const ctx = createMockContext();+ await handlePostgresSession(ctx, mockParams);++ await openConnection(ctx, "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee");+ await openConnection(ctx, "ffffffff-ffff-ffff-ffff-ffffffffffff");++ const opens = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpened);+ expect(opens).toHaveLength(2);+ expect(opens[0].backendPid).not.toBe(opens[1].backendPid);});});diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.tsindex 43d3d89c22..cbf3272638 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts@@ -1,6 +1,4 @@-import { parse as parseSql } from "libpg-query";-import pg from "pg";-import Cursor from "pg-cursor";+import crypto from "crypto";import {TPostgresAccountCredentials,@@ -8,15 +6,18 @@ import {} from "@app/ee/services/pam-resource/postgres/postgres-resource-types";import { logger } from "@app/lib/logger";-import { getSchemasQuery, getTableDetailQuery, getTablesQuery } from "./pam-postgres-data-explorer-metadata";+import {+ createPostgresConnectionController,+ type TPostgresConnectionController+} from "./pam-postgres-connection-controller";+import { fetchSchemasOneShot, fetchTablesOneShot, verifyReachabilityOneShot } from "./pam-postgres-metadata";import {PostgresClientMessageSchema,PostgresClientMessageType,PostgresServerMessageType,type TPostgresCorrelatedServerMessage} from "./pam-postgres-ws-types";-import { parseClientMessage, resolveEndReason } from "./pam-web-access-fns";-import { createPamSqlRepl } from "./pam-web-access-repl";+import { parseClientMessage } from "./pam-web-access-fns";import {SessionEndReason,TerminalServerMessageType,@@ -29,56 +30,52 @@ type TPostgresSessionParams = {credentials: TPostgresAccountCredentials;};+// Fan-out bound inside a single already-authenticated WS session.+const MAX_CONNECTIONS_PER_WS = 20;++// Unwrap a pg driver error into the shape our WS error responses expect.+const toPgErrorFields = (err: unknown) => {+ const pgErr = err as { message?: string; detail?: string; hint?: string };+ return { message: pgErr.message, detail: pgErr.detail, hint: pgErr.hint };+};+export const handlePostgresSession = async (ctx: TSessionContext,params: TPostgresSessionParams): Promise<TSessionHandlerResult> => {- const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =- ctx;+ const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, onCleanup } = ctx;const { connectionDetails, credentials } = params;- // Type parser shared between the pg.Client and pg-cursor instances so all- // results — whether fetched via the simple query path or cursor — apply the- // same normalisation rules.- const pgTypes = {- getTypeParser: (oid: number) => {- // Boolean (OID 16): Postgres wire protocol sends 't'/'f' — expand to 'true'/'false'- // so the Data Explorer UI displays human-readable literals.- if (oid === 16)- return (val: string | Buffer) => {- const raw = typeof val === "string" ? val : val.toString("utf8");- return raw === "t" ? "true" : "false";- };- return (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"));- }+ const oneShotOpts = {+ relayPort,+ username: credentials.username,+ database: connectionDetails.database};- const pgClient = new pg.Client({- host: "localhost",- port: relayPort,- user: credentials.username,- database: connectionDetails.database,- password: "",- ssl: false,- connectionTimeoutMillis: 30_000,- statement_timeout: 30_000,- types: pgTypes- });-- await pgClient.connect();-- const { rows: pidRows } = await pgClient.query<{ pid: number }>("SELECT pg_backend_pid() AS pid");- const backendPid = pidRows[0]?.pid;-- const repl = createPamSqlRepl(pgClient);+ // Early reachability check — fail fast before sending ready, preserving the+ // early "Connection error" UX the FE relies on.+ try {+ await verifyReachabilityOneShot(oneShotOpts);+ } catch (err) {+ logger.error(err, `Postgres reachability check failed [sessionId=${sessionId}]`);+ sendSessionEnd(SessionEndReason.SetupFailed);+ onCleanup();+ try {+ socket.close();+ } catch {+ // ignore+ }+ return {+ cleanup: async () => {}+ };+ }sendMessage({type: TerminalServerMessageType.Ready,- data: `Connected to ${resourceName} (${connectionDetails.database}) as ${credentials.username}\n\n`,- prompt: "=> "+ data: `Connected to ${resourceName} (${connectionDetails.database}) as ${credentials.username}\n\n`});- logger.info({ sessionId }, "Postgres web access session established");+ logger.info(`Postgres web access session established [sessionId=${sessionId}]`);const sendResponse = (msg: TPostgresCorrelatedServerMessage) => {try {@@ -86,289 +83,198 @@ export const handlePostgresSession = async (socket.send(JSON.stringify(msg));}} catch (err) {- logger.error(err, "Failed to send WebSocket message");+ logger.error(err, `Failed to send WebSocket message [sessionId=${sessionId}]`);}};- // Server-side transaction state — updated after every query so the client- // always receives the authoritative value, including for multi-statement SQL.- let isInTransaction = false;+ const controllers = new Map<string, TPostgresConnectionController>();+ // Reserved slots for in-flight opens — counted against the cap so a burst of+ // open-connection messages can't all pass the check before any of them+ // finishes inserting into `controllers`.+ let pendingOpens = 0;- // Shared error handler for correlated query messages- const sendQueryError = async (id: string, err: unknown) => {- const pgErr = err as { message?: string; detail?: string; hint?: string };-- // If the failed query was inside a transaction, roll back so the- // connection is not stuck in an aborted transaction state.- try {- await pgClient.query("ROLLBACK");- } catch {- // ROLLBACK fails if there was no active transaction — safe to ignore.- }+ // Metadata requests (get-schemas / get-tables) are processed outside any+ // controller queue so sidebar refreshes don't block tab work.+ let metadataPromise: Promise<void> = Promise.resolve();- isInTransaction = false;+ // --- Per-message handlers ---- sendResponse({- type: PostgresServerMessageType.Error,- id,- error: pgErr.message ?? "Query execution failed",- detail: pgErr.detail,- hint: pgErr.hint- });- };+ const openTabConnection = async (requestId: string) => {+ if (controllers.size + pendingOpens >= MAX_CONNECTIONS_PER_WS) {+ sendResponse({+ type: PostgresServerMessageType.ConnectionOpenFailed,+ id: requestId,+ error: `Maximum ${MAX_CONNECTIONS_PER_WS} connections per session reached`+ });+ return;+ }- // Cancel the currently running query via pg_cancel_backend.- // Runs on a separate connection so it is not blocked by the sequential queue.- const cancelRunningQuery = async () => {- if (!backendPid) return;- const pid = backendPid;- const cancelClient = new pg.Client({- host: "localhost",- port: relayPort,- user: credentials.username,- database: connectionDetails.database,- password: "",- ssl: false,- connectionTimeoutMillis: 5_000- });+ pendingOpens += 1;+ const connectionId = crypto.randomUUID();try {- await cancelClient.connect();- await cancelClient.query("SELECT pg_cancel_backend($1)", [pid]);+ const controller = await createPostgresConnectionController({+ relayPort,+ username: credentials.username,+ database: connectionDetails.database,+ sessionId,+ connectionId,+ sendResponse,+ onUnexpectedTermination: (reason) => {+ if (!controllers.has(connectionId)) return;+ controllers.delete(connectionId);+ sendResponse({+ type: PostgresServerMessageType.ConnectionClosed,+ connectionId,+ reason+ });+ }+ });+ controllers.set(connectionId, controller);+ sendResponse({+ type: PostgresServerMessageType.ConnectionOpened,+ id: requestId,+ connectionId,+ backendPid: controller.backendPid+ });} catch (err) {- logger.debug(err, "Failed to cancel backend query");+ const msg = err instanceof Error ? err.message : "Failed to open connection";+ logger.error(err, `Failed to open tab connection [sessionId=${sessionId}]`);+ sendResponse({+ type: PostgresServerMessageType.ConnectionOpenFailed,+ id: requestId,+ error: msg+ });} finally {- await cancelClient.end().catch(() => {});+ pendingOpens -= 1;}};- // Sequential message processing to prevent concurrent query issues- let processingPromise = Promise.resolve();-- socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {- const message = parseClientMessage(rawData, PostgresClientMessageSchema);-- // Cancel is handled immediately outside the sequential queue so it can- // interrupt a running query rather than waiting behind it.- if (message?.type === PostgresClientMessageType.Cancel) {- void cancelRunningQuery();- return;- }-- processingPromise = processingPromise+ // Queue a metadata fetch (schemas / tables) behind any in-flight metadata+ // call so one-shot pg.Clients don't pile up. Errors are normalised into+ // PostgresServerMessageType.Error responses tied to the request id.+ const queueMetadata = <T>(+ requestId: string,+ fetcher: () => Promise<T>,+ onSuccess: (rows: T) => TPostgresCorrelatedServerMessage,+ fallbackError: string+ ) => {+ metadataPromise = metadataPromise.then(async () => {- if (!message) {- sendMessage({- type: TerminalServerMessageType.Output,- data: "Invalid message format\n",- prompt: repl.getPrompt()+ try {+ const rows = await fetcher();+ sendResponse(onSuccess(rows));+ } catch (err) {+ const { message: errMsg, detail, hint } = toPgErrorFields(err);+ sendResponse({+ type: PostgresServerMessageType.Error,+ id: requestId,+ error: errMsg ?? fallbackError,+ detail,+ hint});- return;}+ })+ .catch(() => {});+ };- switch (message.type) {- case PostgresClientMessageType.GetSchemas: {- try {- const query = getSchemasQuery();- const result = await pgClient.query(query.text, query.values);- sendResponse({- type: PostgresServerMessageType.Schemas,- id: message.id,- data: result.rows as { name: string }[]- });- } catch (err) {- await sendQueryError(message.id, err);- }- break;- }-- case PostgresClientMessageType.GetTables: {- try {- const query = getTablesQuery(message.schema);- const result = await pgClient.query(query.text, query.values);- sendResponse({- type: PostgresServerMessageType.Tables,- id: message.id,- data: result.rows as { name: string; tableType: string }[]- });- } catch (err) {- await sendQueryError(message.id, err);- }- break;- }-- case PostgresClientMessageType.GetTableDetail: {- try {- const query = getTableDetailQuery(message.schema, message.table);- const result = await pgClient.query<{ result: string }>(query.text, query.values);- const rawDetail = result.rows[0]?.result;- if (!rawDetail) {- sendResponse({- type: PostgresServerMessageType.Error,- id: message.id,- error: "Table not found or no metadata available"- });- break;- }- const detail =- typeof rawDetail === "string"- ? (JSON.parse(rawDetail) as Record<string, unknown>)- : (rawDetail as unknown as Record<string, unknown>);- sendResponse({- type: PostgresServerMessageType.TableDetail,- id: message.id,- data: detail as {- columns: {- name: string;- type: string;- nullable: boolean;- identityGeneration: string | null;- }[];- primaryKeys: string[];- foreignKeys: {- constraintName: string;- columns: string[];- targetSchema: string;- targetTable: string;- targetColumns: string[];- }[];- }- });- } catch (err) {- await sendQueryError(message.id, err);- }- break;- }-- case PostgresClientMessageType.Query: {- try {- const startTime = performance.now();- const MAX_ROWS = 1000;-- // Split the SQL into individual statements using the real PostgreSQL C parser- // (via libpg-query WASM). Each statement is then run through a pg-cursor with- // an explicit row cap — the server sends at most MAX_ROWS+1 rows at the wire- // level regardless of result set size, so memory usage is bounded.- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment- const parsed = await parseSql(message.sql);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const stmtTexts = (parsed.stmts as Array<{ stmt_location?: number; stmt_len?: number }>).map((s) => {- const location = s.stmt_location ?? 0;- return s.stmt_len !== undefined- ? message.sql.slice(location, location + s.stmt_len)- : message.sql.slice(location).trim();- });-- let lastRows: Record<string, unknown>[] = [];- let lastFields: { name: string }[] = [];- let lastRowCount: number | null = null;- let lastCommand = "";- let lastIsTruncated = false;-- for (const stmtSql of stmtTexts) {- const cursor = pgClient.query(new Cursor(stmtSql.trim(), null, { types: pgTypes }));- // eslint-disable-next-line no-await-in-loop- const stmtRows = await cursor.read(MAX_ROWS + 1);- const stmtIsTruncated = stmtRows.length > MAX_ROWS;- if (stmtIsTruncated) stmtRows.splice(MAX_ROWS);- // eslint-disable-next-line no-await-in-loop- await cursor.close();-- // eslint-disable-next-line no-underscore-dangle- const cursorResult = cursor._result;- const cmd = (cursorResult.command ?? "").toUpperCase();- if (cmd === "BEGIN" || cmd === "START") isInTransaction = true;- if (cmd === "COMMIT" || cmd === "ROLLBACK") isInTransaction = false;-- lastRows = stmtRows;- lastFields = (cursorResult.fields ?? []).map((f) => ({ name: f.name }));- lastRowCount = cursorResult.rowCount;- lastCommand = cursorResult.command ?? "";- lastIsTruncated = stmtIsTruncated;- }+ socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {+ const message = parseClientMessage(rawData, PostgresClientMessageSchema);+ if (!message) return;++ switch (message.type) {+ case PostgresClientMessageType.Control: {+ if (message.data === "quit") {+ sendSessionEnd(SessionEndReason.UserQuit);+ onCleanup();+ socket.close();+ }+ break;+ }- const executionTimeMs = Math.round(performance.now() - startTime);- sendResponse({- type: PostgresServerMessageType.QueryResult,- id: message.id,- rows: lastRows,- fields: lastFields,- rowCount: lastRowCount,- isTruncated: lastIsTruncated,- transactionOpen: isInTransaction,- command: lastCommand,- executionTimeMs- });- } catch (err) {- await sendQueryError(message.id, err);- }- break;- }+ case PostgresClientMessageType.OpenConnection: {+ void openTabConnection(message.id);+ break;+ }- case PostgresClientMessageType.Control: {- if (message.data === "quit") {- sendSessionEnd(SessionEndReason.UserQuit);- onCleanup();- socket.close();- return;- }- if (message.data === "clear-buffer") {- repl.clearBuffer();- }- break;- }+ case PostgresClientMessageType.CloseConnection: {+ const controller = controllers.get(message.connectionId);+ if (!controller) return;+ controllers.delete(message.connectionId);+ controller.dispose();+ break;+ }- case PostgresClientMessageType.Input: {- const replResult = await repl.processInput(message.data);+ case PostgresClientMessageType.Cancel: {+ const controller = controllers.get(message.connectionId);+ if (!controller || controller.isDisposing()) {+ logger.debug(+ `Cancel on missing/disposing connection [sessionId=${sessionId}] [connectionId=${message.connectionId}]`+ );+ return;+ }+ controller.handleMessage(message);+ break;+ }- if (replResult.shouldClose) {- sendSessionEnd(SessionEndReason.UserQuit);- onCleanup();- socket.close();- return;- }+ case PostgresClientMessageType.GetSchemas: {+ queueMetadata(+ message.id,+ () => fetchSchemasOneShot(oneShotOpts),+ (rows) => ({ type: PostgresServerMessageType.Schemas, id: message.id, data: rows }),+ "Failed to fetch schemas"+ );+ break;+ }- sendMessage({- type: TerminalServerMessageType.Output,- data: replResult.output,- prompt: replResult.prompt- });- break;- }+ case PostgresClientMessageType.GetTables: {+ queueMetadata(+ message.id,+ () => fetchTablesOneShot(oneShotOpts, message.schema),+ (rows) => ({ type: PostgresServerMessageType.Tables, id: message.id, data: rows }),+ "Failed to fetch tables"+ );+ break;+ }- default:- break;+ case PostgresClientMessageType.GetTableDetail:+ case PostgresClientMessageType.Query: {+ const controller = controllers.get(message.connectionId);+ if (!controller || controller.isDisposing()) {+ sendResponse({+ type: PostgresServerMessageType.Error,+ id: message.id,+ connectionId: message.connectionId,+ error: "Connection not found"+ });+ return;}- })- .catch((err) => {- logger.error(err, "Error processing Postgres message");- sendMessage({- type: TerminalServerMessageType.Output,- data: "Internal error\n",- prompt: "=> "- });- });- });+ controller.handleMessage(message);+ break;+ }- // Tunnel drop detection- pgClient.on("error", (err) => {- logger.error(err, "Database connection error");- sendSessionEnd(resolveEndReason(isNearSessionExpiry));- onCleanup();- socket.close();- });+ case PostgresClientMessageType.Activity: {+ // No-op. The idle timer is reset by the sibling socket.on("message")+ // listener in pam-web-access-service.ts — this branch just keeps the+ // discriminated-union exhaustive so the `default` arm stays unreachable.+ break;+ }- pgClient.on("end", () => {- sendSessionEnd(resolveEndReason(isNearSessionExpiry));- onCleanup();- socket.close();+ default:+ break;+ }});return {cleanup: async () => {- try {- await pgClient.end();- } catch (err) {- logger.debug(err, "Error closing pg client");+ // dispose() is synchronous and fire-and-forget — no await needed.+ const snapshot = Array.from(controllers.values());+ controllers.clear();+ for (const controller of snapshot) {+ try {+ controller.dispose();+ } catch (err) {+ logger.debug(err, `Error disposing controller [sessionId=${sessionId}]`);+ }}}};diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.tsindex bda4395a9e..3877d8bbc1 100644--- a/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts+++ b/backend/src/ee/services/pam-web-access/pam-postgres-ws-types.ts@@ -1,40 +1,40 @@import { z } from "zod";-import { SessionEndReason } from "./pam-web-access-types";-export enum PostgresClientMessageType {- Input = "input",Control = "control",GetSchemas = "get-schemas",GetTables = "get-tables",GetTableDetail = "get-table-detail",Query = "query",- Cancel = "cancel"+ Cancel = "cancel",+ OpenConnection = "open-connection",+ CloseConnection = "close-connection",+ Activity = "activity"}export enum PostgresServerMessageType {- Ready = "ready",- Output = "output",- SessionEnd = "session_end",Schemas = "schemas",Tables = "tables",TableDetail = "table-detail",QueryResult = "query-result",- Error = "error"+ Error = "error",+ ConnectionOpened = "connection-opened",+ ConnectionOpenFailed = "connection-open-failed",+ ConnectionClosed = "connection-closed"}-// --- Shared base for correlated request/response messages ---+// --- Shared bases ---const CorrelatedBaseSchema = z.object({ id: z.string().uuid() });+const TabScopedBaseSchema = CorrelatedBaseSchema.extend({ connectionId: z.string().uuid() });// =====================================================================// Client messages (client → server) — single flat discriminated union// =====================================================================-const InputSchema = z.object({ type: z.literal(PostgresClientMessageType.Input), data: z.string() });-const ControlSchema = z.object({ type: z.literal(PostgresClientMessageType.Control), data: z.string() });+// Metadata messages — not connectionId-scoped; served by one-shot pg.Clients.const GetSchemasRequestSchema = CorrelatedBaseSchema.extend({type: z.literal(PostgresClientMessageType.GetSchemas)});@@ -44,46 +44,61 @@ const GetTablesRequestSchema = CorrelatedBaseSchema.extend({schema: z.string()});-const GetTableDetailRequestSchema = CorrelatedBaseSchema.extend({+// Tab-scoped messages — carry connectionId; routed to a specific controller.+const GetTableDetailRequestSchema = TabScopedBaseSchema.extend({type: z.literal(PostgresClientMessageType.GetTableDetail),schema: z.string(),table: z.string()});-const QueryRequestSchema = CorrelatedBaseSchema.extend({+const QueryRequestSchema = TabScopedBaseSchema.extend({type: z.literal(PostgresClientMessageType.Query),sql: z.string().max(50 * 1024)});-const CancelSchema = z.object({ type: z.literal(PostgresClientMessageType.Cancel) });+// Cancel stays fire-and-forget; gains connectionId for routing but not id.+const CancelSchema = z.object({+ type: z.literal(PostgresClientMessageType.Cancel),+ connectionId: z.string().uuid()+});++// Lifecycle — open/close tab controllers.+const OpenConnectionSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresClientMessageType.OpenConnection)+});++const CloseConnectionSchema = z.object({+ type: z.literal(PostgresClientMessageType.CloseConnection),+ connectionId: z.string().uuid()+});++// Fire-and-forget heartbeat sent by the FE while the browser tab is visible, so+// the server-side idle timer only fires on truly inactive tabs — not on active+// read-only sessions that don't happen to send queries.+const ActivitySchema = z.object({+ type: z.literal(PostgresClientMessageType.Activity)+});export const PostgresClientMessageSchema = z.discriminatedUnion("type", [- InputSchema,ControlSchema,GetSchemasRequestSchema,GetTablesRequestSchema,GetTableDetailRequestSchema,QueryRequestSchema,- CancelSchema+ CancelSchema,+ OpenConnectionSchema,+ CloseConnectionSchema,+ ActivitySchema]);export type TPostgresClientMessage = z.infer<typeof PostgresClientMessageSchema>;// =====================================================================-// Server messages (server → client) — single flat discriminated union+// Server messages (server → client) — correlated request/response schemas.+// Lifecycle messages (ready / session_end) travel on the shared+// TerminalServerMessageType channel defined in pam-web-access-types.ts.// =====================================================================-const OutputSchema = z.object({- type: z.enum([PostgresServerMessageType.Ready, PostgresServerMessageType.Output]),- data: z.string(),- prompt: z.string().default("")-});--const SessionEndSchema = z.object({- type: z.literal(PostgresServerMessageType.SessionEnd),- reason: z.nativeEnum(SessionEndReason)-});-const SchemasResponseSchema = CorrelatedBaseSchema.extend({type: z.literal(PostgresServerMessageType.Schemas),data: z.array(z.object({ name: z.string() }))@@ -94,8 +109,9 @@ const TablesResponseSchema = CorrelatedBaseSchema.extend({data: z.array(z.object({ name: z.string(), tableType: z.string() }))});-const TableDetailResponseSchema = CorrelatedBaseSchema.extend({+const TableDetailResponseSchema = TabScopedBaseSchema.extend({type: z.literal(PostgresServerMessageType.TableDetail),+ transactionOpen: z.boolean(),data: z.object({columns: z.array(z.object({@@ -128,7 +144,7 @@ const TableDetailResponseSchema = CorrelatedBaseSchema.extend({})});-const QueryResultResponseSchema = CorrelatedBaseSchema.extend({+const QueryResultResponseSchema = TabScopedBaseSchema.extend({type: z.literal(PostgresServerMessageType.QueryResult),rows: z.array(z.record(z.string(), z.unknown())),fields: z.array(@@ -145,28 +161,45 @@ const QueryResultResponseSchema = CorrelatedBaseSchema.extend({executionTimeMs: z.number()});+// Error responses carry transactionOpen for tab-scoped errors so the FE banner+// stays in sync after auto-rollback. connectionId is optional because errors+// can come from metadata requests (no connectionId) or unknown-connectionId+// cases tied to a request id.const ErrorResponseSchema = CorrelatedBaseSchema.extend({type: z.literal(PostgresServerMessageType.Error),+ connectionId: z.string().uuid().optional(),+ transactionOpen: z.boolean().optional(),error: z.string(),detail: z.string().optional(),hint: z.string().optional()});-export const PostgresServerMessageSchema = z.discriminatedUnion("type", [- OutputSchema,- SessionEndSchema,- SchemasResponseSchema,- TablesResponseSchema,- TableDetailResponseSchema,- QueryResultResponseSchema,- ErrorResponseSchema-]);+// Lifecycle responses.+const ConnectionOpenedResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.ConnectionOpened),+ connectionId: z.string().uuid(),+ backendPid: z.number().nullable()+});++const ConnectionOpenFailedResponseSchema = CorrelatedBaseSchema.extend({+ type: z.literal(PostgresServerMessageType.ConnectionOpenFailed),+ error: z.string()+});++// Informational — BE pushes this when a controller dies outside clean dispose.+const ConnectionClosedResponseSchema = z.object({+ type: z.literal(PostgresServerMessageType.ConnectionClosed),+ connectionId: z.string().uuid(),+ reason: z.string()+});-// Correlated server messages only (excludes lifecycle messages like ready/output/session_end)export type TPostgresCorrelatedServerMessage = z.infer<| typeof SchemasResponseSchema| typeof TablesResponseSchema| typeof TableDetailResponseSchema| typeof QueryResultResponseSchema| typeof ErrorResponseSchema+ | typeof ConnectionOpenedResponseSchema+ | typeof ConnectionOpenFailedResponseSchema+ | typeof ConnectionClosedResponseSchema>;diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-repl.test.ts b/backend/src/ee/services/pam-web-access/pam-web-access-repl.test.tsdeleted file mode 100644index a8e6a15694..0000000000--- a/backend/src/ee/services/pam-web-access/pam-web-access-repl.test.ts+++ /dev/null@@ -1,238 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import { createPamSqlRepl, TQueryExecutor } from "./pam-web-access-repl";--describe("createPamSqlRepl", () => {- let queryFn: ReturnType<typeof vi.fn>;- let mockExecutor: TQueryExecutor;- let repl: ReturnType<typeof createPamSqlRepl>;-- beforeEach(() => {- queryFn = vi.fn().mockResolvedValue({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 1 }]- });- mockExecutor = { query: queryFn };- repl = createPamSqlRepl(mockExecutor);- });-- // Statement execution- it("executes complete statement", async () => {- const result = await repl.processInput("SELECT 1;");- expect(queryFn).toHaveBeenCalledWith("SELECT 1");- expect(result.output).toContain("1");- expect(result.prompt).toBe("=> ");- expect(result.shouldClose).toBe(false);- });-- it("buffers incomplete input", async () => {- const result = await repl.processInput("SELECT *");- expect(queryFn).not.toHaveBeenCalled();- expect(result.output).toBe("");- expect(result.prompt).toBe("-> ");- expect(result.shouldClose).toBe(false);- });-- it("executes after completing buffered statement", async () => {- await repl.processInput("SELECT *");- expect(queryFn).not.toHaveBeenCalled();-- const result = await repl.processInput("FROM users;");- expect(queryFn).toHaveBeenCalledWith("SELECT *\nFROM users");- expect(result.prompt).toBe("=> ");- });-- it("executes multiple statements sequentially", async () => {- queryFn- .mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 1 }]- })- .mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 2 }]- });-- const result = await repl.processInput("SELECT 1; SELECT 2;");- expect(queryFn).toHaveBeenCalledTimes(2);- expect(queryFn).toHaveBeenCalledWith("SELECT 1");- expect(queryFn).toHaveBeenCalledWith("SELECT 2");- expect(result.prompt).toBe("=> ");- });-- // Quit- it("returns shouldClose for \\q", async () => {- const result = await repl.processInput("\\q");- expect(result.shouldClose).toBe(true);- expect(result.output).toBe("Goodbye!\n");- expect(queryFn).not.toHaveBeenCalled();- });-- it("returns shouldClose for quit", async () => {- const result = await repl.processInput("quit");- expect(result.shouldClose).toBe(true);- });-- it("returns shouldClose for exit", async () => {- const result = await repl.processInput("exit");- expect(result.shouldClose).toBe(true);- });-- it("treats quit as SQL when buffer non-empty", async () => {- await repl.processInput("SELECT");- const result = await repl.processInput("quit;");- expect(result.shouldClose).toBe(false);- expect(queryFn).toHaveBeenCalledWith("SELECT\nquit");- });-- // Buffer management- it("clearBuffer resets to empty", async () => {- await repl.processInput("SELECT *");- expect(repl.getPrompt()).toBe("-> ");-- repl.clearBuffer();- expect(repl.getPrompt()).toBe("=> ");- });-- it("getPrompt returns => when buffer empty", () => {- expect(repl.getPrompt()).toBe("=> ");- });-- it("getPrompt returns -> when buffer has content", async () => {- await repl.processInput("SELECT *");- expect(repl.getPrompt()).toBe("-> ");- });-- // Error handling- it("catches query error and returns formatted error", async () => {- queryFn.mockRejectedValueOnce({- message: 'relation "nonexistent" does not exist'- });-- const result = await repl.processInput("SELECT * FROM nonexistent;");- expect(result.output).toContain("ERROR:");- expect(result.output).toContain("nonexistent");- expect(result.shouldClose).toBe(false);- expect(result.prompt).toBe("=> ");- });-- it("continues working after error", async () => {- queryFn.mockRejectedValueOnce({ message: "error" }).mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 1 }]- });-- await repl.processInput("BAD SQL;");- const result = await repl.processInput("SELECT 1;");- expect(result.output).toContain("1");- expect(result.prompt).toBe("=> ");- });-- // Empty input- it("re-prompts on empty input with empty buffer", async () => {- const result = await repl.processInput("");- expect(queryFn).not.toHaveBeenCalled();- expect(result.prompt).toBe("=> ");- });-- it("skips empty statements (bare ;)", async () => {- const result = await repl.processInput(";");- expect(queryFn).not.toHaveBeenCalled();- expect(result.prompt).toBe("=> ");- });-- it("handles mixed complete + incomplete on one input", async () => {- queryFn.mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 1 }]- });-- const result = await repl.processInput("SELECT 1; SELECT");- expect(queryFn).toHaveBeenCalledTimes(1);- expect(queryFn).toHaveBeenCalledWith("SELECT 1");- expect(result.prompt).toBe("-> ");-- // Complete the second statement- queryFn.mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 2 }]- });-- const result2 = await repl.processInput("2;");- expect(queryFn).toHaveBeenCalledTimes(2);- expect(result2.prompt).toBe("=> ");- });-- it("DML result formatting", async () => {- queryFn.mockResolvedValueOnce({- command: "INSERT",- rowCount: 1,- fields: [],- rows: []- });-- const result = await repl.processInput("INSERT INTO t VALUES(1);");- expect(result.output).toBe("INSERT 0 1\n");- });-- it("returns error and clears buffer when input exceeds 1 MB limit", async () => {- const oversized = "A".repeat(1024 * 1024 + 1);- const result = await repl.processInput(oversized);- expect(result.output).toContain("buffer size exceeded");- expect(result.prompt).toBe("=> ");- expect(result.shouldClose).toBe(false);- expect(queryFn).not.toHaveBeenCalled();-- // REPL should still work after buffer was cleared- queryFn.mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "?column?", dataTypeID: 23 }],- rows: [{ "?column?": 1 }]- });- const next = await repl.processInput("SELECT 1;");- expect(next.output).toContain("1");- expect(next.prompt).toBe("=> ");- });-- it("multi-statement paste", async () => {- queryFn- .mockResolvedValueOnce({- command: "CREATE TABLE",- rowCount: null,- fields: [],- rows: []- })- .mockResolvedValueOnce({- command: "INSERT",- rowCount: 1,- fields: [],- rows: []- })- .mockResolvedValueOnce({- command: "SELECT",- rowCount: 1,- fields: [{ name: "id", dataTypeID: 23 }],- rows: [{ id: 1 }]- });-- const result = await repl.processInput("CREATE TABLE t(id int); INSERT INTO t VALUES(1); SELECT * FROM t;");- expect(queryFn).toHaveBeenCalledTimes(3);- expect(result.output).toContain("CREATE TABLE");- expect(result.output).toContain("INSERT 0 1");- expect(result.output).toContain("(1 row)");- expect(result.prompt).toBe("=> ");- });-});diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-repl.ts b/backend/src/ee/services/pam-web-access/pam-web-access-repl.tsdeleted file mode 100644index 47c5bfb965..0000000000--- a/backend/src/ee/services/pam-web-access/pam-web-access-repl.ts+++ /dev/null@@ -1,93 +0,0 @@-import { formatCommandResult, formatError, formatTable } from "./pam-web-access-sql-formatter";-import { splitStatements } from "./pam-web-access-sql-lexer";--/**- * The REPL only depends on this interface, not on pg.Client directly.- * pg.Client satisfies this interface out of the box.- */-export type TQueryExecutor = {- query(sql: string): Promise<{- command: string;- rowCount: number | null;- fields: Array<{ name: string; dataTypeID: number }>;- rows: Record<string, unknown>[];- }>;-};--export type TPamSqlRepl = ReturnType<typeof createPamSqlRepl>;--const MAX_BUFFER_SIZE = 1024 * 1024; // 1 MB--export const createPamSqlRepl = (queryExecutor: TQueryExecutor) => {- let buffer = "";-- const executeStatement = async (sql: string): Promise<string> => {- try {- const result = await queryExecutor.query(sql);-- if (result.fields?.length > 0) {- return formatTable(result);- }- return formatCommandResult(result);- } catch (err) {- return formatError(err);- }- };-- const processInput = async (- rawInput: string- ): Promise<{- output: string;- prompt: string;- shouldClose: boolean;- }> => {- // Check for quit commands when buffer is empty- if (buffer.trim().length === 0) {- const trimmed = rawInput.trim();- if (trimmed === "\\q" || trimmed === "quit" || trimmed === "exit") {- return { output: "Goodbye!\n", prompt: "", shouldClose: true };- }- }-- // Append input to buffer- if (buffer.length > 0) {- buffer += `\n${rawInput}`;- } else {- buffer = rawInput;- }-- if (buffer.length > MAX_BUFFER_SIZE) {- buffer = "";- return {- output: "ERROR: buffer size exceeded (1 MB limit). Buffer cleared.\n",- prompt: "=> ",- shouldClose: false- };- }-- // Split into complete and incomplete statements- const { complete, remainder } = splitStatements(buffer);- buffer = remainder;-- // Execute each complete statement- let output = "";- for (const stmt of complete) {- const trimmed = stmt.trim();- if (trimmed.length > 0) {- // eslint-disable-next-line no-await-in-loop- output += await executeStatement(trimmed);- }- }-- const prompt = buffer.trim().length > 0 ? "-> " : "=> ";- return { output, prompt, shouldClose: false };- };-- const clearBuffer = () => {- buffer = "";- };-- const getPrompt = () => (buffer.trim().length > 0 ? "-> " : "=> ");-- return { processInput, clearBuffer, getPrompt };-};diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.test.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.test.tsdeleted file mode 100644index 09e3d72d12..0000000000--- a/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.test.ts+++ /dev/null@@ -1,247 +0,0 @@-import { builtins } from "pg-types";-import { describe, expect, it } from "vitest";--import { formatCommandResult, formatError, formatTable } from "./pam-web-access-sql-formatter";--describe("formatTable", () => {- it("formats a simple two-column result", () => {- const result = formatTable({- command: "SELECT",- rowCount: 2,- fields: [- { name: "id", dataTypeID: builtins.INT4 },- { name: "name", dataTypeID: builtins.TEXT }- ],- rows: [- { id: 1, name: "Alice" },- { id: 2, name: "Bob" }- ]- });-- expect(result).toContain("id");- expect(result).toContain("name");- expect(result).toContain("Alice");- expect(result).toContain("Bob");- expect(result).toContain("(2 rows)");- expect(result).toContain("+");- expect(result).toContain("-");- });-- it("right-aligns numeric columns", () => {- const result = formatTable({- command: "SELECT",- rowCount: 2,- fields: [{ name: "num", dataTypeID: builtins.INT4 }],- rows: [{ num: 1 }, { num: 100 }]- });-- const lines = result.split("\n");- // Data rows should have right-aligned numbers- const dataLine1 = lines[2]; // first data row- const dataLine2 = lines[3]; // second data row- // "1" should be padded to width of "100"- expect(dataLine1).toContain(" 1");- expect(dataLine2).toContain("100");- });-- it("handles NULL values as empty strings", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [- { name: "id", dataTypeID: builtins.INT4 },- { name: "name", dataTypeID: builtins.TEXT }- ],- rows: [{ id: 1, name: null }]- });-- expect(result).toContain("(1 row)");- });-- it("zero rows with fields", () => {- const result = formatTable({- command: "SELECT",- rowCount: 0,- fields: [- { name: "id", dataTypeID: builtins.INT4 },- { name: "name", dataTypeID: builtins.TEXT }- ],- rows: []- });-- expect(result).toContain("id");- expect(result).toContain("name");- expect(result).toContain("(0 rows)");- });-- it("single row uses singular footer", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [{ name: "val", dataTypeID: builtins.INT4 }],- rows: [{ val: 42 }]- });-- expect(result).toContain("(1 row)");- expect(result).not.toContain("(1 rows)");- });-- it("column width matches longest value", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [{ name: "x", dataTypeID: builtins.TEXT }],- rows: [{ x: "longvalue" }]- });-- // The separator should be at least as wide as "longvalue"- const lines = result.split("\n");- const separator = lines[1];- // "longvalue" is 9 chars, column should be at least 9 + 2 (padding) = 11- expect(separator.length).toBeGreaterThanOrEqual(11);- });-- it("formats Date values as ISO-like timestamps", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [{ name: "created_at", dataTypeID: builtins.TIMESTAMPTZ }],- rows: [{ created_at: new Date("2026-02-05T19:04:52.000Z") }]- });-- expect(result).toContain("2026-02-05 19:04:52");- expect(result).not.toContain("GMT");- expect(result).not.toContain("Coordinated Universal Time");- });-- it("formats raw string timestamps as-is", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [{ name: "ts", dataTypeID: builtins.TIMESTAMPTZ }],- rows: [{ ts: "2026-02-05 19:04:52+00" }]- });-- expect(result).toContain("2026-02-05 19:04:52+00");- });-- it("formats Buffer values as hex", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [{ name: "data", dataTypeID: builtins.BYTEA }],- rows: [{ data: Buffer.from([0xde, 0xad, 0xbe, 0xef]) }]- });-- expect(result).toContain("\\xdeadbeef");- });-- it("formats Array values with braces", () => {- const result = formatTable({- command: "SELECT",- rowCount: 1,- fields: [{ name: "tags", dataTypeID: 1009 }],- rows: [{ tags: ["a", "b", "c"] }]- });-- expect(result).toContain("{a,b,c}");- });-- it("returns empty string for no fields", () => {- const result = formatTable({- command: "SELECT",- rowCount: 0,- fields: [],- rows: []- });-- expect(result).toBe("");- });-});--describe("formatCommandResult", () => {- it("INSERT with row count", () => {- const result = formatCommandResult({- command: "INSERT",- rowCount: 3,- fields: [],- rows: []- });- expect(result).toBe("INSERT 0 3\n");- });-- it("CREATE TABLE", () => {- const result = formatCommandResult({- command: "CREATE TABLE",- rowCount: null,- fields: [],- rows: []- });- expect(result).toBe("CREATE TABLE\n");- });-- it("BEGIN", () => {- const result = formatCommandResult({- command: "BEGIN",- rowCount: null,- fields: [],- rows: []- });- expect(result).toBe("BEGIN\n");- });-- it("UPDATE with row count", () => {- const result = formatCommandResult({- command: "UPDATE",- rowCount: 5,- fields: [],- rows: []- });- expect(result).toBe("UPDATE 5\n");- });-- it("DELETE with zero rows", () => {- const result = formatCommandResult({- command: "DELETE",- rowCount: 0,- fields: [],- rows: []- });- expect(result).toBe("DELETE\n");- });-});--describe("formatError", () => {- it("formats pg error with message", () => {- const result = formatError({ message: 'relation "nonexistent" does not exist' });- expect(result).toBe('ERROR: relation "nonexistent" does not exist\n');- });-- it("includes DETAIL if present", () => {- const result = formatError({- message: "duplicate key violation",- detail: "Key (id)=(1) already exists."- });- expect(result).toContain("ERROR: duplicate key violation\n");- expect(result).toContain("DETAIL: Key (id)=(1) already exists.\n");- });-- it("includes HINT if present", () => {- const result = formatError({- message: "column does not exist",- hint: 'Perhaps you meant to reference the column "user"."name".'- });- expect(result).toContain("ERROR: column does not exist\n");- expect(result).toContain("HINT:");- });-- it("handles non-pg errors", () => {- const result = formatError("something went wrong");- expect(result).toBe("ERROR: something went wrong\n");- });-- it("handles null/undefined", () => {- const result = formatError(null);- expect(result).toContain("ERROR:");- });-});diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.tsdeleted file mode 100644index f776b8b53f..0000000000--- a/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.ts+++ /dev/null@@ -1,119 +0,0 @@-import { builtins } from "pg-types";--// PostgreSQL numeric type OIDs for right-alignment-const NUMERIC_TYPE_IDS = new Set([- builtins.INT8,- builtins.INT2,- builtins.INT4,- builtins.OID,- builtins.FLOAT4,- builtins.FLOAT8,- builtins.MONEY,- builtins.NUMERIC-]);--type TQueryResult = {- command: string;- rowCount: number | null;- fields: Array<{ name: string; dataTypeID: number }>;- rows: Record<string, unknown>[];-};--/**- * Formats a SELECT query result as a psql-style ASCII table.- */-export const formatTable = (result: TQueryResult): string => {- const { fields, rows } = result;-- if (!fields || fields.length === 0) {- return "";- }-- // Convert all values to display strings.- // With raw type parsers all values are already strings, but handle- // Date/Buffer/Array defensively in case parsed types slip through.- const displayRows = rows.map((row) =>- fields.map((field) => {- const val = row[field.name];- if (val === null || val === undefined) return "";- if (val instanceof Date) return val.toISOString().replace("T", " ").replace("Z", "+00");- if (Buffer.isBuffer(val)) return `\\x${val.toString("hex")}`;- if (Array.isArray(val)) return `{${val.map((v) => String(v ?? "NULL")).join(",")}}`;- return String(val);- })- );-- // Calculate column widths: max of header length and all value lengths- const colWidths = fields.map((field, colIdx) => {- let maxLen = field.name.length;- for (const row of displayRows) {- if (row[colIdx].length > maxLen) {- maxLen = row[colIdx].length;- }- }- return maxLen;- });-- // Determine alignment per column- const isNumeric = fields.map((field) => NUMERIC_TYPE_IDS.has(field.dataTypeID));-- // Build header row- const headerCells = fields.map((field, i) => ` ${field.name.padEnd(colWidths[i])} `);- const headerLine = headerCells.join("|");-- // Build separator row- const separatorCells = colWidths.map((w) => "-".repeat(w + 2));- const separatorLine = separatorCells.join("+");-- // Build data rows- const dataLines = displayRows.map((row) => {- const cells = row.map((val, i) => {- const padded = isNumeric[i] ? val.padStart(colWidths[i]) : val.padEnd(colWidths[i]);- return ` ${padded} `;- });- return cells.join("|");- });-- // Footer- const rowCount = rows.length;- const footer = `(${rowCount} ${rowCount === 1 ? "row" : "rows"})`;-- // Assemble- const parts = [headerLine, separatorLine, ...dataLines, footer, ""];- return parts.join("\n");-};--/**- * Formats a DML/DDL command result (e.g. "INSERT 0 3", "CREATE TABLE", "BEGIN").- */-export const formatCommandResult = (result: TQueryResult): string => {- const { command, rowCount } = result;- if (rowCount != null && rowCount > 0) {- // INSERT returns "INSERT 0 <count>" in psql- if (command === "INSERT") {- return `INSERT 0 ${rowCount}\n`;- }- // UPDATE, DELETE return "<COMMAND> <count>"- return `${command} ${rowCount}\n`;- }- return `${command}\n`;-};--/**- * Formats a PostgreSQL error in psql style.- */-export const formatError = (err: unknown): string => {- if (err && typeof err === "object") {- const pgErr = err as { message?: string; detail?: string; hint?: string; severity?: string };- const parts: string[] = [];- parts.push(`ERROR: ${pgErr.message ?? "Unknown error"}\n`);- if (pgErr.detail) {- parts.push(`DETAIL: ${pgErr.detail}\n`);- }- if (pgErr.hint) {- parts.push(`HINT: ${pgErr.hint}\n`);- }- return parts.join("");- }- return `ERROR: ${String(err)}\n`;-};diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.test.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.test.tsdeleted file mode 100644index 95f827f02c..0000000000--- a/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.test.ts+++ /dev/null@@ -1,138 +0,0 @@-import { describe, expect, it } from "vitest";--import { splitStatements } from "./pam-web-access-sql-lexer";--describe("splitStatements", () => {- // Basic cases- it("single complete statement", () => {- const result = splitStatements("SELECT 1;");- expect(result.complete).toEqual(["SELECT 1"]);- expect(result.remainder).toBe("");- });-- it("multiple statements on one line", () => {- const result = splitStatements("SELECT 1; SELECT 2;");- expect(result.complete).toEqual(["SELECT 1", " SELECT 2"]);- expect(result.remainder).toBe("");- });-- it("incomplete statement (no ;)", () => {- const result = splitStatements("SELECT 1");- expect(result.complete).toEqual([]);- expect(result.remainder).toBe("SELECT 1");- });-- it("mixed complete + incomplete", () => {- const result = splitStatements("SELECT 1; SELECT");- expect(result.complete).toEqual(["SELECT 1"]);- expect(result.remainder).toBe(" SELECT");- });-- it("empty statements", () => {- const result = splitStatements(";;;");- expect(result.complete).toEqual(["", "", ""]);- expect(result.remainder).toBe("");- });-- it("multi-line statement", () => {- const result = splitStatements("SELECT *\nFROM users;");- expect(result.complete).toEqual(["SELECT *\nFROM users"]);- expect(result.remainder).toBe("");- });-- // Quoting- it("semicolon inside single quotes", () => {- const result = splitStatements("SELECT 'a;b';");- expect(result.complete).toEqual(["SELECT 'a;b'"]);- expect(result.remainder).toBe("");- });-- it("escaped single quote", () => {- const result = splitStatements("SELECT 'it''s';");- expect(result.complete).toEqual(["SELECT 'it''s'"]);- expect(result.remainder).toBe("");- });-- it("dollar-quoted string", () => {- const result = splitStatements("SELECT $$a;b$$;");- expect(result.complete).toEqual(["SELECT $$a;b$$"]);- expect(result.remainder).toBe("");- });-- it("dollar-quoted with tag", () => {- const result = splitStatements("SELECT $fn$a;b$fn$;");- expect(result.complete).toEqual(["SELECT $fn$a;b$fn$"]);- expect(result.remainder).toBe("");- });-- it("dollar sign not a quote (positional param)", () => {- const result = splitStatements("SELECT $1;");- expect(result.complete).toEqual(["SELECT $1"]);- expect(result.remainder).toBe("");- });-- // Comments- it("line comment with semicolon", () => {- const result = splitStatements("SELECT 1; -- comment;\nSELECT 2;");- expect(result.complete).toHaveLength(2);- expect(result.complete[0]).toBe("SELECT 1");- expect(result.complete[1].trim()).toContain("SELECT 2");- });-- it("block comment with semicolon", () => {- const result = splitStatements("SELECT /* ; */ 1;");- expect(result.complete).toEqual(["SELECT /* ; */ 1"]);- expect(result.remainder).toBe("");- });-- it("nested block comments", () => {- const result = splitStatements("SELECT /* /* ; */ */ 1;");- expect(result.complete).toEqual(["SELECT /* /* ; */ */ 1"]);- expect(result.remainder).toBe("");- });-- // Edge cases- it("empty input", () => {- const result = splitStatements("");- expect(result.complete).toEqual([]);- expect(result.remainder).toBe("");- });-- it("only whitespace", () => {- const result = splitStatements(" ");- expect(result.complete).toEqual([]);- expect(result.remainder).toBe(" ");- });-- it("only semicolons", () => {- const result = splitStatements(";;;");- expect(result.complete).toEqual(["", "", ""]);- expect(result.remainder).toBe("");- });-- it("statement after line comment", () => {- const result = splitStatements("-- comment\nSELECT 1;");- expect(result.complete).toHaveLength(1);- expect(result.complete[0]).toContain("SELECT 1");- });-- it("unclosed single quote keeps everything in remainder", () => {- const result = splitStatements("SELECT 'unclosed;");- expect(result.complete).toEqual([]);- expect(result.remainder).toBe("SELECT 'unclosed;");- });-- it("unclosed block comment keeps everything in remainder", () => {- const result = splitStatements("SELECT /* unclosed ;");- expect(result.complete).toEqual([]);- expect(result.remainder).toBe("SELECT /* unclosed ;");- });-- it("CREATE FUNCTION with dollar-quoted body", () => {- const sql = `CREATE FUNCTION test() RETURNS void AS $$ BEGIN PERFORM 1; END; $$ LANGUAGE plpgsql;`;- const result = splitStatements(sql);- expect(result.complete).toHaveLength(1);- expect(result.complete[0]).toContain("PERFORM 1;");- expect(result.remainder).toBe("");- });-});diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.tsdeleted file mode 100644index 792e2022a7..0000000000--- a/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.ts+++ /dev/null@@ -1,169 +0,0 @@-type TSplitResult = {- complete: string[];- remainder: string;-};--enum LexerState {- Normal = "normal",- SingleQuote = "single_quote",- DollarQuote = "dollar_quote",- LineComment = "line_comment",- BlockComment = "block_comment"-}--/**- * Tries to parse a dollar-quote tag starting at position i.- * Returns the full tag (e.g. "$$" or "$fn$") if found, null otherwise.- */-const tryParseDollarTag = (sql: string, i: number): string | null => {- // Must start with $- if (sql[i] !== "$") return null;-- // Check for $$ (empty tag)- if (i + 1 < sql.length && sql[i + 1] === "$") {- return "$$";- }-- // Check for $identifier$ pattern- // Identifier must start with [A-Za-z_\x80-\xff]- const startChar = i + 1 < sql.length ? sql.charCodeAt(i + 1) : 0;- const isValidStart =- (startChar >= 65 && startChar <= 90) || // A-Z- (startChar >= 97 && startChar <= 122) || // a-z- startChar === 95 || // _- startChar >= 128; // \x80-\xff-- if (!isValidStart) return null;-- // Scan for the rest of the identifier + closing $- let j = i + 2;- while (j < sql.length) {- const code = sql.charCodeAt(j);- const isValidContinue =- (code >= 65 && code <= 90) || // A-Z- (code >= 97 && code <= 122) || // a-z- (code >= 48 && code <= 57) || // 0-9- code === 95 || // _- code >= 128; // \x80-\xff-- if (code === 36) {- // Found closing $- return sql.substring(i, j + 1);- }- if (!isValidContinue) {- return null;- }- j += 1;- }-- return null;-};--/**- * Splits a SQL string into individual statements by detecting semicolons- * that are actual statement boundaries (not inside strings, comments, etc.).- *- * Returns complete statements (terminated by ;) and any remaining text.- */-export const splitStatements = (sql: string): TSplitResult => {- const complete: string[] = [];- let buffer = "";- let state = LexerState.Normal;- let dollarTag = "";- let blockDepth = 0;- let i = 0;-- while (i < sql.length) {- const ch = sql[i];- const next = i + 1 < sql.length ? sql[i + 1] : "";-- switch (state) {- case LexerState.Normal:- if (ch === ";") {- complete.push(buffer);- buffer = "";- } else if (ch === "'") {- buffer += ch;- state = LexerState.SingleQuote;- } else if (ch === "$") {- // Check for dollar-quote tag: $$ or $identifier$- const tag = tryParseDollarTag(sql, i);- if (tag !== null) {- buffer += tag;- dollarTag = tag;- state = LexerState.DollarQuote;- i += tag.length - 1; // -1 because the loop will i++- } else {- buffer += ch;- }- } else if (ch === "-" && next === "-") {- buffer += "--";- state = LexerState.LineComment;- i += 1;- } else if (ch === "/" && next === "*") {- buffer += "/*";- state = LexerState.BlockComment;- blockDepth = 1;- i += 1;- } else {- buffer += ch;- }- break;-- case LexerState.SingleQuote:- if (ch === "'" && next === "'") {- // Escaped single quote- buffer += "''";- i += 1;- } else if (ch === "'") {- buffer += ch;- state = LexerState.Normal;- } else {- buffer += ch;- }- break;-- case LexerState.DollarQuote:- // Check if we've hit the closing dollar tag- if (ch === "$" && sql.substring(i, i + dollarTag.length) === dollarTag) {- buffer += dollarTag;- i += dollarTag.length - 1;- state = LexerState.Normal;- } else {- buffer += ch;- }- break;-- case LexerState.LineComment:- buffer += ch;- if (ch === "\n") {- state = LexerState.Normal;- }- break;-- case LexerState.BlockComment:- if (ch === "/" && next === "*") {- buffer += "/*";- blockDepth += 1;- i += 1;- } else if (ch === "*" && next === "/") {- buffer += "*/";- blockDepth -= 1;- if (blockDepth === 0) {- state = LexerState.Normal;- }- i += 1;- } else {- buffer += ch;- }- break;-- default:- buffer += ch;- }-- i += 1;- }-- return { complete, remainder: buffer };-};diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.tsindex 2a09937edf..3e9f487afe 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts@@ -43,8 +43,10 @@ export const MAX_WEB_SESSIONS_PER_USER = 5;// WebSocket ping interval (ms) — keeps ALB from killing idle connections (default 60s timeout)export const WS_PING_INTERVAL_MS = 30000;-// Idle timeout (ms) — auto-close sessions with no user input/control messages-export const WS_IDLE_TIMEOUT_MS = 20 * 60 * 1000;+// Idle timeout (ms) — auto-close sessions with no inbound WS traffic. The FE+// sends an `activity` heartbeat while its browser tab is visible, so this fires+// only when the tab has been hidden/backgrounded for the full window.+export const WS_IDLE_TIMEOUT_MS = 10 * 60 * 1000;export type TSessionContext = {socket: WebSocket;diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsx b/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsxindex 434e14e0a7..9161790cde 100644--- a/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsx+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-context-menu.tsx@@ -1,6 +1,12 @@import * as React from "react";import type { ColumnDef, TableMeta } from "@tanstack/react-table";-import { CircleOffIcon, EraserIcon } from "lucide-react";+import {+ CircleOffIcon,+ ClipboardPasteIcon,+ CopyIcon,+ EraserIcon,+ ScissorsIcon+} from "lucide-react";import { toast } from "sonner";import {@@ -32,6 +38,7 @@ export function DataGridContextMenu<TData>({const onRowsDelete = tableMeta?.onRowsDelete;const onCellsCopy = tableMeta?.onCellsCopy;const onCellsCut = tableMeta?.onCellsCut;+ const onCellsPaste = tableMeta?.onCellsPaste;if (!contextMenu.open) return null;@@ -48,6 +55,7 @@ export function DataGridContextMenu<TData>({onRowsDelete={onRowsDelete}onCellsCopy={onCellsCopy}onCellsCut={onCellsCut}+ onCellsPaste={onCellsPaste}/>);}@@ -62,6 +70,7 @@ interface ContextMenuProps<TData>| "onRowsDelete"| "onCellsCopy"| "onCellsCut"+ | "onCellsPaste"| "readOnly">,Required<Pick<TableMeta<TData>, "contextMenu">> {@@ -93,7 +102,8 @@ function ContextMenuImpl<TData>({onDataUpdate,onRowsDelete,onCellsCopy,- onCellsCut+ onCellsCut,+ onCellsPaste}: ContextMenuProps<TData>) {const propsRef = useAsRef({dataGridRef,@@ -102,6 +112,7 @@ function ContextMenuImpl<TData>({onRowsDelete,onCellsCopy,onCellsCut,+ onCellsPaste,columns});@@ -132,6 +143,18 @@ function ContextMenuImpl<TData>({[propsRef]);+ const onCopy = React.useCallback(() => {+ propsRef.current.onCellsCopy?.();+ }, [propsRef]);++ const onCut = React.useCallback(() => {+ propsRef.current.onCellsCut?.();+ }, [propsRef]);++ const onPaste = React.useCallback(() => {+ propsRef.current.onCellsPaste?.();+ }, [propsRef]);+const onClear = React.useCallback(() => {// eslint-disable-next-line @typescript-eslint/no-shadowconst { selectionState, columns, onDataUpdate } = propsRef.current;@@ -197,14 +220,32 @@ function ContextMenuImpl<TData>({className="min-w-[140px] p-0.5 [&_[role=menuitem]]:gap-1.5 [&_[role=menuitem]]:px-2 [&_[role=menuitem]]:py-1 [&_[role=menuitem]]:text-xs [&_svg]:size-3"onCloseAutoFocus={onCloseAutoFocus}>- <DropdownMenuItem onSelect={onClear} isDisabled={tableMeta?.readOnly}>- <EraserIcon />- Clear- </DropdownMenuItem>- <DropdownMenuItem onSelect={onSetNull} isDisabled={tableMeta?.readOnly}>- <CircleOffIcon />- Set NULL+ <DropdownMenuItem onSelect={onCopy}>+ <CopyIcon />+ Copy</DropdownMenuItem>+ {!tableMeta?.readOnly && (+ <>+ <DropdownMenuItem onSelect={onCut}>+ <ScissorsIcon />+ Cut+ </DropdownMenuItem>+ {tableMeta?.enablePaste && (+ <DropdownMenuItem onSelect={onPaste}>+ <ClipboardPasteIcon />+ Paste+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onSelect={onClear}>+ <EraserIcon />+ Clear+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={onSetNull}>+ <CircleOffIcon />+ Set NULL+ </DropdownMenuItem>+ </>+ )}</DropdownMenuContent></DropdownMenu>);diff --git a/frontend/src/components/v3/generic/DataGrid/data-grid-types.ts b/frontend/src/components/v3/generic/DataGrid/data-grid-types.tsindex c2e4e9cfaa..74637172ae 100644--- a/frontend/src/components/v3/generic/DataGrid/data-grid-types.ts+++ b/frontend/src/components/v3/generic/DataGrid/data-grid-types.ts@@ -117,6 +117,7 @@ declare module "@tanstack/react-table" {pasteDialog?: PasteDialogState;onPasteDialogOpenChange?: (open: boolean) => void;readOnly?: boolean;+ enablePaste?: boolean;}}diff --git a/frontend/src/components/v3/generic/DataGrid/use-data-grid.ts b/frontend/src/components/v3/generic/DataGrid/use-data-grid.tsindex 7a71d1c47f..963e78c8fe 100644--- a/frontend/src/components/v3/generic/DataGrid/use-data-grid.ts+++ b/frontend/src/components/v3/generic/DataGrid/use-data-grid.ts@@ -58,7 +58,6 @@ const SEARCH_SHORTCUT_KEY = "f";const NON_NAVIGABLE_COLUMN_IDS = ["select", "actions"];const DOMAIN_REGEX = /^[\w.-]+\.[a-z]{2,}(\/\S*)?$/i;-const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}.*)?$/;const TRUTHY_BOOLEANS = new Set(["true", "1", "yes", "checked"]);const VALID_BOOLEANS = new Set(["true", "false", "1", "0", "yes", "no", "checked", "unchecked"]);@@ -535,12 +534,14 @@ function useDataGrid<TData>({const cellVariant = cell.column.columnDef?.meta?.cell?.variant;let serializedValue = "";- if (cellVariant === "file" || cellVariant === "multi-select") {+ if (value === null || value === undefined) {+ serializedValue = "NULL";+ } else if (cellVariant === "file" || cellVariant === "multi-select") {serializedValue = value ? JSON.stringify(value) : "";} else if (value instanceof Date) {serializedValue = value.toISOString();} else {- serializedValue = String(value ?? "");+ serializedValue = String(value);}cellData.set(cellKey, serializedValue);@@ -632,12 +633,14 @@ function useDataGrid<TData>({const cellVariant = cell.column.columnDef?.meta?.cell?.variant;let serializedValue = "";- if (cellVariant === "file" || cellVariant === "multi-select") {+ if (value === null || value === undefined) {+ serializedValue = "NULL";+ } else if (cellVariant === "file" || cellVariant === "multi-select") {serializedValue = value ? JSON.stringify(value) : "";} else if (value instanceof Date) {serializedValue = value.toISOString();} else {- serializedValue = String(value ?? "");+ serializedValue = String(value);}cellData.set(cellKey, serializedValue);@@ -792,170 +795,134 @@ function useDataGrid<TData>({const cellOpts = column?.columnDef?.meta?.cell;const cellVariant = cellOpts?.variant;- let processedValue: unknown = pastedValue;+ const isNullValue = pastedValue === "NULL";+ let processedValue: unknown = isNullValue ? null : pastedValue;let shouldSkip = false;- switch (cellVariant) {- case "number": {- if (!pastedValue) {- processedValue = null;- } else {- const num = Number.parseFloat(pastedValue);- if (Number.isNaN(num)) shouldSkip = true;- else processedValue = num;- }- break;- }-- case "checkbox": {- if (!pastedValue) {- processedValue = false;- } else {- const lower = pastedValue.toLowerCase();- if (VALID_BOOLEANS.has(lower)) {- processedValue = TRUTHY_BOOLEANS.has(lower);+ if (!isNullValue)+ switch (cellVariant) {+ case "number": {+ if (!pastedValue) {+ processedValue = null;} else {- shouldSkip = true;+ const num = Number.parseFloat(pastedValue);+ if (Number.isNaN(num)) shouldSkip = true;+ else processedValue = num;}+ break;}- break;- }-- case "date": {- if (!pastedValue) {- processedValue = null;- } else {- const date = new Date(pastedValue);- if (Number.isNaN(date.getTime())) shouldSkip = true;- else processedValue = date;- }- break;- }- case "select": {- const options = cellOpts?.options ?? [];- if (!pastedValue) {- processedValue = "";- } else {- const matched = matchSelectOption(pastedValue, options);- if (matched) processedValue = matched;- else shouldSkip = true;+ case "checkbox": {+ if (!pastedValue) {+ processedValue = false;+ } else {+ const lower = pastedValue.toLowerCase();+ if (VALID_BOOLEANS.has(lower)) {+ processedValue = TRUTHY_BOOLEANS.has(lower);+ } else {+ shouldSkip = true;+ }+ }+ break;}- break;- }- case "multi-select": {- const options = cellOpts?.options ?? [];- let values: string[] = [];- try {- const parsed = JSON.parse(pastedValue);- if (Array.isArray(parsed)) {- values = parsed.filter((v): v is string => typeof v === "string");+ case "date": {+ if (!pastedValue) {+ processedValue = null;+ } else {+ const date = new Date(pastedValue);+ if (Number.isNaN(date.getTime())) shouldSkip = true;+ else processedValue = date;}- } catch {- values = pastedValue ? pastedValue.split(",").map((v) => v.trim()) : [];+ break;}- const validated = values- .map((v) => matchSelectOption(v, options))- .filter(Boolean) as string[];-- if (values.length > 0 && validated.length === 0) {- shouldSkip = true;- } else {- processedValue = validated;+ case "select": {+ const options = cellOpts?.options ?? [];+ if (!pastedValue) {+ processedValue = "";+ } else {+ const matched = matchSelectOption(pastedValue, options);+ if (matched) processedValue = matched;+ else shouldSkip = true;+ }+ break;}- break;- }- case "file": {- if (!pastedValue) {- processedValue = [];- } else {+ case "multi-select": {+ const options = cellOpts?.options ?? [];+ let values: string[] = [];try {const parsed = JSON.parse(pastedValue);- if (!Array.isArray(parsed)) {- shouldSkip = true;- } else {- const validFiles = parsed.filter(getIsFileCellData);- if (parsed.length > 0 && validFiles.length === 0) {- shouldSkip = true;- } else {- processedValue = validFiles;- }+ if (Array.isArray(parsed)) {+ values = parsed.filter((v): v is string => typeof v === "string");}} catch {+ values = pastedValue ? pastedValue.split(",").map((v) => v.trim()) : [];+ }++ const validated = values+ .map((v) => matchSelectOption(v, options))+ .filter(Boolean) as string[];++ if (values.length > 0 && validated.length === 0) {shouldSkip = true;+ } else {+ processedValue = validated;}+ break;}- break;- }- case "url": {- if (!pastedValue) {- processedValue = "";- } else {- const firstChar = pastedValue[0];- if (firstChar === "[" || firstChar === "{") {- shouldSkip = true;+ case "file": {+ if (!pastedValue) {+ processedValue = [];} else {try {- new URL(pastedValue);- processedValue = pastedValue;- } catch {- if (DOMAIN_REGEX.test(pastedValue)) {- processedValue = pastedValue;- } else {+ const parsed = JSON.parse(pastedValue);+ if (!Array.isArray(parsed)) {shouldSkip = true;+ } else {+ const validFiles = parsed.filter(getIsFileCellData);+ if (parsed.length > 0 && validFiles.length === 0) {+ shouldSkip = true;+ } else {+ processedValue = validFiles;+ }}+ } catch {+ shouldSkip = true;}}- }- break;- }-- default: {- if (!pastedValue) {- processedValue = "";break;}- if (ISO_DATE_REGEX.test(pastedValue)) {- const date = new Date(pastedValue);- if (!Number.isNaN(date.getTime())) {- processedValue = date.toLocaleDateString();- break;- }- }-- const firstChar = pastedValue[0];- if (- firstChar === "[" ||- firstChar === "{" ||- firstChar === "t" ||- firstChar === "f"- ) {- try {- const parsed = JSON.parse(pastedValue);-- if (Array.isArray(parsed)) {- if (parsed.length > 0 && parsed.every(getIsFileCellData)) {- processedValue = parsed.map((f) => f.name).join(", ");- } else if (parsed.every((v) => typeof v === "string")) {- processedValue = (parsed as string[]).join(", ");+ case "url": {+ if (!pastedValue) {+ processedValue = "";+ } else {+ const firstChar = pastedValue[0];+ if (firstChar === "[" || firstChar === "{") {+ shouldSkip = true;+ } else {+ try {+ new URL(pastedValue);+ processedValue = pastedValue;+ } catch {+ if (DOMAIN_REGEX.test(pastedValue)) {+ processedValue = pastedValue;+ } else {+ shouldSkip = true;+ }}- } else if (typeof parsed === "boolean") {- processedValue = parsed ? "Checked" : "Unchecked";- }- } catch {- const lower = pastedValue.toLowerCase();- if (lower === "true" || lower === "false") {- processedValue = lower === "true" ? "Checked" : "Unchecked";}}+ break;+ }++ default: {+ processedValue = pastedValue;}}- }if (shouldSkip) {cellsSkipped++;@@ -1984,6 +1951,9 @@ function useDataGrid<TData>({get readOnly() {return propsRef.current.readOnly;},+ get enablePaste() {+ return propsRef.current.enablePaste;+ },getIsCellSelected,getIsSearchMatch,getIsActiveSearchMatch,diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsxindex 20fcc43785..8b06b3ee5b 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx@@ -12,16 +12,6 @@ import {} from "lucide-react";import { Spinner } from "@app/components/v2";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle-} from "@app/components/v3/generic/AlertDialog";import { Button } from "@app/components/v3/generic/Button";import { cn } from "@app/components/v3/utils";import { useGetPamAccountById } from "@app/hooks/api/pam";@@ -29,9 +19,9 @@ 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, TableDetail, TableInfo } from "./data-explorer-types";+import type { SchemaInfo, TableInfo } from "./data-explorer-types";import { useDataExplorerSession } from "./use-data-explorer-session";-import { BROWSE_TAB_ID, useQueryTabs } from "./use-query-tabs";+import { useQueryTabs } from "./use-query-tabs";type Props = {reason?: string;@@ -48,26 +38,28 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {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 [selectedTable, setSelectedTable] = useState<string | null>(null);- const [tableDetail, setTableDetail] = useState<TableDetail | null>(null);const [isLoadingSchemas, setIsLoadingSchemas] = useState(false);const [isLoadingTables, setIsLoadingTables] = useState(false);- const [isLoadingDetail, setIsLoadingDetail] = useState(false);const [hasDisconnected, setHasDisconnected] = useState(false);const [disconnectReason, setDisconnectReason] = useState<string | null>(null);- const unsavedChangeCountRef = useRef(0);- const [pendingTableSwitch, setPendingTableSwitch] = useState<string | null>(null);const latestSchemaRequestRef = useRef(0);- const latestDetailRequestRef = useRef(0);+ const tabElRefs = useRef<Map<string, HTMLDivElement | null>>(new Map());const [approvalJustification, setApprovalJustification] = useState("");- const { tabs, activeTabId, atTabLimit, addTab, closeTab, setActiveTab, updateTabSql } =- useQueryTabs();- const [isInTransaction, setIsInTransaction] = useState(false);+ // 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,@@ -81,6 +73,8 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {handleMfaVerification,submitApprovalRequest,approvalRequestUrl,+ openConnection,+ closeConnection,fetchSchemas,fetchTables,fetchTableDetail,@@ -94,12 +88,47 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {accountName: account?.name ?? "",reason,onSessionEnd: (endReason?: string) => {- unsavedChangeCountRef.current = 0;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@@ -123,37 +152,6 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {// eslint-disable-next-line react-hooks/exhaustive-deps}, []);- // Load schemas when connected- const loadSchemas = useCallback(async () => {- setIsLoadingSchemas(true);- try {- const result = await fetchSchemas();- setSchemas(result);- // Determine the active schema- const hasPublic = result.find((s) => s.name === selectedSchema);- const activeSchema = hasPublic ? selectedSchema : (result[0]?.name ?? "public");- if (!hasPublic && result.length > 0) {- setSelectedSchema(activeSchema);- }- // Auto-load tables for the active schema- if (result.length > 0) {- setIsLoadingTables(true);- try {- const tableResult = await fetchTables(activeSchema);- setTables(tableResult);- } catch {- // Error handled by the hook- } finally {- setIsLoadingTables(false);- }- }- } catch {- // Error handled by the hook- } finally {- setIsLoadingSchemas(false);- }- }, [fetchSchemas, fetchTables, selectedSchema]);-const loadTables = useCallback(async (schema: string) => {// Guard against stale responses when the user switches schemas quickly.@@ -176,111 +174,107 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {[fetchTables]);- const loadTableDetail = useCallback(- async (schema: string, tableName: string) => {- latestDetailRequestRef.current += 1;- const requestId = latestDetailRequestRef.current;- setIsLoadingDetail(true);+ const loadSchemas = useCallback(+ async (keepSelected = false) => {+ setIsLoadingSchemas(true);try {- const result = await fetchTableDetail(schema, tableName);- if (latestDetailRequestRef.current !== requestId) return;- setTableDetail(result);+ 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 {- if (latestDetailRequestRef.current === requestId) {- setIsLoadingDetail(false);- }+ setIsLoadingSchemas(false);}},- [fetchTableDetail]+ [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 connectedconst wasConnectedRef = useRef(false);useEffect(() => {if (isConnected && !wasConnectedRef.current) {wasConnectedRef.current = true;setHasDisconnected(false);- loadSchemas();+ (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;}- }, [isConnected, loadSchemas]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isConnected]);const handleSchemaChange = useCallback((schema: string) => {setSelectedSchema(schema);- // Clear immediately so the grid doesn't fire a stale query- // against the new schema with the old table name.- setSelectedTable(null);- setTableDetail(null);loadTables(schema);},[loadTables]);- const handleTableSelect = useCallback(- (tableName: string) => {- if (tableName === selectedTable) {- setActiveTab(BROWSE_TAB_ID);- return;- }- if (unsavedChangeCountRef.current > 0) {- setPendingTableSwitch(tableName);- return;- }- setSelectedTable(tableName);- loadTableDetail(selectedSchema, tableName);- setActiveTab(BROWSE_TAB_ID);+ const handleTableOpen = useCallback(+ (tableName: string, opts: { forceNew: boolean }) => {+ openBrowseTab(selectedSchema, tableName, opts).catch(() => {});},- [selectedTable, selectedSchema, loadTableDetail, setActiveTab]+ [selectedSchema, openBrowseTab]);- const handleDiscardAndSwitch = useCallback(() => {- if (!pendingTableSwitch) return;- unsavedChangeCountRef.current = 0;- setSelectedTable(pendingTableSwitch);- loadTableDetail(selectedSchema, pendingTableSwitch);- setPendingTableSwitch(null);- setActiveTab(BROWSE_TAB_ID);- }, [pendingTableSwitch, selectedSchema, loadTableDetail, setActiveTab]);-- const handleFullRefresh = useCallback(async () => {- // 1. Re-fetch tables for current schema (picks up new/dropped tables)- setIsLoadingTables(true);- try {- const tableResult = await fetchTables(selectedSchema);- setTables(tableResult);-- // 2. If selected table was dropped, deselect and stop- if (selectedTable && !tableResult.find((t) => t.name === selectedTable)) {- setSelectedTable(null);- setTableDetail(null);- return;- }- } catch {- // Error handled by the hook- } finally {- setIsLoadingTables(false);- }-- // 3. Re-fetch table detail for current table (picks up column/PK changes)- if (selectedTable) {- await loadTableDetail(selectedSchema, selectedTable);- }- }, [selectedSchema, selectedTable, fetchTables, loadTableDetail]);-const handleReconnect = useCallback(() => {setHasDisconnected(false);setDisconnectReason(null);setSchemas([]);setTables([]);- setSelectedTable(null);- setTableDetail(null);+ resetTabs();reconnect();- }, [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) ---@@ -398,125 +392,151 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {// --- Main layout ---+ const tabOpeningDisabled = isOpeningTab || atTabLimit;+return (<div ref={mountRef} className="flex h-screen w-screen flex-col bg-bunker-800">- {/* Body */}<div className="flex flex-1 overflow-hidden"><DataExplorerSidebarschemas={schemas}selectedSchema={selectedSchema}onSchemaChange={handleSchemaChange}tables={tables}- selectedTable={selectedTable}- onTableSelect={handleTableSelect}+ activeBrowseTarget={activeBrowseTarget}+ onTableOpen={handleTableOpen}isLoadingSchemas={isLoadingSchemas}isLoadingTables={isLoadingTables}+ disabled={isOpeningTab}/><div className="flex flex-1 flex-col overflow-hidden">- <div className="flex thin-scrollbar shrink-0 items-center overflow-x-auto border-b border-mineshaft-600 bg-mineshaft-800 [&::-webkit-scrollbar]:h-1">- <button- type="button"- onClick={() => setActiveTab(BROWSE_TAB_ID)}- className={cn(- "flex shrink-0 items-center gap-1.5 border-b-2 px-4 py-2 text-xs font-medium transition-colors",- activeTabId === BROWSE_TAB_ID- ? "border-info text-mineshaft-100"- : "border-transparent text-mineshaft-400 hover:text-mineshaft-200"- )}- >- <TableIcon className="size-3.5" />- Browse- </button>-- {tabs.map((tab) => (- <div- key={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",- activeTabId === tab.id- ? "border-info text-mineshaft-100"- : "border-transparent text-mineshaft-400 hover:text-mineshaft-200"- )}- >- <span className="flex items-center gap-1.5">- <TerminalSquareIcon className="size-3.5" />- {tab.title}- </span>- <button- type="button"- onClick={(e) => {- e.stopPropagation();- closeTab(tab.id);+ <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);}}- className="ml-1 rounded p-0.5 text-mineshaft-300 transition-colors hover:text-mineshaft-100"- aria-label={`Close ${tab.title}`}+ 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"+ )}>- <XIcon className="size-3" />- </button>- </div>- ))}+ <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>+ );+ })}<buttontype="button"- onClick={addTab}- disabled={atTabLimit}- 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 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"+ 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>- <div- className={cn("flex flex-1 overflow-hidden", activeTabId !== BROWSE_TAB_ID && "hidden")}- >- {selectedTable ? (- <DataExplorerGrid- key={`${selectedSchema}.${selectedTable}`}- tableDetail={tableDetail}- tableType={tables.find((t) => t.name === selectedTable)?.tableType}- schema={selectedSchema}- table={selectedTable}- executeQuery={executeQuery}- isLoading={isLoadingDetail}- onChangeCountUpdate={(count) => {- unsavedChangeCountRef.current = count;- }}- onFullRefresh={handleFullRefresh}- />- ) : (- <div className="flex flex-1 items-center justify-center">- <div className="text-center">- <DatabaseIcon className="mx-auto mb-3 size-12 text-mineshaft-600" />- <p className="text-sm text-mineshaft-400">- Select a table from the sidebar to browse data- </p>- </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>- )}- </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.map((tab) => (- <div- key={tab.id}- className={cn("flex flex-1 overflow-hidden", activeTabId !== tab.id && "hidden")}- >- <QueryPanel- tab={tab}- executeQuery={executeQuery}- cancelQuery={cancelQuery}- isInTransaction={isInTransaction}- onSqlChange={(sql) => updateTabSql(tab.id, sql)}- onTransactionStateChange={setIsInTransaction}- />+ {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>@@ -537,28 +557,6 @@ export const PamDataExplorerPage = ({ reason }: Props = {}) => {</span></div></div>-- <AlertDialog- open={pendingTableSwitch !== null}- onOpenChange={(open) => {- if (!open) setPendingTableSwitch(null);- }}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Unsaved changes</AlertDialogTitle>- <AlertDialogDescription>- Table contains unsaved changes. Do you want to discard them?- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="danger" onClick={handleDiscardAndSwitch}>- Discard changes- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog></div>);};diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsxindex 2245fb425d..269dbffe48 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import type { CellContext, ColumnDef, HeaderContext } from "@tanstack/react-table";import { EyeIcon } from "lucide-react";@@ -28,7 +28,11 @@ type DataExplorerGridProps = {tableType?: string;schema: string;table: string;- executeQuery: (sql: string) => Promise<{+ connectionId: string;+ executeQuery: (+ connectionId: string,+ sql: string+ ) => Promise<{rows: Record<string, unknown>[];fields: FieldInfo[];rowCount: number | null;@@ -36,8 +40,7 @@ type DataExplorerGridProps = {executionTimeMs: number;}>;isLoading: boolean;- onChangeCountUpdate?: (count: number) => void;- onFullRefresh?: () => Promise<void>;+ onRefresh?: () => Promise<void>;};const ROW_KEY_PREFIX = "__new_";@@ -175,10 +178,10 @@ export const DataExplorerGrid = ({tableType,schema,table,+ connectionId,executeQuery,isLoading,- onChangeCountUpdate,- onFullRefresh+ onRefresh}: DataExplorerGridProps) => {const [originalData, setOriginalData] = useState<Record<string, unknown>[]>([]);const [currentData, setCurrentData] = useState<Record<string, unknown>[]>([]);@@ -238,8 +241,8 @@ export const DataExplorerGrid = ({// 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(selectSql),- executeQuery(countSql)+ executeQuery(connectionId, selectSql),+ executeQuery(connectionId, countSql)]);const taggedRows = dataResult.rows.map((row: Record<string, unknown>) => ({@@ -267,7 +270,7 @@ export const DataExplorerGrid = ({setIsDataLoading(false);}},- [tableDetail, schema, table, primaryKeys, executeQuery]+ [tableDetail, schema, table, primaryKeys, executeQuery, connectionId]);// Fetch data when filters/sorts/pagination change.@@ -350,10 +353,6 @@ export const DataExplorerGrid = ({return count;}, [currentData, originalDataByPk, primaryKeys, newRowTempIds, tableColumns]);- useEffect(() => {- onChangeCountUpdate?.(changeCount);- }, [changeCount, onChangeCountUpdate]);-const handleAddRecord = useCallback(() => {newRowCounterRef.current += 1;const tempId = `${ROW_KEY_PREFIX}${newRowCounterRef.current}`;@@ -401,7 +400,7 @@ export const DataExplorerGrid = ({if (deleteStatements.length > 0) {try {const sql = wrapInTransaction(deleteStatements);- await executeQuery(sql);+ await executeQuery(connectionId, sql);createNotification({text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,type: "success"@@ -424,6 +423,7 @@ export const DataExplorerGrid = ({primaryKeys,schema,table,+ connectionId,executeQuery,fetchData,offset,@@ -506,7 +506,7 @@ export const DataExplorerGrid = ({return;}- await executeQuery(sql);+ await executeQuery(connectionId, sql);createNotification({text: `Saved ${statements.length} change${statements.length !== 1 ? "s" : ""}`,type: "success"@@ -530,6 +530,7 @@ export const DataExplorerGrid = ({primaryKeys,schema,table,+ connectionId,executeQuery,fetchData,offset,@@ -642,7 +643,7 @@ export const DataExplorerGrid = ({if (deleteStatements.length > 0) {try {const sql = wrapInTransaction(deleteStatements);- await executeQuery(sql);+ await executeQuery(connectionId, sql);createNotification({text: `Deleted ${deleteStatements.length} row${deleteStatements.length !== 1 ? "s" : ""}`,type: "success"@@ -663,7 +664,18 @@ export const DataExplorerGrid = ({gridRef.current?.resetRowSelection();selectedRowsRef.current = [];setSelectedRowCount(0);- }, [schema, table, primaryKeys, executeQuery, fetchData, offset, pageSize, filters, sorts]);+ }, [+ schema,+ table,+ primaryKeys,+ connectionId,+ executeQuery,+ fetchData,+ offset,+ pageSize,+ filters,+ sorts+ ]);if (!tableDetail) {return (@@ -697,7 +709,7 @@ export const DataExplorerGrid = ({hasPrimaryKey={hasPrimaryKey}isDataLoading={isDataLoading}onRefresh={async () => {- if (onFullRefresh) await onFullRefresh();+ if (onRefresh) await onRefresh();await fetchData(offset, pageSize, filters, sorts);}}isRefreshing={isDataLoading && hasLoaded}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsxindex 9b66228934..66920b1b05 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerSidebar.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { DatabaseIcon, SearchIcon, TableIcon, ViewIcon } from "lucide-react";import { Input } from "@app/components/v3/generic/Input";@@ -14,15 +14,24 @@ 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[];- selectedTable: string | null;- onTableSelect: (table: string) => void;+ 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 = ({@@ -30,18 +39,40 @@ export const DataExplorerSidebar = ({selectedSchema,onSchemaChange,tables,- selectedTable,- onTableSelect,+ activeBrowseTarget,+ onTableOpen,isLoadingSchemas,- isLoadingTables+ isLoadingTables,+ disabled = false}: DataExplorerSidebarProps) => {const [search, setSearch] = useState("");+ const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);+ const menuRef = useRef<HTMLDivElement>(null);// Reset search when schema changesuseEffect(() => {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) => {@@ -51,6 +82,24 @@ export const DataExplorerSidebar = ({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 */}@@ -58,7 +107,7 @@ export const DataExplorerSidebar = ({{isLoadingSchemas ? (<Skeleton className="h-8 w-full" />) : (- <Select value={selectedSchema} onValueChange={onSchemaChange}>+ <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" />@@ -102,25 +151,48 @@ export const DataExplorerSidebar = ({)}{!isLoadingTables && filteredTables.length > 0 && (<div className="p-1">- {filteredTables.map((t) => (- <button- key={t.name}- type="button"- onClick={() => onTableSelect(t.name)}- 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",- selectedTable === t.name && "bg-container-hover text-foreground"- )}- >- {getTableIcon(t.tableType)}- <span className="truncate" title={t.name}>- {t.name}- </span>- </button>- ))}+ {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/QueryPanel.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsxindex ab4204717e..8ba0b509d2 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/QueryPanel.tsx@@ -26,9 +26,8 @@ type QueryResult = {type Props = {tab: QueryTab;- executeQuery: (sql: string) => Promise<QueryResult>;- cancelQuery: () => void;- isInTransaction: boolean;+ executeQuery: (connectionId: string, sql: string) => Promise<QueryResult>;+ cancelQuery: (connectionId: string) => void;onSqlChange: (sql: string) => void;onTransactionStateChange: (open: boolean) => void;};@@ -37,7 +36,6 @@ export function QueryPanel({tab,executeQuery,cancelQuery,- isInTransaction,onSqlChange,onTransactionStateChange}: Props) {@@ -62,10 +60,13 @@ export function QueryPanel({setIsRunning(true);setError(null);try {- const res = await executeQuery(sqlToRun);+ 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);@@ -115,12 +116,12 @@ export function QueryPanel({<div className="flex h-full w-full flex-col overflow-hidden"><QueryToolbarisRunning={isRunning}- isInTransaction={isInTransaction}+ isInTransaction={tab.isInTransaction}hasSelection={hasSelection}onRun={handleRun}onCommit={handleCommit}onRollback={handleRollback}- onCancel={cancelQuery}+ onCancel={() => cancelQuery(tab.connectionId)}/><divref={containerRef}diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsxindex 0426094cd7..87b36729cd 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/SqlEditor.tsx@@ -3,7 +3,7 @@ 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, type ViewUpdate } from "@codemirror/view";+import { EditorView, keymap, placeholder, type ViewUpdate } from "@codemirror/view";import { tags } from "@lezer/highlight";const infisicalTheme = EditorView.theme({@@ -113,6 +113,7 @@ export function SqlEditor({...defaultKeymap]),maxSqlLength,+ placeholder("Start writing SQL..."),sql({ dialect: PostgreSQL }),infisicalTheme,syntaxHighlighting(infisicalHighlight),diff --git a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.tsindex 6ed264e1c8..0c423f56a5 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts+++ b/frontend/src/pages/pam/PamDataExplorerPage/data-explorer-types.ts@@ -1,18 +1,34 @@// WebSocket message types for the Postgres Data Explorerexport type DataExplorerClientMessage =+ // Metadata (no connectionId) — served by short-lived BE pg.Clients| { type: "get-schemas"; id: string }| { type: "get-tables"; id: string; schema: string }- | { type: "get-table-detail"; id: string; schema: string; table: string }- | { type: "query"; id: string; sql: 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; data: TableDetail }+ | {+ 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;@@ -21,9 +37,19 @@ export type DataExplorerServerMessage =command: string;executionTimeMs: number;}- | { type: "error"; id: string; error: string; detail?: string; hint?: string }- // Lifecycle messages (reused from terminal)- | { type: "ready"; data: string; prompt: string }+ | {+ 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 = {diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.tsindex 7ad045d708..8be7838fa2 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-data-explorer-session.ts@@ -16,6 +16,8 @@ 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 = {@@ -43,10 +45,28 @@ type UseDataExplorerSessionOptions = {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,projectId,@@ -54,7 +74,9 @@ export const useDataExplorerSession = ({resourceName,accountName,reason: accessReason,- onSessionEnd+ onSessionEnd,+ onConnectionClosed,+ onReconnected}: UseDataExplorerSessionOptions) => {const [isConnected, setIsConnected] = useState(false);const [isConnecting, setIsConnecting] = useState(false);@@ -68,10 +90,19 @@ export const useDataExplorerSession = ({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;@@ -104,6 +135,10 @@ export const useDataExplorerSession = ({setIsConnected(true);setIsConnecting(false);readyResolveRef.current?.();+ if (hasConnectedBeforeRef.current) {+ onReconnectedRef.current?.();+ }+ hasConnectedBeforeRef.current = true;return;}@@ -117,7 +152,22 @@ export const useDataExplorerSession = ({return;}- // Request-response correlation+ 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) {@@ -129,6 +179,8 @@ export const useDataExplorerSession = ({.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);}@@ -330,8 +382,10 @@ export const useDataExplorerSession = ({// --- Request helpers ---const sendRequest = useCallback(- // eslint-disable-next-line @typescript-eslint/no-explicit-any- async <T extends DataExplorerServerMessage>(msg: Record<string, any>): Promise<T> => {+ async <T extends DataExplorerServerMessage>(+ msg: Record<string, unknown>,+ opts?: { connectionId?: string }+ ): Promise<T> => {if (readyPromiseRef.current) {await readyPromiseRef.current;}@@ -348,7 +402,8 @@ export const useDataExplorerSession = ({pendingRequestsRef.current.set(id, {resolve: resolve as (m: DataExplorerServerMessage) => void,reject,- timer+ timer,+ connectionId: opts?.connectionId});const ws = wsRef.current;@@ -364,6 +419,35 @@ export const useDataExplorerSession = ({[]);+ 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"@@ -383,40 +467,33 @@ export const useDataExplorerSession = ({);const fetchTableDetail = useCallback(- async (schema: string, table: string): Promise<TableDetail> => {- const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "table-detail" }>>({- type: "get-table-detail",- schema,- table- });- return resp.data;+ 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(() => {+ const cancelQuery = useCallback((connectionId: string) => {const ws = wsRef.current;if (ws && ws.readyState === WebSocket.OPEN) {- ws.send(JSON.stringify({ type: "cancel" }));+ ws.send(JSON.stringify({ type: "cancel", connectionId }));}}, []);const executeQuery = useCallback(- async (- sql: string- ): Promise<{- rows: Record<string, unknown>[];- fields: FieldInfo[];- rowCount: number | null;- isTruncated: boolean;- transactionOpen: boolean;- command: string;- executionTimeMs: number;- }> => {- const resp = await sendRequest<Extract<DataExplorerServerMessage, { type: "query-result" }>>({- type: "query",- sql- });+ 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,@@ -430,8 +507,48 @@ export const useDataExplorerSession = ({[sendRequest]);- // No auto-connect here — the page component drives connection lifecycle,- // same as useWebAccessSession where containerEl gates the connect call.+ // 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,@@ -445,6 +562,8 @@ export const useDataExplorerSession = ({handleMfaVerification,submitApprovalRequest,approvalRequestUrl,+ openConnection,+ closeConnection,fetchSchemas,fetchTables,fetchTableDetail,diff --git a/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts b/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.tsindex 878cb968a3..5d488a827a 100644--- a/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts+++ b/frontend/src/pages/pam/PamDataExplorerPage/use-query-tabs.ts@@ -1,69 +1,308 @@-import { useState } from "react";+import { useCallback, useRef, useState } from "react";-export type QueryTab = {+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 TabState = {- tabs: QueryTab[];- activeTabId: string;- nextTabNumber: number;+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 BROWSE_TAB_ID = "browse";-const MAX_QUERY_TABS = 20;+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 DEFAULT_STATE: TabState = { tabs: [], activeTabId: BROWSE_TAB_ID, nextTabNumber: 1 };+ 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]);-export function useQueryTabs() {- const [state, setState] = useState<TabState>(DEFAULT_STATE);+ // 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 addTab = () => {- setState((prev) => {- if (prev.tabs.length >= MAX_QUERY_TABS) return prev;- const newTab: QueryTab = {- id: crypto.randomUUID(),- title: `Query ${prev.nextTabNumber}`,+ 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: ""- };- return {- tabs: [...prev.tabs, newTab],- activeTabId: newTab.id,- nextTabNumber: prev.nextTabNumber + 1- };- });- };+ }+ ]);+ setActiveTabId(id);+ return id;+ }, [acquireTabConnection]);- const closeTab = (id: string) => {- setState((prev) => {- const idx = prev.tabs.findIndex((t) => t.id === id);- const newTabs = prev.tabs.filter((t) => t.id !== id);- const newActiveId =- prev.activeTabId === id- ? (newTabs[idx - 1]?.id ?? newTabs[0]?.id ?? BROWSE_TAB_ID)- : prev.activeTabId;- return { ...prev, tabs: newTabs, activeTabId: newActiveId };- });- };+ 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 setActiveTab = (id: string) => setState((prev) => ({ ...prev, activeTabId: id }));+ const conn = await acquireTabConnection();+ if (!conn) return null;+ const id = crypto.randomUUID();- const updateTabSql = (id: string, sql: string) => {- setState((prev) => ({- ...prev,- tabs: prev.tabs.map((t) => (t.id === id ? { ...t, sql } : t))- }));- };+ // 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: state.tabs,- activeTabId: state.activeTabId,- atTabLimit: state.tabs.length >= MAX_QUERY_TABS,- addTab,+ tabs,+ activeTabId,+ atTabLimit,+ isOpeningTab,+ openQueryTab,+ openBrowseTab,closeTab,setActiveTab,- updateTabSql+ updateTabSql,+ setTabTransactionOpen,+ markConnectionDead,+ resetTabs,+ refreshBrowseTab,+ MAX_TABS};-}+};