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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(redis): refresh key-prefix tree nodes (#13050)
ccq0998862994e1
diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.subtreeFill.spec.ts b/apps/desktop/src/components/redis/RedisKeyBrowser.subtreeFill.spec.tsindex 359af3d6cd..42023aec30 100644--- a/apps/desktop/src/components/redis/RedisKeyBrowser.subtreeFill.spec.ts+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.subtreeFill.spec.ts@@ -30,6 +30,8 @@ const mocks = vi.hoisted(() => ({listRedisCompletionCommandDocs: vi.fn(),listRedisCompletionKeys: vi.fn(),redisScanPageSize: 100,+ separator: ":",+ keyFilter: "",infiniteScroll: true,queryResultMaxRowsEnabled: true,queryResultMaxRows: 5000,@@ -60,7 +62,7 @@ vi.mock("@/lib/backend/api", () => ({vi.mock("@/stores/connectionStore", () => ({useConnectionStore: () => ({ensureConnected: vi.fn().mockResolvedValue(undefined),- getConfig: () => ({ name: "Redis", redis_key_separator: ":", redis_scan_page_size: mocks.redisScanPageSize }),+ getConfig: () => ({ name: "Redis", redis_key_separator: mocks.separator, redis_key_filter: mocks.keyFilter, redis_scan_page_size: mocks.redisScanPageSize }),updateRedisDbKeyStats: mocks.updateRedisDbKeyStats,listRedisCompletionCommandDocs: mocks.listRedisCompletionCommandDocs,listRedisCompletionKeys: mocks.listRedisCompletionKeys,@@ -222,7 +224,21 @@ vi.mock("@/components/editor/DangerConfirmDialog.vue", async () => {vi.mock("./RedisValueViewer.vue", async () => {const { defineComponent, h } = await import("vue");- return { default: defineComponent({ setup: () => () => h("div") }) };+ return {+ default: defineComponent({+ props: { keyRaw: String, metadata: Object },+ emits: ["deleted", "renamed", "loaded"],+ setup(props, { emit }) {+ return () =>+ h("div", [+ h("output", { "data-viewer-metadata": "" }, JSON.stringify(props.metadata)),+ h("button", { "data-viewer-delete": "", onClick: () => emit("deleted", props.keyRaw) }),+ h("button", { "data-viewer-rename": "", onClick: () => emit("renamed", props.keyRaw, "grp:renamed", "grp:renamed") }),+ h("button", { "data-viewer-loaded": "", onClick: () => emit("loaded", { key_raw: props.keyRaw, key_display: props.metadata?.key_display, redis_type: "string", ttl: 120, data: { kind: "string", content: { display: "updated", raw_base64: "dXBkYXRlZA==", encoding: "utf8" } } }) }),+ ]);+ },+ }),+ };});vi.mock("./RedisPubSubPanel.vue", async () => {@@ -241,8 +257,9 @@ vi.mock("vue-virtual-scroller", async () => {RecycleScroller: defineComponent({inheritAttrs: false,props: { items: { type: Array, default: () => [] } },- setup(props, { attrs, slots }) {+ setup(props, { attrs, slots, expose }) {const visibleItemCount = 50;+ expose({ scrollToItem: () => undefined });return () =>h("div",@@ -334,7 +351,10 @@ function deferred<T>() {function resetApiMocks() {vi.clearAllMocks();+ mocks.redisScanKeysBatch.mockReset();mocks.redisScanPageSize = 100;+ mocks.separator = ":";+ mocks.keyFilter = "";mocks.infiniteScroll = true;mocks.queryResultMaxRowsEnabled = true;mocks.queryResultMaxRows = 5000;@@ -410,6 +430,304 @@ function leafVisible(host: HTMLElement, keyRaw: string): boolean {const SUBTREE_FILL_MAX_CALLS_BY_KEYS = 5;const SUBTREE_FILL_MAX_CALLS_BY_ITERATIONS = 7;+function groupCheckbox(host: HTMLElement, path: string[], db = 0): HTMLInputElement {+ const checkbox = Array.from(host.querySelectorAll<HTMLInputElement>("[data-redis-group]")).find((element) => element.dataset.redisGroup === `group:${db}:${JSON.stringify(path)}`);+ expect(checkbox, `group ${path.join(":")}`).toBeDefined();+ return checkbox!;+}++function refreshGroupButton(host: HTMLElement, path = ["grp"]): HTMLButtonElement {+ const button = Array.from(host.querySelectorAll<HTMLButtonElement>("[data-redis-refresh-group]")).find((element) => element.dataset.redisRefreshGroup === `group:0:${JSON.stringify(path)}`);+ expect(button, `refresh action for ${path.join(":")}`).toBeDefined();+ return button!;+}++describe("RedisKeyBrowser prefix refresh (issue #13028)", () => {+ beforeEach(stubOverflowingViewport);++ function completeTree(keys = ["grp:old", "grp:keep", "other:keep"]) {+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: keys.map(keyInfo), total_keys: keys.length });+ }++ it("replaces only the refreshed prefix and preserves sibling expansion and checked keys", async () => {+ completeTree(["grp:old", "grp:keep", "grp:child:keep", "other:keep"]);+ const host = mountBrowser();+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ groupCheckbox(host, ["grp", "child"]).parentElement!.parentElement!.click();+ groupCheckbox(host, ["other"]).parentElement!.parentElement!.click();+ await settleThoroughly();+ host.querySelector<HTMLInputElement>("[data-redis-leaf='other:keep']")!.click();+ host.querySelector<HTMLInputElement>("[data-redis-leaf='grp:old']")!.click();+ await settleThoroughly();++ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [keyInfo("grp:keep"), keyInfo("grp:new"), keyInfo("grp:child:keep")], total_keys: 4 });+ refreshGroupButton(host).click();+ await settleThoroughly();++ expect(leafVisible(host, "grp:old")).toBe(false);+ expect(leafVisible(host, "grp:new")).toBe(true);+ expect(leafVisible(host, "grp:keep")).toBe(true);+ expect(leafVisible(host, "grp:child:keep")).toBe(true);+ expect(host.querySelector<HTMLInputElement>("[data-redis-leaf='other:keep']")?.checked).toBe(true);+ expect(host.textContent).toContain("redis.deselectAll");+ expect(mocks.redisScanKeysBatch).toHaveBeenLastCalledWith("connection", 0, 0, "grp:*", 100, 8, true);+ });++ it("removes an expired empty prefix without touching a neighboring prefix", async () => {+ completeTree(["grp:old", "grp2:keep"]);+ const host = mountBrowser();+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [], total_keys: 1 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(host.querySelectorAll("[data-redis-group]")).toHaveLength(1);+ groupCheckbox(host, ["grp2"]).parentElement!.parentElement!.click();+ await settleThoroughly();+ expect(leafVisible(host, "grp2:keep")).toBe(true);+ });++ it("refreshes metadata of existing keys", async () => {+ completeTree(["grp:keep"]);+ const host = mountBrowser();+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [{ ...keyInfo("grp:keep"), key_type: "hash", ttl: 3600 }], total_keys: 1 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ const row = host.querySelector("[data-redis-key-raw='grp:keep']")!;+ expect(row.textContent).toContain("hash");+ expect(row.textContent).not.toContain("string");+ expect(row.textContent).not.toContain("redis.noExpiry");+ });++ it("retains the previous tree on failure and retries the prefix", async () => {+ completeTree();+ const host = mountBrowser();+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockRejectedValueOnce(new Error("prefix scan failed"));+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(leafVisible(host, "grp:old")).toBe(true);+ expect(mocks.toast).toHaveBeenCalledWith("prefix scan failed", 5000);+ expect(refreshGroupButton(host).disabled).toBe(false);+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [keyInfo("grp:retry")], total_keys: 2 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(leafVisible(host, "grp:retry")).toBe(true);+ expect(leafVisible(host, "grp:old")).toBe(false);+ });++ it("bounds sparse refreshes and keeps old keys until explicit continuation completes", async () => {+ completeTree();+ const host = mountBrowser();+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => Promise.resolve({ cursor: cursor + 1, keys: [], total_keys: 3 }));+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(subtreeCalls()).toHaveLength(7);+ expect(leafVisible(host, "grp:old")).toBe(true);+ expect(refreshGroupButton(host).title).toBe("redis.loadMoreKeys");+ await settleThoroughly();+ expect(subtreeCalls()).toHaveLength(7);+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [keyInfo("grp:fresh")], total_keys: 2 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(subtreeCalls()[7][2]).toBe(7);+ expect(leafVisible(host, "grp:fresh")).toBe(true);+ expect(leafVisible(host, "grp:old")).toBe(false);+ });++ it("bounds dense refreshes and preserves buffered results across passes", async () => {+ completeTree();+ const host = mountBrowser();+ await settleThoroughly();+ let page = 0;+ mocks.redisScanKeysBatch.mockImplementation(() => Promise.resolve({ cursor: ++page, keys: subtreeBatchKeys(100, page), total_keys: 1000 }));+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(subtreeCalls()).toHaveLength(5);+ expect(host.textContent).toContain("(2)");+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [keyInfo("grp:last")], total_keys: 502 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(subtreeCalls()[5][2]).toBe(5);+ expect(host.textContent).toContain("(501)");+ });++ it("escapes literal prefixes with a custom separator and honors the connection scope", async () => {+ mocks.separator = "/";+ mocks.keyFilter = "g*/*keep*";+ completeTree(["g[1]/keep-old"]);+ const host = mountBrowser();+ await settleThoroughly();+ groupCheckbox(host, ["g[1]"]).parentElement!.parentElement!.click();+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [keyInfo("g[1]/keep-new"), keyInfo("g[1]/hidden")], total_keys: 2 });+ refreshGroupButton(host, ["g[1]"]).click();+ await settleThoroughly();+ expect(mocks.redisScanKeysBatch).toHaveBeenLastCalledWith("connection", 0, 0, "g\\[1\\]/*", 100, 8, true);+ expect(leafVisible(host, "g[1]/keep-new")).toBe(true);+ expect(leafVisible(host, "g[1]/hidden")).toBe(false);+ });++ it("disables duplicate refresh clicks and discards late results after KeepAlive deactivation", async () => {+ completeTree();+ const browser = mountKeptAliveBrowser();+ await settleThoroughly();+ expandFirstGroupRow(browser.host);+ await settleThoroughly();+ const pending = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();+ mocks.redisScanKeysBatch.mockReturnValue(pending.promise);+ refreshGroupButton(browser.host).click();+ await settleThoroughly();+ expect(refreshGroupButton(browser.host).disabled).toBe(true);+ refreshGroupButton(browser.host).click();+ expect(subtreeCalls()).toHaveLength(1);+ await browser.deactivate();+ pending.resolve({ cursor: 0, keys: [keyInfo("grp:late")], total_keys: 1 });+ await settleThoroughly();+ await browser.activate();+ await settleThoroughly();+ expect(leafVisible(browser.host, "grp:old")).toBe(true);+ expect(leafVisible(browser.host, "grp:late")).toBe(false);+ expect(refreshGroupButton(browser.host).disabled).toBe(false);+ });++ it("does not change the main scan cursor when refreshing a partial tree", async () => {+ mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, _cursor: number, pattern: string) => Promise.resolve({ cursor: pattern === "*" ? 91 : 0, keys: [keyInfo("grp:keep")], total_keys: 1000 }));+ const host = mountBrowser();+ await settleThoroughly();+ refreshGroupButton(host).click();+ await settleThoroughly();+ clickLoadMore(host);+ await settleThoroughly();+ const mainCalls = mocks.redisScanKeysBatch.mock.calls.filter((call: unknown[]) => call[3] === "*");+ expect(mainCalls[1][2]).toBe(91);+ });++ it("keeps nonmatching cached keys when refreshing a locally searched full snapshot", async () => {+ mocks.redisScanKeysBatch.mockResolvedValueOnce({ cursor: 91, keys: [keyInfo("grp:keep-old"), keyInfo("grp:hidden")], total_keys: 2 });+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [], total_keys: 0 });+ const host = mountBrowser();+ await settleThoroughly();+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((button) => button.textContent?.includes("redis.fetchAllKeys"))!+ .click();+ await settleThoroughly();+ host.querySelector<HTMLButtonElement>("button[title='redis.fuzzyMatchTitle']")!.click();+ await settleThoroughly();+ const input = host.querySelector<HTMLInputElement>("input[placeholder='redis.fuzzyPattern']")!;+ input.value = "keep";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [keyInfo("grp:keep-new"), keyInfo("grp:hidden")], total_keys: 2 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ input.value = "";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ expect(leafVisible(host, "grp:hidden")).toBe(true);+ });++ it.each(["resolves", "rejects"])("ignores an old prefix refresh that %s after switching databases", async (outcome) => {+ completeTree();+ const db = ref(0);+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp(defineComponent({ setup: () => () => h(RedisKeyBrowser, { connectionId: "connection", db: db.value, blockDangerousRedisCommands: false }) }));+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));+ app.mount(host);+ mountedApps.push({ unmount: () => app.unmount(), host });+ await settleThoroughly();+ const pending = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();+ mocks.redisScanKeysBatch.mockReturnValueOnce(pending.promise);+ refreshGroupButton(host).click();+ await settleThoroughly();+ completeTree(["db1:keep"]);+ db.value = 1;+ await settleThoroughly();+ if (outcome === "resolves") pending.resolve({ cursor: 0, keys: [keyInfo("grp:late")], total_keys: 1 });+ else pending.reject(new Error("late failure"));+ await settleThoroughly();+ expect(mocks.toast).not.toHaveBeenCalled();+ expect(host.querySelectorAll("[data-redis-group]")).toHaveLength(1);+ groupCheckbox(host, ["db1"], 1).parentElement!.parentElement!.click();+ await settleThoroughly();+ expect(leafVisible(host, "db1:keep")).toBe(true);+ expect(leafVisible(host, "grp:late")).toBe(false);+ });++ it("retains unrelated groups' pending subtree cursors after refreshing a prefix", async () => {+ mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number, pattern: string) => {+ if (pattern === "other:*") return Promise.resolve({ cursor: cursor + 1, keys: [], total_keys: 0 });+ if (pattern === "grp:*") return Promise.resolve({ cursor: 0, keys: [keyInfo("grp:new")], total_keys: 1000 });+ return Promise.resolve({ cursor: 91, keys: [keyInfo("grp:old"), keyInfo("other:keep")], total_keys: 1000 });+ });+ const host = mountBrowser();+ await settleThoroughly();+ groupCheckbox(host, ["other"]).parentElement!.parentElement!.click();+ await settleThoroughly();+ refreshGroupButton(host).click();+ await settleThoroughly();+ clickLoadMore(host);+ await settleThoroughly();+ const otherCalls = mocks.redisScanKeysBatch.mock.calls.filter((call: unknown[]) => call[3] === "other:*");+ expect(otherCalls).toHaveLength(14);+ expect(otherCalls[7][2]).toBe(7);+ });++ it("publishes refreshed metadata to the surviving selected detail viewer", async () => {+ completeTree(["grp:keep"]);+ const host = mountBrowser();+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ host.querySelector<HTMLElement>("[data-redis-key-raw='grp:keep']")!.click();+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [{ ...keyInfo("grp:keep"), size: 99, ttl: 120 }], total_keys: 1 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ const metadata = JSON.parse(host.querySelector("[data-viewer-metadata]")!.textContent!);+ expect(metadata.size).toBe(99);+ expect(metadata.ttl).toBe(120);+ });++ it.each(["delete", "rename", "loaded"])("discards buffered prefix records after a confirmed detail %s", async (action) => {+ completeTree();+ const host = mountBrowser();+ await settleThoroughly();+ expandFirstGroupRow(host);+ await settleThoroughly();+ host.querySelector<HTMLElement>("[data-redis-key-raw='grp:old']")!.click();+ await settleThoroughly();+ mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => Promise.resolve({ cursor: cursor + 1, keys: [keyInfo("grp:old")], total_keys: 3 }));+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(refreshGroupButton(host).title).toBe("redis.loadMoreKeys");+ host.querySelector<HTMLButtonElement>(`[data-viewer-${action}]`)!.click();+ await settleThoroughly();+ expect(refreshGroupButton(host).title).toBe("common.refresh");+ const keys = action === "delete" ? [keyInfo("grp:keep")] : action === "rename" ? [keyInfo("grp:keep"), keyInfo("grp:renamed")] : [{ ...keyInfo("grp:old"), ttl: 120 }];+ mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: 2 });+ refreshGroupButton(host).click();+ await settleThoroughly();+ expect(subtreeCalls()[7][2]).toBe(0);+ if (action !== "loaded") expect(leafVisible(host, "grp:old")).toBe(false);+ else expect(host.querySelector("[data-redis-key-raw='grp:old']")!.textContent).not.toContain("redis.noExpiry");+ });+});+beforeEach(() => {resetApiMocks();});diff --git a/apps/desktop/src/components/redis/RedisKeyBrowser.vue b/apps/desktop/src/components/redis/RedisKeyBrowser.vueindex ea856fdf58..622012df33 100644--- a/apps/desktop/src/components/redis/RedisKeyBrowser.vue+++ b/apps/desktop/src/components/redis/RedisKeyBrowser.vue@@ -300,6 +300,14 @@ const subtreePendingGroupCursors = new Map<string, number>();// 旧 generation 的 catch/finally 清掉或覆盖同 id 的新补扫。const subtreeFillOperations = new Map<string, number>();let subtreeFillOperationId = 0;+const refreshingGroupId = ref<string | null>(null);+const groupRefresh = shallowRef<{+ groupId: string;+ pattern: string;+ cursor: number;+ keys: Map<string, { key: RedisKeyInfo; observedAt: number }>;+ totalKeys: number;+} | null>(null);// 刷新前已展开分组的快照(#7173):刷新首屏重建树时,本轮尚未扫到的分组会被// rebuildTree 从 expandedGroupIds 中裁掉;后续 load-more 页面让这些分组重新// 出现时,用该快照恢复展开状态。SCAN 游标归零(本轮已扫尽,仍未出现的分组@@ -340,8 +348,8 @@ function matchesDefaultKeyScope(key: Pick<RedisKeyInfo, "key_display" | "key_rawfunction filterScanResultToScope(result: RedisScanResult): RedisScanResult {return hasDefaultKeyScope.value ? { ...result, keys: result.keys.filter(matchesDefaultKeyScope) } : result;}-/** True while a key-list mutation (delete or batch expiry) owns the visible result set. */-const mutatingKeys = computed(() => deletingKeys.value || savingBatchExpiry.value);+/** True while a key-list mutation owns the visible result set. */+const mutatingKeys = computed(() => deletingKeys.value || savingBatchExpiry.value || refreshingGroupId.value !== null);const selectionBusy = computed(() => mutatingKeys.value || loading.value || loadingMore.value || isFetchingAll.value || searchPending.value);// checkedKeys is always a subset of loaded keys, so size equality is enough.const allLoadedKeysSelected = computed(() => flatKeys.value.length > 0 && checkedKeys.value.size === flatKeys.value.length);@@ -1009,13 +1017,15 @@ function invalidateScanRequests(resetAutoLoadBudget = true): number {loadMoreOperationId++;loadingMore.value = false;subtreeFillOperations.clear();+ groupRefresh.value = null;+ refreshingGroupId.value = null;if (resetAutoLoadBudget) autoLoadBudget = { remaining: AUTO_LOAD_TOTAL_SCAN_ITERATIONS, total: AUTO_LOAD_TOTAL_SCAN_ITERATIONS };return searchRequestId;}function invalidateFetchAllForStructuralMutation() {fetchAllSnapshotComplete.value = false;- if (isFetchingAll.value || fetchAllPublicationRollback) invalidateScanRequests();+ if (isFetchingAll.value || fetchAllPublicationRollback || groupRefresh.value) invalidateScanRequests();}function isCurrentScanOperation(requestId: number, operationId?: number): boolean {@@ -1281,7 +1291,7 @@ async function maybeAutoLoadMoreRedisKeys() {const shouldLoad = shouldLoadMoreRedisKeys({enabled: redisInfiniteScrollEnabled.value,hasMore: hasMore.value,- busy: loading.value || loadingMore.value || searchPending.value || deletingKeys.value || isFetchingAll.value,+ busy: loading.value || loadingMore.value || searchPending.value || mutatingKeys.value || isFetchingAll.value,loadedKeys: flatKeys.value.length,maxKeys: redisInfiniteScrollMaxKeys.value,scrollTop: scroller.scrollTop,@@ -1565,8 +1575,88 @@ const SUBTREE_SCAN_ITERATIONS_PER_CALL = 8;const SUBTREE_FILL_MAX_NEW_KEYS = 500;const SUBTREE_FILL_MAX_SCAN_ITERATIONS = 50;+function groupRefreshLabel(groupId: string): string {+ return groupRefresh.value?.groupId === groupId ? t("redis.loadMoreKeys") : t("common.refresh");+}++async function refreshGroupSubtree(group: RedisKeyTreeGroupNode) {+ if (!redisBrowserIsActive || selectionBusy.value) return;+ const pending = groupRefresh.value?.groupId === group.id ? groupRefresh.value : null;+ // Cancel older main/subtree pages without resetting the main cursor. A late+ // append must not resurrect keys removed by this prefix refresh.+ const requestId = invalidateScanRequests(false);+ const session = pending ?? {+ groupId: group.id,+ pattern: redisGroupSubtreePattern(group.pathSegments, redisKeySeparator.value),+ cursor: 0,+ keys: new Map<string, { key: RedisKeyInfo; observedAt: number }>(),+ totalKeys: lastTotalKeys.value,+ };+ groupRefresh.value = session;+ refreshingGroupId.value = group.id;+ const current = () => requestId === searchRequestId && redisBrowserIsActive && groupRefresh.value === session;+ let iterationsLeft = SUBTREE_FILL_MAX_SCAN_ITERATIONS;+ const initialKeyCount = session.keys.size;+ try {+ while (current() && iterationsLeft > 0 && session.keys.size - initialKeyCount < SUBTREE_FILL_MAX_NEW_KEYS) {+ const iterations = Math.min(SUBTREE_SCAN_ITERATIONS_PER_CALL, iterationsLeft);+ const result = filterScanResultToScope(+ isValueSearchMode.value && valueQuery.value+ ? await api.redisScanValues(props.connectionId, props.db, session.cursor, session.pattern, valueQuery.value, redisScanPageSize.value, searchMode.value === "all")+ : await api.redisScanKeysBatch(props.connectionId, props.db, session.cursor, session.pattern, redisScanPageSize.value, iterations, true),+ );+ if (!current()) return;+ iterationsLeft -= iterations;+ const observedAt = Date.now();+ for (const key of result.keys) {+ if (searchMode.value === "key" && !fetchAllSnapshotComplete.value && !localKeyPatternMatcher.value(key.key_display, key.key_raw)) continue;+ session.keys.set(key.key_raw, { key, observedAt });+ }+ if (session.cursor === 0) session.totalKeys = result.total_keys;+ session.cursor = result.cursor;+ if (session.cursor !== 0) continue;++ // SCAN is not a snapshot: only a completed traversal can establish which+ // previously loaded keys disappeared. Keep old rows intact between passes.+ const matches = createRedisKeyPatternMatcher(session.pattern);+ const retained = flatKeys.value.filter((key) => !matches(key.key_display, key.key_raw));+ for (const key of flatKeys.value) {+ if (matches(key.key_display, key.key_raw)) {+ ttlObservedAtByRaw.delete(key.key_raw);+ positiveTtlKeyRaws.delete(key.key_raw);+ }+ }+ for (const { key, observedAt } of session.keys.values()) {+ retained.push(key);+ recordKeyTtlObservedAt(key);+ if ((key.ttl ?? -2) > 0) ttlObservedAtByRaw.set(key.key_raw, observedAt);+ }+ loadedKeyRaws = new Set(retained.map((key) => key.key_raw));+ replaceFlatKeyRecords(retained);+ for (const candidate of treeIndex?.groupById.values() ?? []) {+ if (candidate.pathSegments.length < group.pathSegments.length || !group.pathSegments.every((segment, index) => candidate.pathSegments[index] === segment)) continue;+ subtreeFilledGroupIds.delete(candidate.id);+ subtreePendingGroupCursors.delete(candidate.id);+ }+ rebuildTree();+ keyMetadataEpoch.value++;+ lastTotalKeys.value = session.totalKeys;+ connectionStore.updateRedisDbKeyStats(props.connectionId, props.db, {+ loaded: hasFilteredKeyRange.value ? undefined : retained.length,+ total: session.totalKeys,+ });+ groupRefresh.value = null;+ return;+ }+ } catch (error) {+ if (current()) toast(errorMessage(error), 5000);+ } finally {+ if (requestId === searchRequestId) refreshingGroupId.value = null;+ }+}+function shouldFillGroupSubtree(): boolean {- return hasMore.value && !useFlatKeySearchRows.value && !hasFilteredKeyRange.value && !isFetchingAll.value;+ return hasMore.value && !useFlatKeySearchRows.value && !hasFilteredKeyRange.value && !isFetchingAll.value && !refreshingGroupId.value;}function mergeScannedKeys(newKeys: RedisKeyInfo[]) {@@ -1783,6 +1873,7 @@ function onKeyLoaded(value: RedisValue) {const previousTtl = flatKeyByRaw.get(keyInfo.key_raw)?.ttl ?? -2;const noExpiryMembershipChanged = (previousTtl === -1) !== (keyInfo.ttl === -1);if (!updateRedisKeyInfoMetadataByRaw(flatKeyByRaw, keyInfo)) return;+ if (groupRefresh.value) invalidateScanRequests(false);// 详情面板回写了最新的 TTL,同步刷新观测时刻,保证两侧倒计时一致recordKeyTtlObservedAt(keyInfo);loadedKeyRaws.add(keyInfo.key_raw);@@ -1850,6 +1941,12 @@ function redisKeyContextMenuItems(node: RedisKeyTreeNode): ContextMenuItem[] {if (node.kind === "group") {const groupPath = node.pathSegments.join(redisKeySeparator.value);const items: ContextMenuItem[] = [+ {+ label: groupRefreshLabel(node.id),+ icon: RefreshCw,+ action: () => refreshGroupSubtree(node),+ disabled: () => selectionBusy.value,+ },{label: t("redis.createKey"),icon: Plus,@@ -2038,6 +2135,7 @@ function applyKeyTtlMetadata(keyRaw: string, ttl: number): boolean {const previousTtl = keyInfo.ttl ?? -2;const nextKeyInfo: RedisKeyInfo = { ...keyInfo, ttl };if (!updateRedisKeyInfoMetadataByRaw(flatKeyByRaw, nextKeyInfo)) return false;+ if (groupRefresh.value) invalidateScanRequests(false);recordKeyTtlObservedAt(nextKeyInfo);if (treeIndex) updateRedisKeyTreeLeafMetadata(treeIndex, nextKeyInfo);return (previousTtl === -1) !== (ttl === -1);@@ -3656,6 +3754,23 @@ defineExpose({ focusSearch, insertCommand, executeCommand: executeAiCommand });</template></div><div class="flex shrink-0 items-center justify-end gap-1">+ <Button+ v-if="row.node.kind === 'group'"+ variant="ghost"+ size="icon"+ class="h-5 w-5 shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ :class="{ 'opacity-100': groupRefresh?.groupId === row.node.id }"+ :title="groupRefreshLabel(row.node.id)"+ :aria-label="groupRefreshLabel(row.node.id)"+ :aria-busy="refreshingGroupId === row.node.id"+ :disabled="selectionBusy"+ :data-redis-refresh-group="row.node.id"+ @click.stop="refreshGroupSubtree(row.node)"+ >+ <Loader2 v-if="refreshingGroupId === row.node.id" class="h-3 w-3 animate-spin" />+ <ChevronDown v-else-if="groupRefresh?.groupId === row.node.id" class="h-3 w-3" />+ <RefreshCw v-else class="h-3 w-3" />+ </Button><Badge v-if="row.node.kind === 'leaf' && redisRowKeyType(row.node)" variant="outline" class="text-xs px-1.5 py-0" :class="typeColor(redisRowKeyType(row.node))">{{ redisRowKeyType(row.node) }}</Badge><!-- TTL 徽标:与类型徽标保持一致的胶囊样式,永不过期为琥珀色、临近过期/已过期为红色警示 --><spandiff --git a/docs/pips/assets/redis-prefix-refresh-13028-continue.png b/docs/pips/assets/redis-prefix-refresh-13028-continue.pngnew file mode 100644index 0000000000..ba17c4853fBinary files /dev/null and b/docs/pips/assets/redis-prefix-refresh-13028-continue.png differdiff --git a/docs/pips/assets/redis-prefix-refresh-13028.png b/docs/pips/assets/redis-prefix-refresh-13028.pngnew file mode 100644index 0000000000..94c816a1e3Binary files /dev/null and b/docs/pips/assets/redis-prefix-refresh-13028.png differdiff --git a/docs/pips/plans/2026-10-21-redis-prefix-refresh.md b/docs/pips/plans/2026-10-21-redis-prefix-refresh.mdnew file mode 100644index 0000000000..baf12f30f3--- /dev/null+++ b/docs/pips/plans/2026-10-21-redis-prefix-refresh.md@@ -0,0 +1,70 @@+# Redis Prefix Refresh Implementation Plan++> **For agentic workers:** Use superpowers:executing-plans in this session. Follow TDD and run a fresh whole-change review after verification.++**Goal:** Refresh a Redis key-prefix node without reloading the database tree.++**Architecture:** Add a node action to the existing RedisKeyBrowser. Scan the literal prefix with an independent cursor, buffer bounded passes, and replace only that prefix after the scan completes. Preserve unrelated rows, selection and expansion; invalidate stale requests through the existing scan generation.++**Tech Stack:** Vue 3, TypeScript, existing Redis SCAN API, Vitest/happy-dom, Playwright.++**Spec:** https://github.com/t8y2/dbx/issues/13028 (user-authorized implementation; no separate requirement package).++## Global Constraints++- Preserve Redis API signatures, main SCAN cursor and existing tree conventions.+- Reuse the existing 50-iteration / 500-key subtree interaction budgets; never scan a large prefix to exhaustion automatically.+- A bounded partial scan offers explicit continuation on the same node; no deletion until completion. Errors keep the previous tree and allow retry.+- Honor literal prefix escaping, configured key separator, search and connection key scope.+- Reuse translated Refresh / Load more labels; do not add dependencies or change lockfiles.+- Work only in the isolated worktree. No commit, push, PR or issue closure without further authorization.++## Review Focus++- Empty complete scans remove expired keys, not neighboring prefixes.+- Failed or incomplete scans do not delete still-unscanned keys.+- Duplicate clicks, old subtree fills, database switches and KeepAlive deactivation cannot publish stale results.+- Pending refresh does not alter the main cursor; explicit continuation stays bounded even after the main scan is exhausted.+- Selection, expanded descendants, scope filtering and refreshed metadata remain consistent.++### Task 1: Prefix Refresh Behavior And UI++**Files:** `apps/desktop/src/components/redis/RedisKeyBrowser.vue`, `apps/desktop/src/components/redis/RedisKeyBrowser.subtreeFill.spec.ts`.++**Interfaces:** Add `refreshGroupSubtree(group: RedisKeyTreeGroupNode): Promise<void>` and a generation-owned buffered prefix scan. Consume `redisScanKeysBatch`, `redisScanValues`, `redisGroupSubtreePattern` and existing tree/index helpers without backend changes.++- [x] Add mounted-component regressions for replacement/addition, empty results, metadata, preserved siblings/selection/expansion, failures, bounded continuation, literal prefixes and stale requests.+- [x] Run the new tests and confirm the missing node refresh action fails first.+- [x] Add the inline accessible refresh/loading action and matching group context-menu action, preserving existing styles.+- [x] Implement independent bounded scanning, atomic scoped replacement, selection/TTL cleanup and generation cancellation.+- [x] Run the Redis component and helper suites; inspect actual pass/fail results.++### Task 2: Verification And Review++**Files:** The same component/tests; this plan tracks execution evidence.++- [x] Run `pnpm test`, `pnpm typecheck`, CI-format/lint checks and offline i18n completeness; distinguish baseline failures.+- [x] Validate the real component in a browser at desktop/narrow widths and light/dark themes; capture screenshots and close task-owned sessions.+- [x] Obtain a fresh whole-change review; fix important findings with failing regressions first.+- [x] Report local implementation, verification gaps and claim status separately from remote delivery.++## Execution Evidence++- Base: `origin/main` at `eeab128d7`; isolated branch `codex/redis-prefix-refresh-13028`.+- Claim: `/claim` accepted by dbx-bot; assignee is `caichangqing1120`.+- Pre-flight: frontend-only change, existing issue is the requirement source, no SE review gate applies. Current checkout's unrelated untracked files are untouched.+- Baseline: original subtree component suite passed 12/12. Initial feature regressions failed because the node action was missing. Cached-search and unrelated-subtree-cursor regressions also reproduced failures before their fixes.+- Task 1: focused suite passed 29/29, including 17 new cases. No commit made: user authorization covers implementation and claim, not Git delivery.+- Final review: fresh read-only reviewer identified stale buffered records after confirmed mutations and stale metadata in a surviving selected viewer. Four regressions reproduced these failures before fixes; all 29 focused cases then passed. No declined findings or deferred minors.+- Type check: default Node heap exhausted at approximately 4 GB; `NODE_OPTIONS=--max-old-space-size=8192 pnpm typecheck` passed without diagnostics.+- First full run: 1,925 files passed, one file failed; 25,526 tests passed and one CSS fallback test timed out at 10 seconds. Its isolated rerun passed 38/38. Final full run uses `CI=1 pnpm test` (repository CI's four-worker setting).+- Final full run: `CI=1 pnpm test` exited 0; 1,926/1,926 files and 25,531/25,531 tests passed in 294.76 seconds. This includes the final review fixes and all 29 prefix/subtree component tests. Test output contains unrelated fixture network-refusal logs and Node SQLite experimental warnings, not unhandled test failures.+- Format: both changed source files pass oxfmt; whole-source check reports the unchanged baseline `apps/desktop/src/components/mqtt/__tests__/MqttAdminConsolePublishTopic.spec.ts`. Its working-tree blob and HEAD blob both equal `3a10f0fdcc1a7a6d1aa4e0805fd4b38f97840bcf`; unrelated formatting was not changed.+- Lint passed with existing repository warnings. Connection-type generation validation and offline i18n dry-run passed; no new locale keys or lockfile changes.+- Browser: actual RedisKeyBrowser and existing components/styles, HTTP boundary mocked with controlled Redis data. Verified expired removal, new key display, preserved expanded sibling, context-menu refresh and bounded explicit continuation. Captured 1440x900 light, 820x800 dark, 390x844 narrow, and continuation screenshots under the task visualization directory. Final DOM check: refreshed key present, expired key absent, sibling present, zero alerts; browser console had zero errors.+- Browser cleanup: owned Playwright session `dbx13028` closed, its daemon/process absent; Vite stopped, temporary preview sources removed, browser logs moved to `/tmp/dbx-13028-browser-logs`. User-owned browser sessions were not touched.+- Not covered: Windows desktop runtime and a live Redis server; backend API and server code are unchanged. Redis SCAN remains non-snapshot under external concurrent writes.+- Initial delivery checkpoint: issue remained open and assigned to `caichangqing1120`; local changes retained on `codex/redis-prefix-refresh-13028`. No commit, push, PR, release or issue closure had been performed.+- Delivery authorization: user subsequently confirmed committing, pushing to `caichangqing1120/dbx` and creating a PR targeting `t8y2/dbx:main`. Merge, release and worktree cleanup remain out of scope.+- Upstream refresh: `origin/main` advanced to `b9690840a`, including the fix for the baseline MQTT formatting issue. Rebase and revalidation precede push; current verification results belong in the PR description.+- PR screenshots: `../assets/redis-prefix-refresh-13028.png` shows completed prefix refresh with the unrelated group still expanded; `../assets/redis-prefix-refresh-13028-continue.png` shows explicit bounded continuation.