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): add opt-in plugin decoder previews
Leondung Chowa799e22ce940
diff --git a/apps/desktop/src/components/redis/RedisPluginCodecView.spec.ts b/apps/desktop/src/components/redis/RedisPluginCodecView.spec.tsnew file mode 100644index 0000000000..ef7d2af7fb--- /dev/null+++ b/apps/desktop/src/components/redis/RedisPluginCodecView.spec.ts@@ -0,0 +1,113 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";+import { createI18n } from "vue-i18n";+import RedisPluginCodecView from "./RedisPluginCodecView.vue";++const mocks = vi.hoisted(() => ({ listPlugins: vi.fn(), invokePlugin: vi.fn() }));+vi.mock("@/lib/backend/api", () => mocks);+vi.mock("@/components/common/JsonTree.vue", () => ({ default: defineComponent({ props: ["value"], setup: (props) => () => h("pre", { "data-json-tree": "" }, JSON.stringify(props.value)) }) }));+vi.mock("@/components/ui/select", () => ({+ Select: defineComponent({+ props: ["modelValue", "disabled"],+ emits: ["update:modelValue"],+ setup:+ (props, { slots, emit }) =>+ () =>+ h("select", { value: props.modelValue, disabled: props.disabled, onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value) }, slots.default?.()),+ }),+ SelectTrigger: defineComponent({+ setup:+ (_, { slots }) =>+ () =>+ h("option", { value: "" }, slots.default?.()),+ }),+ SelectValue: defineComponent({ props: ["placeholder"], setup: (props) => () => props.placeholder }),+ SelectContent: defineComponent({+ setup:+ (_, { slots }) =>+ () =>+ h("optgroup", slots.default?.()),+ }),+ SelectItem: defineComponent({+ props: ["value"],+ setup:+ (props, { slots }) =>+ () =>+ h("option", { value: props.value }, slots.default?.()),+ }),+}));++let app: App | undefined;+let root: HTMLDivElement;+const flush = async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await nextTick();+};+const plugin = { manifest: { id: "test.codec", name: "Test codec", drivers: [], entrypoints: { backend: { executable: "codec" } }, capabilities: [{ id: "custom", label: "Custom", kind: "redis-value-codec-v1" }] }, compatibility: { compatible: true } };+const choose = async () => {+ const select = root.querySelector("select")!;+ select.value = JSON.stringify(["test.codec", "custom"]);+ select.dispatchEvent(new Event("change"));+ await flush();+};++async function mount() {+ mocks.listPlugins.mockResolvedValue([plugin]);+ root = document.createElement("div");+ document.body.appendChild(root);+ const props = reactive({ rawBase64: "AA==", context: { db: 0, keyRaw: "aw==", redisType: "string" } });+ app = createApp({ render: () => h(RedisPluginCodecView, props) });+ app.use(createI18n({ legacy: false, locale: "en", missingWarn: false, fallbackWarn: false, messages: { en: { redis: {} } } }));+ app.mount(root);+ await flush();+ return props;+}+afterEach(() => {+ app?.unmount();+ root?.remove();+ vi.resetAllMocks();+});++describe("RedisPluginCodecView", () => {+ it("waits for selection and renders the selected decoder's JSON", async () => {+ mocks.invokePlugin.mockResolvedValue({ format: "json", value: { name: "Ada" } });+ await mount();+ expect(mocks.invokePlugin).not.toHaveBeenCalled();+ await choose();+ expect(root.querySelector("[data-json-tree]")?.textContent).toBe('{"name":"Ada"}');+ });++ it("discards a late result after the payload changes", async () => {+ let resolveOld!: (value: unknown) => void;+ mocks.invokePlugin+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve;+ }),+ )+ .mockResolvedValue({ format: "text", value: "new value" });+ const props = await mount();+ await choose();+ props.rawBase64 = "AQ==";+ await flush();+ expect(root.textContent).toContain("new value");+ resolveOld({ format: "text", value: "stale value" });+ await flush();+ expect(root.textContent).toContain("new value");+ expect(root.textContent).not.toContain("stale value");+ });++ it("clears previous data on failure and escapes program text", async () => {+ mocks.invokePlugin.mockResolvedValueOnce({ format: "text", value: '<img src=x onerror="alert(1)">' }).mockRejectedValueOnce(new Error("decoder failed"));+ const props = await mount();+ await choose();+ expect(root.querySelector("img")).toBeNull();+ expect(root.textContent).toContain("<img");+ props.rawBase64 = "AQ==";+ await flush();+ expect(root.querySelector('[role="alert"]')?.textContent).toContain("decoder failed");+ expect(root.textContent).not.toContain("<img");+ });+});diff --git a/apps/desktop/src/components/redis/RedisPluginCodecView.vue b/apps/desktop/src/components/redis/RedisPluginCodecView.vuenew file mode 100644index 0000000000..f3af3ad601--- /dev/null+++ b/apps/desktop/src/components/redis/RedisPluginCodecView.vue@@ -0,0 +1,103 @@+<script setup lang="ts">+import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import JsonTree from "@/components/common/JsonTree.vue";+import { copyToClipboard } from "@/lib/common/clipboard";+import * as api from "@/lib/backend/api";+import { decodeRedisPluginValue, listRedisPluginCodecs, type RedisPluginCodec, type RedisPluginCodecContext, type RedisPluginDecodedValue } from "@/lib/redis/redisPluginCodec";++const props = defineProps<{ rawBase64: string; context: RedisPluginCodecContext }>();+const { t } = useI18n();+const codecs = shallowRef<RedisPluginCodec[]>([]);+const selected = ref("");+const result = shallowRef<RedisPluginDecodedValue | null>(null);+const error = ref("");+const loading = ref(false);+const discovering = ref(false);+let revision = 0;+let disposed = false;+const selectedCodec = computed(() => codecs.value.find((codec) => codec.key === selected.value));++async function copyResult() {+ if (!result.value) return;+ try {+ await copyToClipboard(result.value.format === "text" ? String(result.value.value) : JSON.stringify(result.value.value, null, 2));+ } catch (cause) {+ error.value = String(cause);+ }+}++async function discover() {+ discovering.value = true;+ error.value = "";+ try {+ const available = listRedisPluginCodecs(await api.listPlugins());+ if (disposed) return;+ codecs.value = available;+ if (!available.some((codec) => codec.key === selected.value)) selected.value = "";+ } catch (cause) {+ if (!disposed) error.value = String(cause);+ } finally {+ if (!disposed) discovering.value = false;+ }+}++async function decode() {+ const current = ++revision;+ result.value = null;+ error.value = "";+ const codec = selectedCodec.value;+ if (!codec) {+ loading.value = false;+ return;+ }+ loading.value = true;+ try {+ // Only the explicitly selected payload crosses the plugin boundary. No+ // credentials, connection configuration or host driver are passed.+ const decoded = await decodeRedisPluginValue(api.invokePlugin, codec, props.rawBase64, props.context);+ if (!disposed && current === revision) result.value = decoded;+ } catch (cause) {+ if (!disposed && current === revision) error.value = String(cause);+ } finally {+ if (!disposed && current === revision) loading.value = false;+ }+}++watch(+ () => [selected.value, props.rawBase64, props.context.db, props.context.keyRaw, props.context.redisType],+ () => void decode(),+);+onMounted(() => void discover());+onBeforeUnmount(() => {+ disposed = true;+ revision++;+});+</script>++<template>+ <div class="flex min-h-0 flex-1 flex-col overflow-hidden" data-redis-plugin-codec>+ <div class="flex shrink-0 items-center gap-2 border-b px-4 py-2 text-xs">+ <Select v-model="selected" :disabled="discovering">+ <SelectTrigger class="h-7 w-72" :aria-label="t('redis.pluginCodecChoose')"><SelectValue :placeholder="t('redis.pluginCodecChoose')" /></SelectTrigger>+ <SelectContent+ ><SelectItem v-for="codec in codecs" :key="codec.key" :value="codec.key">{{ codec.label }}</SelectItem></SelectContent+ >+ </Select>+ <Button variant="outline" size="sm" :disabled="loading || !selectedCodec" @click="decode">{{ t("redis.pluginCodecDecode") }}</Button>+ <Button variant="ghost" size="sm" :disabled="discovering || loading" @click="discover">{{ t("redis.pluginCodecRefresh") }}</Button>+ <Button variant="ghost" size="sm" :disabled="!result || loading" @click="copyResult">{{ t("redis.pluginCodecCopy") }}</Button>+ <span class="text-muted-foreground">{{ t("redis.pluginCodecReadOnly") }}</span>+ </div>+ <p v-if="error" role="alert" class="shrink-0 whitespace-pre-wrap break-words border-b p-4 text-sm text-destructive">{{ error }}</p>+ <p v-if="loading || discovering" role="status" class="p-4 text-sm text-muted-foreground">{{ t("redis.pluginCodecLoading") }}</p>+ <div v-else-if="result" class="min-h-0 flex-1 overflow-auto p-4 text-sm">+ <JsonTree v-if="result.format === 'json'" :value="result.value" virtualized />+ <pre v-else class="whitespace-pre-wrap break-words">{{ result.value }}</pre>+ </div>+ <p v-else-if="!codecs.length && !error" class="p-4 text-sm text-muted-foreground">{{ t("redis.pluginCodecEmpty") }}</p>+ <p v-else-if="!selected && !error" class="p-4 text-sm text-muted-foreground">{{ t("redis.pluginCodecChoose") }}</p>+ </div>+</template>diff --git a/apps/desktop/src/components/redis/RedisValueViewer.vue b/apps/desktop/src/components/redis/RedisValueViewer.vueindex 71ad427373..17c28c0253 100644--- a/apps/desktop/src/components/redis/RedisValueViewer.vue+++ b/apps/desktop/src/components/redis/RedisValueViewer.vue@@ -70,6 +70,7 @@ import { decompressRedisValue, decodeBase64RedisValue, decodePickle, decodeProtoimport { nextRedisSearchMatchIndex, REDIS_VALUE_SEARCH_MATCH_LIMIT, redisValueSearchStatus } from "@/lib/redis/redisValueSearch";import TextContentSearchBar from "@/components/common/TextContentSearchBar.vue";import RedisHorizontalScrollbar from "@/components/redis/RedisHorizontalScrollbar.vue";+import RedisPluginCodecView from "@/components/redis/RedisPluginCodecView.vue";import { decodeJsonUnicodeEscapes, formatJsonSource, mapDisplayToRaw } from "@/lib/common/safeJsonFormat";import { unixSecondsToCalendarDateTime } from "@/components/ui/date-time-picker/dateTimePicker";import { applyRedisExpiryPolicy, type RedisExpiryMode, redisExpiryModeForTtl, validateRedisExpiry } from "@/lib/redis/redisExpiry";@@ -209,6 +210,9 @@ const stringValueView = ref<RedisValueFormat>(readStoredRedisValueFormat() ?? "uconst memberValueView = ref<RedisValueFormat>(readStoredRedisValueFormat() ?? "utf8");const stringValueCodec = ref<RedisValueCodec>(readStoredRedisValueCodec() ?? "none");const memberValueCodec = ref<RedisValueCodec>(readStoredRedisValueCodec() ?? "none");+const stringPluginCodecView = ref(false);+const memberPluginCodecView = ref(false);+const pluginCodecContext = computed(() => ({ db: props.db, keyRaw: props.keyRaw, redisType: data.value?.data.kind ?? "string" }));const redisJsonWordWrap = ref(readRedisJsonWordWrap());const redisJsonUnicodeMode = ref(readRedisJsonUnicodeMode());const redisJsonDecoded = computed(() => redisJsonUnicodeMode.value === "decoded");@@ -654,7 +658,7 @@ const isBinaryStringValue = computed(() => Boolean(stringValueDetail.value?.binaconst selectedMemberCanEdit = computed(() => selectedMemberContext.value?.canEdit ?? false);// kvrocks 位图不是字符串,写回会成为字符串,因此位图详情只读const canEditCurrentStringFormat = computed(() => !isBitmapKind.value && !isStringValueTruncated.value && Boolean(stringValueDetail.value?.editable) && (stringValueView.value === "utf8" || stringValueView.value === "json"));-const showStringEditActions = computed(() => canEditCurrentStringFormat.value);+const showStringEditActions = computed(() => !stringPluginCodecView.value && canEditCurrentStringFormat.value);const originalStringEditValue = computed(() => (stringBlob.value ? rawRedisValueText(stringBlob.value) : ""));const stringJsonRawBaseline = ref("");const stringJsonDraftBaseline = ref("");@@ -856,7 +860,7 @@ const zsetRows = computed<RedisCollectionRow<RedisZsetItem>[]>(() =>);/** True when Ctrl+F content find applies (STRING, RedisJSON, or open member detail). */-const valueSearchSupported = computed(() => showMemberDetail.value || isStringLikeKind.value || redisKind.value === "json");+const valueSearchSupported = computed(() => !(showMemberDetail.value ? memberPluginCodecView.value : stringPluginCodecView.value) && (showMemberDetail.value || isStringLikeKind.value || redisKind.value === "json"));// Resolve exactly the surface rendered by the active codec/view, including fallbacks.const activeSearchTree = computed(() => {const member = showMemberDetail.value;@@ -1613,6 +1617,7 @@ function setStringValueFormat(format: RedisValueFormat) {function setStringValueCodec(codec: RedisValueCodec) {if (isStringValueTruncated.value && codec !== "none") return;+ stringPluginCodecView.value = false;stringValueCodec.value = codec;rememberRedisValueCodec(codec);}@@ -1640,6 +1645,7 @@ function setMemberValueFormat(format: RedisValueFormat) {}function setMemberValueCodec(codec: RedisValueCodec) {+ memberPluginCodecView.value = false;memberValueCodec.value = codec;rememberRedisValueCodec(codec);}@@ -1853,7 +1859,10 @@ async function load(options: { background?: boolean; notifyParent?: boolean; pre// kvrocks 位图复用字符串的预览/编码渲染链路;位图不允许 JSON 视图与编辑,// 因为它并不是字符串(写回会改变服务端类型)。const allowJsonText = loadedValue.data.kind === "string";- if (loadedValue.data.truncated) stringValueCodec.value = "none";+ if (loadedValue.data.truncated) {+ stringValueCodec.value = "none";+ stringPluginCodecView.value = false;+ }const detail = formatRedisMemberDetail(loadedValue.data.content, { allowJsonText });// Issue #10922: detected JSON opens pretty-printed, detected structured// codecs open decoded — unless the user pinned an explicit format/codec.@@ -3053,7 +3062,9 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving@disable="disableAutoRefresh"@select="selectAutoRefreshInterval"/>- <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :disabled="isStringValueTruncated" :title="isStringValueTruncated ? t('redis.largeStringPreviewActionUnavailable') : t('grid.copyValue')" :aria-label="t('grid.copyValue')" @click="copyValue"><Copy class="h-3.5 w-3.5" /></Button>+ <Button v-if="!stringPluginCodecView" variant="ghost" size="icon" class="h-7 w-7 shrink-0" :disabled="isStringValueTruncated" :title="isStringValueTruncated ? t('redis.largeStringPreviewActionUnavailable') : t('grid.copyValue')" :aria-label="t('grid.copyValue')" @click="copyValue"+ ><Copy class="h-3.5 w-3.5"+ /></Button><Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" :disabled="isStringValueTruncated" :title="isStringValueTruncated ? t('redis.largeStringPreviewActionUnavailable') : t('redis.copyInsertStatement')" :aria-label="t('redis.copyInsertStatement')" @click="copyInsertStatement"><ClipboardCopy class="h-3.5 w-3.5"/></Button>@@ -3128,24 +3139,25 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || savingvariant="ghost"size="sm"class="h-6 shrink-0 rounded-[5px] px-2 text-xs"- :class="{ 'bg-background shadow-sm': stringValueCodec === codec }"+ :class="{ 'bg-background shadow-sm': !stringPluginCodecView && stringValueCodec === codec }":disabled="isStringValueTruncated && codec !== 'none'":title="isStringValueTruncated && codec !== 'none' ? t('redis.largeStringPreviewActionUnavailable') : undefined"@click="setStringValueCodec(codec)">{{ redisCodecLabel(codec) }}</Button>+ <Button variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': stringPluginCodecView }" :disabled="isStringValueTruncated || hasUnsavedRedisDraft" @click="stringPluginCodecView = true">{{ t("redis.pluginCodecLabel") }}</Button></RedisHorizontalScrollbar><Badge v-if="stringValueDetectionLabel" variant="outline" class="shrink-0 text-xs text-muted-foreground" :title="t('redis.detectedBadgeTitle')" :aria-label="t('redis.detectedBadgeTitle')">{{ stringValueDetectionLabel }}</Badge><FileArchive v-if="!isStringValueTruncated && stringGzipBadge && stringValueCodec === 'none'" class="h-3.5 w-3.5 shrink-0 text-muted-foreground" :title="t('redis.gzipBadgeTitle')" :aria-label="t('redis.gzipBadgeTitle')" /><span class="flex-1" />- <label v-if="isTextRedisFormat(stringValueView) || activeStructuredStringDetail || isDecompressCodec(stringValueCodec)" class="flex items-center gap-1.5 text-muted-foreground">+ <label v-if="!stringPluginCodecView && (isTextRedisFormat(stringValueView) || activeStructuredStringDetail || isDecompressCodec(stringValueCodec))" class="flex items-center gap-1.5 text-muted-foreground"><WrapText class="h-3.5 w-3.5" />{{ t("redis.wordWrap") }}<Switch size="sm" :model-value="redisJsonWordWrap" @update:model-value="setRedisJsonWordWrap(Boolean($event))" /></label></div>- <div class="flex h-9 items-center gap-2 border-b px-4 text-xs shrink-0">+ <div v-if="!stringPluginCodecView" class="flex h-9 items-center gap-2 border-b px-4 text-xs shrink-0"><span class="shrink-0 text-muted-foreground">{{ t("redis.viewRowLabel") }}</span><RedisHorizontalScrollbar><Button@@ -3167,8 +3179,9 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<Button variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': redisJsonDecoded }" @click="setRedisJsonUnicodeMode('decoded')">{{ t("redis.jsonViewDecoded") }}</Button></div></div>+ <RedisPluginCodecView v-if="stringPluginCodecView && !isStringValueTruncated" :raw-base64="stringValueDetail.base64Text" :context="pluginCodecContext" /><RedisJsonEditor- v-if="stringValueView === 'json' && stringValueDetail.json && stringValueCodec === 'none'"+ v-else-if="stringValueView === 'json' && stringValueDetail.json && stringValueCodec === 'none'"ref="stringJsonEditorRef":search-highlights="stringSearchHighlights"v-model="editValue"@@ -3987,18 +4000,19 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<div class="flex h-9 items-center gap-2 border-b px-5 text-xs"><span class="shrink-0 text-muted-foreground">{{ t("redis.codecRowLabel") }}</span><RedisHorizontalScrollbar>- <Button v-for="codec in REDIS_VALUE_CODEC_ORDER" :key="codec" variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': memberValueCodec === codec }" @click="setMemberValueCodec(codec)">+ <Button v-for="codec in REDIS_VALUE_CODEC_ORDER" :key="codec" variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': !memberPluginCodecView && memberValueCodec === codec }" @click="setMemberValueCodec(codec)">{{ redisCodecLabel(codec) }}</Button>+ <Button variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': memberPluginCodecView }" :disabled="hasUnsavedRedisDraft" @click="memberPluginCodecView = true">{{ t("redis.pluginCodecLabel") }}</Button></RedisHorizontalScrollbar><span class="flex-1" />- <label v-if="isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec)" class="flex items-center gap-1.5 text-muted-foreground">+ <label v-if="!memberPluginCodecView && (isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec))" class="flex items-center gap-1.5 text-muted-foreground"><WrapText class="h-3.5 w-3.5" />{{ t("redis.wordWrap") }}<Switch size="sm" :model-value="redisJsonWordWrap" @update:model-value="setRedisJsonWordWrap(Boolean($event))" /></label></div>- <div class="flex h-9 items-center gap-2 border-b px-5 text-xs">+ <div v-if="!memberPluginCodecView" class="flex h-9 items-center gap-2 border-b px-5 text-xs"><span class="shrink-0 text-muted-foreground">{{ t("redis.viewRowLabel") }}</span><RedisHorizontalScrollbar><Button@@ -4020,9 +4034,10 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<Button variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': redisJsonDecoded }" @click="setRedisJsonUnicodeMode('decoded')">{{ t("redis.jsonViewDecoded") }}</Button></div></div>+ <RedisPluginCodecView v-if="memberPluginCodecView" :raw-base64="selectedMemberDetail.base64Text" :context="pluginCodecContext" /><RedisJsonEditor:search-highlights="memberSearchHighlights"- v-if="isEditingHashJson"+ v-else-if="isEditingHashJson"ref="memberJsonEditorRef"v-model="memberEditValue"class="min-h-0 flex-1"@@ -4138,7 +4153,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving{{ t("grid.save") }}</Button></template>- <template v-else-if="isEditingHashJson">+ <template v-else-if="!memberPluginCodecView && isEditingHashJson"><Button variant="ghost" :disabled="savingMember || !memberValueChanged" @click="discardHashJsonEdit">{{ t("grid.discard") }}</Button>@@ -4148,11 +4163,11 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving{{ t("grid.save") }}</Button></template>- <Button v-else-if="canEditCurrentMemberFormat" variant="outline" @click="startEditMember">+ <Button v-else-if="!memberPluginCodecView && canEditCurrentMemberFormat" variant="outline" @click="startEditMember"><Pencil class="h-4 w-4" />{{ t("redis.editMember") }}</Button>- <Button variant="outline" @click="copyText(redisClipboardSafeText(memberCopyText))">+ <Button v-if="!memberPluginCodecView" variant="outline" @click="copyText(redisClipboardSafeText(memberCopyText))"><Copy class="h-4 w-4" />{{ t("redis.copyMember") }}</Button>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex a5ff7e0c93..a7b7de4382 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -7249,6 +7249,14 @@ export default {wordWrap: "Word wrap",codecNone: "None",codecRowLabel: "Decode",+ pluginCodecLabel: "Plugin",+ pluginCodecChoose: "Choose a decoder plugin",+ pluginCodecDecode: "Decode",+ pluginCodecRefresh: "Refresh plugins",+ pluginCodecCopy: "Copy result",+ pluginCodecReadOnly: "Read-only preview",+ pluginCodecLoading: "Loading…",+ pluginCodecEmpty: "Install a Redis decoder plugin in Plugin Center to view this value.",viewRowLabel: "View",codecBase64: "Base64",unicodeJsonView: "Unicode JSON",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 571dd376a6..a966b13ef4 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -6454,6 +6454,14 @@ export default withEnglishFallback({wordWrap: "Ajuste de línea",codecNone: "Ninguno",codecRowLabel: "Descodificar",+ pluginCodecLabel: "Plugin",+ pluginCodecChoose: "Elegir un plugin descodificador",+ pluginCodecDecode: "Descodificar",+ pluginCodecRefresh: "Actualizar plugins",+ pluginCodecCopy: "Copiar resultado",+ pluginCodecReadOnly: "Vista previa de solo lectura",+ pluginCodecLoading: "Cargando…",+ pluginCodecEmpty: "Instala un plugin descodificador de Redis en el Centro de plugins para ver este valor.",viewRowLabel: "Vista",codecBase64: "Base64",codecMismatch: "No se pudo decodificar con el códec seleccionado; se muestra el contenido original",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex a8e1d79065..7177c3a690 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -6270,6 +6270,14 @@ export default withEnglishFallback({wordWrap: "A capo automatico",codecNone: "Nessuno",codecRowLabel: "Decodifica",+ pluginCodecLabel: "Plugin",+ pluginCodecChoose: "Scegli un plugin di decodifica",+ pluginCodecDecode: "Decodifica",+ pluginCodecRefresh: "Aggiorna plugin",+ pluginCodecCopy: "Copia risultato",+ pluginCodecReadOnly: "Anteprima di sola lettura",+ pluginCodecLoading: "Caricamento…",+ pluginCodecEmpty: "Installa un plugin di decodifica Redis nel Centro plugin per visualizzare questo valore.",viewRowLabel: "Vista",codecBase64: "Base64",codecMismatch: "Impossibile decodificare con il codec selezionato; viene mostrato il contenuto originale",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 2fd0ce3e59..06eba19dba 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -6296,6 +6296,14 @@ export default withEnglishFallback({wordWrap: "折り返し",codecNone: "なし",codecRowLabel: "デコード",+ pluginCodecLabel: "プラグイン",+ pluginCodecChoose: "デコーダープラグインを選択",+ pluginCodecDecode: "デコード",+ pluginCodecRefresh: "プラグインを更新",+ pluginCodecCopy: "結果をコピー",+ pluginCodecReadOnly: "読み取り専用プレビュー",+ pluginCodecLoading: "読み込み中…",+ pluginCodecEmpty: "この値を表示するには、プラグインセンターで Redis デコーダープラグインをインストールしてください。",viewRowLabel: "表示",codecBase64: "Base64",codecMismatch: "選択したデコード方式では復元できません。元の内容を表示しています",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex c4ea5fed6d..a389b00e44 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -6088,6 +6088,14 @@ export default withEnglishFallback({wordWrap: "자동 줄바꿈",codecNone: "없음",codecRowLabel: "디코딩",+ pluginCodecLabel: "플러그인",+ pluginCodecChoose: "디코더 플러그인 선택",+ pluginCodecDecode: "디코딩",+ pluginCodecRefresh: "플러그인 새로 고침",+ pluginCodecCopy: "결과 복사",+ pluginCodecReadOnly: "읽기 전용 미리 보기",+ pluginCodecLoading: "불러오는 중…",+ pluginCodecEmpty: "이 값을 보려면 플러그인 센터에서 Redis 디코더 플러그인을 설치하세요.",viewRowLabel: "보기",codecBase64: "Base64",codecMismatch: "선택한 디코딩 방식으로 복원할 수 없어 원본 내용을 표시합니다",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 3bba955c2c..7d336ec409 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -6270,6 +6270,14 @@ export default withEnglishFallback({wordWrap: "Quebra de linha",codecNone: "Nenhum",codecRowLabel: "Decodificação",+ pluginCodecLabel: "Plugin",+ pluginCodecChoose: "Escolher um plugin de decodificação",+ pluginCodecDecode: "Decodificar",+ pluginCodecRefresh: "Atualizar plugins",+ pluginCodecCopy: "Copiar resultado",+ pluginCodecReadOnly: "Prévia somente leitura",+ pluginCodecLoading: "Carregando…",+ pluginCodecEmpty: "Instale um plugin de decodificação Redis na Central de plugins para visualizar este valor.",viewRowLabel: "Visualização",codecBase64: "Base64",codecMismatch: "Não foi possível decodificar com o codec selecionado; exibindo o conteúdo original",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 37886d8eaa..fdcc159694 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -7409,6 +7409,14 @@ export default withEnglishFallback({wordWrap: "Перенос по словам",codecNone: "Нет",codecRowLabel: "Декодировать",+ pluginCodecLabel: "Плагин",+ pluginCodecChoose: "Выберите плагин декодирования",+ pluginCodecDecode: "Декодировать",+ pluginCodecRefresh: "Обновить плагины",+ pluginCodecCopy: "Копировать результат",+ pluginCodecReadOnly: "Предпросмотр только для чтения",+ pluginCodecLoading: "Загрузка…",+ pluginCodecEmpty: "Чтобы просмотреть это значение, установите плагин декодирования Redis в центре плагинов.",viewRowLabel: "Просмотр",codecBase64: "Base64",unicodeJsonView: "Unicode JSON",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex b10f30f4de..3f9e114c49 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -7727,6 +7727,14 @@ export default withEnglishFallback({wordWrap: "ตัดบรรทัด",codecNone: "ไม่มี",codecRowLabel: "Decode",+ pluginCodecLabel: "ปลั๊กอิน",+ pluginCodecChoose: "เลือกปลั๊กอินถอดรหัส",+ pluginCodecDecode: "ถอดรหัส",+ pluginCodecRefresh: "รีเฟรชปลั๊กอิน",+ pluginCodecCopy: "คัดลอกผลลัพธ์",+ pluginCodecReadOnly: "แสดงตัวอย่างแบบอ่านอย่างเดียว",+ pluginCodecLoading: "กำลังโหลด…",+ pluginCodecEmpty: "ติดตั้งปลั๊กอินถอดรหัส Redis ในศูนย์ปลั๊กอินเพื่อดูค่านี้",viewRowLabel: "มุมมอง",codecBase64: "Base64",unicodeJsonView: "JSON แบบ Unicode",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 68e0c9b6bc..48f45973a8 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -7223,6 +7223,14 @@ export default withEnglishFallback({wordWrap: "自动换行",codecNone: "无",codecRowLabel: "解码",+ pluginCodecLabel: "插件",+ pluginCodecChoose: "选择解码插件",+ pluginCodecDecode: "解码",+ pluginCodecRefresh: "刷新插件",+ pluginCodecCopy: "复制结果",+ pluginCodecReadOnly: "只读预览",+ pluginCodecLoading: "正在加载…",+ pluginCodecEmpty: "请先在插件中心安装 Redis 解码插件,再查看此值。",viewRowLabel: "视图",codecBase64: "Base64",unicodeJsonView: "Unicode JSON",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex d7d21cb95b..9e51225a18 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -5611,6 +5611,14 @@ export default withEnglishFallback({wordWrap: "自動換行",codecNone: "無",codecRowLabel: "解碼",+ pluginCodecLabel: "外掛",+ pluginCodecChoose: "選擇解碼外掛",+ pluginCodecDecode: "解碼",+ pluginCodecRefresh: "重新整理外掛",+ pluginCodecCopy: "複製結果",+ pluginCodecReadOnly: "唯讀預覽",+ pluginCodecLoading: "載入中…",+ pluginCodecEmpty: "請先在外掛中心安裝 Redis 解碼外掛,再檢視此值。",viewRowLabel: "檢視",codecBase64: "Base64",codecMismatch: "無法按所選解碼方式還原,已顯示原始內容",diff --git a/apps/desktop/src/lib/__tests__/redis/redisPluginCodec.spec.ts b/apps/desktop/src/lib/__tests__/redis/redisPluginCodec.spec.tsnew file mode 100644index 0000000000..68019a68cd--- /dev/null+++ b/apps/desktop/src/lib/__tests__/redis/redisPluginCodec.spec.ts@@ -0,0 +1,42 @@+import { describe, expect, it, vi } from "vitest";+import type { InstalledPlugin } from "@/types/database";+import { decodeRedisPluginValue, listRedisPluginCodecs, REDIS_PLUGIN_CODEC_KIND, validateRedisPluginBytes, validateRedisPluginResult } from "@/lib/redis/redisPluginCodec";++const installed = (id = "example.codec", compatible = true): InstalledPlugin => ({+ manifest: { id, name: id, drivers: [], entrypoints: { backend: { executable: "bin/codec" } }, capabilities: [{ id: "custom", label: "Custom", kind: REDIS_PLUGIN_CODEC_KIND }] },+ compatibility: { compatible },+});++describe("Redis plugin codecs", () => {+ it("offers only compatible native plugins declaring the versioned codec capability", () => {+ const noBackend = installed("frontend");+ noBackend.manifest.entrypoints = {};+ const other = installed("other");+ other.manifest.capabilities![0]!.kind = "unrelated";+ expect(listRedisPluginCodecs([installed(), installed("old", false), noBackend, other]).map((codec) => codec.pluginId)).toEqual(["example.codec"]);+ });++ it("passes binary bytes unchanged and only the selected non-secret context", async () => {+ const invoke = vi.fn().mockResolvedValue({ format: "json", value: { user: "Ada" } });+ const codec = listRedisPluginCodecs([installed()])[0]!;+ const context = { db: 2, keyRaw: "dXNlcjox", redisType: "hash" };+ expect(await decodeRedisPluginValue(invoke, codec, "AP+A", context)).toEqual({ format: "json", value: { user: "Ada" } });+ expect(invoke).toHaveBeenCalledWith("example.codec", "redis/codec/decode", { codecId: "custom", rawBase64: "AP+A", context }, 10000);+ });++ it("rejects malformed, non-canonical and oversized bytes before invoking a program", async () => {+ const invoke = vi.fn();+ const codec = listRedisPluginCodecs([installed()])[0]!;+ for (const raw of ["!", "YQ", "YR==", "YQ==\n", "A".repeat(3 * 1024 * 1024)]) {+ await expect(decodeRedisPluginValue(invoke, codec, raw, { db: 0, keyRaw: "", redisType: "string" })).rejects.toThrow();+ }+ expect(invoke).not.toHaveBeenCalled();+ expect(() => validateRedisPluginBytes("")).not.toThrow();+ });++ it("validates renderer formats and bounds, including escaped text and JSON primitives", () => {+ for (const value of [null, false, 0, "", [], {}]) expect(validateRedisPluginResult({ format: "json", value }).value).toEqual(value);+ expect(validateRedisPluginResult({ format: "text", value: "<script>test</script>" }).value).toBe("<script>test</script>");+ for (const invalid of [null, {}, { format: "html", value: "x" }, { format: "text", value: 1 }, { format: "json" }, { format: "text", value: "\0".repeat(400000) }]) expect(() => validateRedisPluginResult(invalid)).toThrow();+ });+});diff --git a/apps/desktop/src/lib/redis/redisPluginCodec.ts b/apps/desktop/src/lib/redis/redisPluginCodec.tsnew file mode 100644index 0000000000..1c727e8a4b--- /dev/null+++ b/apps/desktop/src/lib/redis/redisPluginCodec.ts@@ -0,0 +1,63 @@+import type { InstalledPlugin } from "@/types/database";++/** Versioned capability kind; older hosts simply ignore it. */+export const REDIS_PLUGIN_CODEC_KIND = "redis-value-codec-v1";+export const REDIS_PLUGIN_CODEC_MAX_BYTES = 2 * 1024 * 1024;+export const REDIS_PLUGIN_CODEC_TIMEOUT_MS = 10_000;++export interface RedisPluginCodec {+ key: string;+ pluginId: string;+ codecId: string;+ label: string;+}++export interface RedisPluginCodecContext {+ db: number;+ keyRaw: string;+ redisType: string;+}++export interface RedisPluginDecodedValue {+ format: "json" | "text";+ value: unknown;+}++export function listRedisPluginCodecs(plugins: readonly InstalledPlugin[]): RedisPluginCodec[] {+ return plugins+ .filter((plugin) => plugin.compatibility.compatible && plugin.manifest.entrypoints?.backend)+ .flatMap((plugin) =>+ (plugin.manifest.capabilities ?? [])+ .filter((capability) => capability.kind === REDIS_PLUGIN_CODEC_KIND)+ .map((capability) => ({+ key: JSON.stringify([plugin.manifest.id, capability.id]),+ pluginId: plugin.manifest.id,+ codecId: capability.id,+ label: `${plugin.manifest.name} · ${capability.label}`,+ })),+ )+ .sort((left, right) => left.label.localeCompare(right.label));+}++export function validateRedisPluginBytes(rawBase64: string): void {+ if (rawBase64.length > Math.ceil(REDIS_PLUGIN_CODEC_MAX_BYTES / 3) * 4) throw new Error("Redis codec input exceeds 2 MiB");+ const bytes = atob(rawBase64);+ if (bytes.length > REDIS_PLUGIN_CODEC_MAX_BYTES || btoa(bytes) !== rawBase64) throw new Error("Invalid or oversized Redis codec input");+}++export function validateRedisPluginResult(result: unknown): RedisPluginDecodedValue {+ if (!result || typeof result !== "object") throw new Error("Invalid Redis codec response");+ const response = result as Partial<RedisPluginDecodedValue>;+ if (response.format !== "json" && response.format !== "text") throw new Error("Redis codec must return json or text");+ if (response.format === "text" && typeof response.value !== "string") throw new Error("Redis text codec must return a string");+ const serialized = JSON.stringify(response.value);+ if (serialized === undefined || new TextEncoder().encode(serialized).length > REDIS_PLUGIN_CODEC_MAX_BYTES) throw new Error("Invalid or oversized Redis codec result");+ return { format: response.format, value: response.value };+}++export type RedisCodecInvoker = (pluginId: string, method: string, params: unknown, timeoutMs: number) => Promise<unknown>;++export async function decodeRedisPluginValue(invoke: RedisCodecInvoker, codec: RedisPluginCodec, rawBase64: string, context: RedisPluginCodecContext): Promise<RedisPluginDecodedValue> {+ validateRedisPluginBytes(rawBase64);+ return validateRedisPluginResult(await invoke(codec.pluginId, "redis/codec/decode", { codecId: codec.codecId, rawBase64, context }, REDIS_PLUGIN_CODEC_TIMEOUT_MS));+}diff --git a/docs/content/docs/redis.cn.mdx b/docs/content/docs/redis.cn.mdxindex b16f0c8b07..7e93796339 100644--- a/docs/content/docs/redis.cn.mdx+++ b/docs/content/docs/redis.cn.mdx@@ -42,6 +42,14 @@ List、Set、Hash、Sorted Set 和 Stream 的成员详情同样提供「解压大型集合类型会分页加载。数量、已加载数量和继续加载入口会显示在详情中。+## 插件解码++如果值采用业务自定义的二进制格式,可以安装声明了 `redis-value-codec-v1` 能力的原生插件。在 String 值或集合成员详情的“解码”行选择“插件”,再选择解码器,DBX 会在当前详情中展示插件返回的 JSON 树或文本。++只有选定解码器后,当前值的原始字节才会发送给该插件;不会提供数据库连接配置或密码。输入和 JSON 化结果各限制为 2 MiB,超时为 10 秒,截断的值不能解码。失败会显示错误,点击内置解码选项可返回原始视图。++插件解码结果目前为只读预览,不会重新序列化并写回 Redis。开发者可参考[Redis 编解码插件协议](https://github.com/t8y2/dbx/blob/main/plugins/README.md#redis-value-codec-capability)。+## 创建与编辑 Key创建 Key 时选择数据类型并填写初始内容。可设置正整数 TTL;留空或按界面选择可创建永不过期 Key。diff --git a/docs/content/docs/redis.mdx b/docs/content/docs/redis.mdxindex fa3db6710c..66ec3bf18f 100644--- a/docs/content/docs/redis.mdx+++ b/docs/content/docs/redis.mdx@@ -42,6 +42,23 @@ List, Set, Hash, Sorted Set, and Stream member details provide the same DecompreLarge collection types load in pages and display total and loaded counts where available.+## Plugin Decoding++For application-specific binary values, install a native plugin declaring the+`redis-value-codec-v1` capability. In String or collection-member details, choose+**Plugin** in the Decode row, then select a decoder. Its JSON tree or text+appears in the existing value viewer.++Only the explicitly selected decoder receives the current bytes; it gets no+database credentials or connection configuration. Input and serialized output+are each limited to 2 MiB, calls time out after 10 seconds, and truncated+previews cannot be decoded. Errors stay visible; choose a built-in decoder to+return to the raw view.++Decoded previews are read-only and are not serialized back into Redis. See the+[Redis codec protocol](https://github.com/t8y2/dbx/blob/main/plugins/README.md#redis-value-codec-capability)+for plugin development.+## Create and Edit KeysChoose a data type and initial content when creating a key. Set a positive TTL or choose a persistent key.diff --git a/plugins/README.md b/plugins/README.mdindex 4dfc628988..397d9dea12 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -800,6 +800,55 @@ Host rules (`crates/dbx-core/src/ai/plugin_tools.rs`):- Names are exposed as `<prefix>__<tool>` (`io.dbx.ssh` → `ssh__…`). Schemas are reduced to a provider-portable subset (`type`, `description`, `properties`, `required`, `items`, string `enum`, numeric/length/item bounds); argument names must match `[A-Za-z_][A-Za-z0-9_]{0,63}`.- Discovery times out after 8 s per connection, calls after 120 s, and results are compacted before reaching the model.+## Redis value codec capability++Native plugins can expose decoders in Redis String/bitmap and collection-member+details using Manifest v1 capability metadata:++```json+{ "capabilities": [{ "id": "my-codec", "label": "My format", "kind": "redis-value-codec-v1" }] }+```++The user opens **Plugin** in the Decode row and explicitly selects a codec.+Listing the plugins sends no value. The selection stays local to that view,+and later visible-payload changes re-run that decoder; stale responses are+discarded. Compatible plugins must have a native backend entrypoint.++The host invokes the chosen sidecar's `redis/codec/decode` method:++```json+{+ "codecId": "my-codec",+ "rawBase64": "AP+A",+ "context": { "db": 0, "keyRaw": "opaque-key-identity", "redisType": "string" }+}+```++`rawBase64` is canonical standard Base64 of the original bytes, including NUL+and non-UTF-8 data. `keyRaw` is the existing Redis API's opaque Key identity;+do not reinterpret its encoding. For collection members, the bytes belong to+the selected member/field value and `redisType` names the containing Redis+type; no field or index identity is supplied. The plugin receives no database+credentials, connection configuration, connection string or host driver.++Return `{ "format": "json", "value": <JSON value> }` or+`{ "format": "text", "value": "UTF-8 text" }`. The host uses its JSON tree or+escaped text renderer, never HTML. JSON primitives, including `null`, are valid.+JSON numbers follow JavaScript semantics; use strings for precise large integers.++Calls time out after 10 seconds. Raw input and the UTF-8 serialized result+value are each limited to 2 MiB. Truncated previews are not passed to plugins.+Errors clear the previous decoded result; choose a built-in codec to return+to the raw view. This surface is read-only: it never calls an encoder or+writes data back to Redis. Plugins may expose encode and round-trip tests in+their own workbench. External-program plugins should use binary stdin/stdout,+bounded execution/output, and stderr for diagnostics.++This requires a DBX build with the Redis plugin codec view; older hosts may+install a plugin but do not offer it in Redis details. Package with the current+source CLI if an older published CLI rejects `capabilities`: the current+Manifest schema and runtime accept that field.+## Backend protocolThe backend is a persistent child process with stdin/stdout reserved for the DBX protocol. Diagnostics must go to stderr.