Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

207 KB
Raw Blame
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { canTreeNodeShowExpander } from "@/lib/sidebar/sidebarTreeItemLayout";
import { filterLocallySearchedTables } from "@/lib/sidebar/sidebarSearchTree";
import { encodeSchemaTreeCache } from "@/lib/metadata/schemaTreeCache";
import type { ConnectionConfig, ObjectInfo, TableInfo, TreeNode } from "@/types/database";

function installLocalStorage() {
  const data = new Map<string, string>();
  vi.stubGlobal("localStorage", {
    getItem: vi.fn((key: string) => data.get(key) ?? null),
    setItem: vi.fn((key: string, value: string) => data.set(key, value)),
    removeItem: vi.fn((key: string) => data.delete(key)),
  });
}

// Mirrors SIDEBAR_TABLE_SEARCH_RESULT_BUDGET in connectionStore.ts (4× the
// default sidebar_table_page_size of 500). Kept as a local constant because
// connectionStore must stay dynamically imported for vi.doMock isolation.
const SIDEBAR_SEARCH_RESULT_BUDGET = 2000;

function postgresConnection(): ConnectionConfig {
  return {
    id: "pg-1",
    name: "Postgres",
    db_type: "postgres",
    host: "127.0.0.1",
    port: 5432,
    username: "postgres",
    password: "",
    database: "app",
  } as ConnectionConfig;
}

function mysqlConnection(): ConnectionConfig {
  return {
    id: "mysql-1",
    name: "MySQL",
    db_type: "mysql",
    host: "127.0.0.1",
    port: 3306,
    username: "root",
    password: "",
    database: "app",
  } as ConnectionConfig;
}

function doltConnection(): ConnectionConfig {
  return {
    ...mysqlConnection(),
    id: "dolt-1",
    name: "Dolt",
    driver_profile: "dolt",
    external_config: { doltShowSystemTables: true },
  } as ConnectionConfig;
}

function dorisConnection(): ConnectionConfig {
  return {
    ...mysqlConnection(),
    id: "doris-1",
    name: "Doris",
    db_type: "doris",
    port: 9030,
  } as ConnectionConfig;
}

function oracleConnection(): ConnectionConfig {
  return {
    id: "oracle-1",
    name: "Oracle",
    db_type: "oracle",
    host: "127.0.0.1",
    port: 1521,
    username: "SYSTEM",
    password: "",
    database: "XE",
  } as ConnectionConfig;
}

function xuguConnection(): ConnectionConfig {
  return {
    id: "xugu-1",
    name: "XuguDB",
    db_type: "xugu",
    host: "127.0.0.1",
    port: 5138,
    username: "app_user",
    password: "",
    database: "app_db",
  } as ConnectionConfig;
}

function sundbConnection(): ConnectionConfig {
  return {
    id: "sundb-1",
    name: "SUNDB",
    db_type: "sundb",
    host: "10.156.156.86",
    port: 22581,
    username: "app_user",
    password: "",
    database: "vpnccw",
  } as ConnectionConfig;
}

function genericJdbcConnection(): ConnectionConfig {
  return {
    id: "jdbc-1",
    name: "Generic JDBC",
    db_type: "jdbc",
    host: "127.0.0.1",
    port: 0,
    username: "app",
    password: "",
    database: "testdb",
    driver_profile: "jdbc",
    connection_string: "jdbc:example://127.0.0.1/testdb",
  } as ConnectionConfig;
}

function oracleJdbcConnection(): ConnectionConfig {
  return {
    ...genericJdbcConnection(),
    id: "jdbc-oracle-1",
    name: "Oracle JDBC",
    username: "DBX_TEST",
    database: undefined,
    connection_string: "jdbc:oracle:thin:@//127.0.0.1:1521/XE",
    jdbc_driver_class: "oracle.jdbc.OracleDriver",
  } as ConnectionConfig;
}

function informixConnection(): ConnectionConfig {
  return {
    id: "informix-1",
    name: "Informix",
    db_type: "informix",
    host: "127.0.0.1",
    port: 9088,
    username: "informix",
    password: "",
    database: "prulife",
  } as ConnectionConfig;
}

function gbase8sConnection(): ConnectionConfig {
  return {
    ...informixConnection(),
    id: "gbase8s-1",
    name: "GBase 8s",
    db_type: "gbase8s",
    driver_profile: "gbase8s",
    database: "dbx_test",
  } as ConnectionConfig;
}

function procedure(name: string): ObjectInfo {
  return {
    name,
    object_type: "PROCEDURE",
    schema: "app",
    comment: null,
    created_at: null,
    updated_at: null,
    parent_schema: null,
    parent_name: null,
  };
}

describe("connectionStore metadata loading", () => {
  beforeEach(() => {
    vi.resetModules();
    vi.unstubAllGlobals();
    installLocalStorage();
    setActivePinia(createPinia());
  });

  it.each([
    ["oracle", "group-triggers"],
    ["oceanbase-oracle", "group-triggers"],
    ["dameng", "group-triggers"],
    ["jdbc", "group-triggers"],
    ["oracle", "schema"],
    ["oceanbase-oracle", "schema"],
    ["dameng", "schema"],
    ["jdbc", "schema"],
  ] as const)(
    "keeps exact trigger identity in remote sidebar search (%s/%s)",
    async (dbType, nodeType) => {
      const owner = " Trigger.Owner ",
        name = ' Tr"igger ';
      const metadata = { contractVersion: 1, identityMode: "exact", engine: dbType === "dameng" ? "dm" : dbType === "jdbc" ? "oracle" : dbType, owner, name, objectId: "9007199254740993", scope: "SCHEMA", parent: null };
      const row = { ...procedure(name), name, schema: owner, object_type: "TRIGGER", trigger: { name, oracle_metadata: metadata } } as ObjectInfo;
      const listObjects = vi.fn().mockResolvedValue([row]);
      vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
      vi.doMock("@/lib/backend/api", () => ({ listObjects, cancelQuery: vi.fn(), listInstalledAgents: vi.fn().mockResolvedValue([]) }));
      const { MetadataResultCache } = await import("@/lib/metadata/metadataResultCache");
      const cachedRead = vi.spyOn(MetadataResultCache.prototype, "get");
      const { useConnectionStore } = await import("@/stores/connectionStore");
      const store = useConnectionStore();
      const connection = { ...postgresConnection(), id: "remote-trigger", db_type: dbType, ...(dbType === "jdbc" ? { database_info: { productName: "Oracle" } } : {}) } as ConnectionConfig;
      store.connections = [connection];
      store.connectedIds.add(connection.id);
      const node: TreeNode = { id: "trigger-group", label: "Triggers", type: nodeType, connectionId: connection.id, database: "service", schema: owner, catalog: "catalog-a" };
      const children = await store.searchSidebarObjects(node, "igger", new AbortController().signal);
      expect(listObjects).toHaveBeenCalledWith(connection.id, "service", owner, expect.arrayContaining(["TRIGGER"]), "igger", expect.any(Number), 0, "catalog-a", undefined, expect.stringMatching(/^sidebar-search-/), { identityMode: "exact", catalog: "catalog-a" });
      expect(children).toHaveLength(1);
      expect(children[0]).toMatchObject({ objectName: name, schema: owner, catalog: "catalog-a", meta: { oracle_metadata: metadata } });
      expect(cachedRead).toHaveBeenCalledWith(expect.objectContaining({ kind: "sidebar-object-search-page", extra: { catalog: "catalog-a", oracleTriggerContract: 1 } }), { allowStale: true });
      cachedRead.mockRestore();
    },
    15_000,
  );

  // Dynamic import of the merged connectionStore plus the scoped metadata
  // load can exceed Vitest's 5s default on slower CI runners; the assertion
  // is deterministic, so allow a wider timeout.
  it("loads Xugu package members through the scoped completion endpoint", async () => {
    const completionAssistantSearch = vi.fn().mockResolvedValue({
      candidates: [
        { name: "process_item", kind: "procedure", signature: "p_id IN INT" },
        { name: "process_item", kind: "procedure", signature: "p_code IN VARCHAR" },
        { name: "item_count", kind: "function", data_type: "INT" },
      ],
      incomplete: false,
      fallback_used: false,
    });
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      completionAssistantSearch,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = xuguConnection();
    const packageNode: TreeNode = {
      id: "xugu-1:app_db:app_schema:package:business_api",
      label: "business_api",
      type: "package",
      connectionId: connection.id,
      database: "app_db",
      schema: "app_schema",
      children: [],
      isExpanded: true,
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);
    store.treeNodes = [packageNode];

    await store.loadPackageMembers(packageNode);

    expect(completionAssistantSearch).toHaveBeenCalledWith({
      connection_id: connection.id,
      database: "app_db",
      schema: "app_schema",
      object_kinds: ["routine"],
      mask: "",
      case_sensitive: true,
      global_search: false,
      max_results: 1000,
      search_in_comments: false,
      search_in_definitions: false,
      parent_schema: "app_schema",
      parent_name: "business_api",
      parent_type: "package",
      match_mode: "prefix",
    });
    expect(packageNode.isExpanded).toBe(true);
    expect(packageNode.children?.map((child) => [child.type, child.label, child.objectCount])).toEqual([
      ["group-procedures", "tree.procedures", 2],
      ["group-functions", "tree.functions", 1],
    ]);
    expect(packageNode.children?.flatMap((group) => group.children ?? []).map((child) => child.label)).toEqual(["process_item(p_id IN INT)", "process_item(p_code IN VARCHAR)", "item_count"]);
    expect(packageNode.children?.flatMap((group) => group.children ?? []).every((child) => child.parentName === "business_api")).toBe(true);

    completionAssistantSearch.mockResolvedValueOnce({
      candidates: [{ name: "next_item", kind: "function", data_type: "INT" }],
      incomplete: false,
      fallback_used: false,
    });
    const functionGroup = packageNode.children?.find((child) => child.type === "group-functions");
    await store.refreshTreeNode(functionGroup!);

    expect(completionAssistantSearch).toHaveBeenCalledTimes(2);
    expect(packageNode.children?.map((child) => [child.type, child.objectCount])).toEqual([["group-functions", 1]]);
    expect(packageNode.children?.[0]?.children?.map((child) => child.label)).toEqual(["next_item"]);
  }, 15000);

  it("loads Xugu object type members through the scoped completion endpoint", async () => {
    const completionAssistantSearch = vi.fn(async (request: { object_kinds?: string[] }) => ({
      candidates: request.object_kinds?.includes("column")
        ? [
            { name: "street", kind: "column", data_type: "VARCHAR(120)" },
            { name: "created_at", kind: "column", data_type: "DATETIME" },
          ]
        : [{ name: "format", kind: "function", signature: "p_locale IN VARCHAR", data_type: "VARCHAR" }],
      incomplete: false,
      fallback_used: false,
    }));
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({ checkConnectionHealth: vi.fn().mockResolvedValue(undefined), completionAssistantSearch }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = xuguConnection();
    const typeNode: TreeNode = {
      id: "xugu-1:app_db:app_schema:type:address_t",
      label: "ADDRESS_T",
      type: "type",
      objectName: "ADDRESS_T",
      connectionId: connection.id,
      database: "app_db",
      schema: "app_schema",
      xuguTypeMembersExpandable: true,
      children: [],
      isExpanded: false,
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);
    store.treeNodes = [typeNode];

    await store.loadXuguTypeMembers(typeNode);

    expect(completionAssistantSearch).toHaveBeenCalledTimes(2);
    expect(completionAssistantSearch).toHaveBeenCalledWith(
      expect.objectContaining({
        connection_id: connection.id,
        database: "app_db",
        schema: "app_schema",
        object_kinds: ["column"],
        parent_schema: "app_schema",
        parent_name: "ADDRESS_T",
        parent_type: "type",
      }),
    );
    expect(completionAssistantSearch).toHaveBeenCalledWith(
      expect.objectContaining({
        connection_id: connection.id,
        database: "app_db",
        schema: "app_schema",
        object_kinds: ["routine"],
        parent_schema: "app_schema",
        parent_name: "ADDRESS_T",
        parent_type: "type",
      }),
    );
    expect(typeNode.isExpanded).toBe(true);
    expect(typeNode.children?.map((child) => ({ label: child.label, objectCount: child.objectCount }))).toEqual([
      { label: "tree.attributes", objectCount: 2 },
      { label: "tree.methods", objectCount: 1 },
    ]);
    expect(typeNode.children?.[0].children?.map((child) => child.label)).toEqual(["street (VARCHAR(120))", "created_at (DATETIME)"]);
    expect(typeNode.children?.[1].children?.map((child) => child.label)).toEqual(["FUNCTION format(p_locale IN VARCHAR) → VARCHAR"]);
    expect(typeNode.children?.every((child) => child.parentName === "ADDRESS_T")).toBe(true);
  }, 15000);

  it("keeps expanded Xugu type members loaded during forced tree refresh", async () => {
    const completionAssistantSearch = vi.fn(async (request: { object_kinds?: string[] }) => ({
      candidates: request.object_kinds?.includes("column") ? [{ name: "street", kind: "column", data_type: "VARCHAR(120)" }] : [],
      incomplete: false,
      fallback_used: false,
    }));
    const getCustomTypeDetails = vi.fn().mockRejectedValue(new Error("custom type loader must not be called for Xugu types"));
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      completionAssistantSearch,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      getCustomTypeDetails,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = xuguConnection();
    const typeNode: TreeNode = {
      id: "xugu-1:app_db:app_schema:type:address_t",
      label: "ADDRESS_T",
      type: "type",
      objectName: "ADDRESS_T",
      connectionId: connection.id,
      database: "app_db",
      schema: "app_schema",
      xuguTypeMembersExpandable: true,
      children: [],
      isExpanded: false,
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);
    store.treeNodes = [typeNode];

    await store.refreshTreeNode(typeNode);

    expect(getCustomTypeDetails).not.toHaveBeenCalled();
    expect(completionAssistantSearch).toHaveBeenCalledTimes(2);
    expect(typeNode.children?.map((child) => [child.type, child.objectCount])).toEqual([["type-attributes", 1]]);
    expect(typeNode.isExpanded).toBe(true);
  }, 15000);

  it("hides the Xugu type expander after loading no members", async () => {
    const completionAssistantSearch = vi.fn().mockResolvedValue({ candidates: [], incomplete: false, fallback_used: false });
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({ checkConnectionHealth: vi.fn().mockResolvedValue(undefined), completionAssistantSearch }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = xuguConnection();
    const typeNode: TreeNode = {
      id: "xugu-1:app_db:app_schema:type:empty_t",
      label: "EMPTY_T",
      type: "type",
      objectName: "EMPTY_T",
      connectionId: connection.id,
      database: "app_db",
      schema: "app_schema",
      xuguTypeMembersExpandable: true,
      children: [],
      isExpanded: false,
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);
    store.treeNodes = [typeNode];

    await store.loadXuguTypeMembers(typeNode);

    expect(completionAssistantSearch).toHaveBeenCalledTimes(2);
    expect(typeNode.children).toEqual([]);
    expect(typeNode.isExpanded).toBe(false);
    expect(typeNode.xuguTypeMembersExpandable).toBe(false);
    expect(
      canTreeNodeShowExpander({
        type: typeNode.type,
        childCount: typeNode.children?.length ?? 0,
        explicitContainer: typeNode.xuguTypeMembersExpandable === true,
      }),
    ).toBe(false);
  }, 15000);

  it("preserves loaded Xugu type members when a search projection collapses the type", async () => {
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({ checkConnectionHealth: vi.fn().mockResolvedValue(undefined) }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = xuguConnection();
    const typeNode: TreeNode = {
      id: "xugu-1:app_db:app_schema:type:address_t",
      label: "ADDRESS_T",
      type: "type",
      objectName: "ADDRESS_T",
      connectionId: connection.id,
      database: "app_db",
      schema: "app_schema",
      xuguTypeMembersExpandable: true,
      isExpanded: true,
      children: Array.from({ length: 400 }, (_, index) => ({
        id: `xugu-1:app_db:app_schema:type:address_t:attribute:${index}`,
        label: `attribute_${index}`,
        type: "type-attribute" as const,
        connectionId: connection.id,
        database: "app_db",
        schema: "app_schema",
      })),
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);
    store.treeNodes = [typeNode];

    await store.loadXuguTypeMembers(typeNode, { preserveCollapsedChildren: true });

    expect(typeNode.isExpanded).toBe(false);
    expect(typeNode.children).toHaveLength(400);
  });

  it("loads Oracle package overloads through the shared package member path", async () => {
    const completionAssistantSearch = vi.fn().mockResolvedValue({
      candidates: [
        { name: "CALCULATE", kind: "procedure", signature: "P_VALUE IN NUMBER" },
        { name: "CALCULATE", kind: "procedure", signature: "P_VALUE IN VARCHAR2" },
        { name: "ITEM_COUNT", kind: "function", data_type: "NUMBER" },
      ],
      incomplete: false,
      fallback_used: false,
    });
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({ checkConnectionHealth: vi.fn().mockResolvedValue(undefined), completionAssistantSearch }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = oracleConnection();
    const packageNode: TreeNode = {
      id: "oracle-1:XE:APP:package:BUSINESS_API",
      label: "BUSINESS_API",
      type: "package",
      connectionId: connection.id,
      database: "XE",
      schema: "APP",
      children: [],
      isExpanded: false,
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);
    store.treeNodes = [packageNode];

    await store.loadPackageMembers(packageNode);

    expect(completionAssistantSearch).toHaveBeenCalledWith({
      connection_id: connection.id,
      database: "XE",
      schema: "APP",
      object_kinds: ["routine"],
      mask: "",
      case_sensitive: true,
      global_search: false,
      max_results: 1000,
      search_in_comments: false,
      search_in_definitions: false,
      parent_schema: "APP",
      parent_name: "BUSINESS_API",
      match_mode: "prefix",
    });
    expect(packageNode.isExpanded).toBe(true);
    expect(packageNode.children?.map((child) => child.label)).toEqual(["CALCULATE(P_VALUE IN NUMBER)", "CALCULATE(P_VALUE IN VARCHAR2)", "ITEM_COUNT"]);
  }, 15000);

  it("does not query package members for unsupported databases", async () => {
    const completionAssistantSearch = vi.fn();
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({ checkConnectionHealth: vi.fn().mockResolvedValue(undefined), completionAssistantSearch }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = { ...xuguConnection(), id: "dameng-1", db_type: "dameng" } as ConnectionConfig;
    const packageNode: TreeNode = {
      id: "dameng-1:APP:package:BUSINESS_API",
      label: "BUSINESS_API",
      type: "package",
      connectionId: connection.id,
      database: "APP",
      schema: "APP",
      children: [],
      isExpanded: false,
    };
    store.connections = [connection];
    store.connectedIds = new Set([connection.id]);

    await store.loadPackageMembers(packageNode);

    expect(completionAssistantSearch).not.toHaveBeenCalled();
    expect(packageNode.isExpanded).toBe(false);
  }, 15000);

  it("loads missing database roots only for connected sidebar search targets", async () => {
    const checkConnectionHealth = vi.fn().mockResolvedValue(undefined);
    const listDatabases = vi.fn().mockResolvedValue([{ name: "dajia", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { filterSidebarTree } = await import("@/lib/sidebar/sidebarSearchTree");
    const store = useConnectionStore();
    const active = { ...mysqlConnection(), id: "mysql-active", name: "localhost" };
    const connected = { ...mysqlConnection(), id: "mysql-connected", name: "PLM-PRO" };
    const disconnected = { ...mysqlConnection(), id: "mysql-disconnected", name: "offline" };
    const nodes: TreeNode[] = [
      {
        id: active.id,
        label: active.name,
        type: "connection",
        connectionId: active.id,
        isExpanded: true,
        children: [{ id: `${active.id}:dajia`, label: "dajia", type: "database", connectionId: active.id, database: "dajia", isExpanded: false }],
      },
      { id: connected.id, label: connected.name, type: "connection", connectionId: connected.id, isExpanded: false, children: [] },
      { id: disconnected.id, label: disconnected.name, type: "connection", connectionId: disconnected.id, isExpanded: false, children: [] },
    ];
    store.connections = [active, connected, disconnected];
    store.connectedIds = new Set([active.id, connected.id]);
    store.activeConnectionId = active.id;
    store.treeNodes = nodes;

    await Promise.all(nodes.map((node) => store.loadConnectedConnectionRootForSidebarSearch(node.connectionId!)));

    expect(listDatabases).toHaveBeenCalledTimes(1);
    expect(listDatabases).toHaveBeenCalledWith(connected.id);
    expect(checkConnectionHealth).not.toHaveBeenCalled();
    expect(store.activeConnectionId).toBe(active.id);
    expect(nodes.map((node) => node.isExpanded)).toEqual([true, false, false]);
    expect(filterSidebarTree(nodes, "dajia", new Set()).map((node) => node.id)).toEqual([active.id, connected.id]);
  }, 10_000);

  it("does not collapse a connection whose normal root load is already in flight", async () => {
    let resolveDatabases!: (databases: Array<{ name: string; comment: null }>) => void;
    let markListStarted!: () => void;
    const listStarted = new Promise<void>((resolve) => {
      markListStarted = resolve;
    });
    const listDatabases = vi.fn(
      () =>
        new Promise<Array<{ name: string; comment: null }>>((resolve) => {
          resolveDatabases = resolve;
          markListStarted();
        }),
    );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = mysqlConnection();
    const node: TreeNode = { id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [node];

    const normalLoad = store.loadDatabases(connection.id);
    await listStarted;
    const searchLoad = store.loadConnectedConnectionRootForSidebarSearch(connection.id);
    let searchLoadSettled = false;
    void searchLoad.finally(() => {
      searchLoadSettled = true;
    });
    await Promise.resolve();

    expect(searchLoadSettled).toBe(false);

    resolveDatabases([{ name: "dajia", comment: null }]);
    await Promise.all([normalLoad, searchLoad]);

    expect(listDatabases).toHaveBeenCalledTimes(1);
    expect(node.isExpanded).toBe(true);
  }, 10_000);

  it("discovers schema nodes for unknown generic JDBC databases", async () => {
    const listSchemaInfos = vi.fn().mockResolvedValue([
      { name: "app", comment: null },
      { name: "reporting", comment: null },
    ]);
    const listTables = vi.fn().mockResolvedValue([]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listSchemaInfos,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = genericJdbcConnection();
    const databaseNode: TreeNode = { id: "jdbc-1:testdb", label: "testdb", type: "database", connectionId: connection.id, database: "testdb", isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: true, children: [databaseNode] }];

    await store.loadTreeNodeChildren(databaseNode, { force: true });

    expect(listSchemaInfos).toHaveBeenCalledWith(connection.id, "testdb");
    expect(listTables).not.toHaveBeenCalled();
    expect(databaseNode.children?.map((node) => [node.type, node.label, node.schema])).toEqual([
      ["schema", "app", "app"],
      ["schema", "reporting", "reporting"],
      ["saved-sql-root", "tree.queries", undefined],
    ]);
  });

  it("loads SunDB tables under the discovered schema instead of the catalog name", async () => {
    // SUNDB's database is a catalog, and the driver matches getTables' schemaPattern
    // literally, so sending the catalog name returned zero rows and the sidebar showed
    // an empty "表 0" node (issue #11360). The database node must discover schemas and
    // every table request must carry that schema.
    const listSchemaInfos = vi.fn().mockResolvedValue([{ name: "APP", comment: null }]);
    const listTables = vi.fn().mockResolvedValue([{ name: "ITEMS", table_type: "TABLE", comment: null }]);
    const listObjects = vi.fn().mockResolvedValue([]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listSchemaInfos,
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";
    const store = useConnectionStore();
    const connection = sundbConnection();
    const databaseNode: TreeNode = { id: "sundb-1:vpnccw", label: "vpnccw", type: "database", connectionId: connection.id, database: "vpnccw", isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: true, children: [databaseNode] }];

    await store.loadTreeNodeChildren(databaseNode, { force: true });

    expect(listSchemaInfos).toHaveBeenCalledWith(connection.id, "vpnccw");
    expect(listTables).not.toHaveBeenCalled();
    const schemaNode = databaseNode.children!.find((node) => node.type === "schema")!;
    expect([schemaNode.label, schemaNode.schema]).toEqual(["APP", "APP"]);

    await store.loadTreeNodeChildren(schemaNode, { force: true });

    const firstTableRequest = listTables.mock.calls[0] as unknown[];
    expect(firstTableRequest.slice(0, 3)).toEqual([connection.id, "vpnccw", "APP"]);
  });

  it.each(["simple", "grouped"] as const)("isolates discovered JDBC schemas, pages and cached objects in %s mode", async (mode) => {
    const schemas = ["APP", "OTHER", "app", "A_B", "AXB", "_SYS_EPM"];
    const rowsForSchema = (schema: string): TableInfo[] => [...Array.from({ length: 3 }, (_, index) => ({ name: `${schema}_table_${index}`, table_type: "TABLE", comment: null })), ...Array.from({ length: 3 }, (_, index) => ({ name: `${schema}_view_${index}`, table_type: "VIEW", comment: null }))];
    // Empty schema models JDBC's unrestricted metadata request. Deliberately
    // omit row-level schema fields: the requested scope must reach child nodes.
    const listTables = vi.fn(async (_id: string, _database: string, schema: string, _filter?: string, limit?: number, offset = 0, types?: string[]) => {
      const rows = (schema ? rowsForSchema(schema) : schemas.flatMap(rowsForSchema)).filter((row) => !types || types.includes(row.table_type));
      return rows.slice(offset, offset + (limit ?? rows.length));
    });
    const listObjects = vi.fn(async (_id: string, _database: string, schema: string) => [{ ...procedure(`${schema}_procedure`), schema }]);
    const listSchemaInfos = vi.fn().mockResolvedValue(schemas.map((name) => ({ name, comment: null })));
    const saveSchemaCache = vi.fn().mockResolvedValue(undefined);
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listSchemaInfos,
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache,
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));
    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    useSettingsStore().editorSettings.sidebarObjectDisplay = mode;
    useSettingsStore().desktopSettings.sidebar_table_page_size = 2;
    const store = useConnectionStore();
    const connection = { ...genericJdbcConnection(), connection_string: "jdbc:sap://localhost:443/?currentschema=APP", jdbc_driver_class: "com.sap.db.jdbc.Driver", show_system_schemas: true };
    const database: TreeNode = { id: `${connection.id}:testdb`, label: "testdb", type: "database", connectionId: connection.id, database: "testdb", children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [database] }];
    await store.loadTreeNodeChildren(database);
    expect(listSchemaInfos).toHaveBeenCalledOnce();
    const schemaNodes = database.children!.filter((node) => node.type === "schema");
    expect(new Set(schemaNodes.map((node) => node.schema))).toEqual(new Set(schemas));

    for (const node of schemaNodes) {
      await store.loadTreeNodeChildren(node);
      const parents = mode === "simple" ? [node] : node.children!.filter((child) => child.type === "group-tables" || child.type === "group-views");
      expect(parents).toHaveLength(mode === "simple" ? 1 : 2);
      for (const parent of parents) {
        expect(parent.schema).toBe(node.schema);
        if (mode === "grouped") await store.loadTreeNodeChildren(parent);
        expect(parent.children?.filter((child) => child.type === "table" || child.type === "view")).toHaveLength(2);
        let more = parent.children?.find((child) => child.type === "load-more");
        expect(more).toBeDefined();
        while (more) {
          await store.loadMoreObjectGroupChildren(more);
          more = parent.children?.find((child) => child.type === "load-more");
        }
        const children = parent.children!.filter((child) => child.type === "table" || child.type === "view");
        const expected = rowsForSchema(node.schema!).filter((row) => mode === "simple" || row.table_type === (parent.type === "group-tables" ? "TABLE" : "VIEW"));
        expect(children.map((child) => [child.label, child.schema, child.type])).toEqual(expected.map((row) => [row.name, node.schema, row.table_type.toLowerCase()]));
        const calls = listTables.mock.calls.length;
        await store.loadTreeNodeChildren(parent);
        expect(listTables).toHaveBeenCalledTimes(calls);
      }
      if (mode === "grouped") await store.loadTreeNodeChildren(node.children!.find((child) => child.type === "group-procedures")!);
      await vi.waitFor(() => expect(node.children!.flatMap((child) => (mode === "simple" ? [child] : (child.children ?? []))).some((child) => child.label === `${node.schema}_procedure` && child.schema === node.schema)).toBe(true));
    }
    for (const schema of schemas) {
      const calls = listTables.mock.calls.filter((call) => call[2] === schema);
      expect(calls.map((call) => call[5])).toEqual(mode === "simple" ? [0, 2, 4] : [0, 2, 0, 2]);
      expect(calls.every((call) => call[1] === "testdb" && call[4] === 3)).toBe(true);
    }
    expect(listTables).toHaveBeenCalledTimes(schemas.length * (mode === "simple" ? 3 : 4));
    expect(listObjects.mock.calls.map((call) => call[2]).sort()).toEqual([...schemas].sort());
    const objectWrites = saveSchemaCache.mock.calls.filter(([key]) => key.includes("objects-"));
    expect(objectWrites.length).toBeGreaterThan(0);
    expect(objectWrites.every(([key]) => key.includes("-jdbc-schema-v1"))).toBe(true);
    expect(new Set(objectWrites.map(([key]) => key.split(":")[2]))).toEqual(new Set(schemas));
  });

  it.each(["simple", "grouped"] as const)("ignores persisted JDBC objects from before schema scoping in %s mode", async (mode) => {
    const connection = genericJdbcConnection();
    const stale: TreeNode = { id: "stale", label: "OTHER_table", type: "table", connectionId: connection.id, database: "testdb" };
    const legacyKeys = new Set(["jdbc-1:testdb:APP:objects-simple-v9", "jdbc-1:testdb:APP:objects-grouped-v9", "jdbc-1:testdb:APP:group-tables:objects-v9"]);
    const loadSchemaCache = vi.fn(async (key: string) => (legacyKeys.has(key) ? encodeSchemaTreeCache([stale]) : null));
    const listTables = vi.fn().mockResolvedValue([{ name: "APP_table", table_type: "TABLE", comment: null }]);
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache,
      listObjects: vi.fn().mockResolvedValue([]),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));
    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    useSettingsStore().editorSettings.sidebarObjectDisplay = mode;
    const store = useConnectionStore();
    const node: TreeNode = { id: "jdbc-1:testdb:APP", label: "APP", type: "schema", connectionId: connection.id, database: "testdb", schema: "APP", children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [node];
    await store.loadTreeNodeChildren(node);
    const parent = mode === "simple" ? node : node.children!.find((child) => child.type === "group-tables")!;
    expect(parent).toBeDefined();
    if (mode === "grouped") await store.loadTreeNodeChildren(parent);
    expect(parent.children?.map((child) => [child.label, child.schema])).toEqual([["APP_table", "APP"]]);
    expect(loadSchemaCache).toHaveBeenCalled();
    expect(loadSchemaCache.mock.calls.every(([key]) => !legacyKeys.has(key) && key.includes("-jdbc-schema-v1"))).toBe(true);
  });

  it("loads inferred Oracle JDBC schemas without requesting empty catalogs", async () => {
    const listDatabases = vi.fn().mockResolvedValue([]);
    const listSchemas = vi.fn().mockResolvedValue(["ANONYMOUS", "DBX_TEST", "SYS", "SYSTEM"]);
    const listTables = vi.fn().mockResolvedValue([{ name: "sheet", table_type: "TABLE", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    const executeQuery = vi.fn().mockResolvedValue({
      columns: ["OWNER", "DB_LINK", "USERNAME", "HOST", "CREATED"],
      rows: [
        ["DBX_TEST", "PRIVATE.EXAMPLE", "REMOTE", "service", ""],
        ["PUBLIC", "PUBLIC.EXAMPLE", "REMOTE", "service", ""],
      ],
    });
    vi.doMock("@/lib/backend/api", () => ({
      executeQuery,
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listObjects: vi.fn().mockResolvedValue([]),
      listSchemas,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";
    const connection = oracleJdbcConnection();
    const connectionNode: TreeNode = { id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadDatabases(connection.id, { force: true });

    expect(listDatabases).not.toHaveBeenCalled();
    expect(listSchemas).toHaveBeenCalledWith(connection.id, "");
    expect(connectionNode.children?.map((node) => [node.type, node.label, node.database, node.schema])).toEqual([
      ["schema", "DBX_TEST", "DBX_TEST", "DBX_TEST"],
      ["oracle-db-links", "tree.databaseLinks", "", undefined],
      ["database-job-admin", "tree.nativeJobs", "", undefined],
      ["user-admin", "tree.userAdmin", "", undefined],
    ]);

    const linkRoot = connectionNode.children!.find((node) => node.type === "oracle-db-links")!;
    await store.loadTreeNodeChildren(linkRoot, { force: true });
    expect(executeQuery).toHaveBeenCalledWith(connection.id, "", expect.stringContaining("SESSION_USER"), undefined, undefined, { maxRows: 10000, timeoutSecs: 15 });
    expect(linkRoot.children?.map((node) => [node.type, node.label, node.schema])).toEqual([
      ["oracle-db-link", "PRIVATE.EXAMPLE", "DBX_TEST"],
      ["oracle-db-link", "PUBLIC.EXAMPLE", "PUBLIC"],
    ]);
    expect(linkRoot.objectCount).toBe(2);
    executeQuery.mockResolvedValue({ columns: ["OWNER", "DB_LINK"], rows: [] });
    await store.refreshOracleDatabaseLinks(connection.id);
    expect(linkRoot.children).toEqual([]);
    expect(linkRoot.objectCount).toBe(0);

    const schemaNode = connectionNode.children?.[0];
    expect(schemaNode).toBeDefined();
    await store.loadTreeNodeChildren(schemaNode!, { force: true });

    expect(listTables.mock.calls[0]?.slice(0, 3)).toEqual([connection.id, "DBX_TEST", "DBX_TEST"]);
    expect(schemaNode?.children?.map((node) => [node.type, node.label, node.schema])).toEqual([["table", "sheet", "DBX_TEST"]]);
  });

  it("omits oracle-db-links when show_database_links is configured as false", async () => {
    vi.resetModules();
    const listDatabases = vi.fn().mockResolvedValue([]);
    const listSchemas = vi.fn().mockResolvedValue(["DBX_TEST"]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listObjects: vi.fn().mockResolvedValue([]),
      listSchemas,
      listTables: vi.fn().mockResolvedValue([]),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = { ...oracleJdbcConnection(), show_database_links: false };
    const connectionNode: TreeNode = { id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadDatabases(connection.id, { force: true });

    expect(connectionNode.children?.map((node) => [node.type, node.label])).toEqual([
      ["schema", "DBX_TEST"],
      ["database-job-admin", "tree.nativeJobs"],
      ["user-admin", "tree.userAdmin"],
    ]);
  });

  it.each([
    { mode: "simple", names: [] },
    { mode: "grouped", names: [] },
    { mode: "simple", names: ["", " "] },
    { mode: "grouped", names: ["", " "] },
  ] as const)("keeps the flat JDBC catalog fallback in $mode mode for schema discovery $names", async ({ mode, names }) => {
    const listSchemaInfos = vi.fn().mockResolvedValue(names.map((name) => ({ name, comment: null })));
    const listTables = vi.fn().mockResolvedValue([{ name: "t", table_type: "TABLE", comment: null }]);
    const saveSchemaCache = vi.fn().mockResolvedValue(undefined);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listObjects: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache,
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = mode;
    const connection = genericJdbcConnection();
    const databaseNode: TreeNode = { id: "jdbc-1:testdb", label: "testdb", type: "database", connectionId: connection.id, database: "testdb", isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: true, children: [databaseNode] }];

    await store.loadTreeNodeChildren(databaseNode, { force: true });

    expect(listSchemaInfos).toHaveBeenCalledWith(connection.id, "testdb");
    const parent = mode === "simple" ? databaseNode : databaseNode.children!.find((child) => child.type === "group-tables")!;
    if (mode === "grouped") await store.loadTreeNodeChildren(parent);
    expect(listTables).toHaveBeenCalled();
    expect(listTables.mock.calls[0].slice(0, 3)).toEqual([connection.id, "testdb", ""]);
    expect(parent.children?.filter((node) => node.type !== "saved-sql-root").map((node) => [node.type, node.label, node.schema])).toEqual([["table", "t", undefined]]);
    expect(saveSchemaCache.mock.calls.every(([key]) => !key.includes("-jdbc-schema-v1"))).toBe(true);
  });

  it("keeps failed JDBC schema discovery as an error without loading unrestricted tables", async () => {
    const listSchemaInfos = vi.fn().mockRejectedValue(new Error("schema discovery denied"));
    const listTables = vi.fn();
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      listSchemaInfos,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));
    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = genericJdbcConnection();
    const node: TreeNode = { id: "jdbc-1:testdb", label: "testdb", type: "database", connectionId: connection.id, database: "testdb", children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [node];
    await expect(store.loadTreeNodeChildren(node)).rejects.toThrow("schema discovery denied");
    expect(listTables).not.toHaveBeenCalled();
    expect(node.children).toEqual([]);
    expect(node.isLoading).toBe(false);
    expect(store.isTreeNodeChildrenLoaded(node.id)).toBe(false);
  });

  it("keeps the flat object tree for GBase 8s databases that cannot qualify schemas in DML", async () => {
    const listSchemaInfos = vi.fn().mockResolvedValue([]);
    const listTables = vi.fn().mockResolvedValue([{ name: "connection_smoke", table_type: "TABLE", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listObjects: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";
    const connection = gbase8sConnection();
    const databaseNode: TreeNode = { id: `${connection.id}:dbx_test`, label: "dbx_test", type: "database", connectionId: connection.id, database: "dbx_test", isExpanded: false, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: true, children: [databaseNode] }];

    await store.loadTreeNodeChildren(databaseNode, { force: true });

    expect(listSchemaInfos).toHaveBeenCalledWith(connection.id, "dbx_test");
    expect(listTables).toHaveBeenCalled();
    expect(databaseNode.children?.map((node) => [node.type, node.label, node.schema])).toEqual([
      ["table", "connection_smoke", undefined],
      ["saved-sql-root", "tree.queries", undefined],
    ]);
  });

  it("renders simple-mode table children without waiting for supplemental objects", async () => {
    const tables: TableInfo[] = [{ name: "users", table_type: "BASE TABLE", comment: null }];
    const listTables = vi.fn().mockResolvedValue(tables);
    const listObjects = vi.fn(() => new Promise(() => undefined));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listObjects,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "simple";

    const connection = postgresConnection();
    const schemaNode: TreeNode = {
      id: "pg-1:app:public",
      label: "public",
      type: "schema",
      connectionId: connection.id,
      database: "app",
      schema: "public",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "pg-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [schemaNode],
          },
        ],
      },
    ];

    const result = await Promise.race([store.loadTables(connection.id, "app", "public").then(() => "done"), new Promise((resolve) => setTimeout(() => resolve("timeout"), 50))]);

    expect(result).toBe("done");
    expect(listTables).toHaveBeenCalledWith(connection.id, "app", "public", undefined, 1001, 0);
    expect(listObjects).toHaveBeenCalled();
    expect(schemaNode.children?.map((node) => node.label)).toEqual(["users"]);
  });

  it("keeps concurrent table-tree and local-index refreshes in separate cache entries", async () => {
    const treeCacheKey = "pg-1:app:public:group-tables:objects-v9";
    const indexCacheKey = `${treeCacheKey}:table-search-index-v1`;
    const cachedPayloads = new Map<string, unknown>([
      [
        treeCacheKey,
        {
          version: 3,
          cachedAt: new Date().toISOString(),
          children: [{ id: "old", label: "old_table", type: "table", connectionId: "pg-1", database: "app", schema: "public", isExpanded: false }],
        },
      ],
    ]);
    let releaseTableLists!: () => void;
    let tableListCalls = 0;
    const bothTableListsStarted = new Promise<void>((resolve) => {
      releaseTableLists = resolve;
    });
    const listTables = vi.fn(async (_connectionId: string, _database: string, _schema: string, _filter?: string, limit?: number) => {
      tableListCalls += 1;
      if (tableListCalls === 2) releaseTableLists();
      await bothTableListsStarted;
      return limit === 2 ? ([{ name: "indexed_table", table_type: "TABLE", comment: null }] satisfies TableInfo[]) : ([{ name: "fresh_table", table_type: "TABLE", comment: null }] satisfies TableInfo[]);
    });
    const loadSchemaCache = vi.fn(async (key: string) => {
      const payload = cachedPayloads.get(key) ?? null;
      await Promise.resolve();
      return payload == null ? null : structuredClone(payload);
    });
    const saveSchemaCache = vi.fn(async (key: string, payload: unknown) => {
      cachedPayloads.set(key, structuredClone(payload));
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      loadSchemaCache,
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache,
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { decodeSchemaTreeCache } = await import("@/lib/metadata/schemaTreeCache");
    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().desktopSettings.sidebar_table_page_size = 2;

    const connection = postgresConnection();
    const tablesGroup: TreeNode = {
      id: "pg-1:app:public:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      schema: "public",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "pg-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [
              {
                id: "pg-1:app:public",
                label: "public",
                type: "schema",
                connectionId: connection.id,
                database: "app",
                schema: "public",
                isExpanded: true,
                children: [tablesGroup],
              },
            ],
          },
        ],
      },
    ];

    await Promise.all([store.loadObjectGroupChildren(tablesGroup, { force: true }), store.refreshSidebarTableSearchIndex(tablesGroup.id)]);

    const treeCache = decodeSchemaTreeCache<TreeNode[]>(cachedPayloads.get(treeCacheKey));
    const indexCache = decodeSchemaTreeCache<TreeNode[]>(cachedPayloads.get(indexCacheKey));
    expect(treeCache?.children.map((node) => node.label)).toEqual(["fresh_table"]);
    // The local table index preserves comments for regex search matching.
    expect(indexCache?.tableSearchIndex?.entries).toEqual([{ name: "indexed_table", tableType: "TABLE", comment: null }]);
    await expect(store.loadSidebarTableSearchIndex(tablesGroup.id)).resolves.toEqual([{ name: "indexed_table", table_type: "TABLE", comment: null }]);
    // The refreshed index is served from the in-memory cache; refreshing
    // additionally registers the scope by reading the sidebar index manifest.
    expect(loadSchemaCache).toHaveBeenLastCalledWith("dbx:sidebar-table-search-index-manifest-v1");
  });

  it("bypasses Oracle object-group caches created before DIP visibility was fixed", async () => {
    const listTables = vi.fn().mockResolvedValue([
      { name: "V_ONE", table_type: "VIEW", comment: null },
      { name: "V_TWO", table_type: "VIEW", comment: null },
      { name: "V_THREE", table_type: "VIEW", comment: null },
    ] satisfies TableInfo[]);
    const legacyChildren: TreeNode[] = [
      { id: "oracle-1:XE:DIP:__views:DIP:V_ONE", label: "V_ONE", type: "view", connectionId: "oracle-1", database: "XE", schema: "DIP", isExpanded: false },
      { id: "oracle-1:XE:DIP:__views:DIP:V_TWO", label: "V_TWO", type: "view", connectionId: "oracle-1", database: "XE", schema: "DIP", isExpanded: false },
    ];
    const loadSchemaCache = vi.fn(async (key: string) =>
      key.endsWith(":objects-v6")
        ? {
            version: 2,
            cachedAt: new Date().toISOString(),
            children: legacyChildren,
          }
        : null,
    );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      loadSchemaCache,
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().desktopSettings.sidebar_table_page_size = 200;
    const connection = oracleConnection();
    const viewGroup: TreeNode = {
      id: "oracle-1:XE:DIP:__views",
      label: "tree.views",
      type: "group-views",
      connectionId: connection.id,
      database: "XE",
      schema: "DIP",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "oracle-1:XE:DIP",
            label: "DIP",
            type: "schema",
            connectionId: connection.id,
            database: "XE",
            schema: "DIP",
            isExpanded: true,
            children: [viewGroup],
          },
        ],
      },
    ];

    const storedViewGroup = store.treeNodes[0].children?.[0].children?.[0];
    expect(storedViewGroup?.type).toBe("group-views");
    await store.loadObjectGroupChildren(storedViewGroup!);

    expect(loadSchemaCache).toHaveBeenCalledWith("oracle-1:XE:DIP:group-views:objects-v8-oracle-trigger-exact-v1");
    expect(listTables).toHaveBeenCalledWith(connection.id, "XE", "DIP", undefined, 201, 0, ["VIEW"]);
    expect(storedViewGroup?.children?.map((node) => node.label)).toEqual(["V_ONE", "V_THREE", "V_TWO"]);
  });

  it("ignores stale table filter refreshes that finish out of order", async () => {
    let resolveFirst!: (tables: TableInfo[]) => void;
    let resolveSecond!: (tables: TableInfo[]) => void;
    let firstStarted!: () => void;
    let secondStarted!: () => void;
    const firstStartedPromise = new Promise<void>((resolve) => {
      firstStarted = resolve;
    });
    const secondStartedPromise = new Promise<void>((resolve) => {
      secondStarted = resolve;
    });
    const listTables = vi
      .fn()
      .mockImplementationOnce(
        () =>
          new Promise<TableInfo[]>((resolve) => {
            resolveFirst = resolve;
            firstStarted();
          }),
      )
      .mockImplementationOnce(
        () =>
          new Promise<TableInfo[]>((resolve) => {
            resolveSecond = resolve;
            secondStarted();
          }),
      );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const tableGroup: TreeNode = {
      id: "pg-1:app:public:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      schema: "public",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "pg-1:app:public",
            label: "public",
            type: "schema",
            connectionId: connection.id,
            database: "app",
            schema: "public",
            isExpanded: true,
            children: [tableGroup],
          },
        ],
      },
    ];
    const scopeKey = store.tableNameFilterScopeKey({
      connectionId: connection.id,
      database: "app",
      schema: "public",
      nodeKind: "group-tables",
    });
    const currentTableGroup = () => store.treeNodes[0].children?.[0].children?.[0] as TreeNode;

    const firstRevision = store.setSidebarTableNameFilter(scopeKey, { includePatterns: ["old_%"], excludePatterns: [] });
    const firstRefresh = store.refreshTreeNodeForTableNameFilter(currentTableGroup(), scopeKey, firstRevision);
    await firstStartedPromise;
    const secondRevision = store.setSidebarTableNameFilter(scopeKey, { includePatterns: ["new_%"], excludePatterns: [] });
    const secondRefresh = store.refreshTreeNodeForTableNameFilter(currentTableGroup(), scopeKey, secondRevision);
    await secondStartedPromise;

    resolveSecond([{ name: "new_users", table_type: "BASE TABLE", comment: null }]);
    await secondRefresh;
    expect(currentTableGroup().children?.map((node) => node.label)).toEqual(["new_users"]);

    resolveFirst([{ name: "old_users", table_type: "BASE TABLE", comment: null }]);
    await firstRefresh;
    expect(currentTableGroup().children?.map((node) => node.label)).toEqual(["new_users"]);
  });

  it("applies include filters to Doris internal table groups", async () => {
    const listTables = vi.fn().mockResolvedValue([{ name: "ads_pgc_report", table_type: "BASE TABLE", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = dorisConnection();
    const tableGroup: TreeNode = {
      id: "doris-1:warehouse:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "warehouse",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "doris-1:warehouse",
            label: "warehouse",
            type: "database",
            connectionId: connection.id,
            database: "warehouse",
            isExpanded: true,
            children: [tableGroup],
          },
        ],
      },
    ];

    const scopeKey = store.tableNameFilterScopeKey({
      connectionId: connection.id,
      database: "warehouse",
      nodeKind: "group-tables",
    });
    const revision = store.setSidebarTableNameFilter(scopeKey, { includePatterns: ["ads_pgc_%"], excludePatterns: [] });
    await store.refreshTreeNodeForTableNameFilter(tableGroup, scopeKey, revision);

    expect(listTables).toHaveBeenCalledWith(connection.id, "warehouse", "warehouse", undefined, 1001, 0, ["TABLE"], undefined, { includePatterns: ["ads_pgc_%"], excludePatterns: [] });
    expect(tableGroup.children?.map((node) => node.label)).toEqual(["ads_pgc_report"]);
  });

  it("loads Dolt user and system table groups with independent pre-pagination filters", async () => {
    const listTables = vi.fn(async (...args: unknown[]) => {
      const tableNameFilter = args[8] as { includePatterns: string[]; excludePatterns: string[] } | undefined;
      if (tableNameFilter?.includePatterns.includes("dolt%")) {
        return [{ name: "dolt_log", table_type: "BASE TABLE", comment: null }];
      }
      return [{ name: "orders", table_type: "BASE TABLE", comment: null }];
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "grouped";
    const connection = doltConnection();
    const databaseNode: TreeNode = {
      id: `${connection.id}:app`,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];

    await store.loadTables(connection.id, "app", undefined, { force: true });
    const userTables = databaseNode.children?.find((node) => node.type === "group-tables");
    const systemTables = databaseNode.children?.find((node) => node.type === "group-dolt-system-tables");
    expect(systemTables?.label).toBe("tree.doltSystemTables");

    await store.loadObjectGroupChildren(userTables!, { force: true });
    await store.loadObjectGroupChildren(systemTables!, { force: true });

    expect(userTables?.children?.map((node) => node.label)).toEqual(["orders"]);
    expect(systemTables?.children?.map((node) => node.label)).toEqual(["dolt_log"]);
    expect(listTables).toHaveBeenCalledWith(connection.id, "app", "app", undefined, 1001, 0, ["TABLE"], undefined, { includePatterns: [], excludePatterns: ["dolt%"] });
    expect(listTables).toHaveBeenCalledWith(connection.id, "app", "app", undefined, 1001, 0, ["TABLE"], undefined, { includePatterns: ["dolt%"], excludePatterns: [] });
  });

  it("clears a stale connection error after a schema metadata retry succeeds", async () => {
    const listSchemaInfos = vi
      .fn()
      .mockRejectedValueOnce(new Error("connection slots exhausted"))
      .mockResolvedValueOnce([{ name: "public", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: `${connection.id}:app`,
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: false,
            children: [],
          },
        ],
      },
    ];

    await expect(store.loadSchemas(connection.id, "app", { force: true })).rejects.toThrow("connection slots exhausted");
    expect(store.connectionErrors[connection.id]).toBe("connection slots exhausted");

    await store.loadSchemas(connection.id, "app", { force: true });

    expect(store.connectionErrors[connection.id]).toBeUndefined();
    expect(store.treeNodes[0]?.children?.[0]?.children?.map((node) => node.label)).toEqual(["public", "tree.extensions", "tree.eventTriggers", "tree.queries"]);
  });

  it("preserves the last successful tree snapshot when a forced metadata refresh fails", async () => {
    const listSchemaInfos = vi.fn().mockRejectedValue(new Error("Agent RPC call timed out (5s)"));
    const deleteSchemaCachePrefix = vi.fn().mockResolvedValue(undefined);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const previousSchema: TreeNode = {
      id: `${connection.id}:app:public`,
      label: "public",
      type: "schema",
      connectionId: connection.id,
      database: "app",
      schema: "public",
      isExpanded: false,
      children: [],
    };
    const databaseNode: TreeNode = {
      id: `${connection.id}:app`,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [previousSchema],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];

    await expect(store.refreshTreeNode(databaseNode)).rejects.toThrow("Agent RPC call timed out (5s)");

    expect(databaseNode.children).toEqual([previousSchema]);
    expect(databaseNode.isExpanded).toBe(true);
    expect(store.connectionErrors[connection.id]).toBe("Agent RPC call timed out (5s)");
    expect(deleteSchemaCachePrefix).toHaveBeenCalledWith("pg-1:app:");
  });

  it("does not let an older refresh resume after a newer refresh succeeds", async () => {
    let resolveOlderMetadata!: (value: Array<{ name: string; comment: null }>) => void;
    const olderMetadata = new Promise<Array<{ name: string; comment: null }>>((resolve) => {
      resolveOlderMetadata = resolve;
    });
    const deleteSchemaCachePrefix = vi.fn().mockResolvedValue(undefined);
    const listSchemaInfos = vi
      .fn()
      .mockImplementationOnce(() => olderMetadata)
      .mockResolvedValue([{ name: "latest", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const databaseNode: TreeNode = {
      id: `${connection.id}:app`,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];

    const olderRefresh = store.refreshTreeNode(databaseNode);
    await vi.waitFor(() => expect(listSchemaInfos).toHaveBeenCalledTimes(1));
    await store.refreshTreeNode(databaseNode);
    resolveOlderMetadata([{ name: "stale", comment: null }]);
    await olderRefresh;

    expect(listSchemaInfos).toHaveBeenCalledTimes(2);
    expect(databaseNode.children?.map((node) => node.label)).toEqual(["latest", "tree.extensions", "tree.eventTriggers", "tree.queries"]);
  });

  it("does not let an older refresh failure overwrite a newer successful refresh", async () => {
    let rejectOlderMetadata!: (reason: Error) => void;
    const olderMetadata = new Promise<Array<{ name: string; comment: null }>>((_, reject) => {
      rejectOlderMetadata = reject;
    });
    const listSchemaInfos = vi
      .fn()
      .mockImplementationOnce(() => olderMetadata)
      .mockResolvedValue([{ name: "latest", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const databaseNode: TreeNode = {
      id: `${connection.id}:app`,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];

    const olderRefresh = store.refreshTreeNode(databaseNode);
    await vi.waitFor(() => expect(listSchemaInfos).toHaveBeenCalledTimes(1));
    await store.refreshTreeNode(databaseNode);
    rejectOlderMetadata(new Error("connection closed"));
    await expect(olderRefresh).rejects.toThrow("connection closed");

    expect(databaseNode.children?.map((node) => node.label)).toEqual(["latest", "tree.extensions", "tree.eventTriggers", "tree.queries"]);
    expect(store.connectionErrors[connection.id]).toBeUndefined();
    expect(store.connectedIds.has(connection.id)).toBe(true);
  });

  it("does not restore a pre-disconnect snapshot into a same-id reconnected node", async () => {
    let rejectMetadata!: (reason: Error) => void;
    const pendingMetadata = new Promise<Array<{ name: string; comment: null }>>((_, reject) => {
      rejectMetadata = reject;
    });
    const listSchemaInfos = vi.fn().mockReturnValue(pendingMetadata);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      disconnectDb: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const databaseId = `${connection.id}:app`;
    const staleSchema: TreeNode = {
      id: `${databaseId}:stale`,
      label: "stale",
      type: "schema",
      connectionId: connection.id,
      database: "app",
      schema: "stale",
      children: [],
    };
    const databaseNode: TreeNode = {
      id: databaseId,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [staleSchema],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [databaseNode],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const staleRefresh = store.refreshTreeNode(databaseNode);
    await vi.waitFor(() => expect(listSchemaInfos).toHaveBeenCalledTimes(1));
    await store.disconnect(connection.id);

    const freshSchema: TreeNode = {
      id: `${databaseId}:fresh`,
      label: "fresh",
      type: "schema",
      connectionId: connection.id,
      database: "app",
      schema: "fresh",
      children: [],
    };
    const reconnectedDatabaseNode: TreeNode = {
      ...databaseNode,
      children: [freshSchema],
    };
    connectionNode.children = [reconnectedDatabaseNode];
    store.connectedIds.add(connection.id);

    rejectMetadata(new Error("disconnected refresh"));
    await expect(staleRefresh).rejects.toThrow("disconnected refresh");

    expect(reconnectedDatabaseNode.children?.map((child) => child.label)).toEqual(["fresh"]);
  });

  it.each(["opengauss", "kingbase"] as const)("reloads %s sidebar schemas when system visibility changes", async (dbType) => {
    const listSchemaInfos = vi.fn().mockResolvedValue([
      { name: "information_schema", comment: null },
      { name: "pg_catalog", comment: null },
      { name: "public", comment: null },
    ]);
    const loadSchemaCache = vi.fn().mockResolvedValue(null);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache,
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = { ...postgresConnection(), id: `${dbType}-1`, db_type: dbType, show_system_schemas: false } as ConnectionConfig;
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: `${connection.id}:app`,
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: false,
            children: [],
          },
        ],
      },
    ];
    const databaseNode = store.treeNodes[0]!.children![0]!;

    await store.loadSchemas(connection.id, "app");
    expect(databaseNode.children?.filter((node) => node.type === "schema").map((node) => node.label)).toEqual(["public"]);

    store.connections[0]!.show_system_schemas = true;
    databaseNode.children = [];
    databaseNode.isExpanded = false;
    await store.loadSchemas(connection.id, "app");

    expect(loadSchemaCache.mock.calls.map(([key]) => key)).toEqual([`${connection.id}:app:schemas-v3:hide-system`, `${connection.id}:app:schemas-v3:show-system`]);
    expect(databaseNode.children?.filter((node) => node.type === "schema").map((node) => node.label)).toEqual(["information_schema", "pg_catalog", "public"]);
  });

  it("clears a failed metadata warning when the driver hint finishes during retry", async () => {
    let resolveAgents!: (drivers: Array<{ db_type: string; installed: boolean; update_available: boolean }>) => void;
    let resolveSchemas!: (schemas: Array<{ name: string; comment: null }>) => void;
    const listInstalledAgents = vi.fn(
      () =>
        new Promise<Array<{ db_type: string; installed: boolean; update_available: boolean }>>((resolve) => {
          resolveAgents = resolve;
        }),
    );
    const listSchemaInfos = vi
      .fn()
      .mockRejectedValueOnce(new Error("connection slots exhausted"))
      .mockImplementationOnce(
        () =>
          new Promise<Array<{ name: string; comment: null }>>((resolve) => {
            resolveSchemas = resolve;
          }),
      );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents,
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = { ...postgresConnection(), db_type: "oracle" } as ConnectionConfig;
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: `${connection.id}:app`,
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: false,
            children: [],
          },
        ],
      },
    ];

    await expect(store.loadSchemas(connection.id, "app", { force: true })).rejects.toThrow("connection slots exhausted");
    expect(store.connectionErrors[connection.id]).toBe("connection slots exhausted");

    const retry = store.loadSchemas(connection.id, "app", { force: true });
    await vi.waitFor(() => expect(listSchemaInfos).toHaveBeenCalledTimes(2));

    resolveAgents([{ db_type: "oracle", installed: true, update_available: true }]);
    await vi.waitFor(() => expect(store.connectionErrors[connection.id]).toContain("built-in driver update"));

    resolveSchemas([{ name: "public", comment: null }]);
    await retry;

    expect(store.connectionErrors[connection.id]).toBeUndefined();
  });

  it("does not clear a newer error when an older metadata request succeeds", async () => {
    let resolveSchemas!: (schemas: Array<{ name: string; comment: null }>) => void;
    const listSchemaInfos = vi.fn(
      () =>
        new Promise<Array<{ name: string; comment: null }>>((resolve) => {
          resolveSchemas = resolve;
        }),
    );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: `${connection.id}:app`,
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: false,
            children: [],
          },
        ],
      },
    ];
    store.setConnectionError(connection.id, "old error");

    const load = store.loadSchemas(connection.id, "app", { force: true });
    await vi.waitFor(() => expect(listSchemaInfos).toHaveBeenCalledOnce());
    store.setConnectionError(connection.id, "newer error");
    resolveSchemas([{ name: "public", comment: null }]);
    await load;

    expect(store.connectionErrors[connection.id]).toBe("newer error");
  });

  it("keeps an expanding schema attached while its parent refreshes", async () => {
    const listSchemaInfos = vi.fn().mockResolvedValue([{ name: "core", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const schemaNode: TreeNode = {
      id: "pg-1:app:core",
      label: "core",
      type: "schema",
      connectionId: connection.id,
      database: "app",
      schema: "core",
      isExpanded: true,
      isLoading: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "pg-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [schemaNode],
          },
        ],
      },
    ];

    const storedSchema = store.treeNodes[0].children?.[0].children?.[0];
    await store.loadSchemas(connection.id, "app", { force: true });

    const refreshedSchema = store.treeNodes[0].children?.[0].children?.[0];
    expect(refreshedSchema).toBe(storedSchema);
    expect(refreshedSchema?.isExpanded).toBe(true);
    expect(refreshedSchema?.isLoading).toBe(true);
  });

  it("paginates procedure groups and appends the next page", async () => {
    const firstPage = Array.from({ length: 201 }, (_, index) => procedure(`p_${String(index + 1).padStart(4, "0")}`));
    const listObjects = vi
      .fn()
      .mockResolvedValueOnce(firstPage)
      .mockResolvedValueOnce([procedure("p_0201"), procedure("p_0202")])
      .mockResolvedValueOnce([procedure("p_0999")]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection = mysqlConnection();
    const procedureGroup: TreeNode = {
      id: "mysql-1:app:__procedures",
      label: "tree.procedures",
      type: "group-procedures",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [procedureGroup],
          },
        ],
      },
    ];

    const storedProcedureGroup = store.treeNodes[0].children?.[0].children?.[0];
    expect(storedProcedureGroup?.type).toBe("group-procedures");
    await store.loadObjectGroupChildren(storedProcedureGroup!);

    expect(listObjects).toHaveBeenNthCalledWith(1, connection.id, "app", "app", ["PROCEDURE"], undefined, 201, 0);
    expect(storedProcedureGroup?.children).toHaveLength(201);
    expect(storedProcedureGroup?.children?.[0].label).toBe("p_0001");
    expect(storedProcedureGroup?.children?.[199].label).toBe("p_0200");
    expect(storedProcedureGroup?.children?.[200].label).toBe("tree.loadMore");

    const loadMoreNode = storedProcedureGroup?.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");
    await store.loadMoreObjectGroupChildren(loadMoreNode!);

    expect(listObjects).toHaveBeenNthCalledWith(2, connection.id, "app", "app", ["PROCEDURE"], undefined, 201, 200);
    expect(storedProcedureGroup?.children).toHaveLength(202);
    expect(storedProcedureGroup?.children?.at(-1)?.label).toBe("p_0202");

    store.sidebarSearchQuery = "p_0999";
    await store.loadObjectGroupChildren(storedProcedureGroup!, { force: true, searchFilter: "p_0999" });

    expect(listObjects).toHaveBeenNthCalledWith(3, connection.id, "app", "app", ["PROCEDURE"], "p_0999", undefined, undefined);
    expect(storedProcedureGroup?.children?.map((node) => node.label)).toEqual(["p_0999"]);
  });

  it("keeps Kingbase procedure overloads and zero-argument identities across pages", async () => {
    const objects: ObjectInfo[] = [
      ...Array.from({ length: 10 }, (_, index) => ({ name: `p_${String(index).padStart(2, "0")}`, object_type: "PROCEDURE", schema: "app", signature: "" })),
      { name: "run", object_type: "PROCEDURE", schema: "app", signature: "v integer" },
      { name: "run", object_type: "PROCEDURE", schema: "app", signature: "v text" },
    ];
    const listObjects = vi.fn((_connectionId: string, _database: string, _schema: string, _objectTypes: string[], _filter?: string, limit?: number, offset = 0) => Promise.resolve(objects.slice(offset, offset + (limit ?? objects.length))));
    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));
    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settings = useSettingsStore();
    settings.editorSettings.sidebarObjectDisplay = "grouped";
    settings.desktopSettings.sidebar_table_page_size = 11;
    const connection = { ...postgresConnection(), id: "kingbase-1", name: "Kingbase", db_type: "kingbase" as const, database: "onepass" };
    const group: TreeNode = { id: "kingbase-1:onepass:app:__procedures", label: "tree.procedures", type: "group-procedures", connectionId: connection.id, database: "onepass", schema: "app", children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [{ id: "kingbase-1:onepass:app", label: "app", type: "schema", connectionId: connection.id, database: "onepass", schema: "app", children: [group] }] }];

    await store.loadObjectGroupChildren(group);
    expect(listObjects).toHaveBeenNthCalledWith(1, connection.id, "onepass", "app", ["PROCEDURE"], undefined, 12, 0);
    expect(group.children?.filter((node) => node.type === "procedure")).toHaveLength(11);
    const more = group.children?.at(-1);
    expect(more?.type).toBe("load-more");
    await store.loadMoreObjectGroupChildren(more!);

    expect(listObjects).toHaveBeenNthCalledWith(2, connection.id, "onepass", "app", ["PROCEDURE"], undefined, 12, 11);
    const procedures = group.children?.filter((node) => node.type === "procedure") ?? [];
    expect(procedures).toHaveLength(12);
    expect(new Set(procedures.map((node) => node.id)).size).toBe(12);
    expect(procedures.filter((node) => node.objectName === "run").map((node) => node.signature)).toEqual(["v integer", "v text"]);
    expect(procedures.filter((node) => node.objectName !== "run").map((node) => node.signature)).toEqual(Array(10).fill(""));
    expect(group.children?.some((node) => node.type === "load-more")).toBe(false);
  }, 20000);

  it("merges Xugu package body metadata when it arrives on the next page", async () => {
    const packageSpec: ObjectInfo = {
      name: "business_api",
      object_type: "PACKAGE",
      schema: "app_schema",
      valid: true,
      comment: null,
      created_at: null,
      updated_at: null,
      parent_schema: null,
      parent_name: null,
    };
    const packageBody: ObjectInfo = {
      ...packageSpec,
      object_type: "PACKAGE_BODY",
      valid: false,
    };
    const listObjects = vi.fn().mockResolvedValueOnce([packageSpec, packageBody]).mockResolvedValueOnce([packageBody]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 1;

    const connection = xuguConnection();
    const packageGroup: TreeNode = {
      id: "xugu-1:app_db:app_schema:__packages",
      label: "tree.packages",
      type: "group-packages",
      connectionId: connection.id,
      database: "app_db",
      schema: "app_schema",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "xugu-1:app_db",
            label: "app_db",
            type: "database",
            connectionId: connection.id,
            database: "app_db",
            isExpanded: true,
            children: [
              {
                id: "xugu-1:app_db:app_schema",
                label: "app_schema",
                type: "schema",
                connectionId: connection.id,
                database: "app_db",
                schema: "app_schema",
                isExpanded: true,
                children: [packageGroup],
              },
            ],
          },
        ],
      },
    ];

    await store.loadObjectGroupChildren(packageGroup);
    const packageNode = packageGroup.children?.[0];
    expect(packageNode).toEqual(expect.objectContaining({ type: "package", label: "business_api", xuguPackageBodyAvailable: undefined, valid: true }));
    const packageNodeId = packageNode?.id;

    const loadMoreNode = packageGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");
    await store.loadMoreObjectGroupChildren(loadMoreNode!);

    expect(packageGroup.children).toHaveLength(1);
    expect(packageGroup.children?.[0]?.id).toBe(packageNodeId);
    expect(packageGroup.children?.[0]).toEqual(
      expect.objectContaining({
        type: "package",
        label: "business_api",
        xuguPackageBodyAvailable: true,
        xuguPackageBodyValid: false,
        valid: false,
      }),
    );
  });

  it("reloads a collapsed database after a forced connection database refresh", async () => {
    const listDatabases = vi
      .fn()
      .mockResolvedValueOnce([
        { name: "test1", comment: null },
        { name: "test2", comment: null },
      ])
      .mockResolvedValueOnce([{ name: "test1", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [
        {
          id: test1Id,
          label: "test1",
          type: "database",
          connectionId: connection.id,
          database: "test1",
          isExpanded: false,
          children: [],
        },
      ],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadTables(connection.id, "test1");
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
    expect(connectionNode.children![0].children?.length).toBeGreaterThan(0);

    connectionNode.children![0].isExpanded = false;
    connectionNode.children![0].children = [];

    await store.loadDatabases(connection.id, { force: true });
    expect(listDatabases).toHaveBeenCalledTimes(1);
    expect(connectionNode.children![0].children?.map((node) => node.type)).toEqual(["saved-sql-root"]);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(false);

    await store.loadTables(connection.id, "test1");
    expect(connectionNode.children![0].children?.length).toBeGreaterThan(0);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
  });

  it("reloads a collapsed database in simple mode after a forced connection database refresh", async () => {
    const tables: TableInfo[] = [{ name: "users", table_type: "TABLE", comment: null }];
    const listDatabases = vi
      .fn()
      .mockResolvedValueOnce([{ name: "test1", comment: null }])
      .mockResolvedValueOnce([{ name: "test1", comment: null }]);
    const listTables = vi.fn().mockResolvedValue(tables);
    const listObjects = vi.fn().mockResolvedValue([]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [
        {
          id: test1Id,
          label: "test1",
          type: "database",
          connectionId: connection.id,
          database: "test1",
          isExpanded: false,
          children: [],
        },
      ],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadTables(connection.id, "test1");
    expect(listTables).toHaveBeenCalledTimes(1);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);

    connectionNode.children![0].isExpanded = false;
    connectionNode.children![0].children = [];

    await store.loadDatabases(connection.id, { force: true });
    listTables.mockClear();

    await store.loadTables(connection.id, "test1");
    expect(connectionNode.children![0].children?.length ?? 0).toBeGreaterThan(0);
  });

  it("refetches a simple empty database after DDL-driven same-id shell refresh", async () => {
    const listDatabases = vi.fn().mockResolvedValue([{ name: "test1", comment: null }]);
    const listTables = vi
      .fn()
      .mockResolvedValueOnce([])
      .mockResolvedValueOnce([{ name: "users", table_type: "TABLE", comment: null }]);
    const listObjects = vi.fn().mockResolvedValue([]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [
        {
          id: test1Id,
          label: "test1",
          type: "database",
          connectionId: connection.id,
          database: "test1",
          isExpanded: false,
          children: [],
        },
      ],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadTables(connection.id, "test1");
    expect(listTables).toHaveBeenCalledTimes(1);
    expect(store.canUseLoadedTreeNodeToggle(store.treeNodes[0].children![0])).toBe(true);

    connectionNode.children![0].isExpanded = false;
    connectionNode.children![0].children = [];

    // DDL created the first table; connection-level refresh rebuilds the same-id empty shell.
    await store.loadDatabases(connection.id, { force: true });
    listTables.mockClear();

    await store.loadTables(connection.id, "test1");
    expect(listTables).toHaveBeenCalledTimes(1);
    expect(connectionNode.children![0].children?.some((child) => child.label === "users")).toBe(true);
  });

  it("does not refetch a legitimately empty simple-mode database on re-expand", async () => {
    const listTables = vi.fn().mockResolvedValue([]);
    const listObjects = vi.fn().mockResolvedValue([]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: test1Id,
            label: "test1",
            type: "database",
            connectionId: connection.id,
            database: "test1",
            isExpanded: true,
            children: [],
          },
        ],
      },
    ];

    await store.loadTables(connection.id, "test1");
    expect(listTables).toHaveBeenCalledTimes(1);
    expect(store.canUseLoadedTreeNodeToggle(store.treeNodes[0].children![0])).toBe(true);

    listTables.mockClear();
    await store.loadTables(connection.id, "test1");
    expect(listTables).not.toHaveBeenCalled();
  });

  it("clears grouped object-group markers when the database shell goes stale", async () => {
    const tables: TableInfo[] = [{ name: "users", table_type: "TABLE", comment: null }];
    const listTables = vi.fn().mockResolvedValue(tables);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const dbNode: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [dbNode],
      },
    ];

    await store.loadTables(connection.id, "test1");
    const tablesGroup = dbNode.children?.find((child) => child.type === "group-tables");
    expect(tablesGroup).toBeDefined();
    await store.loadObjectGroupChildren(tablesGroup!);
    const tablesGroupInTree = dbNode.children?.find((child) => child.type === "group-tables");
    expect(tablesGroupInTree?.children?.length ?? 0).toBeGreaterThan(0);
    const groupId = tablesGroupInTree!.id;
    expect(store.isTreeNodeChildrenLoaded(groupId)).toBe(true);
    expect(store.canUseLoadedTreeNodeToggle(tablesGroupInTree!)).toBe(true);

    dbNode.children = [];
    listTables.mockClear();
    await store.loadTables(connection.id, "test1");

    expect(store.isTreeNodeChildrenLoaded(groupId)).toBe(false);
    expect(store.canUseLoadedTreeNodeToggle({ ...tablesGroup!, id: groupId, children: [] } as TreeNode)).toBe(false);

    const refreshedTablesGroup = dbNode.children?.find((child) => child.type === "group-tables");
    expect(refreshedTablesGroup).toBeDefined();
    await store.loadObjectGroupChildren(refreshedTablesGroup!);
    expect(listTables).toHaveBeenCalledTimes(1);
    expect(refreshedTablesGroup?.children?.length).toBeGreaterThan(0);
  });

  it("applies async table loads to the current tree node after an in-tree replacement", async () => {
    const tables: TableInfo[] = [{ name: "users", table_type: "TABLE", comment: null }];
    let resolveTables!: (tables: TableInfo[]) => void;
    const listTablesPromise = new Promise<TableInfo[]>((resolve) => {
      resolveTables = resolve;
    });
    const listTables = vi.fn(() => listTablesPromise);
    const listObjects = vi.fn().mockResolvedValue([]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const staleDbNode: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [staleDbNode],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const loadPromise = store.loadTables(connection.id, "test1");
    await vi.waitFor(() => expect(listTables).toHaveBeenCalled());
    const replacementDb: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    connectionNode.children = [replacementDb];
    resolveTables(tables);
    await loadPromise;

    expect(staleDbNode.children?.length ?? 0).toBe(0);
    expect(replacementDb.children?.length ?? 0).toBeGreaterThan(0);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
  });

  it("applies persisted cache to the current tree node after an in-tree replacement", async () => {
    const cachedTable: TreeNode = {
      id: "mysql-1:test1:users",
      label: "users",
      type: "table",
      connectionId: "mysql-1",
      database: "test1",
      isExpanded: false,
      children: [],
    };
    let resolveCache!: (payload: unknown) => void;
    const loadSchemaCachePromise = new Promise<unknown>((resolve) => {
      resolveCache = resolve;
    });
    const loadSchemaCache = vi.fn(() => loadSchemaCachePromise);
    const listTables = vi.fn();

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      loadSchemaCache,
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const staleDbNode: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [staleDbNode],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const loadPromise = store.loadTables(connection.id, "test1");
    await vi.waitFor(() => expect(loadSchemaCache).toHaveBeenCalled());
    const replacementDb: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    connectionNode.children = [replacementDb];
    resolveCache({
      version: 2,
      cachedAt: new Date().toISOString(),
      children: [cachedTable],
    });
    await loadPromise;

    expect(listTables).not.toHaveBeenCalled();
    expect(staleDbNode.children?.length ?? 0).toBe(0);
    expect(replacementDb.children?.length ?? 0).toBeGreaterThan(0);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
  });

  it("keeps database loaded markers when connection children are reordered only", async () => {
    const listDatabases = vi.fn().mockResolvedValue([{ name: "test1", comment: null }]);
    const listTables = vi.fn().mockResolvedValue([{ name: "users", table_type: "TABLE", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: test1Id,
            label: "test1",
            type: "database",
            connectionId: connection.id,
            database: "test1",
            isExpanded: true,
            children: [],
          },
        ],
      },
    ];

    await store.loadDatabases(connection.id, { force: true });
    await store.loadTables(connection.id, "test1");
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
    listTables.mockClear();

    await store.loadDatabases(connection.id);
    expect(listDatabases).toHaveBeenCalledTimes(1);
    expect(listTables).not.toHaveBeenCalled();
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
  });

  it("keeps database loaded markers when connection refresh passes utility-only children", async () => {
    const listDatabases = vi
      .fn()
      .mockResolvedValueOnce([{ name: "test1", comment: null }])
      .mockResolvedValueOnce([]);
    const listTables = vi.fn().mockResolvedValue([{ name: "users", table_type: "TABLE", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [],
      },
    ];

    await store.loadDatabases(connection.id, { force: true });
    await store.loadTables(connection.id, "test1");
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
    listTables.mockClear();

    await store.loadDatabases(connection.id, { force: true });

    expect(listDatabases).toHaveBeenCalledTimes(2);
    expect(listTables).not.toHaveBeenCalled();
    expect(store.treeNodes[0].children?.some((child) => child.id === test1Id && child.type === "database")).toBe(true);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
  });

  it("adds the Xugu user-permissions utility only to Xugu connection roots", async () => {
    const listDatabases = vi.fn().mockResolvedValue([{ name: "testdb", comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const xugu = xuguConnection();
    const mysql = mysqlConnection();
    store.connections = [xugu, mysql];
    store.connectedIds = new Set([xugu.id, mysql.id]);
    store.treeNodes = [xugu, mysql].map((connection) => ({
      id: connection.id,
      label: connection.name,
      type: "connection" as const,
      connectionId: connection.id,
      isExpanded: false,
      children: [],
    }));

    await store.loadDatabases(xugu.id, { connectedOnly: true });
    await store.loadDatabases(mysql.id, { connectedOnly: true });

    const xuguRoot = store.treeNodes.find((node) => node.connectionId === xugu.id)!;
    const mysqlRoot = store.treeNodes.find((node) => node.connectionId === mysql.id)!;
    expect(xuguRoot.children?.filter((node) => node.type === "xugu-user-admin")).toHaveLength(1);
    expect(mysqlRoot.children?.some((node) => node.type === "xugu-user-admin")).toBe(false);
    expect(mysqlRoot.children?.some((node) => node.type === "user-admin")).toBe(true);
  }, 15000);

  it("clears connection loading after disconnect even when metadata apply is skipped", async () => {
    let resolveDatabases!: (value: { name: string; comment: null }[]) => void;
    const listDatabases = vi.fn(
      () =>
        new Promise<{ name: string; comment: null }[]>((resolve) => {
          resolveDatabases = resolve;
        }),
    );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = mysqlConnection();
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const loadPromise = store.loadDatabases(connection.id, { force: true });
    await vi.waitFor(() => expect(listDatabases).toHaveBeenCalled());
    expect(connectionNode.isLoading).toBe(true);
    store.connectedIds.delete(connection.id);
    resolveDatabases([{ name: "app", comment: null }]);
    await loadPromise;

    const liveConnection = store.treeNodes.find((node) => node.id === connection.id);
    expect(liveConnection?.isLoading).toBe(false);
    expect(connectionNode.isLoading).toBe(false);
  });

  it("ignores stale metadata results after disconnect and same-id reconnect", async () => {
    let resolveOldTables!: (tables: TableInfo[]) => void;
    let resolveNewTables!: (tables: TableInfo[]) => void;
    let listTablesCalls = 0;
    const listTables = vi.fn(() => {
      listTablesCalls += 1;
      if (listTablesCalls === 1) {
        return new Promise<TableInfo[]>((resolve) => {
          resolveOldTables = resolve;
        });
      }
      return new Promise<TableInfo[]>((resolve) => {
        resolveNewTables = resolve;
      });
    });
    const listObjects = vi.fn().mockResolvedValue([]);
    const connectDb = vi.fn().mockResolvedValue("mysql-1");
    const disconnectDb = vi.fn().mockResolvedValue(undefined);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      connectDb,
      disconnectDb,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [
        {
          id: test1Id,
          label: "test1",
          type: "database",
          connectionId: connection.id,
          database: "test1",
          isExpanded: true,
          children: [],
        },
      ],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const staleLoad = store.loadTables(connection.id, "test1");
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(1));

    await store.disconnect(connection.id);
    expect(store.connectedIds.has(connection.id)).toBe(false);

    const reconnectedDb: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
      isLoading: false,
    };
    connectionNode.children = [reconnectedDb];
    await store.connect(connection);
    expect(store.connectedIds.has(connection.id)).toBe(true);

    const freshLoad = store.loadTables(connection.id, "test1", undefined, { force: true });
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(2));
    expect(reconnectedDb.isLoading).toBe(true);

    resolveOldTables([{ name: "stale_users", table_type: "TABLE", comment: null }]);
    await staleLoad;

    expect(reconnectedDb.children?.some((child) => child.label === "stale_users")).toBe(false);
    expect(reconnectedDb.isLoading).toBe(true);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(false);

    resolveNewTables([{ name: "fresh_users", table_type: "TABLE", comment: null }]);
    await freshLoad;
    expect(reconnectedDb.children?.some((child) => child.label === "fresh_users")).toBe(true);
    expect(reconnectedDb.isLoading).toBe(false);
  });

  it("keeps database loading spinner when ensureConnected reconnects during the same load", async () => {
    let resolveTables!: (tables: TableInfo[]) => void;
    const listTables = vi.fn(
      () =>
        new Promise<TableInfo[]>((resolve) => {
          resolveTables = resolve;
        }),
    );
    const listObjects = vi.fn().mockResolvedValue([]);
    const checkConnectionHealth = vi.fn().mockRejectedValueOnce(new Error("pool dead")).mockResolvedValue(undefined);
    const connectDb = vi.fn().mockResolvedValue("mysql-1");

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth,
      connectDb,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const dbNode: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [dbNode],
      },
    ];

    const loadPromise = store.loadTables(connection.id, "test1");
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(1));
    expect(checkConnectionHealth).toHaveBeenCalled();
    expect(connectDb).toHaveBeenCalled();
    expect(dbNode.isLoading).toBe(true);

    resolveTables([{ name: "users", table_type: "TABLE", comment: null }]);
    await loadPromise;

    expect(dbNode.children?.some((child) => child.label === "users")).toBe(true);
    expect(dbNode.isLoading).toBe(false);
  });

  it("finishes an expanding database when the connection refresh adds siblings", async () => {
    let resolveSchemas!: (schemas: { name: string; comment: null }[]) => void;
    const listSchemaInfos = vi.fn(
      () =>
        new Promise<{ name: string; comment: null }[]>((resolve) => {
          resolveSchemas = resolve;
        }),
    );
    const listDatabases = vi.fn().mockResolvedValue([
      { name: "app", comment: null },
      { name: "postgres", comment: null },
    ]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const databaseNode: TreeNode = {
      id: `${connection.id}:app`,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      isLoading: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];
    const liveDatabaseNode = store.treeNodes[0]!.children![0]!;

    const schemaLoad = store.loadSchemas(connection.id, "app");
    await vi.waitFor(() => expect(listSchemaInfos).toHaveBeenCalledTimes(1));
    expect(liveDatabaseNode.isLoading).toBe(true);

    await store.loadDatabases(connection.id, { connectedOnly: true });

    const databaseDuringRefresh = store.treeNodes[0]?.children?.find((child) => child.id === databaseNode.id);
    expect(databaseDuringRefresh).toBe(liveDatabaseNode);
    expect(databaseDuringRefresh?.isLoading).toBe(true);

    resolveSchemas([{ name: "public", comment: null }]);
    await schemaLoad;

    const loadedDatabase = store.treeNodes[0]?.children?.find((child) => child.id === databaseNode.id);
    expect(loadedDatabase).toBe(liveDatabaseNode);
    expect(loadedDatabase?.isLoading).toBe(false);
    expect(loadedDatabase?.isExpanded).toBe(true);
    expect(loadedDatabase?.children?.map((child) => child.label)).toContain("public");
  });

  it("clears sticky subtree loading when health-check reconnect bumps revision", async () => {
    let resolveTables!: (tables: TableInfo[]) => void;
    const listTables = vi.fn(
      () =>
        new Promise<TableInfo[]>((resolve) => {
          resolveTables = resolve;
        }),
    );
    const listObjects = vi.fn().mockResolvedValue([]);
    const checkConnectionHealth = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValue(new Error("pool dead"));
    const connectDb = vi.fn().mockResolvedValue("mysql-1");

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth,
      connectDb,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const dbNode: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: true,
      children: [],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [dbNode],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const staleLoad = store.loadTables(connection.id, "test1");
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(1));
    expect(dbNode.isLoading).toBe(true);
    expect(checkConnectionHealth).toHaveBeenCalledTimes(1);

    // Expire the health-check TTL, then ensureConnected: failed health → reconnect
    // bumps the epoch while the same DB node object survives (unlike disconnect).
    await new Promise((resolve) => setTimeout(resolve, 2100));
    await store.ensureConnected(connection.id);
    expect(checkConnectionHealth).toHaveBeenCalledTimes(2);
    expect(connectDb).toHaveBeenCalled();
    expect(store.connectedIds.has(connection.id)).toBe(true);
    expect(connectionNode.children?.[0]).toBe(dbNode);
    expect(dbNode.isLoading).toBe(false);

    resolveTables([{ name: "stale_users", table_type: "TABLE", comment: null }]);
    await staleLoad;

    expect(dbNode.children?.some((child) => child.label === "stale_users")).toBe(false);
    expect(dbNode.isLoading).toBe(false);
    expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(false);
  });

  it("does not re-expand a node collapsed while its load is still in flight", async () => {
    let resolveTables!: (tables: TableInfo[]) => void;
    const listTables = vi.fn(
      () =>
        new Promise<TableInfo[]>((resolve) => {
          resolveTables = resolve;
        }),
    );
    const listObjects = vi.fn().mockResolvedValue([]);
    const checkConnectionHealth = vi.fn().mockResolvedValue(undefined);
    const connectDb = vi.fn().mockResolvedValue("mysql-1");

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth,
      connectDb,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listTables,
      listObjects,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";

    const connection = mysqlConnection();
    const test1Id = `${connection.id}:test1`;
    const dbNode: TreeNode = {
      id: test1Id,
      label: "test1",
      type: "database",
      connectionId: connection.id,
      database: "test1",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [dbNode],
      },
    ];

    const loadPromise = store.loadTables(connection.id, "test1");
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(1));
    expect(dbNode.isLoading).toBe(true);
    expect(dbNode.isExpanded).toBe(false);

    // Simulate the user collapsing the node while the metadata load is still in flight.
    dbNode.isExpanded = false;
    store.cancelTreeNodeLoad(dbNode.id);

    resolveTables([{ name: "users", table_type: "TABLE", comment: null }]);
    await loadPromise;

    // The in-flight load must not re-expand the node, and the spinner must be cleared.
    expect(dbNode.isLoading).toBe(false);
    expect(dbNode.isExpanded).toBe(false);
  });

  it("does not re-expand an Informix schema collapsed while its metadata cache is being saved", async () => {
    let resolveCacheSave!: () => void;
    const saveSchemaCache = vi.fn(
      () =>
        new Promise<void>((resolve) => {
          resolveCacheSave = resolve;
        }),
    );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache,
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "grouped";

    const connection = informixConnection();
    const databaseNode: TreeNode = {
      id: `${connection.id}:prulife`,
      label: "prulife",
      type: "database",
      connectionId: connection.id,
      database: "prulife",
      isExpanded: true,
      children: [],
    };
    const schemaNode: TreeNode = {
      id: `${connection.id}:prulife:xtdpcky`,
      label: "xtdpcky",
      type: "schema",
      connectionId: connection.id,
      database: "prulife",
      schema: "xtdpcky",
      isExpanded: true,
      children: [],
    };
    databaseNode.children = [schemaNode];
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];

    const loadPromise = store.loadTables(connection.id, "prulife", "xtdpcky", { force: true });
    await vi.waitFor(() => expect(saveSchemaCache).toHaveBeenCalledTimes(1));
    expect(saveSchemaCache.mock.calls[0]?.[0]).toBe(`${connection.id}:prulife:xtdpcky:objects-grouped-v9-informix-owner-v2`);
    expect(schemaNode.isLoading).toBe(true);

    schemaNode.isExpanded = false;
    store.cancelTreeNodeLoad(schemaNode.id);
    resolveCacheSave();
    await loadPromise;

    expect(schemaNode.isLoading).toBe(false);
    expect(schemaNode.isExpanded).toBe(false);
  });

  it("does not let an Informix schema load reclaim ownership after collapse during a health check", async () => {
    let resolveHealthCheck!: () => void;
    const checkConnectionHealth = vi.fn(
      () =>
        new Promise<void>((resolve) => {
          resolveHealthCheck = resolve;
        }),
    );
    const saveSchemaCache = vi.fn().mockResolvedValue(undefined);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth,
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache,
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "grouped";

    const connection = informixConnection();
    const schemaNode: TreeNode = {
      id: `${connection.id}:prulife:xtdpcky`,
      label: "xtdpcky",
      type: "schema",
      connectionId: connection.id,
      database: "prulife",
      schema: "xtdpcky",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: `${connection.id}:prulife`,
            label: "prulife",
            type: "database",
            connectionId: connection.id,
            database: "prulife",
            isExpanded: true,
            children: [schemaNode],
          },
        ],
      },
    ];

    const loadPromise = store.loadTables(connection.id, "prulife", "xtdpcky", { force: true });
    await vi.waitFor(() => expect(checkConnectionHealth).toHaveBeenCalledTimes(1));
    expect(schemaNode.isLoading).toBe(true);

    schemaNode.isExpanded = false;
    store.cancelTreeNodeLoad(schemaNode.id);
    resolveHealthCheck();
    await loadPromise;

    expect(saveSchemaCache).not.toHaveBeenCalled();
    expect(schemaNode.isLoading).toBe(false);
    expect(schemaNode.isExpanded).toBe(false);
  });

  it("does not apply load-more results after the parent generation is invalidated", async () => {
    const firstPage = Array.from({ length: 201 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const refreshedFirstPage = firstPage.map((table) => ({ ...table, name: `fresh_${table.name}` }));
    let resolveSecondPage!: (tables: TableInfo[]) => void;
    const secondPagePromise = new Promise<TableInfo[]>((resolve) => {
      resolveSecondPage = resolve;
    });
    const listTables = vi
      .fn()
      .mockResolvedValueOnce(firstPage)
      .mockImplementationOnce(() => secondPagePromise)
      .mockResolvedValueOnce(refreshedFirstPage);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [
        {
          id: "mysql-1:app",
          label: "app",
          type: "database",
          connectionId: connection.id,
          database: "app",
          isExpanded: true,
          children: [tablesGroup],
        },
      ],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadObjectGroupChildren(tablesGroup);
    const loadMoreNode = tablesGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");

    const loadMorePromise = store.loadMoreObjectGroupChildren(loadMoreNode!);
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(2));

    // Force-reload the parent group while load-more is in flight. Parent stays in-tree, but its
    // generation advances; the stale page must not merge into the refreshed children.
    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.some((child) => child.label?.startsWith("fresh_"))).toBe(true);

    resolveSecondPage([{ name: "t_0201", table_type: "TABLE", comment: null }]);
    await loadMorePromise;

    expect(tablesGroup.children?.some((child) => child.label === "t_0201")).toBe(false);
    expect(tablesGroup.children?.some((child) => child.label?.startsWith("fresh_"))).toBe(true);
  });

  it("automatically drains only opted-in table groups", async () => {
    const rows = Array.from({ length: 5 }, (_, index) => ({
      name: `object_${index + 1}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, searchFilter?: string, limit?: number, offset?: number, objectTypes?: string[]) => {
      const tableType = objectTypes?.includes("VIEW") ? "VIEW" : "TABLE";
      const matches = searchFilter ? rows.filter((row) => row.name.includes(searchFilter)) : rows;
      return Promise.resolve(matches.slice(offset ?? 0, (offset ?? 0) + (limit ?? matches.length)).map((row) => ({ ...row, table_type: tableType })));
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 2;

    const connection = { ...mysqlConnection(), sidebar_auto_load_all_tables: true };
    const tablesGroup: TreeNode = {
      id: `${connection.id}:app:__tables`,
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    const viewsGroup: TreeNode = {
      ...tablesGroup,
      id: `${connection.id}:app:__views`,
      label: "tree.views",
      type: "group-views",
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [tablesGroup, viewsGroup] }];

    await store.loadObjectGroupChildren(tablesGroup);

    expect(listTables.mock.calls.map((call) => call[5])).toEqual([0, 2, 4]);
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(rows.map((row) => row.name));
    expect(tablesGroup.children?.some((child) => child.type === "load-more")).toBe(false);
    const filteredTree = filterLocallySearchedTables(store.treeNodes, {
      enabled: true,
      queries: { [tablesGroup.id]: "object_5" },
      indexedResults: {},
    });
    expect(filteredTree[0].children?.[0]?.children?.map((child) => child.label)).toEqual(["object_5"]);

    await store.loadObjectGroupChildren(viewsGroup);

    expect(listTables).toHaveBeenCalledTimes(4);
    expect(viewsGroup.children?.map((child) => child.label)).toEqual(["object_1", "object_2", "tree.loadMore"]);

    const searchedTablesGroup: TreeNode = { ...tablesGroup, id: `${connection.id}:search:__tables`, database: "search", children: [] };
    store.treeNodes[0].children!.push(searchedTablesGroup);
    store.sidebarSearchQuery = "object_5";
    await store.loadObjectGroupChildren(searchedTablesGroup, { force: true });

    expect(listTables).toHaveBeenCalledTimes(5);
    expect(listTables.mock.calls.at(-1)?.slice(3, 6)).toEqual(["object_5", SIDEBAR_SEARCH_RESULT_BUDGET, undefined]);
    expect(searchedTablesGroup.children?.map((child) => child.label)).toEqual(["object_5"]);
  });

  it("keeps legacy connections on the first table page", async () => {
    const rows = Array.from({ length: 3 }, (_, index) => ({
      name: `table_${index + 1}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, _searchFilter?: string, limit?: number, offset?: number) => Promise.resolve(rows.slice(offset ?? 0, (offset ?? 0) + (limit ?? rows.length))));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 2;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: `${connection.id}:app:__tables`,
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [tablesGroup] }];

    await store.loadObjectGroupChildren(tablesGroup);

    expect(listTables).toHaveBeenCalledTimes(1);
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(["table_1", "table_2", "tree.loadMore"]);
  });

  it("restores and drains unfiltered pages when expand-all races a search clear reload", async () => {
    const tables = Array.from({ length: 5 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    let resolveSearchClearReload!: (tables: TableInfo[]) => void;
    let unfilteredFirstPageCalls = 0;
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, searchFilter?: string, limit?: number, offset?: number) => {
      if (searchFilter) return Promise.resolve(tables.filter((table) => table.name.includes(searchFilter)));
      if ((offset ?? 0) === 0 && ++unfilteredFirstPageCalls === 1) {
        return new Promise<TableInfo[]>((resolve) => {
          resolveSearchClearReload = resolve;
        });
      }
      return Promise.resolve(tables.slice(offset ?? 0, (offset ?? 0) + (limit ?? tables.length)));
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 2;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];

    store.sidebarSearchQuery = "0003";
    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(["t_0003"]);
    expect(store.isTreeNodeChildrenLoaded(tablesGroup.id)).toBe(true);

    store.sidebarSearchQuery = "";
    const searchClearReload = store.loadObjectGroupChildren(tablesGroup, { force: true });
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(2));

    await store.loadAllObjectGroupChildren(tablesGroup);
    resolveSearchClearReload(tables.slice(0, 3));
    await searchClearReload;

    expect(tablesGroup.children?.map((child) => child.label)).toEqual(tables.map((table) => table.name));
    expect(tablesGroup.children?.some((child) => child.type === "load-more")).toBe(false);
    expect(tablesGroup.objectCount).toBe(5);
    expect(tablesGroup.isLoading).toBe(false);
    expect(listTables.mock.calls.map((call) => [call[3], call[4], call[5]])).toEqual([
      ["0003", SIDEBAR_SEARCH_RESULT_BUDGET, undefined],
      [undefined, 3, 0],
      [undefined, 3, 0],
      [undefined, 3, 2],
      [undefined, 3, 4],
    ]);

    await store.loadAllObjectGroupChildren(tablesGroup);
    expect(listTables).toHaveBeenCalledTimes(5);
  });

  it("restores the pre-search pages when a remote sidebar search is cleared", async () => {
    const tables = Array.from({ length: 5 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, searchFilter?: string, limit?: number, offset?: number) => {
      const matches = searchFilter ? tables.filter((table) => table.name.includes(searchFilter)) : tables;
      const start = offset ?? 0;
      return Promise.resolve(matches.slice(start, start + (limit ?? matches.length)));
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 2;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];

    // The user expands the group and pages through "load more" until every table is in memory.
    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    while (tablesGroup.children?.some((child) => child.type === "load-more")) {
      await store.loadMoreObjectGroupChildren(tablesGroup.children.find((child) => child.type === "load-more")!);
    }
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(tables.map((table) => table.name));
    expect(tablesGroup.objectCount).toBe(5);
    const unfilteredPageOneCalls = listTables.mock.calls.filter((call) => !call[3] && (call[5] ?? 0) === 0).length;

    // Typing a search swaps the children for a filtered projection.
    store.sidebarSearchQuery = "0003";
    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(["t_0003"]);

    // Clearing the query must put the previously loaded pages back, without
    // dropping the user back to the first page through a fresh reload.
    store.sidebarSearchQuery = "";
    expect(store.restoreFilteredObjectGroupChildren(tablesGroup)).toBe(true);
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(tables.map((table) => table.name));
    expect(tablesGroup.objectCount).toBe(5);
    expect(tablesGroup.isExpanded).toBe(true);
    expect(store.isTreeNodeChildrenLoaded(tablesGroup.id)).toBe(true);
    expect(listTables.mock.calls.filter((call) => !call[3] && (call[5] ?? 0) === 0).length).toBe(unfilteredPageOneCalls);

    // With no captured list (a group that was never loaded) the caller falls back to a reload.
    const untouchedGroup: TreeNode = { ...tablesGroup, id: "mysql-1:app:__views", type: "group-views", children: [] };
    expect(store.restoreFilteredObjectGroupChildren(untouchedGroup)).toBe(false);
  });

  async function installAggregatedCacheDeleteStore(options?: { initialChildren?: TreeNode[] }) {
    const tables = Array.from({ length: 5 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const listTables = vi.fn(() => Promise.resolve(tables));
    const deleteSchemaCachePrefix = vi.fn().mockResolvedValue(undefined);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: options?.initialChildren ?? [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];
    return { store, tablesGroup, listTables, deleteSchemaCachePrefix, tables };
  }

  it("aggregates persisted cache deletes for discarded sibling nodes into one ancestor prefix", async () => {
    const { store, tablesGroup, listTables, deleteSchemaCachePrefix, tables } = await installAggregatedCacheDeleteStore();

    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(tables.map((table) => table.name));
    // Nothing was discarded yet, so no persisted cache delete may fire.
    expect(deleteSchemaCachePrefix).not.toHaveBeenCalled();

    // The refreshed list drops four of the five tables: their per-node cache
    // deletes must collapse into a single ancestor-prefix request pair.
    listTables.mockImplementation(() => Promise.resolve(tables.slice(4)));
    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(["t_0005"]);
    expect(deleteSchemaCachePrefix.mock.calls.map((call) => call[0]).sort()).toEqual(["mysql-1%3Aapp%3A__tables:", "mysql-1:app:__tables:"]);
  });

  it("keeps per-node persisted deletes for discarded ids outside the ancestor prefix", async () => {
    const strayNode: TreeNode = {
      id: "foreign:id",
      label: "legacy",
      type: "table",
      connectionId: "mysql-1",
      database: "app",
      isExpanded: false,
      children: [],
    };
    const { store, tablesGroup, deleteSchemaCachePrefix, tables } = await installAggregatedCacheDeleteStore({ initialChildren: [strayNode] });

    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(tables.map((table) => table.name));
    // The stray child does not live under the group's id prefix, so it cannot be
    // covered by the ancestor delete and must keep its own request pair.
    expect(deleteSchemaCachePrefix.mock.calls.map((call) => call[0]).sort()).toEqual(["foreign%3Aid:", "foreign:id:"]);
  });

  it("shares one persisted delete between nested discarded prefixes", async () => {
    const strayParent: TreeNode = {
      id: "x:a",
      label: "outer",
      type: "table",
      connectionId: "mysql-1",
      database: "app",
      isExpanded: false,
      children: [],
    };
    const strayChild: TreeNode = {
      id: "x:a:b",
      label: "inner",
      type: "table",
      connectionId: "mysql-1",
      database: "app",
      isExpanded: false,
      children: [],
    };
    const { store, tablesGroup, deleteSchemaCachePrefix } = await installAggregatedCacheDeleteStore({ initialChildren: [strayParent, strayChild] });

    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    // "x:a:b" is covered by the "x:a" prefix, so only the covering pair fires.
    expect(deleteSchemaCachePrefix.mock.calls.map((call) => call[0]).sort()).toEqual(["x%3Aa:", "x:a:"]);
    expect(deleteSchemaCachePrefix).toHaveBeenCalledTimes(2);
  });

  it("issues no persisted cache delete when the refreshed list keeps every child", async () => {
    const { store, tablesGroup, deleteSchemaCachePrefix, tables } = await installAggregatedCacheDeleteStore();

    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    await store.loadObjectGroupChildren(tablesGroup, { force: true });
    expect(tablesGroup.children?.map((child) => child.label)).toEqual(tables.map((table) => table.name));
    expect(deleteSchemaCachePrefix).not.toHaveBeenCalled();
  });

  it("pages table-scoped search results instead of truncating at the search budget", async () => {
    const tables = Array.from({ length: 5 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, searchFilter?: string, limit?: number, offset?: number) => {
      const matches = searchFilter ? tables.filter((table) => table.name.includes(searchFilter)) : tables;
      const start = offset ?? 0;
      return Promise.resolve(matches.slice(start, start + (limit ?? matches.length)));
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 2;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];

    store.sidebarTableSearchQueries[tablesGroup.id] = "t";
    await store.loadObjectGroupChildren(tablesGroup, {
      force: true,
      searchFilter: "t",
      sidebarTableSearchParentId: tablesGroup.id,
      expectedSidebarTableSearchQuery: "t",
    });

    expect(tablesGroup.children?.map((child) => child.label)).toEqual(["t_0001", "t_0002", "tree.loadMore"]);
    expect(tablesGroup.children?.at(-1)?.type).toBe("load-more");
    expect(listTables.mock.calls[0].slice(3, 6)).toEqual(["t", 3, 0]);

    await store.loadMoreObjectGroupChildren(tablesGroup.children!.at(-1)!, { searchFilter: "t" });

    expect(tablesGroup.children?.map((child) => child.label)).toEqual(["t_0001", "t_0002", "t_0003", "t_0004", "tree.loadMore"]);
    expect(tablesGroup.children?.at(-1)?.type).toBe("load-more");
    expect(listTables.mock.calls[1].slice(3, 6)).toEqual(["t", 3, 2]);
  });

  it("discards a collapsed remote-search projection so the next expansion reloads the ordinary page", async () => {
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, searchFilter?: string, limit?: number) => {
      if (searchFilter) {
        return Promise.resolve([{ name: "zz_late_probe", table_type: "TABLE" as const, comment: null }]);
      }
      return Promise.resolve(
        Array.from({ length: Math.min(limit ?? 1001, 1001) }, (_, index) => ({
          name: `t_${String(index + 1).padStart(4, "0")}`,
          table_type: "TABLE" as const,
          comment: null,
        })),
      );
    });
    const deleteSchemaCachePrefix = vi.fn().mockResolvedValue(undefined);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix,
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 1000;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [tablesGroup] }];

    store.sidebarSearchQuery = "zz_late_probe";
    await store.loadObjectGroupChildren(tablesGroup, { force: true });

    expect(listTables).toHaveBeenLastCalledWith(connection.id, "app", "app", "zz_late_probe", SIDEBAR_SEARCH_RESULT_BUDGET, undefined, ["TABLE"]);
    expect(tablesGroup.children?.map((node) => node.label)).toEqual(["zz_late_probe"]);
    expect(tablesGroup.objectCount).toBe(1);
    expect(store.canUseLoadedTreeNodeToggle(tablesGroup)).toBe(true);

    tablesGroup.isExpanded = false;
    expect(store.discardFilteredTreeNodeChildren(tablesGroup.id)).toBe(true);
    expect(tablesGroup.children).toEqual([]);
    expect(tablesGroup.objectCount).toBeUndefined();
    expect(store.canUseLoadedTreeNodeToggle(tablesGroup)).toBe(false);
    expect(deleteSchemaCachePrefix).not.toHaveBeenCalled();

    store.sidebarSearchQuery = "";
    await store.loadObjectGroupChildren(tablesGroup);

    expect(listTables).toHaveBeenLastCalledWith(connection.id, "app", "app", undefined, 1001, 0, ["TABLE"]);
    expect(tablesGroup.children).toHaveLength(1001);
    expect(tablesGroup.children?.at(-1)?.type).toBe("load-more");
  });

  it("keeps connection-name matches out of object metadata filters", async () => {
    const listTables = vi.fn((_connectionId: string, _database: string, _schema: string, searchFilter?: string) => Promise.resolve(searchFilter === "orders" || !searchFilter ? [{ name: "orders", table_type: "TABLE" as const, comment: null }] : []));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;
    const connection = { ...mysqlConnection(), name: "60307" };
    const tablesGroup: TreeNode = {
      id: "mysql-1:basic:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "basic",
      isExpanded: true,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [tablesGroup] }];

    store.sidebarSearchQuery = "60307";
    await store.loadObjectGroupChildren(tablesGroup, { force: true, searchFilter: "", allowGlobalSearchMismatch: true, expectedSidebarSearchQuery: "60307" });

    expect(listTables).toHaveBeenLastCalledWith(connection.id, "basic", "basic", undefined, 201, 0, ["TABLE"]);
    expect(tablesGroup.children?.map((node) => node.label)).toEqual(["orders"]);

    store.sidebarSearchQuery = "orders";
    await store.loadObjectGroupChildren(tablesGroup, { force: true });

    expect(listTables).toHaveBeenLastCalledWith(connection.id, "basic", "basic", "orders", SIDEBAR_SEARCH_RESULT_BUDGET, undefined, ["TABLE"]);
    expect(tablesGroup.children?.map((node) => node.label)).toEqual(["orders"]);

    let resolveAncestorLoad!: (tables: TableInfo[]) => void;
    listTables.mockImplementationOnce(
      () =>
        new Promise<TableInfo[]>((resolve) => {
          resolveAncestorLoad = resolve;
        }),
    );
    store.sidebarSearchQuery = "60307";
    const ancestorLoad = store.loadObjectGroupChildren(tablesGroup, {
      force: true,
      searchFilter: "",
      allowGlobalSearchMismatch: true,
      expectedSidebarSearchQuery: "60307",
    });
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(3));

    store.sidebarSearchQuery = "customers";
    resolveAncestorLoad([{ name: "stale_table", table_type: "TABLE", comment: null }]);
    await ancestorLoad;

    expect(tablesGroup.children?.map((node) => node.label)).toEqual(["orders"]);
  });

  it("merges load-more table pages onto the live group node after an in-tree replacement", async () => {
    const firstPage = Array.from({ length: 201 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    let resolveSecondPage!: (tables: TableInfo[]) => void;
    const secondPagePromise = new Promise<TableInfo[]>((resolve) => {
      resolveSecondPage = resolve;
    });
    const listTables = vi
      .fn()
      .mockResolvedValueOnce(firstPage)
      .mockImplementationOnce(() => secondPagePromise);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection = mysqlConnection();
    const staleTablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [
        {
          id: "mysql-1:app",
          label: "app",
          type: "database",
          connectionId: connection.id,
          database: "app",
          isExpanded: true,
          children: [staleTablesGroup],
        },
      ],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    await store.loadObjectGroupChildren(staleTablesGroup);
    const loadMoreNode = staleTablesGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");

    const loadMorePromise = store.loadMoreObjectGroupChildren(loadMoreNode!);
    await vi.waitFor(() => expect(listTables).toHaveBeenCalledTimes(2));

    const concurrentTable: TreeNode = {
      id: "mysql-1:app:__concurrent_marker",
      label: "__concurrent_marker",
      type: "table",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    const liveTablesGroup: TreeNode = {
      ...staleTablesGroup,
      children: [...(staleTablesGroup.children?.filter((child) => child.type !== "load-more") ?? []), concurrentTable, loadMoreNode!],
    };
    connectionNode.children![0].children = [liveTablesGroup];

    resolveSecondPage([{ name: "t_0201", table_type: "TABLE", comment: null }]);
    await loadMorePromise;

    expect(staleTablesGroup.children?.some((child) => child.label === "t_0201")).toBe(false);
    expect(liveTablesGroup.children?.some((child) => child.id === concurrentTable.id)).toBe(true);
    expect(liveTablesGroup.children?.some((child) => child.label === "t_0201")).toBe(true);
  });

  it("keeps table column loaded markers when a tables group appends via load-more", async () => {
    const firstPage = Array.from({ length: 201 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    const listTables = vi
      .fn()
      .mockResolvedValueOnce(firstPage)
      .mockResolvedValueOnce([{ name: "t_0201", table_type: "TABLE", comment: null }]);
    const getColumns = vi.fn().mockResolvedValue([{ name: "id", data_type: "INT", is_nullable: false, column_default: null, is_primary_key: true, extra: null, comment: null }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      getColumns,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];

    await store.loadObjectGroupChildren(tablesGroup);
    const firstTable = tablesGroup.children?.find((child) => child.type === "table");
    expect(firstTable).toBeDefined();
    await store.loadTableGroups(connection.id, "app", firstTable!.label, undefined, firstTable!.id);
    const columnsGroupId = `${firstTable!.id}:__columns`;
    await store.loadColumns(connection.id, "app", firstTable!.label, undefined, columnsGroupId);
    expect(store.isTreeNodeChildrenLoaded(columnsGroupId)).toBe(true);

    const loadMoreNode = tablesGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");
    getColumns.mockClear();
    await store.loadMoreObjectGroupChildren(loadMoreNode!);

    expect(store.isTreeNodeChildrenLoaded(columnsGroupId)).toBe(true);
    expect(getColumns).not.toHaveBeenCalled();
  });

  it("re-reads the displayed table window when the next page no longer opens with the anchored row", async () => {
    const firstPage = Array.from({ length: 201 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    // Between the two page loads a table that sorts to the very front was created, so every
    // later offset now points one row earlier: offset 200 no longer opens with the first
    // page's peek row t_0201 but with t_0199. Appending that page would leave the freshly
    // created t_0000b (and the row the window slid past) out of the tree for good (#9400).
    const afterCreate = [
      { name: "t_0000b", table_type: "TABLE" as const, comment: null },
      ...firstPage,
      ...Array.from({ length: 200 }, (_, index) => ({
        name: `t_${String(index + 202).padStart(4, "0")}`,
        table_type: "TABLE" as const,
        comment: null,
      })),
    ];
    const listTables = vi
      .fn()
      .mockResolvedValueOnce(firstPage)
      .mockImplementation((_connectionId: string, _database: string, _schema: string, _searchFilter?: string, limit?: number, offset?: number) => Promise.resolve(afterCreate.slice(offset ?? 0, (offset ?? 0) + (limit ?? afterCreate.length))));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];

    await store.loadObjectGroupChildren(tablesGroup);
    const loadMoreNode = tablesGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");
    expect(loadMoreNode?.loadMore?.offset).toBe(200);
    expect(listTables.mock.calls[0].slice(3, 6)).toEqual([undefined, 201, 0]);

    await store.loadMoreObjectGroupChildren(loadMoreNode!);

    // The drifted page is replaced by one re-read of the whole displayed range (offset 0,
    // pageSize 200 + the 200 rows already shown), so nothing is skipped or repeated.
    expect(listTables).toHaveBeenCalledTimes(3);
    expect(listTables.mock.calls[1].slice(3, 6)).toEqual([undefined, 201, 200]);
    expect(listTables.mock.calls[2].slice(3, 6)).toEqual([undefined, 401, 0]);

    const labels = (tablesGroup.children ?? []).filter((child) => child.type === "table").map((child) => child.label);
    expect(labels).toContain("t_0000b");
    expect(labels).toContain("t_0201");
    expect(labels.filter((label) => label === "t_0199")).toHaveLength(1);
    expect(labels.filter((label) => label === "t_0200")).toHaveLength(1);

    const nextLoadMore = tablesGroup.children?.at(-1);
    expect(nextLoadMore?.type).toBe("load-more");
    expect(nextLoadMore?.loadMore?.offset).toBe(400);
    expect(nextLoadMore?.loadMore?.anchor).toBeDefined();
  });

  it("re-reads the displayed window when the next page comes back empty after rows were dropped", async () => {
    const firstPage = Array.from({ length: 201 }, (_, index) => ({
      name: `t_${String(index + 1).padStart(4, "0")}`,
      table_type: "TABLE" as const,
      comment: null,
    }));
    // The three leading tables were dropped between the two page loads, so offset 200 now
    // points past the end of the list. Keeping the empty page would leave the deleted rows
    // on screen and the rows the window slid onto (t_0201) out of the tree forever (#9400).
    const afterDrop = firstPage.slice(3);
    const listTables = vi
      .fn()
      .mockResolvedValueOnce(firstPage)
      .mockImplementation((_connectionId: string, _database: string, _schema: string, _searchFilter?: string, limit?: number, offset?: number) => Promise.resolve(afterDrop.slice(offset ?? 0, (offset ?? 0) + (limit ?? afterDrop.length))));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection = mysqlConnection();
    const tablesGroup: TreeNode = {
      id: "mysql-1:app:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "app",
      isExpanded: false,
      children: [],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [
          {
            id: "mysql-1:app",
            label: "app",
            type: "database",
            connectionId: connection.id,
            database: "app",
            isExpanded: true,
            children: [tablesGroup],
          },
        ],
      },
    ];

    await store.loadObjectGroupChildren(tablesGroup);
    const loadMoreNode = tablesGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");
    expect(loadMoreNode?.loadMore?.offset).toBe(200);

    await store.loadMoreObjectGroupChildren(loadMoreNode!);

    expect(listTables.mock.calls[1].slice(3, 6)).toEqual([undefined, 201, 200]);
    expect(listTables.mock.calls[2].slice(3, 6)).toEqual([undefined, 401, 0]);

    // The window slides onto t_0201 instead of staying on the pre-drop window, and the
    // list is now known to be complete, so the dead load-more node goes away. Rows the
    // server no longer returns are left to the sidebar's own staleness prunes.
    const labels = (tablesGroup.children ?? []).filter((child) => child.type === "table").map((child) => child.label);
    expect(labels).toContain("t_0201");
    expect(labels.filter((label) => label === "t_0201")).toHaveLength(1);
    expect(tablesGroup.children?.some((child) => child.type === "load-more")).toBe(false);
  });

  it("applies SQL Server database object loads to the current tree node after an in-tree replacement", async () => {
    let resolveSchemas!: (schemas: string[]) => void;
    const listSchemas = vi.fn(
      () =>
        new Promise<string[]>((resolve) => {
          resolveSchemas = resolve;
        }),
    );

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listSchemas,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    useSettingsStore().editorSettings.sidebarObjectDisplay = "grouped";

    const connection = {
      id: "sqlserver-1",
      name: "SQL Server",
      db_type: "sqlserver",
      host: "127.0.0.1",
      port: 1433,
      username: "sa",
      password: "",
      database: "master",
    } as ConnectionConfig;
    const dbId = `${connection.id}:app`;
    const staleDbNode: TreeNode = {
      id: dbId,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    const connectionNode: TreeNode = {
      id: connection.id,
      label: connection.name,
      type: "connection",
      connectionId: connection.id,
      isExpanded: true,
      children: [staleDbNode],
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];

    const loadPromise = store.loadSqlServerDatabaseObjects(connection.id, "app", { force: true });
    await vi.waitFor(() => expect(listSchemas).toHaveBeenCalled());
    const replacementDb: TreeNode = {
      id: dbId,
      label: "app",
      type: "database",
      connectionId: connection.id,
      database: "app",
      isExpanded: true,
      children: [],
    };
    connectionNode.children = [replacementDb];
    resolveSchemas(["dbo"]);
    await loadPromise;

    expect(staleDbNode.children?.length ?? 0).toBe(0);
    expect(replacementDb.children?.length ?? 0).toBeGreaterThan(0);
    expect(store.isTreeNodeChildrenLoaded(dbId)).toBe(true);
  });

  it("loads custom type members into the current tree node and ignores stale responses", async () => {
    let resolveFirst!: (value: any) => void;
    const first = new Promise((resolve) => {
      resolveFirst = resolve;
    });
    const getCustomTypeDetails = vi
      .fn()
      .mockReturnValueOnce(first)
      .mockResolvedValueOnce({
        name: "status",
        schema: "app",
        kind: "enum",
        members: [{ name: "", dataType: "", ordinal: 1, enumValue: "published" }],
        properties: { domainConstraints: [] },
      });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      getCustomTypeDetails,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = postgresConnection();
    const typeNode: TreeNode = {
      id: `${connection.id}:app:types:status`,
      label: "status",
      objectName: "status",
      type: "type",
      connectionId: connection.id,
      database: "app",
      schema: "app",
      children: undefined,
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        children: [typeNode],
      },
    ];

    const staleLoad = store.loadCustomTypeChildren(typeNode, { force: true });
    await vi.waitFor(() => expect(getCustomTypeDetails).toHaveBeenCalledTimes(1));
    await store.loadCustomTypeChildren(typeNode, { force: true });
    resolveFirst({
      name: "status",
      schema: "app",
      kind: "enum",
      members: [{ name: "", dataType: "", ordinal: 1, enumValue: "draft" }],
      properties: { domainConstraints: [] },
    });
    await staleLoad;

    expect(typeNode.isExpanded).toBe(true);
    expect(typeNode.customTypeKind).toBe("enum");
    expect(typeNode.hasMembers).toBe(true);
    expect(typeNode.children?.map((child) => child.label)).toEqual(["published"]);
    expect(store.isTreeNodeChildrenLoaded(typeNode.id)).toBe(true);
  });

  it("loads Oracle TYPE attributes on demand, caches known-empty results, retries failures, and ignores stale detail responses", async () => {
    let resolveStale!: (value: any) => void;
    const stale = new Promise((resolve) => {
      resolveStale = resolve;
    });
    const oracleDetails = (attributes: any[]) => ({
      name: "TYPE_OBJ",
      schema: "APP",
      kind: "object",
      members: [],
      oracleMetadata: {
        attributesRead: { state: "available" },
        methodsRead: { state: "available" },
        propertiesRead: { state: "available" },
        collectionRead: { state: "unsupported" },
        bodyRead: { state: "unsupported" },
        attributes,
        methods: [],
      },
    });
    const getCustomTypeDetails = vi
      .fn()
      .mockResolvedValueOnce(oracleDetails([]))
      .mockRejectedValueOnce(new Error("temporary catalog failure"))
      .mockResolvedValueOnce(oracleDetails([{ name: "STREET", ordinal: 1, typeName: "VARCHAR2" }]))
      .mockReturnValueOnce(stale)
      .mockResolvedValueOnce(oracleDetails([{ name: "CITY", ordinal: 1, typeName: "VARCHAR2" }]));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      getCustomTypeDetails,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = oracleConnection();
    const typeNode: TreeNode = {
      id: `${connection.id}:XE:APP:TYPE_OBJ`,
      label: "TYPE_OBJ",
      objectName: "TYPE_OBJ",
      type: "type",
      connectionId: connection.id,
      database: "XE",
      schema: "APP",
      children: undefined,
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [typeNode] }];

    await store.loadCustomTypeChildren(typeNode, { force: true });
    expect(typeNode.hasMembers).toBe(false);
    expect(typeNode.children).toEqual([]);
    await expect(store.loadCustomTypeChildren(typeNode, { force: true })).rejects.toThrow("temporary catalog failure");
    await store.loadCustomTypeChildren(typeNode, { force: true });
    expect(typeNode.hasMembers).toBe(true);
    expect(typeNode.children?.map((child) => child.label)).toEqual(["STREET"]);

    const staleLoad = store.loadCustomTypeChildren(typeNode, { force: true });
    await vi.waitFor(() => expect(getCustomTypeDetails).toHaveBeenCalledTimes(4));
    await store.loadCustomTypeChildren(typeNode, { force: true });
    resolveStale(oracleDetails([{ name: "STALE", ordinal: 1, typeName: "VARCHAR2" }]));
    await staleLoad;
    expect(typeNode.children?.map((child) => child.label)).toEqual(["CITY"]);
    expect(typeNode.hasMembers).toBe(true);
  });

  it("keeps Oracle attributes unknown and retryable when a successful detail DTO reports unavailable or incomplete reads", async () => {
    const oracleDetails = (read: { state: string; reason?: string }, attributes: any[]) => ({
      name: "TYPE_OBJ",
      schema: "APP",
      kind: "object",
      members: [],
      oracleMetadata: {
        attributesRead: read,
        methodsRead: { state: "available" },
        propertiesRead: { state: "available" },
        collectionRead: { state: "unsupported" },
        bodyRead: { state: "unsupported" },
        attributes,
        methods: [],
      },
    });
    const getCustomTypeDetails = vi
      .fn()
      .mockResolvedValueOnce(oracleDetails({ state: "unavailable", reason: "Dictionary access denied." }, []))
      .mockResolvedValueOnce(oracleDetails({ state: "incomplete", reason: "One attribute row could not be read." }, [{ name: "STREET", ordinal: 1, typeName: "VARCHAR2" }]))
      .mockResolvedValueOnce(oracleDetails({ state: "available" }, []));

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      getCustomTypeDetails,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    const connection = oracleConnection();
    const typeNode: TreeNode = {
      id: `${connection.id}:XE:APP:TYPE_OBJ`,
      label: "TYPE_OBJ",
      objectName: "TYPE_OBJ",
      type: "type",
      connectionId: connection.id,
      database: "XE",
      schema: "APP",
      children: undefined,
    };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [{ id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, children: [typeNode] }];

    await store.loadCustomTypeChildren(typeNode);
    expect(typeNode.hasMembers).toBeUndefined();
    expect(typeNode.children).toEqual([]);
    expect(store.isTreeNodeChildrenLoaded(typeNode.id)).toBe(false);

    await store.loadCustomTypeChildren(typeNode);
    expect(typeNode.hasMembers).toBeUndefined();
    expect(typeNode.children?.map((child) => child.label)).toEqual(["STREET"]);
    expect(store.isTreeNodeChildrenLoaded(typeNode.id)).toBe(false);

    await store.loadCustomTypeChildren(typeNode);
    expect(typeNode.hasMembers).toBe(false);
    expect(typeNode.children).toEqual([]);
    expect(store.isTreeNodeChildrenLoaded(typeNode.id)).toBe(true);
    expect(getCustomTypeDetails).toHaveBeenCalledTimes(3);
  });

  it("loads more object group children for catalogless databases with empty database string", async () => {
    const firstPageTables = Array.from({ length: 201 }, (_, i) => ({
      name: `t_${String(i + 1).padStart(4, "0")}`,
      table_type: "BASE TABLE",
      comment: null,
    }));
    const secondPageTables = [
      {
        name: "t_0201",
        table_type: "BASE TABLE",
        comment: null,
      },
    ];
    const listTables = vi.fn(async (...args: unknown[]) => {
      const offset = args[5] as number;
      if (offset === 0) return firstPageTables;
      return secondPageTables;
    });

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listTables,
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const { useSettingsStore } = await import("@/stores/settingsStore");
    const store = useConnectionStore();
    const settingsStore = useSettingsStore();
    settingsStore.editorSettings.sidebarObjectDisplay = "grouped";
    settingsStore.desktopSettings.sidebar_table_page_size = 200;

    const connection: ConnectionConfig = {
      id: "hana-1",
      name: "SAP HANA",
      db_type: "saphana",
      host: "127.0.0.1",
      port: 39015,
      username: "SYSTEM",
      password: "",
      database: "",
    } as ConnectionConfig;

    const tablesGroup: TreeNode = {
      id: "hana-1:::APP:__tables",
      label: "tree.tables",
      type: "group-tables",
      connectionId: connection.id,
      database: "",
      schema: "APP",
      isExpanded: false,
      children: [],
    };
    const schemaNode: TreeNode = {
      id: "hana-1:::APP",
      label: "APP",
      type: "schema",
      connectionId: connection.id,
      database: "",
      schema: "APP",
      isExpanded: true,
      children: [tablesGroup],
    };
    const databaseNode: TreeNode = {
      id: "hana-1::",
      label: "tree.defaultDatabase",
      type: "database",
      connectionId: connection.id,
      database: "",
      isExpanded: true,
      children: [schemaNode],
    };

    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [
      {
        id: connection.id,
        label: connection.name,
        type: "connection",
        connectionId: connection.id,
        isExpanded: true,
        children: [databaseNode],
      },
    ];

    await store.loadObjectGroupChildren(tablesGroup);
    const loadMoreNode = tablesGroup.children?.at(-1);
    expect(loadMoreNode?.type).toBe("load-more");

    await store.loadMoreObjectGroupChildren(loadMoreNode!);

    expect(listTables).toHaveBeenCalledTimes(2);
    expect(listTables.mock.calls[1][1]).toBe("");
    expect(listTables.mock.calls[1][2]).toBe("APP");
    expect(listTables.mock.calls[1][5]).toBe(200);
    const labels = (tablesGroup.children ?? []).filter((child) => child.type === "table").map((child) => child.label);
    expect(labels).toContain("t_0201");
  });

  it("expands the catalogless default database on open and refreshes it after saving a schema filter", async () => {
    const listDatabases = vi.fn().mockResolvedValue([]);
    const listSchemaInfos = vi.fn().mockResolvedValue([{ name: "APP_USER" }, { name: "APP_USER_ARCHIVE" }, { name: "SYS" }]);

    vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
    vi.doMock("@/lib/backend/api", () => ({
      checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
      deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
      listDatabases,
      listInstalledAgents: vi.fn().mockResolvedValue([]),
      listObjects: vi.fn().mockResolvedValue([]),
      listSchemaInfos,
      listTables: vi.fn().mockResolvedValue([]),
      loadSchemaCache: vi.fn().mockResolvedValue(null),
      saveSchemaCache: vi.fn().mockResolvedValue(undefined),
      saveConnections: vi.fn().mockResolvedValue(undefined),
      saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
    }));

    const { useConnectionStore } = await import("@/stores/connectionStore");
    const store = useConnectionStore();
    // A Zenith (GaussDB 100) server through generic JDBC: no catalogs, users are schemas.
    const connection = {
      ...genericJdbcConnection(),
      id: "zenith-1",
      name: "Zenith",
      database: "",
      connection_string: "jdbc:zenith:@127.0.0.1:1888",
      jdbc_driver_class: "com.huawei.gauss.jdbc.ZenithDriver",
    } as ConnectionConfig;
    const connectionNode: TreeNode = { id: connection.id, label: connection.name, type: "connection", connectionId: connection.id, isExpanded: true, children: [] };
    store.connections = [connection];
    store.connectedIds.add(connection.id);
    store.treeNodes = [connectionNode];
    store.sidebarLayout = { groups: [], order: [{ type: "connection", id: connection.id }] };

    await store.loadDatabases(connection.id, { force: true });
    // Saving the filter rebuilds the tree, so always resolve the live node.
    const findById = (nodes: TreeNode[], id: string): TreeNode | undefined => {
      for (const node of nodes) {
        if (node.id === id) return node;
        const found = findById(node.children ?? [], id);
        if (found) return found;
      }
      return undefined;
    };
    const defaultDatabase = () => findById(store.treeNodes, "zenith-1:")!;
    const schemaLabels = () =>
      defaultDatabase()
        .children?.filter((node) => node.type === "schema")
        .map((node) => node.label);
    // Opening the connection expands the placeholder default database so the schemas show at once.
    expect(defaultDatabase().id).toBe("zenith-1:");
    expect(defaultDatabase().isExpanded).toBe(true);
    expect(schemaLabels()).toEqual(["APP_USER", "APP_USER_ARCHIVE", "SYS"]);

    await store.setVisibleSchemas(connection.id, "", ["APP_USER"]);

    // The saved filter must show without a manual refresh of the connection.
    expect(store.getConfig(connection.id)?.visible_schemas).toEqual({ "": ["APP_USER"] });
    expect(schemaLabels()).toEqual(["APP_USER"]);
  });
});