Files
dbx/apps/desktop/src/components/redis/RedisKeyBrowser.expiry.spec.ts
T

1679 lines
70 KiB
TypeScript
Vendored

// @vitest-environment happy-dom
import { CalendarDateTime, resetLocalTimeZone, setLocalTimeZone } from "@internationalized/date";
import { createApp, defineComponent, h, KeepAlive, nextTick, ref, type ComponentPublicInstance } from "vue";
import { createI18n } from "vue-i18n";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { calendarDateTimeToUnixSeconds } from "@/components/ui/date-time-picker/dateTimePicker";
import type { RedisKeyInfo } from "@/lib/backend/api";
const mocks = vi.hoisted(() => ({
redisScanKeysBatch: vi.fn(),
redisGetValue: vi.fn(),
redisSetString: vi.fn(),
redisJsonSet: vi.fn(),
redisHashSet: vi.fn(),
redisListPush: vi.fn(),
redisSetAdd: vi.fn(),
redisZadd: vi.fn(),
redisStreamAdd: vi.fn(),
redisSetTtl: vi.fn(),
redisSetExpireAt: vi.fn(),
redisCheckJsonModule: vi.fn(),
redisDeleteKey: vi.fn(),
redisDeleteKeys: vi.fn(),
redisExecuteCommand: vi.fn(),
saveHistory: vi.fn(),
canBuildRedisFuzzyTree: vi.fn((loadedKeyCount: number) => loadedKeyCount <= 200_000),
toast: vi.fn(),
updateRedisDbKeyStats: vi.fn(),
listRedisCompletionCommandDocs: vi.fn(),
listRedisCompletionKeys: vi.fn(),
redisScanPageSize: 100,
infiniteScroll: false,
queryResultMaxRowsEnabled: true,
queryResultMaxRows: 5000,
}));
vi.mock("@/lib/backend/api", () => ({
redisScanKeysBatch: mocks.redisScanKeysBatch,
redisGetValue: mocks.redisGetValue,
redisSetString: mocks.redisSetString,
redisJsonSet: mocks.redisJsonSet,
redisHashSet: mocks.redisHashSet,
redisListPush: mocks.redisListPush,
redisSetAdd: mocks.redisSetAdd,
redisZadd: mocks.redisZadd,
redisStreamAdd: mocks.redisStreamAdd,
redisSetTtl: mocks.redisSetTtl,
redisSetExpireAt: mocks.redisSetExpireAt,
redisCheckJsonModule: mocks.redisCheckJsonModule,
redisDeleteKey: mocks.redisDeleteKey,
redisDeleteKeys: mocks.redisDeleteKeys,
redisExecuteCommand: mocks.redisExecuteCommand,
saveHistory: mocks.saveHistory,
}));
vi.mock("@/lib/redis/redisKeyTree", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/redis/redisKeyTree")>();
return { ...actual, canBuildRedisFuzzyTree: mocks.canBuildRedisFuzzyTree };
});
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: vi.fn().mockResolvedValue(undefined),
getConfig: () => ({ name: "Redis", redis_key_separator: ":", redis_scan_page_size: mocks.redisScanPageSize }),
updateRedisDbKeyStats: mocks.updateRedisDbKeyStats,
listRedisCompletionCommandDocs: mocks.listRedisCompletionCommandDocs,
listRedisCompletionKeys: mocks.listRedisCompletionKeys,
invalidateCompletionCache: vi.fn(),
refreshRedisDbKeyCounts: vi.fn(),
}),
}));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings: {
infiniteScroll: mocks.infiniteScroll,
queryResultMaxRowsEnabled: mocks.queryResultMaxRowsEnabled,
queryResultMaxRows: mocks.queryResultMaxRows,
},
}),
}));
vi.mock("@/composables/useEditorFontFamilyStyle", () => ({
useEditorFontFamilyStyle: () => ({}),
}));
vi.mock("@/composables/useToast", () => ({
useToast: () => ({ toast: mocks.toast }),
}));
vi.mock("@/components/ui/button", async () => {
const { defineComponent, h } = await import("vue");
return {
Button: defineComponent({
inheritAttrs: false,
props: { disabled: Boolean },
setup(props, { attrs, slots }) {
return () => h("button", { ...attrs, disabled: props.disabled }, slots.default?.());
},
}),
};
});
vi.mock("@/components/ui/input", async () => {
const { defineComponent, h, mergeProps } = await import("vue");
return {
Input: defineComponent({
inheritAttrs: false,
props: { modelValue: String, disabled: Boolean },
emits: ["update:modelValue"],
setup(props, { attrs, emit }) {
return () =>
h(
"input",
mergeProps(attrs, {
value: props.modelValue ?? "",
disabled: props.disabled,
onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value),
}),
);
},
}),
};
});
vi.mock("@/components/ui/badge", async () => {
const { defineComponent, h } = await import("vue");
return {
Badge: defineComponent({
setup:
(_, { attrs, slots }) =>
() =>
h("span", attrs, slots.default?.()),
}),
};
});
vi.mock("@/components/ui/dialog", async () => {
const { defineComponent, h } = await import("vue");
const slotContainer = defineComponent({
setup:
(_, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return {
Dialog: defineComponent({
props: { open: Boolean },
setup(props, { slots }) {
return () => (props.open ? h("div", { "data-test-dialog": "" }, slots.default?.()) : null);
},
}),
DialogContent: slotContainer,
DialogFooter: slotContainer,
DialogHeader: slotContainer,
DialogTitle: slotContainer,
};
});
vi.mock("@/components/ui/select", async () => {
const { defineComponent, h } = await import("vue");
type SelectRoot = HTMLElement & { selectTestValue?: (value: string) => void };
const slotContainer = defineComponent({
setup:
(_, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return {
Select: defineComponent({
inheritAttrs: false,
props: { modelValue: String, disabled: Boolean },
emits: ["update:modelValue", "update:open"],
setup(props, { emit, slots }) {
const selectValue = (value: string) => {
if (!props.disabled) emit("update:modelValue", value);
};
return () =>
h(
"div",
{
"data-test-select-root": "",
ref: (element: Element | ComponentPublicInstance | null) => {
if (element instanceof HTMLElement) (element as SelectRoot).selectTestValue = selectValue;
},
},
slots.default?.(),
);
},
}),
SelectContent: slotContainer,
SelectItem: defineComponent({
props: { value: String },
setup(props, { slots }) {
return () => h("button", { type: "button", "data-test-select-value": props.value }, slots.default?.());
},
}),
SelectTrigger: slotContainer,
SelectValue: slotContainer,
};
});
vi.mock("@/components/ui/option-help-panel", async () => {
const { defineComponent, h } = await import("vue");
return { OptionHelpPanel: defineComponent({ setup: () => () => h("div") }) };
});
vi.mock("@/components/ui/tabs", async () => {
const { defineComponent, h } = await import("vue");
const slotContainer = defineComponent({
setup:
(_, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return { Tabs: slotContainer, TabsContent: slotContainer, TabsList: slotContainer, TabsTrigger: slotContainer };
});
vi.mock("@/components/ui/switch", async () => {
const { defineComponent, h } = await import("vue");
return { Switch: defineComponent({ setup: () => () => h("button", { type: "button" }) }) };
});
vi.mock("@/components/ui/date-time-picker/DateTimePicker.vue", async () => {
const { CalendarDateTime } = await import("@internationalized/date");
const { defineComponent, h } = await import("vue");
return {
default: defineComponent({
props: { disabled: Boolean },
emits: ["update:modelValue"],
setup(props, { emit }) {
return () =>
h(
"button",
{
type: "button",
disabled: props.disabled,
"data-test-absolute-date": "",
onClick: () => emit("update:modelValue", new CalendarDateTime(2030, 1, 2, 3, 4, 5)),
},
"Set date",
);
},
}),
};
});
vi.mock("@/components/ui/CustomContextMenu.vue", async () => {
const { defineComponent, h } = await import("vue");
return {
default: defineComponent({
setup(_, { slots }) {
return () => h("div", slots.default?.({ onContextMenu: () => undefined }));
},
}),
};
});
vi.mock("@/components/editor/DangerConfirmDialog.vue", async () => {
const { defineComponent, h } = await import("vue");
return {
default: defineComponent({
props: { open: Boolean, loading: Boolean, details: String },
emits: ["confirm"],
setup(props, { emit }) {
return () =>
props.open
? h("div", { "data-test-danger-dialog": "" }, [
h("div", { "data-test-danger-details": "" }, props.details),
h(
"button",
{
type: "button",
disabled: props.loading,
"data-test-danger-confirm": "",
onClick: () => emit("confirm"),
},
"Confirm",
),
])
: null;
},
}),
};
});
vi.mock("./RedisValueViewer.vue", async () => {
const { defineComponent, h } = await import("vue");
return { default: defineComponent({ setup: () => () => h("div") }) };
});
vi.mock("./RedisPubSubPanel.vue", async () => {
const { defineComponent, h } = await import("vue");
return { default: defineComponent({ setup: () => () => h("div") }) };
});
vi.mock("./RedisSlowlogPanel.vue", async () => {
const { defineComponent, h } = await import("vue");
return { default: defineComponent({ setup: () => () => h("div") }) };
});
vi.mock("vue-virtual-scroller", async () => {
const { defineComponent, h } = await import("vue");
return {
RecycleScroller: defineComponent({
inheritAttrs: false,
props: { items: { type: Array, default: () => [] } },
setup(props, { attrs, slots }) {
// Mirror the real scroller: interaction tests should render a viewport,
// not every row in a deliberately large result set.
const visibleItemCount = 50;
return () =>
h(
"div",
attrs,
props.items.slice(0, visibleItemCount).map((item) => slots.default?.({ item })),
);
},
}),
};
});
vi.mock("splitpanes", async () => {
const { defineComponent, h } = await import("vue");
const slotContainer = defineComponent({
setup:
(_, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return { Splitpanes: slotContainer, Pane: slotContainer };
});
import RedisKeyBrowser from "./RedisKeyBrowser.vue";
const KEY_NAME = "new-key";
const KEY_RAW = "bmV3LWtleQ==";
const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
type CreateType = "string" | "hash" | "list" | "set" | "zset" | "stream" | "json";
type TestSelectRoot = HTMLElement & { selectTestValue?: (value: string) => void };
function redisValue(keyRaw = KEY_RAW) {
return {
key_display: KEY_NAME,
key_raw: keyRaw,
ttl: 90,
redis_type: "string" as const,
data: { kind: "string" as const, content: { raw_base64: "dmFsdWU=", encoding: "utf8" as const } },
};
}
function redisKeyInfo(keyType = "json") {
return { key_display: KEY_NAME, key_raw: KEY_RAW, key_type: keyType, ttl: 90, size: 7, value_preview: "{}" };
}
const completionCommands = [
{ name: "GET", group: "string", arity: 2, keySpecs: [{ beginSearch: { type: "index" as const, index: 1 }, findKeys: { type: "range" as const, lastKey: 0, keyStep: 1, limit: 0 } }] },
{ name: "GETEX", group: "string", arity: -2, keySpecs: [{ beginSearch: { type: "index" as const, index: 1 }, findKeys: { type: "range" as const, lastKey: 0, keyStep: 1, limit: 0 } }] },
{ name: "GETSET", group: "string", arity: 3, keySpecs: [{ beginSearch: { type: "index" as const, index: 1 }, findKeys: { type: "range" as const, lastKey: 0, keyStep: 1, limit: 0 } }] },
{ name: "PING", group: "connection", arity: -1, keySpecs: [] },
{ name: "SET", group: "string", arity: -3, keySpecs: [{ beginSearch: { type: "index" as const, index: 1 }, findKeys: { type: "range" as const, lastKey: 0, keyStep: 1, limit: 0 } }] },
{ name: "VGET", group: "string", arity: 2, summary: "Reads a vendor key.", keySpecs: [{ beginSearch: { type: "index" as const, index: 1 }, findKeys: { type: "range" as const, lastKey: 0, keyStep: 1, limit: 0 } }] },
];
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((next, fail) => {
resolve = next;
reject = fail;
});
return { promise, resolve, reject };
}
function resetApiMocks() {
vi.clearAllMocks();
mocks.redisScanPageSize = 100;
mocks.infiniteScroll = false;
mocks.queryResultMaxRowsEnabled = true;
mocks.queryResultMaxRows = 5000;
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys: [], total_keys: 0 });
mocks.redisGetValue.mockImplementation((_connectionId: string, _db: number, keyRaw: string) => Promise.resolve(redisValue(keyRaw)));
mocks.redisSetString.mockResolvedValue(undefined);
mocks.redisJsonSet.mockResolvedValue(undefined);
mocks.redisHashSet.mockResolvedValue(undefined);
mocks.redisListPush.mockResolvedValue(undefined);
mocks.redisSetAdd.mockResolvedValue(undefined);
mocks.redisZadd.mockResolvedValue(undefined);
mocks.redisStreamAdd.mockResolvedValue(undefined);
mocks.redisSetTtl.mockResolvedValue(undefined);
mocks.redisSetExpireAt.mockResolvedValue(undefined);
mocks.redisCheckJsonModule.mockResolvedValue(true);
mocks.redisDeleteKey.mockResolvedValue(undefined);
mocks.redisDeleteKeys.mockResolvedValue(0);
mocks.redisExecuteCommand.mockResolvedValue({ value: "OK" });
mocks.saveHistory.mockResolvedValue(undefined);
mocks.listRedisCompletionCommandDocs.mockResolvedValue(completionCommands);
mocks.listRedisCompletionKeys.mockResolvedValue(["user:1"]);
mocks.canBuildRedisFuzzyTree.mockImplementation((loadedKeyCount: number) => loadedKeyCount <= 200_000);
}
function mountBrowser() {
const host = document.createElement("div");
document.body.append(host);
const app = createApp(RedisKeyBrowser, { connectionId: "connection", db: 0, blockDangerousRedisCommands: false });
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
return host;
}
function mountScopedBrowser() {
const connectionId = ref("connection");
const db = ref(0);
const host = document.createElement("div");
document.body.append(host);
const app = createApp(
defineComponent({
setup() {
return () => h(RedisKeyBrowser, { connectionId: connectionId.value, 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 });
return {
host,
async setScope(nextConnectionId: string, nextDb: number) {
connectionId.value = nextConnectionId;
db.value = nextDb;
await settle();
},
};
}
function mountKeptAliveBrowser() {
const active = ref(true);
const host = document.createElement("div");
document.body.append(host);
const app = createApp(
defineComponent({
setup() {
return () =>
h(KeepAlive, null, {
default: () => (active.value ? h(RedisKeyBrowser, { connectionId: "connection", db: 0, blockDangerousRedisCommands: false }) : null),
});
},
}),
);
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ unmount: () => app.unmount(), host });
return {
async deactivate() {
active.value = false;
await settle();
},
async activate() {
active.value = true;
await settle();
},
};
}
async function settle() {
await nextTick();
await Promise.resolve();
await nextTick();
await Promise.resolve();
await nextTick();
}
function requiredElement<T extends Element>(selector: string): T {
const element = document.querySelector<T>(selector);
expect(element, selector).not.toBeNull();
return element!;
}
function clickButtonWithText(text: string) {
const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((candidate) => candidate.textContent?.includes(text));
expect(button, text).toBeDefined();
button!.click();
}
async function setInput(selector: string, value: string) {
const input = requiredElement<HTMLInputElement>(selector);
input.value = value;
input.dispatchEvent(new Event("input", { bubbles: true }));
await settle();
}
async function submitKeySearch(value: string) {
const input = requiredElement<HTMLInputElement>("[data-redis-search-input]");
input.value = value;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
}
function groupRow(label: string): HTMLElement {
const labelElement = Array.from(document.querySelectorAll<HTMLElement>(".dbx-editor-font-family")).find((element) => element.textContent === label);
expect(labelElement, label).toBeDefined();
const row = labelElement?.closest<HTMLElement>(".group");
expect(row, label).toBeDefined();
return row!;
}
function redisCheckboxes(): HTMLElement[] {
return Array.from(document.querySelectorAll<HTMLElement>('input[type="checkbox"]'));
}
function groupCheckbox(label: string): HTMLElement {
const checkbox = groupRow(label).querySelector<HTMLElement>('input[type="checkbox"]');
expect(checkbox, label).toBeDefined();
return checkbox!;
}
function leafCheckbox(label: string): HTMLElement {
const checkbox = redisCheckboxes().find((el) => el.closest(".group")?.querySelector(".dbx-editor-font-family")?.textContent === label);
expect(checkbox, label).toBeDefined();
return checkbox!;
}
function isCheckboxChecked(el: HTMLElement): boolean {
return (el as HTMLInputElement).checked;
}
function isCheckboxMixed(el: HTMLElement): boolean {
return (el as HTMLInputElement).indeterminate;
}
/** Select a folder via its left-side checkbox (same single-click path as leaf keys). */
async function selectGroup(label: string) {
groupCheckbox(label).dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await settle();
}
async function select(value: string) {
const item = requiredElement<HTMLButtonElement>(`[data-test-select-value="${value}"]`);
const root = item.closest<TestSelectRoot>("[data-test-select-root]");
expect(root).not.toBeNull();
expect(root?.selectTestValue).toEqual(expect.any(Function));
root!.selectTestValue!(value);
await settle();
}
async function openCreateDialog() {
requiredElement<HTMLButtonElement>('button[title="redis.createKey"]').click();
await settle();
await setInput('input[placeholder="redis.createKeyNamePlaceholder"]', KEY_NAME);
}
async function openCommandPanel() {
const trigger = document.querySelector<HTMLElement>('[value="command"]');
expect(trigger, "redis.commandLine trigger").toBeDefined();
trigger!.click();
await settle();
}
function commandCompletionLabels(): string[] {
return Array.from(document.querySelectorAll<HTMLButtonElement>('[role="option"]')).map((item) => item.textContent?.trim() ?? "");
}
async function setCommandInput(value: string) {
await setInput("[data-redis-command-input]", value);
}
async function fillCreateValue(type: CreateType) {
if (type === "string") {
const textarea = requiredElement<HTMLTextAreaElement>("textarea");
textarea.value = "value";
textarea.dispatchEvent(new Event("input", { bubbles: true }));
await settle();
return;
}
await select(type);
if (type === "json") {
const textarea = requiredElement<HTMLTextAreaElement>("textarea");
textarea.value = '{"value":true}';
textarea.dispatchEvent(new Event("input", { bubbles: true }));
await settle();
return;
}
if (type === "hash" || type === "stream") {
await setInput('input[placeholder="redis.createFieldPlaceholder"]', "field");
await setInput('input[placeholder="redis.createValuePlaceholder"]', "value");
return;
}
if (type === "zset") {
await setInput('input[placeholder="0"]', "1");
await setInput('input[placeholder="redis.createMember"]', "member");
return;
}
await setInput('input[placeholder="redis.createValuePlaceholder"]', "value");
}
async function submitCreate() {
clickButtonWithText("redis.createKeySubmit");
await settle();
}
function expectWriterBefore(mock: { mock: { invocationCallOrder: number[] } }, after: { mock: { invocationCallOrder: number[] } }) {
expect(mock.mock.invocationCallOrder).toHaveLength(1);
expect(after.mock.invocationCallOrder).toHaveLength(1);
expect(mock.mock.invocationCallOrder[0]).toBeLessThan(after.mock.invocationCallOrder[0]!);
}
const writerForType = {
string: mocks.redisSetString,
hash: mocks.redisHashSet,
list: mocks.redisListPush,
set: mocks.redisSetAdd,
zset: mocks.redisZadd,
stream: mocks.redisStreamAdd,
json: mocks.redisJsonSet,
} as const;
beforeEach(() => {
resetApiMocks();
setLocalTimeZone("UTC");
});
afterEach(() => {
for (const { unmount, host } of mountedApps.splice(0)) {
unmount();
host.remove();
}
resetLocalTimeZone();
});
describe("RedisKeyBrowser scope changes", () => {
it("reloads the new database and discards a late scan from the previous one", async () => {
const previousDatabase = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();
const currentKey = { key_display: "db1-key", key_raw: "ZGIxLWtleQ==", key_type: "string", ttl: -1 };
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, db: number) => {
if (db === 0) return previousDatabase.promise;
return Promise.resolve({ cursor: 0, keys: [currentKey], total_keys: 1 });
});
const browser = mountScopedBrowser();
await settle();
expect(mocks.redisScanKeysBatch).toHaveBeenCalledWith("connection", 0, 0, "*", 100, 8, true);
await browser.setScope("connection", 1);
expect(mocks.redisScanKeysBatch).toHaveBeenCalledWith("connection", 1, 0, "*", 100, 8, true);
previousDatabase.resolve({
cursor: 0,
keys: [{ key_display: "db0-key", key_raw: "ZGIwLWtleQ==", key_type: "string", ttl: -1 }],
total_keys: 1,
});
await settle();
expect(browser.host.textContent).toContain("db1-key");
expect(browser.host.textContent).not.toContain("db0-key");
});
});
describe("RedisKeyBrowser command completion", () => {
it("uses the connected server's module command docs and accepts the selection with Tab", async () => {
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("VGE");
expect(mocks.listRedisCompletionCommandDocs).toHaveBeenCalledWith("connection", "0");
expect(commandCompletionLabels()).toContain("VGETReads a vendor key.string");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true }));
await settle();
expect(input.value).toBe("VGE");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true }));
await settle();
expect(input.value).toBe("VGET ");
});
it("completes known keys only at a documented key argument", async () => {
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("VGET ");
expect(mocks.listRedisCompletionKeys).toHaveBeenCalledWith("connection", "0");
expect(commandCompletionLabels()).toContain("user:1key");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true }));
await settle();
expect(input.value).toBe("VGET user:1");
});
it("replaces an incomplete quoted key with the executable completion text", async () => {
mocks.listRedisCompletionKeys.mockResolvedValueOnce(["user name"]);
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput('VGET "user');
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true }));
await settle();
expect(input.value).toBe('VGET "user name"');
});
it("does not guess command candidates when server metadata is unavailable", async () => {
mocks.listRedisCompletionCommandDocs.mockRejectedValueOnce(new Error("unknown subcommand 'DOCS'"));
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("GE");
expect(commandCompletionLabels()).toEqual([]);
});
it("keeps one selected completion while pointer and keyboard move it", async () => {
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("GE");
const options = Array.from(document.querySelectorAll<HTMLButtonElement>('[role="option"]'));
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
const listbox = requiredElement<HTMLElement>('[role="listbox"]');
expect(options.length).toBeGreaterThan(1);
expect(options.filter((option) => option.getAttribute("aria-selected") === "true")).toEqual([options[0]]);
expect(options.every((option) => !option.hasAttribute("title"))).toBe(true);
expect(input.getAttribute("aria-controls")).toBe(listbox.id);
expect(input.getAttribute("aria-activedescendant")).toBe(options[0]!.id);
options[1]!.dispatchEvent(new Event("pointerenter", { bubbles: true }));
await settle();
expect(options.filter((option) => option.getAttribute("aria-selected") === "true")).toEqual([options[1]]);
expect(input.getAttribute("aria-activedescendant")).toBe(options[1]!.id);
listbox.scrollTop = 20;
vi.spyOn(listbox, "getBoundingClientRect").mockReturnValue({ top: 100, bottom: 200 } as DOMRect);
vi.spyOn(options[2]!, "getBoundingClientRect").mockReturnValue({ top: 180, bottom: 224 } as DOMRect);
input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
await settle();
expect(options.filter((option) => option.getAttribute("aria-selected") === "true")).toEqual([options[2]]);
expect(listbox.scrollTop).toBe(44);
input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
await settle();
expect(options.filter((option) => option.getAttribute("aria-selected") === "true")).toEqual([options[2]]);
vi.spyOn(options[1]!, "getBoundingClientRect").mockReturnValue({ top: 76, bottom: 120 } as DOMRect);
vi.spyOn(options[0]!, "getBoundingClientRect").mockReturnValue({ top: 100, bottom: 144 } as DOMRect);
input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }));
input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }));
input.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }));
await settle();
expect(options.filter((option) => option.getAttribute("aria-selected") === "true")).toEqual([options[0]]);
expect(listbox.scrollTop).toBe(20);
});
it("accepts a documented argument keyword and advances to its value", async () => {
mocks.listRedisCompletionCommandDocs.mockResolvedValueOnce([
...completionCommands,
{
name: "XREAD",
group: "stream",
arity: -4,
keySpecs: [],
arguments: [
{ name: "count", token: "COUNT", type: "integer", optional: true },
{ name: "streams", token: "STREAMS", type: "block", arguments: [{ name: "key", type: "key", multiple: true }] },
],
},
]);
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("XREAD C");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true }));
await settle();
expect(input.value).toBe("XREAD COUNT ");
expect(commandCompletionLabels()).toEqual([]);
});
it("accepts the selected completion before executing on Enter", async () => {
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("SE");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
expect(input.value).toBe("SET ");
expect(commandCompletionLabels()).toContain("user:1key");
});
it("waits for command metadata instead of sending a partial command on Enter", async () => {
const docs = deferred<typeof completionCommands>();
mocks.listRedisCompletionCommandDocs.mockReturnValueOnce(docs.promise);
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("SE");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
expect(input.value).toBe("SE");
expect(mocks.redisExecuteCommand).not.toHaveBeenCalled();
docs.resolve(completionCommands);
await settle();
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
expect(input.value).toBe("SET ");
expect(mocks.redisExecuteCommand).not.toHaveBeenCalled();
});
it("executes an exact command instead of completing it a second time", async () => {
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("PING");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
expect(mocks.redisExecuteCommand).toHaveBeenCalledWith("connection", 0, "PING", true);
expect(input.value).toBe("");
});
});
describe("RedisKeyBrowser command console echo", () => {
it("echoes the submitted command to the terminal before the response arrives, then fills in the result", async () => {
const pending = deferred<{ value: unknown }>();
mocks.redisExecuteCommand.mockReturnValueOnce(pending.promise);
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("PING");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
// The command must show up in the terminal right away — while the
// request is still in flight — not only once the response resolves.
const terminal = requiredElement<HTMLElement>(".redis-command-terminal");
expect(terminal.textContent).toContain("PING");
expect(terminal.querySelectorAll(".mb-2")).toHaveLength(1);
expect(terminal.textContent).not.toContain("PONG");
pending.resolve({ value: "PONG" });
await settle();
expect(terminal.textContent).toContain("PONG");
// The result fills in the same echoed entry rather than adding a second one.
expect(terminal.querySelectorAll(".mb-2")).toHaveLength(1);
});
it("attaches a failed command's error to the same echoed entry", async () => {
const pending = deferred<{ value: unknown }>();
mocks.redisExecuteCommand.mockReturnValueOnce(pending.promise);
mountBrowser();
await settle();
await openCommandPanel();
await setCommandInput("PING");
const input = requiredElement<HTMLInputElement>("[data-redis-command-input]");
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
await settle();
const terminal = requiredElement<HTMLElement>(".redis-command-terminal");
expect(terminal.textContent).toContain("PING");
expect(terminal.querySelectorAll(".mb-2")).toHaveLength(1);
pending.reject(new Error("ERR unknown command"));
await settle();
expect(terminal.textContent).toContain("ERR unknown command");
expect(terminal.querySelectorAll(".mb-2")).toHaveLength(1);
});
});
describe("RedisKeyBrowser expiry creation", () => {
it.each(["string", "hash", "list", "set", "zset", "stream", "json"] as const)("writes %s before applying one relative TTL", async (type) => {
mountBrowser();
await settle();
await openCreateDialog();
await fillCreateValue(type);
await select("ttl");
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
await submitCreate();
const writer = writerForType[type];
expect(mocks.redisSetTtl).toHaveBeenCalledWith("connection", 0, KEY_RAW, 90);
expect(mocks.redisSetExpireAt).not.toHaveBeenCalled();
expectWriterBefore(writer, mocks.redisSetTtl);
});
it("uses PERSIST after a String write when no expiry is selected", async () => {
mountBrowser();
await settle();
await openCreateDialog();
await fillCreateValue("string");
await submitCreate();
expect(mocks.redisSetTtl).toHaveBeenCalledWith("connection", 0, KEY_RAW, -1);
expect(mocks.redisSetExpireAt).not.toHaveBeenCalled();
expectWriterBefore(mocks.redisSetString, mocks.redisSetTtl);
});
it("uses EXPIREAT after a String write when an absolute time is selected", async () => {
mountBrowser();
await settle();
await openCreateDialog();
await fillCreateValue("string");
await select("at");
requiredElement<HTMLButtonElement>("[data-test-absolute-date]").click();
await settle();
await submitCreate();
const expected = calendarDateTimeToUnixSeconds(new CalendarDateTime(2030, 1, 2, 3, 4, 5));
expect(mocks.redisSetExpireAt).toHaveBeenCalledWith("connection", 0, KEY_RAW, expected);
expect(mocks.redisSetTtl).not.toHaveBeenCalled();
expectWriterBefore(mocks.redisSetString, mocks.redisSetExpireAt);
});
it("does not roll back a written key when its expiry command fails and refreshes it", async () => {
mocks.redisSetTtl.mockRejectedValueOnce(new Error("TTL command failed"));
mountBrowser();
await settle();
await openCreateDialog();
await fillCreateValue("string");
await select("ttl");
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
await submitCreate();
expectWriterBefore(mocks.redisSetString, mocks.redisSetTtl);
expect(mocks.redisGetValue).toHaveBeenCalledWith("connection", 0, KEY_RAW);
expect(mocks.redisDeleteKey).not.toHaveBeenCalled();
expect(mocks.redisDeleteKeys).not.toHaveBeenCalled();
expect(mocks.toast).toHaveBeenCalledWith("TTL command failed", 5000);
});
it("removes an existing RedisJSON key only after recovery confirms its deletion", async () => {
mocks.redisScanKeysBatch.mockResolvedValueOnce({ cursor: 0, keys: [redisKeyInfo()], total_keys: 1 });
mocks.redisSetTtl.mockRejectedValueOnce(new Error("TTL command failed"));
mocks.redisGetValue.mockRejectedValueOnce(new Error("RedisJSON key no longer exists")).mockRejectedValueOnce(new Error("RedisJSON key no longer exists"));
mountBrowser();
await settle();
await openCreateDialog();
await fillCreateValue("json");
await select("ttl");
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
await submitCreate();
await settle();
expect(mocks.redisGetValue).toHaveBeenCalledTimes(2);
expect(mocks.updateRedisDbKeyStats).toHaveBeenCalledWith("connection", 0, { loaded: 0, totalDelta: -1 });
expect(mocks.toast).toHaveBeenCalledWith("TTL command failed", 5000);
});
it("keeps an existing RedisJSON key when retry cannot confirm its deletion", async () => {
mocks.redisScanKeysBatch.mockResolvedValueOnce({ cursor: 0, keys: [redisKeyInfo()], total_keys: 1 });
mocks.redisSetTtl.mockRejectedValueOnce(new Error("TTL command failed"));
mocks.redisGetValue.mockRejectedValueOnce(new Error("RedisJSON key no longer exists")).mockRejectedValueOnce(new Error("network unavailable"));
mountBrowser();
await settle();
await openCreateDialog();
await fillCreateValue("json");
await select("ttl");
await setInput('input[placeholder="redis.createKeyTtlPlaceholder"]', "90");
await submitCreate();
await settle();
expect(mocks.updateRedisDbKeyStats).not.toHaveBeenCalledWith("connection", 0, { loaded: 0, totalDelta: -1 });
expect(mocks.toast).toHaveBeenCalledWith("TTL command failed", 5000);
});
});
describe("RedisKeyBrowser fuzzy key hierarchy", () => {
it("preserves the cursor and finds a sparse fuzzy match after a bounded continuation", async () => {
mocks.redisScanPageSize = 1_000;
mountBrowser();
await settle();
clickButtonWithText("redis.fuzzyMatch");
await settle();
const target = { key_display: "issue5012:target", key_raw: "aXNzdWU1MDEyOnRhcmdldA==", key_type: "string", ttl: -1 };
let batch = 0;
mocks.redisScanKeysBatch.mockReset();
mocks.redisScanKeysBatch.mockImplementation(() => {
batch += 1;
if (batch === 8) return Promise.resolve({ cursor: 801, keys: [target], total_keys: 0 });
return Promise.resolve({ cursor: batch * 100, keys: [], total_keys: batch === 1 ? 200_000 : 0 });
});
await submitKeySearch("issue5012:target");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(7));
await settle();
expect(document.body.textContent).not.toContain("target");
expect(document.body.textContent).toContain("redis.noKeysInScanHint");
clickButtonWithText("redis.loadMoreKeys");
await vi.waitFor(() => {
const labels = Array.from(document.querySelectorAll<HTMLElement>(".dbx-editor-font-family")).map((element) => element.textContent);
expect(labels).toContain("target");
});
expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(8);
expect(mocks.redisScanKeysBatch.mock.calls.every((call) => call[3] === "*issue5012:target*")).toBe(true);
});
it("bounds a large no-match keyspace and exposes the saved-cursor continuation", async () => {
mocks.redisScanPageSize = 1_000;
mountBrowser();
await settle();
clickButtonWithText("redis.fuzzyMatch");
await settle();
let batch = 0;
mocks.redisScanKeysBatch.mockReset();
mocks.redisScanKeysBatch.mockImplementation(() => {
batch += 1;
return Promise.resolve({ cursor: batch, keys: [], total_keys: batch === 1 ? 5_000_000 : 0 });
});
await submitKeySearch("missing-key");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(7));
await settle();
expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(7);
expect(mocks.redisScanKeysBatch.mock.calls[mocks.redisScanKeysBatch.mock.calls.length - 1]?.[2]).toBe(6);
expect(document.body.textContent).toContain("redis.noKeysInScanHint");
expect(Array.from(document.querySelectorAll("button")).some((button) => button.textContent?.includes("redis.loadMoreKeys"))).toBe(true);
clickButtonWithText("redis.loadMoreKeys");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(14));
expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(14);
expect(mocks.redisScanKeysBatch.mock.calls[7]?.[2]).toBe(7);
expect(document.body.textContent).toContain("redis.noKeysInScanHint");
});
it("keeps existing matches while continuing to the next sparse fuzzy result", async () => {
mocks.redisScanPageSize = 1_000;
mountBrowser();
await settle();
clickButtonWithText("redis.fuzzyMatch");
await settle();
const first = { key_display: "issue5012:first", key_raw: "aXNzdWU1MDEyOmZpcnN0", key_type: "string", ttl: -1 };
const next = { key_display: "issue5012:next", key_raw: "aXNzdWU1MDEyOm5leHQ=", key_type: "string", ttl: -1 };
let continuationBatch = 0;
mocks.redisScanKeysBatch.mockReset();
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => {
if (cursor === 0) return Promise.resolve({ cursor: 1, keys: [first], total_keys: 200_000 });
continuationBatch += 1;
if (continuationBatch === 8) return Promise.resolve({ cursor: 0, keys: [next], total_keys: 0 });
return Promise.resolve({ cursor: continuationBatch + 1, keys: [], total_keys: 0 });
});
await submitKeySearch("issue5012");
await vi.waitFor(() => expect(document.body.textContent).toContain("first"));
clickButtonWithText("redis.loadMoreKeys");
await vi.waitFor(() => expect(continuationBatch).toBe(7));
expect(document.body.textContent).toContain("first");
expect(document.body.textContent).not.toContain("next");
clickButtonWithText("redis.loadMoreKeys");
await vi.waitFor(() => expect(document.body.textContent).toContain("next"));
expect(continuationBatch).toBe(8);
expect(document.body.textContent).toContain("first");
});
it("cancels a sparse scan immediately when the search text changes", async () => {
mocks.redisScanPageSize = 1_000;
mountBrowser();
await settle();
clickButtonWithText("redis.fuzzyMatch");
await settle();
const oldPage = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();
const fresh = { key_display: "new:result", key_raw: "bmV3OnJlc3VsdA==", key_type: "string", ttl: -1 };
mocks.redisScanKeysBatch.mockReset();
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, _cursor: number, pattern: string) => {
if (pattern === "*old*") return oldPage.promise;
return Promise.resolve({ cursor: 0, keys: [fresh], total_keys: 1 });
});
await submitKeySearch("old");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch).toHaveBeenCalledTimes(1));
const input = requiredElement<HTMLInputElement>("[data-redis-search-input]");
input.value = "new";
input.dispatchEvent(new Event("input", { bubbles: true }));
await settle();
oldPage.resolve({ cursor: 1, keys: [], total_keys: 1_000_000 });
await settle();
expect(mocks.redisScanKeysBatch.mock.calls.filter((call) => call[3] === "*old*")).toHaveLength(1);
await vi.waitFor(() => expect(document.body.textContent).toContain("result"));
expect(mocks.redisScanKeysBatch.mock.calls.map((call) => call[3])).toEqual(["*old*", "*new*"]);
});
it("keeps a current continuation locked when an older load-more request finishes", async () => {
mocks.redisScanPageSize = 1_000;
mountBrowser();
await settle();
clickButtonWithText("redis.fuzzyMatch");
await settle();
const oldContinuation = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();
const currentContinuation = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();
const oldInitial = { key_display: "old:initial", key_raw: "b2xkOmluaXRpYWw=", key_type: "string", ttl: -1 };
const currentInitial = { key_display: "new:initial", key_raw: "bmV3OmluaXRpYWw=", key_type: "string", ttl: -1 };
const currentFirstPage = { key_display: "new:first-page", key_raw: "bmV3OmZpcnN0LXBhZ2U=", key_type: "string", ttl: -1 };
const currentLastPage = { key_display: "new:last-page", key_raw: "bmV3Omxhc3QtcGFnZQ==", key_type: "string", ttl: -1 };
mocks.redisScanKeysBatch.mockReset();
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number, pattern: string) => {
if (pattern === "*old*") {
if (cursor === 0) return Promise.resolve({ cursor: 11, keys: [oldInitial], total_keys: 100 });
return oldContinuation.promise;
}
if (pattern === "*new*") {
if (cursor === 0) return Promise.resolve({ cursor: 21, keys: [currentInitial], total_keys: 100 });
if (cursor === 21) return Promise.resolve({ cursor: 22, keys: [currentFirstPage], total_keys: 0 });
if (cursor === 22) return currentContinuation.promise;
}
return Promise.resolve({ cursor: 0, keys: [], total_keys: 0 });
});
await submitKeySearch("old");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch.mock.calls.filter((call) => call[2] === 0 && call[3] === "*old*")).toHaveLength(1));
clickButtonWithText("redis.loadMoreKeys");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch.mock.calls.some((call) => call[2] === 11)).toBe(true));
await submitKeySearch("new");
await vi.waitFor(() => expect(mocks.redisScanKeysBatch.mock.calls.filter((call) => call[2] === 0 && call[3] === "*new*")).toHaveLength(1));
const firstCurrentLoadMore = await vi.waitFor(() => {
const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).filter((candidate) => candidate.textContent?.includes("redis.loadMoreKeys"));
const button = buttons.find((candidate) => !candidate.disabled);
expect(button).toBeDefined();
return button!;
});
firstCurrentLoadMore.click();
await vi.waitFor(() => expect(mocks.redisScanKeysBatch.mock.calls.filter((call) => call[2] === 21)).toHaveLength(1));
const secondCurrentLoadMore = await vi.waitFor(() => {
const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((candidate) => candidate.textContent?.includes("redis.loadMoreKeys") && !candidate.disabled);
expect(button).toBeDefined();
return button!;
});
secondCurrentLoadMore.click();
await vi.waitFor(() => expect(mocks.redisScanKeysBatch.mock.calls.filter((call) => call[2] === 22)).toHaveLength(1));
oldContinuation.resolve({ cursor: 12, keys: [], total_keys: 0 });
await settle();
const loadMoreButtons = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).filter((button) => button.textContent?.includes("redis.loadMoreKeys"));
expect(loadMoreButtons.length).toBeGreaterThan(0);
expect(loadMoreButtons.every((button) => button.disabled)).toBe(true);
loadMoreButtons[0]!.click();
await settle();
expect(mocks.redisScanKeysBatch.mock.calls.filter((call) => call[2] === 22)).toHaveLength(1);
currentContinuation.resolve({ cursor: 0, keys: [currentLastPage], total_keys: 0 });
await vi.waitFor(() => expect(Array.from(document.querySelectorAll<HTMLButtonElement>("button")).filter((button) => button.textContent?.includes("redis.loadMoreKeys"))).toHaveLength(0));
const labels = Array.from(document.querySelectorAll<HTMLElement>(".dbx-editor-font-family")).map((element) => element.textContent);
expect(labels).toContain("new");
expect(labels).not.toContain("old");
});
it("keeps NUL-containing fuzzy groups isolated when selecting keys to delete", async () => {
const firstKeyRaw = "cmF3LWZpcnN0";
const secondKeyRaw = "cmF3LXNlY29uZA==";
const keys = [
{ key_display: `a\0b:c:x`, key_raw: firstKeyRaw, key_type: "string", ttl: -1 },
{ key_display: `a:b\0c:y`, key_raw: secondKeyRaw, key_type: "string", ttl: -1 },
];
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mocks.redisDeleteKeys.mockResolvedValue(1);
mountBrowser();
await settle();
await submitKeySearch("a");
clickButtonWithText("redis.fuzzyMatch");
await settle();
await selectGroup(`a\0b`);
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === "1");
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
expect(mocks.redisDeleteKeys).toHaveBeenCalledTimes(1);
expect(mocks.redisDeleteKeys).toHaveBeenCalledWith("connection", 0, [firstKeyRaw]);
expect(mocks.redisDeleteKeys.mock.calls[0]?.[2]).not.toContain(secondKeyRaw);
});
it("keeps regular key searches flat, then selects and deletes a loaded fuzzy branch", async () => {
const keys = [
{ key_display: "user:profile:email", key_raw: "cmF3LWVtYWls", key_type: "string", ttl: -1 },
{ key_display: "user:profile:name", key_raw: "cmF3LW5hbWU=", key_type: "string", ttl: -1 },
{ key_display: "user:settings", key_raw: "cmF3LXNldHRpbmdz", key_type: "hash", ttl: -1 },
];
// The first page is intentionally incomplete: branch selection must only
// submit the currently loaded raw keys, never widen into a new SCAN.
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 7, keys, total_keys: 20 });
mocks.redisDeleteKeys.mockResolvedValue(keys.length);
mountBrowser();
await settle();
await submitKeySearch("user");
// Regular glob search keeps the pre-existing flat, virtualized result path.
expect(document.querySelectorAll('input[type="checkbox"]')).toHaveLength(keys.length);
clickButtonWithText("redis.fuzzyMatch");
await settle();
// Hierarchy restores leaf + group checkboxes (groups stay opacity-0 until hover/selection).
expect(document.querySelectorAll('input[type="checkbox"]')).toHaveLength(keys.length + 2);
await selectGroup("user");
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === String(keys.length));
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
expect(mocks.redisDeleteKeys).toHaveBeenCalledTimes(1);
const [connectionId, db, deletedKeyRaws] = mocks.redisDeleteKeys.mock.calls[0] ?? [];
expect(connectionId).toBe("connection");
expect(db).toBe(0);
expect(new Set(deletedKeyRaws)).toEqual(new Set(keys.map((key) => key.key_raw)));
expect(document.querySelectorAll('input[type="checkbox"]')).toHaveLength(0);
});
it("selects hierarchy folders in the normal tree the same way as fuzzy groups", async () => {
const keys = [
{ key_display: "course:incr_class_id-1004", key_raw: "Y291cnNlOjEwMDQ=", key_type: "string", ttl: -1 },
{ key_display: "course:incr_class_id-172", key_raw: "Y291cnNlOjE3Mg==", key_type: "string", ttl: -1 },
{ key_display: "other:item", key_raw: "b3RoZXI6aXRlbQ==", key_type: "string", ttl: -1 },
];
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mocks.redisDeleteKeys.mockResolvedValue(2);
mountBrowser();
await settle();
// Single-click the folder checkbox (left side) selects all loaded keys under it.
await selectGroup("course");
expect(isCheckboxChecked(groupCheckbox("course"))).toBe(true);
expect(document.querySelector("[data-redis-batch-delete]")?.textContent).toContain("2");
// Expand and uncheck children — parent must clear (not stay checked).
groupRow("course").dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await settle();
for (const input of redisCheckboxes()) {
const label = input.closest(".group")?.querySelector(".dbx-editor-font-family")?.textContent;
if (label?.startsWith("incr_class_id-") && isCheckboxChecked(input)) {
input.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
}
}
await settle();
expect(isCheckboxChecked(groupCheckbox("course"))).toBe(false);
expect(isCheckboxMixed(groupCheckbox("course"))).toBe(false);
expect(document.querySelector("[data-redis-batch-delete]")).toBeNull();
// Re-select the folder and delete only its keys.
await selectGroup("course");
expect(isCheckboxChecked(groupCheckbox("course"))).toBe(true);
requiredElement<HTMLButtonElement>("[data-redis-batch-delete]").click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
expect(mocks.redisDeleteKeys).toHaveBeenCalledWith("connection", 0, expect.arrayContaining(["Y291cnNlOjEwMDQ=", "Y291cnNlOjE3Mg=="]));
expect(mocks.redisDeleteKeys.mock.calls[0]?.[2]).not.toContain("b3RoZXI6aXRlbQ==");
});
it("falls back to flat rows at the fuzzy tree limit while retaining loaded-result delete wording", async () => {
const keys = [
{ key_display: "user:profile:email", key_raw: "cmF3LWVtYWls", key_type: "string", ttl: -1 },
{ key_display: "user:profile:name", key_raw: "cmF3LW5hbWU=", key_type: "string", ttl: -1 },
];
mocks.canBuildRedisFuzzyTree.mockReturnValue(false);
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mocks.redisDeleteKeys.mockResolvedValue(1);
mountBrowser();
await settle();
await submitKeySearch("user");
clickButtonWithText("redis.fuzzyMatch");
await settle();
// The group controls disappear when the view falls back to virtualized rows.
expect(document.querySelectorAll('input[type="checkbox"]')).toHaveLength(keys.length);
expect(document.body.textContent).toContain("redis.fuzzyTreeLimit");
requiredElement<HTMLElement>('input[type="checkbox"]').click();
await settle();
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === "1");
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
expect(requiredElement<HTMLElement>("[data-test-danger-details]").textContent).toContain("redis.deleteLoadedSearchKeysDetails");
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
expect(mocks.redisDeleteKeys).toHaveBeenCalledWith("connection", 0, [keys[0]!.key_raw]);
});
it("keeps a selected fuzzy group partial when a later SCAN page adds matching keys", async () => {
const firstPageKeys = [{ key_display: "user:one", key_raw: "dXNlci1vbmU=", key_type: "string", ttl: -1 }];
const laterPageKeys = [{ key_display: "user:two", key_raw: "dXNlci10d28=", key_type: "string", ttl: -1 }];
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => Promise.resolve(cursor === 0 ? { cursor: 7, keys: firstPageKeys, total_keys: 2 } : { cursor: 0, keys: laterPageKeys, total_keys: 0 }));
mocks.redisDeleteKeys.mockResolvedValue(1);
mountBrowser();
await settle();
await submitKeySearch("user");
clickButtonWithText("redis.fuzzyMatch");
await settle();
await selectGroup("user");
clickButtonWithText("redis.loadMoreKeys");
await settle();
const updatedUserCheckbox = groupCheckbox("user");
expect(isCheckboxChecked(updatedUserCheckbox)).toBe(false);
expect(isCheckboxMixed(updatedUserCheckbox)).toBe(true);
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === "1");
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
expect(mocks.redisDeleteKeys).toHaveBeenCalledWith("connection", 0, [firstPageKeys[0]!.key_raw]);
});
it("sends a large selected fuzzy group in bounded delete batches", async () => {
const keys = Array.from({ length: 1_001 }, (_, index) => ({
key_display: `batch:${String(index).padStart(4, "0")}`,
key_raw: `cmF3LWJhdGNoLS${index}`,
key_type: "string",
ttl: -1,
}));
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mocks.redisDeleteKeys.mockImplementation(async (_connectionId: string, _db: number, keyRaws: string[]) => keyRaws.length);
mountBrowser();
await settle();
await submitKeySearch("batch");
clickButtonWithText("redis.fuzzyMatch");
await settle();
await selectGroup("batch");
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === String(keys.length));
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
await settle();
expect(mocks.redisDeleteKeys.mock.calls.map((call) => call[2]?.length)).toEqual([1_000, 1]);
expect(new Set(mocks.redisDeleteKeys.mock.calls.flatMap((call) => call[2] ?? []))).toEqual(new Set(keys.map((key) => key.key_raw)));
});
it("reloads the result set when a later delete batch fails after an earlier batch succeeds", async () => {
const keys = Array.from({ length: 1_001 }, (_, index) => ({
key_display: `batch:${String(index).padStart(4, "0")}`,
key_raw: `cmF3LWJhdGNoLS${index}`,
key_type: "string",
ttl: -1,
}));
const freshKeys = [{ key_display: "fresh:remaining", key_raw: "ZnJlc2gtcmVtYWluaW5n", key_type: "string", ttl: -1 }];
let returnFreshResults = false;
mocks.redisScanKeysBatch.mockImplementation(() => Promise.resolve(returnFreshResults ? { cursor: 0, keys: freshKeys, total_keys: 1 } : { cursor: 0, keys, total_keys: keys.length }));
mocks.redisDeleteKeys.mockResolvedValueOnce(1_000).mockImplementationOnce(async () => {
returnFreshResults = true;
throw new Error("second batch failed");
});
mountBrowser();
await settle();
await submitKeySearch("batch");
clickButtonWithText("redis.fuzzyMatch");
await settle();
await selectGroup("batch");
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === String(keys.length));
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
await settle();
expect(mocks.redisDeleteKeys.mock.calls.map((call) => call[2]?.length)).toEqual([1_000, 1]);
expect(mocks.toast).toHaveBeenCalledWith("second batch failed", 5000);
expect(document.body.textContent).toContain("fresh");
expect(document.body.textContent).not.toContain("0000");
});
it("reloads after a later delete batch fails while the browser is deactivated", async () => {
const keys = Array.from({ length: 1_001 }, (_, index) => ({
key_display: `batch:${String(index).padStart(4, "0")}`,
key_raw: `cmF3LWJhdGNoLS${index}`,
key_type: "string",
ttl: -1,
}));
const freshKeys = [{ key_display: "fresh:remaining", key_raw: "ZnJlc2gtcmVtYWluaW5n", key_type: "string", ttl: -1 }];
const laterDelete = deferred<number>();
let returnFreshResults = false;
mocks.redisScanKeysBatch.mockImplementation(() => Promise.resolve(returnFreshResults ? { cursor: 0, keys: freshKeys, total_keys: 1 } : { cursor: 0, keys, total_keys: keys.length }));
mocks.redisDeleteKeys.mockResolvedValueOnce(1_000).mockImplementationOnce(() => laterDelete.promise);
const browser = mountKeptAliveBrowser();
await settle();
await submitKeySearch("batch");
clickButtonWithText("redis.fuzzyMatch");
await settle();
await selectGroup("batch");
const deleteButton = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === String(keys.length));
expect(deleteButton).toBeDefined();
deleteButton!.click();
await settle();
requiredElement<HTMLButtonElement>("[data-test-danger-confirm]").click();
await settle();
expect(mocks.redisDeleteKeys.mock.calls.map((call) => call[2]?.length)).toEqual([1_000, 1]);
await browser.deactivate();
returnFreshResults = true;
laterDelete.reject(new Error("second batch failed while inactive"));
await settle();
const scanCountBeforeActivation = mocks.redisScanKeysBatch.mock.calls.length;
await browser.activate();
await settle();
expect(mocks.toast).toHaveBeenCalledWith("second batch failed while inactive", 5000);
expect(mocks.redisScanKeysBatch.mock.calls.length).toBeGreaterThan(scanCountBeforeActivation);
expect(document.body.textContent).toContain("fresh");
expect(document.body.textContent).not.toContain("0000");
});
});
describe("RedisKeyBrowser interrupted Fetch All", () => {
it("reloads instead of advancing past an uncommitted buffered page after reactivation", async () => {
const bufferedPage = deferred<{ cursor: number; keys: Array<{ key_display: string; key_raw: string; key_type: string; ttl: number }>; total_keys: number }>();
let returnFreshPage = false;
let freshPageRequests = 0;
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => {
if (cursor === 1) return bufferedPage.promise;
if (returnFreshPage) freshPageRequests++;
return Promise.resolve(returnFreshPage ? { cursor: 0, keys: [{ key_display: "fresh:key", key_raw: "ZnJlc2gta2V5", key_type: "string", ttl: -1 }], total_keys: 2 } : { cursor: 1, keys: [{ key_display: "initial:key", key_raw: "aW5pdGlhbC1rZXk=", key_type: "string", ttl: -1 }], total_keys: 2 });
});
const browser = mountKeptAliveBrowser();
await settle();
clickButtonWithText("redis.fetchAllKeys");
await settle();
await browser.deactivate();
returnFreshPage = true;
bufferedPage.resolve({ cursor: 0, keys: [{ key_display: "buffered:key", key_raw: "YnVmZmVyZWQta2V5", key_type: "string", ttl: -1 }], total_keys: 0 });
await settle();
await browser.activate();
await settle();
expect(document.body.textContent).toContain("fresh");
expect(document.body.textContent).not.toContain("buffered");
expect(freshPageRequests).toBeGreaterThan(0);
});
it("selects all loaded keys from the toolbar and clears the multi-selection", async () => {
const keys = [
{ key_display: "alpha", key_raw: "YWxwaGE=", key_type: "string", ttl: -1 },
{ key_display: "bravo", key_raw: "YnJhdm8=", key_type: "string", ttl: -1 },
{ key_display: "charlie", key_raw: "Y2hhcmxpZQ==", key_type: "string", ttl: -1 },
];
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mountBrowser();
await settle();
const selectAll = requiredElement<HTMLButtonElement>("[data-redis-select-all]");
selectAll.click();
await settle();
const checkboxes = Array.from(document.querySelectorAll<HTMLElement>('input[type="checkbox"]'));
expect(checkboxes).toHaveLength(keys.length);
expect(checkboxes.every((checkbox) => isCheckboxChecked(checkbox as HTMLElement))).toBe(true);
expect(document.querySelector("[data-redis-select-all]")).toBeNull();
expect(document.querySelector("[data-redis-batch-delete]")?.textContent).toContain(String(keys.length));
expect(document.activeElement).toBe(document.querySelector(".redis-key-pane"));
requiredElement<HTMLButtonElement>("[data-redis-deselect-all]").click();
await settle();
expect(Array.from(document.querySelectorAll<HTMLElement>('input[type="checkbox"]')).every((checkbox) => !isCheckboxChecked(checkbox))).toBe(true);
expect(document.querySelector("[data-redis-batch-delete]")).toBeNull();
expect(document.querySelector("[data-redis-select-all]")).not.toBeNull();
expect(document.activeElement).toBe(document.querySelector(".redis-key-pane"));
});
it("fetches remaining scan pages before selecting all keys", async () => {
const first = { key_display: "first", key_raw: "Zmlyc3Q=", key_type: "string", ttl: -1 };
const second = { key_display: "second", key_raw: "c2Vjb25k", key_type: "string", ttl: -1 };
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => {
if (cursor === 0) return Promise.resolve({ cursor: 1, keys: [first], total_keys: 2 });
return Promise.resolve({ cursor: 0, keys: [second], total_keys: 0 });
});
mountBrowser();
await settle();
expect(document.body.textContent).toContain("redis.loadMoreKeys");
const keyPane = requiredElement<HTMLElement>(".redis-key-pane");
keyPane.focus();
keyPane.dispatchEvent(new KeyboardEvent("keydown", { key: "a", ctrlKey: true, bubbles: true, cancelable: true }));
await vi.waitFor(() => expect(document.querySelector("[data-redis-batch-delete]")?.textContent).toContain("2"));
expect(document.body.textContent).toContain("second");
expect(Array.from(document.querySelectorAll<HTMLElement>('input[type="checkbox"]')).every(isCheckboxChecked)).toBe(true);
expect(document.querySelector("[data-redis-select-all]")).toBeNull();
});
it("does not select stale keys when a search changes during select-all scanning", async () => {
const oldPage = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();
const oldKey = { key_display: "old", key_raw: "b2xk", key_type: "string", ttl: -1 };
const freshKey = { key_display: "fresh", key_raw: "ZnJlc2g=", key_type: "string", ttl: -1 };
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number, pattern: string) => {
if (pattern === "*" && cursor === 0) return Promise.resolve({ cursor: 1, keys: [oldKey], total_keys: 2 });
if (pattern === "*") return oldPage.promise;
return Promise.resolve({ cursor: 0, keys: [freshKey], total_keys: 1 });
});
mountBrowser();
await settle();
requiredElement<HTMLButtonElement>("[data-redis-select-all]").click();
await vi.waitFor(() => expect(mocks.redisScanKeysBatch.mock.calls.length).toBeGreaterThan(1));
const input = requiredElement<HTMLInputElement>("[data-redis-search-input]");
input.value = "fresh";
input.dispatchEvent(new Event("input", { bubbles: true }));
await settle();
oldPage.resolve({ cursor: 0, keys: [oldKey], total_keys: 0 });
await settle();
await vi.waitFor(() => expect(document.body.textContent).toContain("fresh"));
expect(document.body.textContent).not.toContain("old");
expect(document.querySelector("[data-redis-batch-delete]")).toBeNull();
});
it("does not downgrade Ctrl+A to a partial selection when fetch-all is stopped", async () => {
const continuation = deferred<{ cursor: number; keys: RedisKeyInfo[]; total_keys: number }>();
const first = { key_display: "first", key_raw: "Zmlyc3Q=", key_type: "string", ttl: -1 };
mocks.redisScanKeysBatch.mockImplementation((_connectionId: string, _db: number, cursor: number) => {
if (cursor === 0) return Promise.resolve({ cursor: 1, keys: [first], total_keys: 2 });
return continuation.promise;
});
mountBrowser();
await settle();
requiredElement<HTMLButtonElement>("[data-redis-select-all]").click();
await vi.waitFor(() => expect(document.body.textContent).toContain("redis.stopFetchAll"));
clickButtonWithText("redis.stopFetchAll");
continuation.resolve({ cursor: 1, keys: [], total_keys: 0 });
await settle();
expect(document.querySelector("[data-redis-batch-delete]")).toBeNull();
expect(document.querySelector("[data-redis-select-all]")).not.toBeNull();
});
it("shows a native checked mark after selecting a single leaf key", async () => {
const keys = [
{ key_display: "solo-a", key_raw: "c29sby1h", key_type: "string", ttl: -1 },
{ key_display: "solo-b", key_raw: "c29sby1i", key_type: "string", ttl: -1 },
];
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mountBrowser();
await settle();
const leafA = leafCheckbox("solo-a");
expect(leafA.className).toContain("accent-primary");
expect(leafA.className).toContain("h-3.5");
leafA.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await settle();
expect(isCheckboxChecked(leafCheckbox("solo-a"))).toBe(true);
expect(document.querySelector("[data-redis-batch-delete]")?.textContent).toContain("1");
});
it("keeps parent and child checkbox DOM state in sync", async () => {
const keys = [
{ key_display: "pack:user_select", key_raw: "cGFjazp1c2VyX3NlbGVjdA==", key_type: "string", ttl: -1 },
{ key_display: "other:item", key_raw: "b3RoZXI6aXRlbQ==", key_type: "string", ttl: -1 },
];
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mountBrowser();
await settle();
// Select parent folder → child leaf must also appear checked.
await selectGroup("pack");
groupRow("pack").dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await settle();
const child = leafCheckbox("user_select");
expect(isCheckboxChecked(groupCheckbox("pack"))).toBe(true);
expect(isCheckboxChecked(child)).toBe(true);
// Uncheck child → parent must clear.
child.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await settle();
expect(isCheckboxChecked(leafCheckbox("user_select"))).toBe(false);
expect(isCheckboxChecked(groupCheckbox("pack"))).toBe(false);
expect(isCheckboxMixed(groupCheckbox("pack"))).toBe(false);
});
it("supports Shift multi-line selection and Ctrl/Cmd+A on the key list", async () => {
const keys = [
{ key_display: "k1", key_raw: "azE=", key_type: "string", ttl: -1 },
{ key_display: "k2", key_raw: "azI=", key_type: "string", ttl: -1 },
{ key_display: "k3", key_raw: "azM=", key_type: "string", ttl: -1 },
{ key_display: "k4", key_raw: "azQ=", key_type: "string", ttl: -1 },
];
mocks.redisScanKeysBatch.mockResolvedValue({ cursor: 0, keys, total_keys: keys.length });
mountBrowser();
await settle();
const checkboxes = Array.from(document.querySelectorAll<HTMLElement>('input[type="checkbox"]'));
expect(checkboxes).toHaveLength(keys.length);
checkboxes[0]!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await settle();
expect(isCheckboxChecked(checkboxes[0]!)).toBe(true);
checkboxes[2]!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, shiftKey: true }));
await settle();
expect(checkboxes.map((checkbox) => isCheckboxChecked(checkbox as HTMLElement))).toEqual([true, true, true, false]);
expect(document.querySelector("[data-redis-batch-delete]")?.textContent).toContain("3");
const keyPane = requiredElement<HTMLElement>(".redis-key-pane");
keyPane.focus();
keyPane.dispatchEvent(new KeyboardEvent("keydown", { key: "a", ctrlKey: true, bubbles: true, cancelable: true }));
await settle();
expect(checkboxes.every((checkbox) => isCheckboxChecked(checkbox as HTMLElement))).toBe(true);
expect(document.querySelector("[data-redis-batch-delete]")?.textContent).toContain("4");
keyPane.dispatchEvent(new KeyboardEvent("keydown", { key: "a", metaKey: true, bubbles: true, cancelable: true }));
await settle();
expect(checkboxes.every((checkbox) => !isCheckboxChecked(checkbox as HTMLElement))).toBe(true);
});
});