Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(devdock): query keys only in the Local Database inspector (#23023)

Innei1b9d3c6ac646
diff --git a/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts b/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts
index 19884b10540..0a4618d1e3d 100644
--- a/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts
@@ -3,6 +3,10 @@ import type {
DesktopLocalDatabaseCollectionInfo,
DesktopLocalDatabaseEntry,
DesktopLocalDatabaseKey,
+ DesktopLocalDatabaseKeyGroup,
+ DesktopLocalDatabaseKeyGroupQuery,
+ DesktopLocalDatabaseKeyPage,
+ DesktopLocalDatabaseKeyQuery,
DesktopLocalDatabasePrefix,
DesktopLocalDatabaseSet,
} from '@lobechat/electron-client-ipc';
@@ -51,6 +55,25 @@ export default class LocalDatabaseController extends ControllerModule {
return this.service.get(collection, key);
}
+ @IpcMethod()
+ async keyGroupsByPrefix({
+ collection,
+ delimiter,
+ prefix,
+ }: DesktopLocalDatabaseKeyGroupQuery): Promise<DesktopLocalDatabaseKeyGroup[]> {
+ return this.service.keyGroupsByPrefix(collection, prefix, delimiter);
+ }
+
+ @IpcMethod()
+ async keysByPrefix({
+ collection,
+ limit,
+ prefix,
+ search,
+ }: DesktopLocalDatabaseKeyQuery): Promise<DesktopLocalDatabaseKeyPage> {
+ return this.service.keysByPrefix(collection, prefix, { limit, search });
+ }
+
@IpcMethod()
async listCollections(): Promise<DesktopLocalDatabaseCollectionInfo[]> {
return this.service.listCollections();
diff --git a/apps/desktop/src/main/services/LocalDatabaseSrv.ts b/apps/desktop/src/main/services/LocalDatabaseSrv.ts
index bfa584e083e..11a007d35bf 100644
--- a/apps/desktop/src/main/services/LocalDatabaseSrv.ts
+++ b/apps/desktop/src/main/services/LocalDatabaseSrv.ts
@@ -4,8 +4,10 @@ import type {
DesktopLocalDatabaseBatchOperation,
DesktopLocalDatabaseCollectionInfo,
DesktopLocalDatabaseEntry,
+ DesktopLocalDatabaseKeyGroup,
+ DesktopLocalDatabaseKeyPage,
} from '@lobechat/electron-client-ipc';
-import { and, asc, eq, gte, lt } from 'drizzle-orm';
+import { and, asc, count, eq, gte, lt, sql } from 'drizzle-orm';
import { createLocalDatabaseRuntime, type LocalDatabaseRuntime } from '@/database/client';
import { localRecords } from '@/database/schema';
@@ -104,6 +106,58 @@ export default class LocalDatabaseService extends ServiceModule {
return row?.value;
}
+ async keyGroupsByPrefix(
+ collection: string,
+ prefix: string,
+ delimiter: string,
+ ): Promise<DesktopLocalDatabaseKeyGroup[]> {
+ const { lowerBound, upperBound } = prefixRange(collection, prefix);
+ const rows = await this.getRuntime()
+ .db.select({ id: localRecords.id })
+ .from(localRecords)
+ .where(and(gte(localRecords.id, lowerBound), lt(localRecords.id, upperBound)));
+ const counts = new Map<string, number>();
+
+ for (const { id } of rows) {
+ const delimiterIndex = id.indexOf(delimiter, lowerBound.length);
+ if (delimiterIndex < 0) continue;
+
+ const name = id.slice(lowerBound.length, delimiterIndex);
+ counts.set(name, (counts.get(name) ?? 0) + 1);
+ }
+
+ return [...counts.entries()]
+ .map(([name, entryCount]) => ({ entryCount, name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ }
+
+ async keysByPrefix(
+ collection: string,
+ prefix: string,
+ { limit, search }: { limit?: number; search?: string } = {},
+ ): Promise<DesktopLocalDatabaseKeyPage> {
+ const { lowerBound, upperBound } = prefixRange(collection, prefix);
+ const keyPrefix = collectionPrefix(collection);
+ const term = search?.trim().toLowerCase();
+ // SQLite substr() counts code points while String#length counts UTF-16 units.
+ const keyStart = [...keyPrefix].length + 1;
+ const where = and(
+ gte(localRecords.id, lowerBound),
+ lt(localRecords.id, upperBound),
+ term ? sql`instr(lower(substr(${localRecords.id}, ${keyStart})), ${term}) > 0` : undefined,
+ );
+ const { db } = this.getRuntime();
+ const [{ total }] = await db.select({ total: count() }).from(localRecords).where(where);
+ const query = db
+ .select({ id: localRecords.id })
+ .from(localRecords)
+ .where(where)
+ .orderBy(asc(localRecords.id));
+ const rows = await (limit === undefined ? query : query.limit(limit));
+
+ return { keys: rows.map(({ id }) => id.slice(keyPrefix.length)), total };
+ }
+
async listCollections(): Promise<DesktopLocalDatabaseCollectionInfo[]> {
const rows = await this.getRuntime().db.select({ id: localRecords.id }).from(localRecords);
const counts = new Map<string, number>();
diff --git a/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts b/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts
index 018de33ae00..bafc840ca01 100644
--- a/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts
@@ -62,6 +62,37 @@ describe('LocalDatabaseService', () => {
]);
});
+ it('lists, counts, searches and groups keys without reading values', async () => {
+ await service.batch([
+ { collection: 'cache', key: 'replica:topicList:v1:user:Agent_1', type: 'set', value: 'a' },
+ { collection: 'cache', key: 'replica:topicList:v1:user:agent_2', type: 'set', value: 'b' },
+ { collection: 'cache', key: 'replica:agentDetail:v1:user:agent_1', type: 'set', value: 'c' },
+ { collection: 'cache', key: 'plain', type: 'set', value: 'd' },
+ { collection: 'other', key: 'replica:topicList:v1:user:agent_1', type: 'set', value: 'e' },
+ ]);
+
+ await expect(service.keysByPrefix('cache', '', { limit: 2 })).resolves.toEqual({
+ keys: ['plain', 'replica:agentDetail:v1:user:agent_1'],
+ total: 4,
+ });
+ await expect(service.keysByPrefix('cache', 'replica:topicList:')).resolves.toEqual({
+ keys: ['replica:topicList:v1:user:Agent_1', 'replica:topicList:v1:user:agent_2'],
+ total: 2,
+ });
+ await expect(service.keysByPrefix('cache', '', { search: ' AGENT_1 ' })).resolves.toEqual({
+ keys: ['replica:agentDetail:v1:user:agent_1', 'replica:topicList:v1:user:Agent_1'],
+ total: 2,
+ });
+ await expect(service.keysByPrefix('cache', '', { search: 'cache' })).resolves.toEqual({
+ keys: [],
+ total: 0,
+ });
+ await expect(service.keyGroupsByPrefix('cache', 'replica:', ':')).resolves.toEqual([
+ { entryCount: 1, name: 'agentDetail' },
+ { entryCount: 2, name: 'topicList' },
+ ]);
+ });
+
it('commits mixed batch operations atomically', async () => {
await service.set('cache', 'legacy', 'old');
await service.batch([
diff --git a/packages/electron-client-ipc/src/types/localDatabase.ts b/packages/electron-client-ipc/src/types/localDatabase.ts
index 04f0f2a4102..8ed899b05f0 100644
--- a/packages/electron-client-ipc/src/types/localDatabase.ts
+++ b/packages/electron-client-ipc/src/types/localDatabase.ts
@@ -18,6 +18,25 @@ export interface DesktopLocalDatabaseCollectionInfo {
name: string;
}
+export interface DesktopLocalDatabaseKeyQuery extends DesktopLocalDatabasePrefix {
+ limit?: number;
+ search?: string;
+}
+
+export interface DesktopLocalDatabaseKeyPage {
+ keys: string[];
+ total: number;
+}
+
+export interface DesktopLocalDatabaseKeyGroupQuery extends DesktopLocalDatabasePrefix {
+ delimiter: string;
+}
+
+export interface DesktopLocalDatabaseKeyGroup {
+ entryCount: number;
+ name: string;
+}
+
export interface DesktopLocalDatabaseSet extends DesktopLocalDatabaseKey {
value: string;
}
diff --git a/src/features/DevPanel/LocalDatabase/CollectionList.tsx b/src/features/DevPanel/LocalDatabase/CollectionList.tsx
index e0b52fbfb2b..46937d2f229 100644
--- a/src/features/DevPanel/LocalDatabase/CollectionList.tsx
+++ b/src/features/DevPanel/LocalDatabase/CollectionList.tsx
@@ -5,16 +5,15 @@ import { Boxes, Table2 } from 'lucide-react';
import { useState } from 'react';
import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
-import type { LocalDatabaseCollectionInfo } from '@/libs/localDatabase';
+import type { LocalDatabaseCollectionInfo, LocalDatabaseKeyGroup } from '@/libs/localDatabase';
import { inspectorStyles as styles } from '../inspectorStyles';
-import type { ReplicaResourceGroup } from './model';
interface CollectionListProps {
collections: LocalDatabaseCollectionInfo[];
onSelectCollection: (name: string) => void;
onSelectResource: (resource: string | null) => void;
- resources: ReplicaResourceGroup[];
+ resources: LocalDatabaseKeyGroup[];
selectedCollection: string | null;
selectedResource: string | null;
}
diff --git a/src/features/DevPanel/LocalDatabase/RecordDetails.tsx b/src/features/DevPanel/LocalDatabase/RecordDetails.tsx
index 2a1fc83d225..6baeac39bd7 100644
--- a/src/features/DevPanel/LocalDatabase/RecordDetails.tsx
+++ b/src/features/DevPanel/LocalDatabase/RecordDetails.tsx
@@ -1,24 +1,76 @@
'use client';
-import { cx, Input } from '@lobehub/ui';
-import { useState } from 'react';
+import { cx, Input, Spin } from '@lobehub/ui';
+import { useMemo, useState } from 'react';
import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+import type { LocalDatabaseEntry } from '@/libs/localDatabase';
import { inspectorStyles as styles } from '../inspectorStyles';
import {
filterLocalDatabaseFields,
formatLocalDatabaseFieldValue,
- type LocalDatabaseTableRow,
+ getLocalDatabaseFields,
+ parseReplicaStorageKey,
} from './model';
+const MAX_VALUE_CHARS = 20_000;
+
interface RecordDetailsProps {
- row: LocalDatabaseTableRow | undefined;
+ entry: LocalDatabaseEntry | null;
+ isLoading: boolean;
+ selectedKey: string | null;
}
-const RecordDetails = ({ row }: RecordDetailsProps) => {
+const clip = (text: string): string =>
+ text.length > MAX_VALUE_CHARS
+ ? `${text.slice(0, MAX_VALUE_CHARS)}\n… ${text.length - MAX_VALUE_CHARS} more characters`
+ : text;
+
+const RecordDetails = ({ entry, isLoading, selectedKey }: RecordDetailsProps) => {
const [search, setSearch] = useState('');
- const visibleFields = filterLocalDatabaseFields(row?.fields ?? [], search);
+ // A single persisted value can be several MB; serialize it once per record, not per keystroke.
+ const fields = useMemo(
+ () =>
+ entry
+ ? getLocalDatabaseFields(entry, parseReplicaStorageKey(entry.key)).map((field) => ({
+ ...field,
+ text: clip(formatLocalDatabaseFieldValue(field.value)),
+ }))
+ : [],
+ [entry],
+ );
+ const visibleFields = useMemo(() => filterLocalDatabaseFields(fields, search), [fields, search]);
+
+ const renderBody = () => {
+ if (selectedKey === null) {
+ return <div className={styles.empty}>Select a row to load its value.</div>;
+ }
+
+ if (!entry) {
+ return (
+ <div className={styles.empty}>{isLoading ? <Spin /> : 'This record no longer exists.'}</div>
+ );
+ }
+
+ return (
+ <div className={styles.detailFields}>
+ {visibleFields.length === 0 ? (
+ <div className={styles.empty}>No fields match.</div>
+ ) : (
+ visibleFields.map((field) => (
+ <div className={styles.detailField} key={field.id}>
+ <div className={styles.detailLabel}>
+ <span>{field.label}</span>
+ <span className={styles.detailType}>{field.type}</span>
+ </div>
+ <pre className={styles.detailValue}>{field.text}</pre>
+ </div>
+ ))
+ )}
+ </div>
+ );
+ };
return (
<aside
@@ -30,7 +82,7 @@ const RecordDetails = ({ row }: RecordDetailsProps) => {
<Input
allowClear
className={devDockPanelStyles.searchInput}
- disabled={!row}
+ disabled={!entry}
placeholder={'Search fields…'}
size={'small'}
value={search}
@@ -38,27 +90,7 @@ const RecordDetails = ({ row }: RecordDetailsProps) => {
onChange={(event) => setSearch(event.target.value)}
/>
</div>
- {row ? (
- <div className={styles.detailFields}>
- {visibleFields.length === 0 ? (
- <div className={styles.empty}>No fields match.</div>
- ) : (
- visibleFields.map((field) => (
- <div className={styles.detailField} key={field.id}>
- <div className={styles.detailLabel}>
- <span>{field.label}</span>
- <span className={styles.detailType}>{field.type}</span>
- </div>
- <pre className={styles.detailValue}>
- {formatLocalDatabaseFieldValue(field.value)}
- </pre>
- </div>
- ))
- )}
- </div>
- ) : (
- <div className={styles.empty}>Select a row to inspect its fields.</div>
- )}
+ {renderBody()}
</aside>
);
};
diff --git a/src/features/DevPanel/LocalDatabase/RecordTable.tsx b/src/features/DevPanel/LocalDatabase/RecordTable.tsx
index 533946178f2..70b7c986d80 100644
--- a/src/features/DevPanel/LocalDatabase/RecordTable.tsx
+++ b/src/features/DevPanel/LocalDatabase/RecordTable.tsx
@@ -10,10 +10,9 @@ import {
formatLocalDatabaseCellValue,
type LocalDatabaseColumn,
type LocalDatabaseTableRow,
+ MAX_RENDERED_ROWS,
} from './model';
-export const MAX_RENDERED_ROWS = 300;
-
interface RecordTableProps {
columns: LocalDatabaseColumn[];
isLoading: boolean;
@@ -23,7 +22,7 @@ interface RecordTableProps {
onSelect: (key: string) => void;
rows: LocalDatabaseTableRow[];
rowSearch: string;
- selectedKey: string | undefined;
+ selectedKey: string | null;
title: string;
totalCount: number;
}
@@ -62,7 +61,7 @@ const RecordTable = ({
<Input
allowClear
className={styles.toolbarSearch}
- placeholder={'Search rows…'}
+ placeholder={'Search keys…'}
size={'small'}
style={{ flex: 1 }}
value={rowSearch}
@@ -101,20 +100,20 @@ const RecordTable = ({
</thead>
<tbody>
{rows.map((row) => {
- const active = row.entry.key === selectedKey;
+ const active = row.key === selectedKey;
return (
<tr
- aria-label={row.entry.key}
+ aria-label={row.key}
aria-selected={active}
className={active ? styles.rowActive : undefined}
- key={row.entry.key}
+ key={row.key}
tabIndex={0}
- onClick={() => onSelect(row.entry.key)}
+ onClick={() => onSelect(row.key)}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
- onSelect(row.entry.key);
+ onSelect(row.key);
}
}}
>
@@ -135,13 +134,15 @@ const RecordTable = ({
</table>
{rows.length === 0 && (
<div className={styles.tableEmpty}>
- {rowSearch ? `No rows match “${rowSearch}”.` : 'This collection is empty.'}
+ {rowSearch ? `No keys match “${rowSearch}”.` : 'This collection is empty.'}
</div>
)}
</div>
<div className={devDockPanelStyles.statusBar}>
<span>{rowRange}</span>
- {matchingCount > MAX_RENDERED_ROWS && <span>Refine the search to inspect later rows.</span>}
+ {matchingCount > MAX_RENDERED_ROWS && (
+ <span>Refine the key search to inspect later rows.</span>
+ )}
</div>
</main>
);
diff --git a/src/features/DevPanel/LocalDatabase/index.tsx b/src/features/DevPanel/LocalDatabase/index.tsx
index ed02320887c..ca8ed49a9a9 100644
--- a/src/features/DevPanel/LocalDatabase/index.tsx
+++ b/src/features/DevPanel/LocalDatabase/index.tsx
@@ -1,7 +1,6 @@
'use client';
import { Button, Spin } from '@lobehub/ui';
-import { useMemo, useState } from 'react';
import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
@@ -9,53 +8,43 @@ import { inspectorStyles as styles } from '../inspectorStyles';
import CollectionList from './CollectionList';
import {
createLocalDatabaseTableRows,
- filterLocalDatabaseRows,
- filterRowsByResource,
getLocalDatabaseColumns,
- getReplicaResourceGroups,
type LocalDatabaseColumn,
} from './model';
import RecordDetails from './RecordDetails';
-import RecordTable, { MAX_RENDERED_ROWS } from './RecordTable';
+import RecordTable from './RecordTable';
import { useLocalDatabaseInspector } from './useLocalDatabaseInspector';
-const EMPTY_COLUMNS: LocalDatabaseColumn[] = [
- { id: '__key', label: 'key' },
- { id: 'value', label: 'value' },
-];
+const KEY_ONLY_COLUMNS: LocalDatabaseColumn[] = [{ id: '__key', label: 'key' }];
const LocalDatabasePanel = () => {
- const { collections, entries, error, isLoading, refresh, selectCollection, selectedCollection } =
- useLocalDatabaseInspector();
- const [rowSearch, setRowSearch] = useState('');
- const [selectedKey, setSelectedKey] = useState<string | null>(null);
- const [selectedResource, setSelectedResource] = useState<string | null>(null);
+ const {
+ collections,
+ error,
+ isLoading,
+ isRecordLoading,
+ keys,
+ matchingCount,
+ refresh,
+ resources,
+ search,
+ selectCollection,
+ selectKey,
+ selectResource,
+ selectedCollection,
+ selectedEntry,
+ selectedKey,
+ selectedResource,
+ setSearch,
+ } = useLocalDatabaseInspector();
- const tableRows = useMemo(() => createLocalDatabaseTableRows(entries), [entries]);
- const resources = useMemo(() => getReplicaResourceGroups(tableRows), [tableRows]);
- const activeResource = resources.some(({ name }) => name === selectedResource)
- ? selectedResource
- : null;
- const resourceRows = useMemo(
- () => filterRowsByResource(tableRows, activeResource),
- [activeResource, tableRows],
- );
- const columns = useMemo(() => {
- const resolved = getLocalDatabaseColumns(resourceRows);
- return resolved.length > 0 ? resolved : EMPTY_COLUMNS;
- }, [resourceRows]);
- const matchingRows = useMemo(
- () => filterLocalDatabaseRows(resourceRows, rowSearch),
- [resourceRows, rowSearch],
- );
- const renderedRows = matchingRows.slice(0, MAX_RENDERED_ROWS);
- const selectedRow =
- renderedRows.find(({ entry }) => entry.key === selectedKey) ?? renderedRows.at(0);
-
- const resetSelection = () => {
- setRowSearch('');
- setSelectedKey(null);
- };
+ const rows = createLocalDatabaseTableRows(keys);
+ const columns = rows.length > 0 ? getLocalDatabaseColumns(rows) : KEY_ONLY_COLUMNS;
+ const totalCount =
+ (selectedResource
+ ? resources.find(({ name }) => name === selectedResource)
+ : collections.find(({ name }) => name === selectedCollection)
+ )?.entryCount ?? 0;
if (error) {
return (
@@ -87,31 +76,29 @@ const LocalDatabasePanel = () => {
collections={collections}
resources={resources}
selectedCollection={selectedCollection}
- selectedResource={activeResource}
- onSelectCollection={(name) => {
- resetSelection();
- setSelectedResource(null);
- void selectCollection(name);
- }}
- onSelectResource={(resource) => {
- resetSelection();
- setSelectedResource(resource);
- }}
+ selectedResource={selectedResource}
+ onSelectCollection={(name) => void selectCollection(name)}
+ onSelectResource={(resource) => void selectResource(resource)}
/>
<RecordTable
columns={columns}
isLoading={isLoading}
- matchingCount={matchingRows.length}
- rowSearch={rowSearch}
- rows={renderedRows}
- selectedKey={selectedRow?.entry.key}
- title={activeResource ?? selectedCollection ?? 'Local Database'}
- totalCount={resourceRows.length}
+ matchingCount={matchingCount}
+ rowSearch={search}
+ rows={rows}
+ selectedKey={selectedKey}
+ title={selectedResource ?? selectedCollection ?? 'Local Database'}
+ totalCount={totalCount}
onRefresh={() => void refresh()}
- onRowSearchChange={setRowSearch}
- onSelect={setSelectedKey}
+ onRowSearchChange={(value) => void setSearch(value)}
+ onSelect={(key) => void selectKey(key)}
+ />
+ <RecordDetails
+ entry={selectedEntry}
+ isLoading={isRecordLoading}
+ key={selectedCollection ?? ''}
+ selectedKey={selectedKey}
/>
- <RecordDetails key={selectedCollection ?? ''} row={selectedRow} />
</div>
</div>
);
diff --git a/src/features/DevPanel/LocalDatabase/model.test.ts b/src/features/DevPanel/LocalDatabase/model.test.ts
index d73117d1141..6e1db9bc987 100644
--- a/src/features/DevPanel/LocalDatabase/model.test.ts
+++ b/src/features/DevPanel/LocalDatabase/model.test.ts
@@ -5,12 +5,11 @@ import type { LocalDatabaseEntry } from '@/libs/localDatabase';
import {
createLocalDatabaseTableRows,
filterLocalDatabaseFields,
- filterLocalDatabaseRows,
- filterRowsByResource,
formatLocalDatabaseFieldValue,
getLocalDatabaseColumns,
- getReplicaResourceGroups,
+ getLocalDatabaseFields,
parseReplicaStorageKey,
+ replicaResourcePrefix,
} from './model';
const replicaKey = (resource: string, scope: string, queryKey: string, version = 1) =>
@@ -44,8 +43,8 @@ describe('Local Database table model', () => {
expect(parseReplicaStorageKey('swr:message:list')).toBeUndefined();
});
- it('expands timestamped envelopes into replica columns before the data fields', () => {
- const rows = createLocalDatabaseTableRows(entries);
+ it('builds table rows and columns from keys alone', () => {
+ const rows = createLocalDatabaseTableRows([...entries.map(({ key }) => key), 'not-a-replica']);
expect(getLocalDatabaseColumns(rows).map(({ label }) => label)).toEqual([
'key',
@@ -53,23 +52,35 @@ describe('Local Database table model', () => {
'version',
'scope',
'query',
+ ]);
+ expect(rows[2].fields.map(({ label }) => label)).toEqual(['key']);
+ expect(replicaResourcePrefix('topicList')).toBe('replica:topicList:');
+ expect(entries[0].key.startsWith(replicaResourcePrefix('topicList'))).toBe(true);
+ });
+
+ it('expands a loaded timestamped envelope into detail fields after the key fields', () => {
+ const fields = getLocalDatabaseFields(entries[1], parseReplicaStorageKey(entries[1].key));
+
+ expect(fields.map(({ label }) => label)).toEqual([
+ 'key',
+ 'resource',
+ 'version',
+ 'scope',
+ 'query',
'updatedAt',
'id',
- 'items',
- 'total',
'title',
]);
- expect(rows[1].fields.find(({ label }) => label === 'updatedAt')?.value).toEqual(
- new Date(1000),
- );
+ expect(fields.find(({ label }) => label === 'updatedAt')?.value).toEqual(new Date(1000));
});
it('keeps data fields that collide with key columns under a data prefix', () => {
- const [row] = createLocalDatabaseTableRows([
- { key: 'plain', value: { data: { key: 'k', version: 'v2' }, updatedAt: 0, version: '7' } },
- ]);
+ const fields = getLocalDatabaseFields({
+ key: 'plain',
+ value: { data: { key: 'k', version: 'v2' }, updatedAt: 0, version: '7' },
+ });
- expect(row.fields.map(({ label }) => label)).toEqual([
+ expect(fields.map(({ label }) => label)).toEqual([
'key',
'version',
'updatedAt',
@@ -78,27 +89,11 @@ describe('Local Database table model', () => {
]);
});
- it('groups replica rows by resource and filters the table to one resource', () => {
- const rows = createLocalDatabaseTableRows([
- ...entries,
- { key: 'not-a-replica', value: 1 },
- { key: replicaKey('topicList', 'user-b', 'agent_2'), value: { data: null, updatedAt: 0 } },
- ]);
-
- expect(getReplicaResourceGroups(rows)).toEqual([
- { entryCount: 1, name: 'agentDetail' },
- { entryCount: 2, name: 'topicList' },
- ]);
- expect(filterRowsByResource(rows, 'topicList')).toHaveLength(2);
- expect(filterRowsByResource(rows, null)).toHaveLength(4);
- });
-
- it('finds rows and details by field names or nested persisted values', () => {
- const rows = createLocalDatabaseTableRows(entries);
+ it('finds detail fields by name, type or nested persisted values', () => {
+ const fields = getLocalDatabaseFields(entries[0], parseReplicaStorageKey(entries[0].key));
- expect(filterLocalDatabaseRows(rows, 'storage')).toEqual([rows[0]]);
- expect(filterLocalDatabaseRows(rows, 'alpha')).toEqual([rows[1]]);
- expect(filterLocalDatabaseFields(rows[0].fields, 'array').map(({ label }) => label)).toEqual([
+ expect(filterLocalDatabaseFields(fields, 'array').map(({ label }) => label)).toEqual(['items']);
+ expect(filterLocalDatabaseFields(fields, 'storage').map(({ label }) => label)).toEqual([
'items',
]);
});
diff --git a/src/features/DevPanel/LocalDatabase/model.ts b/src/features/DevPanel/LocalDatabase/model.ts
index 2e8df9173ce..d281656618e 100644
--- a/src/features/DevPanel/LocalDatabase/model.ts
+++ b/src/features/DevPanel/LocalDatabase/model.ts
@@ -13,8 +13,8 @@ export interface LocalDatabaseColumn {
}
export interface LocalDatabaseTableRow {
- entry: LocalDatabaseEntry;
fields: LocalDatabaseField[];
+ key: string;
replica?: ReplicaStorageKey;
}
@@ -25,10 +25,12 @@ export interface ReplicaStorageKey {
version: number;
}
-export interface ReplicaResourceGroup {
- entryCount: number;
- name: string;
-}
+export const MAX_RENDERED_ROWS = 300;
+export const REPLICA_KEY_PREFIX = 'replica:';
+export const REPLICA_KEY_DELIMITER = ':';
+
+export const replicaResourcePrefix = (resource: string): string =>
+ `${REPLICA_KEY_PREFIX}${resource}${REPLICA_KEY_DELIMITER}`;
const FIELD_PRIORITY = new Map([
['key', 0],
@@ -143,11 +145,11 @@ const pushValueFields = (fields: LocalDatabaseField[], prefix: string, value: un
}
};
-export const getLocalDatabaseFields = (
- entry: LocalDatabaseEntry,
+const getLocalDatabaseKeyFields = (
+ key: string,
replica?: ReplicaStorageKey,
): LocalDatabaseField[] => {
- const fields = [createField('__key', 'key', entry.key)];
+ const fields = [createField('__key', 'key', key)];
if (replica) {
fields.push(
@@ -158,6 +160,14 @@ export const getLocalDatabaseFields = (
);
}
+ return fields;
+};
+
+export const getLocalDatabaseFields = (
+ entry: LocalDatabaseEntry,
+ replica?: ReplicaStorageKey,
+): LocalDatabaseField[] => {
+ const fields = getLocalDatabaseKeyFields(entry.key, replica);
const { value } = entry;
if (isTimestampEnvelope(value)) {
@@ -174,33 +184,12 @@ export const getLocalDatabaseFields = (
return byPriority(fields, (field) => field.label);
};
-export const createLocalDatabaseTableRows = (
- entries: LocalDatabaseEntry[],
-): LocalDatabaseTableRow[] =>
- entries.map((entry) => {
- const replica = parseReplicaStorageKey(entry.key);
- return { entry, fields: getLocalDatabaseFields(entry, replica), replica };
+export const createLocalDatabaseTableRows = (keys: string[]): LocalDatabaseTableRow[] =>
+ keys.map((key) => {
+ const replica = parseReplicaStorageKey(key);
+ return { fields: getLocalDatabaseKeyFields(key, replica), key, replica };
});
-export const getReplicaResourceGroups = (rows: LocalDatabaseTableRow[]): ReplicaResourceGroup[] => {
- const counts = new Map<string, number>();
-
- for (const { replica } of rows) {
- if (!replica) continue;
- counts.set(replica.resource, (counts.get(replica.resource) ?? 0) + 1);
- }
-
- return [...counts.entries()]
- .map(([name, entryCount]) => ({ entryCount, name }))
- .sort((a, b) => a.name.localeCompare(b.name));
-};
-
-export const filterRowsByResource = (
- rows: LocalDatabaseTableRow[],
- resource: string | null,
-): LocalDatabaseTableRow[] =>
- resource ? rows.filter(({ replica }) => replica?.resource === resource) : rows;
-
export const getLocalDatabaseColumns = (rows: LocalDatabaseTableRow[]): LocalDatabaseColumn[] => {
const columns = new Map<string, LocalDatabaseColumn>();
@@ -213,26 +202,10 @@ export const getLocalDatabaseColumns = (rows: LocalDatabaseTableRow[]): LocalDat
return byPriority([...columns.values()], (column) => column.label);
};
-export const filterLocalDatabaseRows = (
- rows: LocalDatabaseTableRow[],
+export const filterLocalDatabaseFields = <T extends LocalDatabaseField>(
+ fields: T[],
search: string,
-): LocalDatabaseTableRow[] => {
- const term = search.trim().toLowerCase();
- if (!term) return rows;
-
- return rows.filter(({ fields }) =>
- fields.some(
- ({ label, value }) =>
- label.toLowerCase().includes(term) ||
- formatLocalDatabaseCellValue(value).toLowerCase().includes(term),
- ),
- );
-};
-
-export const filterLocalDatabaseFields = (
- fields: LocalDatabaseField[],
- search: string,
-): LocalDatabaseField[] => {
+): T[] => {
const term = search.trim().toLowerCase();
if (!term) return fields;
diff --git a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts
index 2254097464a..b2780bb2cb6 100644
--- a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts
+++ b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts
@@ -5,6 +5,9 @@ import { useLocalDatabaseInspector } from './useLocalDatabaseInspector';
const mocks = vi.hoisted(() => ({
entriesByPrefix: vi.fn(),
+ get: vi.fn(),
+ keyGroupsByPrefix: vi.fn(),
+ keysByPrefix: vi.fn(),
listCollections: vi.fn(),
}));
@@ -12,6 +15,9 @@ vi.mock('@/libs/localDatabase', () => ({
localDatabase: mocks,
}));
+const TOPIC_KEY = 'replica:topicList:v1:user-a:agent_1';
+const AGENT_KEY = 'replica:agentDetail:v1:user-a:agent_1';
+
describe('useLocalDatabaseInspector', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -19,47 +25,103 @@ describe('useLocalDatabaseInspector', () => {
{ entryCount: 2, name: 'query-projections' },
{ entryCount: 1, name: 'swr-cache' },
]);
- mocks.entriesByPrefix.mockImplementation(async (collection: string) =>
+ mocks.keyGroupsByPrefix.mockImplementation(async (collection: string) =>
collection === 'query-projections'
? [
- { key: 'agent::1', value: { id: '1' } },
- { key: 'topic::2', value: { id: '2' } },
+ { entryCount: 1, name: 'agentDetail' },
+ { entryCount: 1, name: 'topicList' },
]
- : [{ key: 'message:list', value: { data: [] } }],
+ : [],
);
+ mocks.keysByPrefix.mockImplementation(async (collection: string, prefix: string) => {
+ if (collection !== 'query-projections') return { keys: ['message:list'], total: 1 };
+ const keys = [AGENT_KEY, TOPIC_KEY].filter((key) => key.startsWith(prefix));
+ return { keys, total: keys.length };
+ });
+ mocks.get.mockResolvedValue({ data: { id: 'agent_1' }, updatedAt: 0 });
});
- it('discovers collections and opens the first collection as a readable snapshot', async () => {
+ it('opens the first collection with one bounded key query and reads no values', async () => {
const { result } = renderHook(() => useLocalDatabaseInspector());
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.selectedCollection).toBe('query-projections');
- expect(result.current.entries).toHaveLength(2);
- expect(mocks.entriesByPrefix).toHaveBeenCalledWith('query-projections', '');
+ expect(result.current.keys).toEqual([AGENT_KEY, TOPIC_KEY]);
+ expect(result.current.matchingCount).toBe(2);
+ expect(result.current.resources.map(({ name }) => name)).toEqual(['agentDetail', 'topicList']);
+ expect(mocks.keysByPrefix).toHaveBeenCalledExactlyOnceWith('query-projections', '', {
+ limit: 300,
+ search: '',
+ });
+ expect(mocks.entriesByPrefix).not.toHaveBeenCalled();
+ expect(mocks.get).not.toHaveBeenCalled();
+ expect(result.current.selectedKey).toBeNull();
+ });
+
+ it('loads a single value only for the selected row', async () => {
+ const { result } = renderHook(() => useLocalDatabaseInspector());
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ await act(() => result.current.selectKey(AGENT_KEY));
+
+ expect(mocks.get).toHaveBeenCalledExactlyOnceWith('query-projections', AGENT_KEY);
+ expect(result.current.selectedEntry).toEqual({
+ key: AGENT_KEY,
+ value: { data: { id: 'agent_1' }, updatedAt: 0 },
+ });
+ expect(mocks.entriesByPrefix).not.toHaveBeenCalled();
+ });
+
+ it('pushes resource and search filters down to the key query', async () => {
+ const { result } = renderHook(() => useLocalDatabaseInspector());
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ await act(() => result.current.selectKey(AGENT_KEY));
+ await act(() => result.current.selectResource('topicList'));
+
+ expect(result.current.selectedResource).toBe('topicList');
+ expect(result.current.keys).toEqual([TOPIC_KEY]);
+ expect(result.current.selectedKey).toBeNull();
+ expect(result.current.selectedEntry).toBeNull();
+ expect(mocks.keysByPrefix).toHaveBeenLastCalledWith('query-projections', 'replica:topicList:', {
+ limit: 300,
+ search: '',
+ });
+
+ await act(() => result.current.setSearch('agent_1'));
+
+ expect(result.current.search).toBe('agent_1');
+ expect(mocks.keysByPrefix).toHaveBeenLastCalledWith('query-projections', 'replica:topicList:', {
+ limit: 300,
+ search: 'agent_1',
+ });
});
- it('switches collections and preserves the selected collection when refreshed', async () => {
+ it('switches collections and preserves the selection when refreshed', async () => {
const { result } = renderHook(() => useLocalDatabaseInspector());
await waitFor(() => expect(result.current.isLoading).toBe(false));
await act(() => result.current.selectCollection('swr-cache'));
expect(result.current.selectedCollection).toBe('swr-cache');
- expect(result.current.entries).toEqual([{ key: 'message:list', value: { data: [] } }]);
+ expect(result.current.keys).toEqual(['message:list']);
+ await act(() => result.current.selectKey('message:list'));
mocks.listCollections.mockResolvedValue([
{ entryCount: 2, name: 'query-projections' },
{ entryCount: 2, name: 'swr-cache' },
]);
- mocks.entriesByPrefix.mockResolvedValueOnce([
- { key: 'message:list', value: { data: [] } },
- { key: 'topic:list', value: { data: ['topic-1'] } },
- ]);
+ mocks.keysByPrefix.mockResolvedValueOnce({ keys: ['message:list', 'topic:list'], total: 2 });
+ mocks.get.mockResolvedValueOnce({ data: ['fresh'] });
await act(() => result.current.refresh());
expect(result.current.selectedCollection).toBe('swr-cache');
- expect(result.current.entries).toHaveLength(2);
+ expect(result.current.keys).toHaveLength(2);
expect(result.current.collections[1].entryCount).toBe(2);
+ expect(result.current.selectedEntry).toEqual({
+ key: 'message:list',
+ value: { data: ['fresh'] },
+ });
});
});
diff --git a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts
index 6ff96917cd4..6555498f285 100644
--- a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts
+++ b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts
@@ -4,22 +4,54 @@ import {
localDatabase,
type LocalDatabaseCollectionInfo,
type LocalDatabaseEntry,
+ type LocalDatabaseKeyGroup,
+ type LocalDatabaseKeyPage,
} from '@/libs/localDatabase';
+import {
+ MAX_RENDERED_ROWS,
+ REPLICA_KEY_DELIMITER,
+ REPLICA_KEY_PREFIX,
+ replicaResourcePrefix,
+} from './model';
+
+interface InspectorQuery {
+ collection: string | null;
+ resource: string | null;
+ search: string;
+}
+
interface LocalDatabaseInspectorState {
collections: LocalDatabaseCollectionInfo[];
- entries: LocalDatabaseEntry[];
error: string | null;
isLoading: boolean;
+ isRecordLoading: boolean;
+ keys: string[];
+ matchingCount: number;
+ resources: LocalDatabaseKeyGroup[];
+ search: string;
selectedCollection: string | null;
+ selectedEntry: LocalDatabaseEntry | null;
+ selectedKey: string | null;
+ selectedResource: string | null;
}
+const INITIAL_QUERY: InspectorQuery = { collection: null, resource: null, search: '' };
+const EMPTY_PAGE: LocalDatabaseKeyPage = { keys: [], total: 0 };
+
const INITIAL_STATE: LocalDatabaseInspectorState = {
collections: [],
- entries: [],
error: null,
isLoading: true,
+ isRecordLoading: false,
+ keys: [],
+ matchingCount: 0,
+ resources: [],
+ search: '',
selectedCollection: null,
+ selectedEntry: null,
+ selectedKey: null,
+ selectedResource: null,
};
const errorMessage = (error: unknown): string =>
@@ -27,61 +59,148 @@ const errorMessage = (error: unknown): string =>
export const useLocalDatabaseInspector = () => {
const [state, setState] = useState<LocalDatabaseInspectorState>(INITIAL_STATE);
+ const queryRef = useRef(INITIAL_QUERY);
+ const selectedKeyRef = useRef<string | null>(null);
const requestIdRef = useRef(0);
+ const recordRequestIdRef = useRef(0);
- const loadSnapshot = useCallback(async (preferredCollection: string | null) => {
+ const loadKeys = useCallback(async (query: InspectorQuery, reloadCollections: boolean) => {
const requestId = ++requestIdRef.current;
- setState((current) => ({ ...current, error: null, isLoading: true }));
+ const previous = queryRef.current;
+ const sameTable =
+ previous.collection === query.collection && previous.resource === query.resource;
+ queryRef.current = query;
+
+ if (!sameTable) {
+ recordRequestIdRef.current += 1;
+ selectedKeyRef.current = null;
+ }
+
+ setState((current) => ({
+ ...current,
+ error: null,
+ isLoading: true,
+ search: query.search,
+ selectedCollection: query.collection,
+ selectedResource: query.resource,
+ ...(!sameTable && {
+ isRecordLoading: false,
+ keys: [],
+ selectedEntry: null,
+ selectedKey: null,
+ }),
+ }));
try {
- const collections = await localDatabase.listCollections();
- const selectedCollection =
- collections.find(({ name }) => name === preferredCollection)?.name ??
- collections.at(0)?.name ??
- null;
- const entries = selectedCollection
- ? await localDatabase.entriesByPrefix(selectedCollection, '')
- : [];
+ let { collection, resource } = query;
+ let collections: LocalDatabaseCollectionInfo[] | undefined;
+
+ if (reloadCollections) {
+ collections = await localDatabase.listCollections();
+ collection =
+ collections.find(({ name }) => name === collection)?.name ??
+ collections.at(0)?.name ??
+ null;
+ }
+
+ let resources: LocalDatabaseKeyGroup[] = [];
+ let page = EMPTY_PAGE;
+
+ if (collection) {
+ resources = await localDatabase.keyGroupsByPrefix(
+ collection,
+ REPLICA_KEY_PREFIX,
+ REPLICA_KEY_DELIMITER,
+ );
+ if (!resources.some(({ name }) => name === resource)) resource = null;
+
+ page = await localDatabase.keysByPrefix(
+ collection,
+ resource ? replicaResourcePrefix(resource) : '',
+ { limit: MAX_RENDERED_ROWS, search: query.search },
+ );
+ }
if (requestId !== requestIdRef.current) return;
- setState({ collections, entries, error: null, isLoading: false, selectedCollection });
+ queryRef.current = { collection, resource, search: query.search };
+ setState((current) => ({
+ ...current,
+ collections: collections ?? current.collections,
+ isLoading: false,
+ keys: page.keys,
+ matchingCount: page.total,
+ resources,
+ selectedCollection: collection,
+ selectedResource: resource,
+ }));
} catch (error) {
if (requestId !== requestIdRef.current) return;
setState((current) => ({ ...current, error: errorMessage(error), isLoading: false }));
}
}, []);
- const selectCollection = useCallback(async (selectedCollection: string) => {
- const requestId = ++requestIdRef.current;
+ const selectKey = useCallback(async (key: string) => {
+ const { collection } = queryRef.current;
+ if (!collection) return;
+
+ const requestId = ++recordRequestIdRef.current;
+ selectedKeyRef.current = key;
setState((current) => ({
...current,
- entries: [],
- error: null,
- isLoading: true,
- selectedCollection,
+ isRecordLoading: true,
+ selectedEntry: current.selectedKey === key ? current.selectedEntry : null,
+ selectedKey: key,
}));
try {
- const entries = await localDatabase.entriesByPrefix(selectedCollection, '');
- if (requestId !== requestIdRef.current) return;
- setState((current) => ({ ...current, entries, isLoading: false }));
+ const value = await localDatabase.get(collection, key);
+ if (requestId !== recordRequestIdRef.current) return;
+ setState((current) => ({
+ ...current,
+ isRecordLoading: false,
+ selectedEntry: value === undefined ? null : { key, value },
+ }));
} catch (error) {
- if (requestId !== requestIdRef.current) return;
- setState((current) => ({ ...current, error: errorMessage(error), isLoading: false }));
+ if (requestId !== recordRequestIdRef.current) return;
+ setState((current) => ({
+ ...current,
+ error: errorMessage(error),
+ isRecordLoading: false,
+ }));
}
}, []);
useEffect(() => {
- void loadSnapshot(null);
+ void loadKeys(INITIAL_QUERY, true);
return () => {
requestIdRef.current += 1;
+ recordRequestIdRef.current += 1;
};
- }, [loadSnapshot]);
+ }, [loadKeys]);
+
+ const selectCollection = useCallback(
+ (collection: string) => loadKeys({ collection, resource: null, search: '' }, false),
+ [loadKeys],
+ );
- const refresh = useCallback(
- () => loadSnapshot(state.selectedCollection),
- [loadSnapshot, state.selectedCollection],
+ const selectResource = useCallback(
+ (resource: string | null) =>
+ loadKeys({ collection: queryRef.current.collection, resource, search: '' }, false),
+ [loadKeys],
);
- return { ...state, refresh, selectCollection };
+ const setSearch = useCallback(
+ (search: string) => loadKeys({ ...queryRef.current, search }, false),
+ [loadKeys],
+ );
+
+ const refresh = useCallback(async () => {
+ const selectedKey = selectedKeyRef.current;
+ await Promise.all([
+ loadKeys(queryRef.current, true),
+ selectedKey === null ? undefined : selectKey(selectedKey),
+ ]);
+ }, [loadKeys, selectKey]);
+
+ return { ...state, refresh, selectCollection, selectKey, selectResource, setSearch };
};
diff --git a/src/libs/localDatabase/electronAdapter.test.ts b/src/libs/localDatabase/electronAdapter.test.ts
index 9607913a0c5..62bef5d38de 100644
--- a/src/libs/localDatabase/electronAdapter.test.ts
+++ b/src/libs/localDatabase/electronAdapter.test.ts
@@ -15,6 +15,8 @@ const mocks = vi.hoisted(() => ({
entriesByPrefix: vi.fn(),
get: vi.fn(),
initialize: vi.fn(),
+ keyGroupsByPrefix: vi.fn(),
+ keysByPrefix: vi.fn(),
listCollections: vi.fn(),
set: vi.fn(),
}));
@@ -79,6 +81,33 @@ describe('createElectronLocalDatabaseAdapter', () => {
await expect(adapter.get('cache', 'item')).resolves.toEqual(value);
});
+ it('forwards key-only queries without deserializing any value', async () => {
+ const adapter = createElectronLocalDatabaseAdapter();
+ mocks.keysByPrefix.mockResolvedValue({ keys: ['scope::1'], total: 5 });
+ mocks.keyGroupsByPrefix.mockResolvedValue([{ entryCount: 5, name: 'scope' }]);
+
+ await expect(
+ adapter.keysByPrefix('cache', 'scope::', { limit: 1, search: 'x' }),
+ ).resolves.toEqual({ keys: ['scope::1'], total: 5 });
+ await expect(adapter.keyGroupsByPrefix('cache', '', '::')).resolves.toEqual([
+ { entryCount: 5, name: 'scope' },
+ ]);
+
+ expect(mocks.keysByPrefix).toHaveBeenCalledWith({
+ collection: 'cache',
+ limit: 1,
+ prefix: 'scope::',
+ search: 'x',
+ });
+ expect(mocks.keyGroupsByPrefix).toHaveBeenCalledWith({
+ collection: 'cache',
+ delimiter: '::',
+ prefix: '',
+ });
+ expect(mocks.entriesByPrefix).not.toHaveBeenCalled();
+ expect(mocks.get).not.toHaveBeenCalled();
+ });
+
it('supports prefix queries and atomic batch payloads through IPC', async () => {
const adapter = createElectronLocalDatabaseAdapter();
diff --git a/src/libs/localDatabase/electronAdapter.ts b/src/libs/localDatabase/electronAdapter.ts
index 60d141197b3..a0dc7bc1c71 100644
--- a/src/libs/localDatabase/electronAdapter.ts
+++ b/src/libs/localDatabase/electronAdapter.ts
@@ -39,6 +39,10 @@ export const createElectronLocalDatabaseAdapter = (): LocalDatabaseAdapter => ({
initialize: async () => {
await ensureElectronIpc().localDatabase.initialize();
},
+ keyGroupsByPrefix: async (collection, prefix, delimiter) =>
+ ensureElectronIpc().localDatabase.keyGroupsByPrefix({ collection, delimiter, prefix }),
+ keysByPrefix: async (collection, prefix, query) =>
+ ensureElectronIpc().localDatabase.keysByPrefix({ collection, prefix, ...query }),
listCollections: async () => ensureElectronIpc().localDatabase.listCollections(),
set: async (collection, key, value) => {
await ensureElectronIpc().localDatabase.set({
diff --git a/src/libs/localDatabase/index.test.ts b/src/libs/localDatabase/index.test.ts
index 8da6e8f093f..856820796a2 100644
--- a/src/libs/localDatabase/index.test.ts
+++ b/src/libs/localDatabase/index.test.ts
@@ -40,6 +40,28 @@ describe('localDatabase', () => {
]);
});
+ it('lists, searches and groups keys within one collection', async () => {
+ await localDatabase.batch([
+ { collection, key: 'replica:topicList:v1:user:Agent_1', type: 'set', value: 1 },
+ { collection, key: 'replica:topicList:v1:user:agent_2', type: 'set', value: 2 },
+ { collection, key: 'replica:agentDetail:v1:user:agent_1', type: 'set', value: 3 },
+ { collection, key: 'plain', type: 'set', value: 4 },
+ { collection: otherCollection, key: 'replica:topicList:v1:x', type: 'set', value: 5 },
+ ]);
+
+ await expect(localDatabase.keysByPrefix(collection, '', { limit: 2 })).resolves.toEqual({
+ keys: ['plain', 'replica:agentDetail:v1:user:agent_1'],
+ total: 4,
+ });
+ await expect(
+ localDatabase.keysByPrefix(collection, 'replica:topicList:', { search: 'AGENT_1' }),
+ ).resolves.toEqual({ keys: ['replica:topicList:v1:user:Agent_1'], total: 1 });
+ await expect(localDatabase.keyGroupsByPrefix(collection, 'replica:', ':')).resolves.toEqual([
+ { entryCount: 1, name: 'agentDetail' },
+ { entryCount: 2, name: 'topicList' },
+ ]);
+ });
+
it('discovers populated collections with current entry counts', async () => {
await localDatabase.batch([
{ collection, key: 'first', type: 'set', value: 1 },
@@ -74,6 +96,8 @@ describe('localDatabase', () => {
entriesByPrefix: vi.fn().mockResolvedValue([]),
get: vi.fn().mockResolvedValue({ source: 'electron' }),
initialize: vi.fn().mockResolvedValue(undefined),
+ keyGroupsByPrefix: vi.fn().mockResolvedValue([]),
+ keysByPrefix: vi.fn().mockResolvedValue({ keys: [], total: 0 }),
listCollections: vi.fn().mockResolvedValue([{ entryCount: 1, name: 'runtime' }]),
set: vi.fn().mockResolvedValue(undefined),
};
diff --git a/src/libs/localDatabase/index.ts b/src/libs/localDatabase/index.ts
index 931a2b8eb4f..8ee71fa25ae 100644
--- a/src/libs/localDatabase/index.ts
+++ b/src/libs/localDatabase/index.ts
@@ -1,11 +1,18 @@
import { createIndexedDBLocalDatabaseAdapter } from './indexedDBAdapter';
-import type { LocalDatabaseAdapter, LocalDatabaseBatchOperation } from './types';
+import type {
+ LocalDatabaseAdapter,
+ LocalDatabaseBatchOperation,
+ LocalDatabaseKeyQuery,
+} from './types';
export type {
LocalDatabaseAdapter,
LocalDatabaseBatchOperation,
LocalDatabaseCollectionInfo,
LocalDatabaseEntry,
+ LocalDatabaseKeyGroup,
+ LocalDatabaseKeyPage,
+ LocalDatabaseKeyQuery,
} from './types';
let activeAdapter: LocalDatabaseAdapter = createIndexedDBLocalDatabaseAdapter();
@@ -35,6 +42,10 @@ export const localDatabase = {
get: <T>(collection: string, key: string): Promise<T | undefined> =>
activeAdapter.get<T>(collection, key),
initialize: (): Promise<void> => activeAdapter.initialize(),
+ keyGroupsByPrefix: (collection: string, prefix: string, delimiter: string) =>
+ activeAdapter.keyGroupsByPrefix(collection, prefix, delimiter),
+ keysByPrefix: (collection: string, prefix: string, query?: LocalDatabaseKeyQuery) =>
+ activeAdapter.keysByPrefix(collection, prefix, query),
listCollections: () => activeAdapter.listCollections(),
set: (collection: string, key: string, value: unknown): Promise<void> =>
activeAdapter.set(collection, key, value),
diff --git a/src/libs/localDatabase/indexedDBAdapter.ts b/src/libs/localDatabase/indexedDBAdapter.ts
index 850d8e7e3a6..af79b5e84e9 100644
--- a/src/libs/localDatabase/indexedDBAdapter.ts
+++ b/src/libs/localDatabase/indexedDBAdapter.ts
@@ -11,6 +11,9 @@ import type {
LocalDatabaseBatchOperation,
LocalDatabaseCollectionInfo,
LocalDatabaseEntry,
+ LocalDatabaseKeyGroup,
+ LocalDatabaseKeyPage,
+ LocalDatabaseKeyQuery,
} from './types';
interface IndexedDBRecord {
@@ -122,6 +125,15 @@ export const createIndexedDBLocalDatabaseAdapter = (): LocalDatabaseAdapter => {
return result;
};
+ const keysInRange = async (collection: string, prefix: string): Promise<string[]> => {
+ const storageKeys = await runTransaction<IDBValidKey[]>('readonly', (store) =>
+ store.getAllKeys(storageRange(collection, prefix)),
+ );
+ const keyOffset = collectionPrefix(collection).length;
+
+ return storageKeys.map((storageKey) => String(storageKey).slice(keyOffset));
+ };
+
return {
batch: async (operations: LocalDatabaseBatchOperation[]): Promise<void> => {
if (operations.length === 0) return;
@@ -180,6 +192,39 @@ export const createIndexedDBLocalDatabaseAdapter = (): LocalDatabaseAdapter => {
await getDatabase();
},
+ keyGroupsByPrefix: async (
+ collection: string,
+ prefix: string,
+ delimiter: string,
+ ): Promise<LocalDatabaseKeyGroup[]> => {
+ const counts = new Map<string, number>();
+
+ for (const key of await keysInRange(collection, prefix)) {
+ const delimiterIndex = key.indexOf(delimiter, prefix.length);
+ if (delimiterIndex < 0) continue;
+
+ const name = key.slice(prefix.length, delimiterIndex);
+ counts.set(name, (counts.get(name) ?? 0) + 1);
+ }
+
+ return [...counts.entries()]
+ .map(([name, entryCount]) => ({ entryCount, name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ },
+
+ keysByPrefix: async (
+ collection: string,
+ prefix: string,
+ { limit, search }: LocalDatabaseKeyQuery = {},
+ ): Promise<LocalDatabaseKeyPage> => {
+ const term = search?.trim().toLowerCase();
+ const keys = (await keysInRange(collection, prefix)).filter(
+ (key) => !term || key.toLowerCase().includes(term),
+ );
+
+ return { keys: limit === undefined ? keys : keys.slice(0, limit), total: keys.length };
+ },
+
listCollections: async (): Promise<LocalDatabaseCollectionInfo[]> => {
const keys = await runTransaction<IDBValidKey[]>('readonly', (store) => store.getAllKeys());
const counts = new Map<string, number>();
diff --git a/src/libs/localDatabase/types.ts b/src/libs/localDatabase/types.ts
index 0d5debfab10..ec08dcdd037 100644
--- a/src/libs/localDatabase/types.ts
+++ b/src/libs/localDatabase/types.ts
@@ -8,6 +8,21 @@ export interface LocalDatabaseCollectionInfo {
name: string;
}
+export interface LocalDatabaseKeyQuery {
+ limit?: number;
+ search?: string;
+}
+
+export interface LocalDatabaseKeyPage {
+ keys: string[];
+ total: number;
+}
+
+export interface LocalDatabaseKeyGroup {
+ entryCount: number;
+ name: string;
+}
+
export type LocalDatabaseBatchOperation =
| {
collection: string;
@@ -34,6 +49,16 @@ export interface LocalDatabaseAdapter {
entriesByPrefix: <T>(collection: string, prefix: string) => Promise<LocalDatabaseEntry<T>[]>;
get: <T>(collection: string, key: string) => Promise<T | undefined>;
initialize: () => Promise<void>;
+ keyGroupsByPrefix: (
+ collection: string,
+ prefix: string,
+ delimiter: string,
+ ) => Promise<LocalDatabaseKeyGroup[]>;
+ keysByPrefix: (
+ collection: string,
+ prefix: string,
+ query?: LocalDatabaseKeyQuery,
+ ) => Promise<LocalDatabaseKeyPage>;
listCollections: () => Promise<LocalDatabaseCollectionInfo[]>;
set: (collection: string, key: string, value: unknown) => Promise<void>;
}