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.

✨ feat(devdock): add Local Database and Replica inspectors, fix empty project list skeleton (#21015)

Inneia0e8addfac58
diff --git a/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts b/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts
index ddd8a682d30..19884b10540 100644
--- a/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalDatabaseCtr.ts
@@ -1,5 +1,6 @@
import type {
DesktopLocalDatabaseBatchOperation,
+ DesktopLocalDatabaseCollectionInfo,
DesktopLocalDatabaseEntry,
DesktopLocalDatabaseKey,
DesktopLocalDatabasePrefix,
@@ -50,6 +51,11 @@ export default class LocalDatabaseController extends ControllerModule {
return this.service.get(collection, key);
}
+ @IpcMethod()
+ async listCollections(): Promise<DesktopLocalDatabaseCollectionInfo[]> {
+ return this.service.listCollections();
+ }
+
@IpcMethod()
async set({ collection, key, value }: DesktopLocalDatabaseSet): Promise<void> {
await this.service.set(collection, key, value);
diff --git a/apps/desktop/src/main/services/LocalDatabaseSrv.ts b/apps/desktop/src/main/services/LocalDatabaseSrv.ts
index 4e1306c1fcb..bfa584e083e 100644
--- a/apps/desktop/src/main/services/LocalDatabaseSrv.ts
+++ b/apps/desktop/src/main/services/LocalDatabaseSrv.ts
@@ -2,6 +2,7 @@ import path from 'node:path';
import type {
DesktopLocalDatabaseBatchOperation,
+ DesktopLocalDatabaseCollectionInfo,
DesktopLocalDatabaseEntry,
} from '@lobechat/electron-client-ipc';
import { and, asc, eq, gte, lt } from 'drizzle-orm';
@@ -18,6 +19,19 @@ const PREFIX_UPPER_BOUND = '\u{10FFFF}';
const collectionPrefix = (collection: string) => `${collection.length}:${collection}`;
const storageKey = (collection: string, key: string) => `${collectionPrefix(collection)}${key}`;
+const collectionFromStorageKey = (key: string): string | undefined => {
+ const separatorIndex = key.indexOf(':');
+ if (separatorIndex < 1) return undefined;
+
+ const collectionLength = Number(key.slice(0, separatorIndex));
+ if (!Number.isSafeInteger(collectionLength) || collectionLength < 0) return undefined;
+
+ const collectionStart = separatorIndex + 1;
+ const collectionEnd = collectionStart + collectionLength;
+ if (collectionEnd > key.length) return undefined;
+
+ return key.slice(collectionStart, collectionEnd);
+};
const prefixRange = (collection: string, prefix: string) => {
const lowerBound = storageKey(collection, prefix);
return { lowerBound, upperBound: `${lowerBound}${PREFIX_UPPER_BOUND}` };
@@ -90,6 +104,21 @@ export default class LocalDatabaseService extends ServiceModule {
return row?.value;
}
+ async listCollections(): Promise<DesktopLocalDatabaseCollectionInfo[]> {
+ const rows = await this.getRuntime().db.select({ id: localRecords.id }).from(localRecords);
+ const counts = new Map<string, number>();
+
+ for (const { id } of rows) {
+ const collection = collectionFromStorageKey(id);
+ if (collection === undefined) continue;
+ counts.set(collection, (counts.get(collection) ?? 0) + 1);
+ }
+
+ return [...counts.entries()]
+ .map(([name, entryCount]) => ({ entryCount, name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ }
+
async set(collection: string, key: string, value: string): Promise<void> {
await this.getRuntime()
.db.insert(localRecords)
diff --git a/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts b/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts
index 20e711547b1..018de33ae00 100644
--- a/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/LocalDatabaseSrv.test.ts
@@ -28,6 +28,11 @@ describe('LocalDatabaseService', () => {
await service.set('first', 'scope-b::1', 'first-3');
await service.set('second', 'scope-a::1', 'second-1');
+ await expect(service.listCollections()).resolves.toEqual([
+ { entryCount: 3, name: 'first' },
+ { entryCount: 1, name: 'second' },
+ ]);
+
await expect(service.entriesByPrefix('first', 'scope-a::')).resolves.toEqual([
{ key: 'scope-a::1', value: 'first-1' },
{ key: 'scope-a::2', value: 'first-2' },
@@ -39,6 +44,10 @@ describe('LocalDatabaseService', () => {
{ key: 'scope-b::1', value: 'first-3' },
]);
await expect(service.get('second', 'scope-a::1')).resolves.toBe('second-1');
+ await expect(service.listCollections()).resolves.toEqual([
+ { entryCount: 1, name: 'first' },
+ { entryCount: 1, name: 'second' },
+ ]);
});
it('preserves keys when collection names contain key-like delimiters', async () => {
diff --git a/packages/electron-client-ipc/src/types/localDatabase.ts b/packages/electron-client-ipc/src/types/localDatabase.ts
index 7c186e0dcc1..04f0f2a4102 100644
--- a/packages/electron-client-ipc/src/types/localDatabase.ts
+++ b/packages/electron-client-ipc/src/types/localDatabase.ts
@@ -13,6 +13,11 @@ export interface DesktopLocalDatabaseEntry {
value: string;
}
+export interface DesktopLocalDatabaseCollectionInfo {
+ entryCount: number;
+ name: string;
+}
+
export interface DesktopLocalDatabaseSet extends DesktopLocalDatabaseKey {
value: string;
}
diff --git a/src/features/DevDock/registerBuiltinItems.ts b/src/features/DevDock/registerBuiltinItems.ts
index fb4753f1862..cfe4c734c5e 100644
--- a/src/features/DevDock/registerBuiltinItems.ts
+++ b/src/features/DevDock/registerBuiltinItems.ts
@@ -4,11 +4,13 @@ import {
ArrowUpDown,
Bot,
Cpu,
+ Database,
Flag,
Gauge,
Gpu,
GraduationCap,
Languages,
+ Layers3,
LayoutGrid,
MemoryStick,
RotateCw,
@@ -59,6 +61,22 @@ export const registerBuiltinDevDockItems = () => {
load: () => import('@/features/DevPanel/RenderGallery'),
type: 'panel',
},
+ {
+ defaultPinned: true,
+ icon: Database,
+ id: 'local-database',
+ label: 'Local Database',
+ load: () => import('@/features/DevPanel/LocalDatabase'),
+ type: 'panel',
+ },
+ {
+ defaultPinned: true,
+ icon: Layers3,
+ id: 'replica',
+ label: 'Replica',
+ load: () => import('@/features/DevPanel/Replica'),
+ type: 'panel',
+ },
{
defaultPinned: true,
icon: Route,
diff --git a/src/features/DevPanel/LocalDatabase/CollectionList.tsx b/src/features/DevPanel/LocalDatabase/CollectionList.tsx
new file mode 100644
index 00000000000..7331fbda1f4
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/CollectionList.tsx
@@ -0,0 +1,118 @@
+'use client';
+
+import { Input } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { Boxes, Table2 } from 'lucide-react';
+import { useState } from 'react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+import type { LocalDatabaseCollectionInfo } 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[];
+ selectedCollection: string | null;
+ selectedResource: string | null;
+}
+
+interface ListItemProps {
+ active: boolean;
+ count: number;
+ icon: typeof Table2;
+ indent?: boolean;
+ name: string;
+ onClick: () => void;
+}
+
+const ListItem = ({ active, count, icon: Icon, indent, name, onClick }: ListItemProps) => (
+ <button
+ aria-pressed={active}
+ title={name}
+ type={'button'}
+ className={cx(
+ styles.listItem,
+ indent && styles.listItemNested,
+ active && styles.listItemActive,
+ )}
+ onClick={onClick}
+ >
+ <Icon className={styles.listIcon} size={14} />
+ <span className={styles.listName}>{name}</span>
+ <span className={styles.listCount}>{count}</span>
+ </button>
+);
+
+const CollectionList = ({
+ collections,
+ onSelectCollection,
+ onSelectResource,
+ resources,
+ selectedCollection,
+ selectedResource,
+}: CollectionListProps) => {
+ const [search, setSearch] = useState('');
+ const term = search.trim().toLowerCase();
+ const visibleCollections = term
+ ? collections.filter(({ name }) => name.toLowerCase().includes(term))
+ : collections;
+
+ return (
+ <aside
+ aria-label={'Database collections'}
+ className={cx(styles.sidePane, devDockPanelStyles.paneDividerEnd)}
+ >
+ <div className={devDockPanelStyles.paneHeader}>Collections</div>
+ <div className={devDockPanelStyles.paneSearch}>
+ <Input
+ allowClear
+ className={devDockPanelStyles.searchInput}
+ placeholder={'Search collections…'}
+ size={'small'}
+ value={search}
+ variant={'borderless'}
+ onChange={(event) => setSearch(event.target.value)}
+ />
+ </div>
+ <div className={styles.list}>
+ {visibleCollections.length === 0 ? (
+ <div className={styles.empty}>{search ? 'No collections match.' : 'No collections.'}</div>
+ ) : (
+ visibleCollections.map(({ entryCount, name }) => {
+ const active = name === selectedCollection;
+
+ return (
+ <div key={name}>
+ <ListItem
+ active={active && !selectedResource}
+ count={entryCount}
+ icon={Table2}
+ name={name}
+ onClick={() => (active ? onSelectResource(null) : onSelectCollection(name))}
+ />
+ {active &&
+ resources.map((resource) => (
+ <ListItem
+ indent
+ active={resource.name === selectedResource}
+ count={resource.entryCount}
+ icon={Boxes}
+ key={resource.name}
+ name={resource.name}
+ onClick={() => onSelectResource(resource.name)}
+ />
+ ))}
+ </div>
+ );
+ })
+ )}
+ </div>
+ </aside>
+ );
+};
+
+export default CollectionList;
diff --git a/src/features/DevPanel/LocalDatabase/RecordDetails.tsx b/src/features/DevPanel/LocalDatabase/RecordDetails.tsx
new file mode 100644
index 00000000000..3deadb0d7ce
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/RecordDetails.tsx
@@ -0,0 +1,67 @@
+'use client';
+
+import { Input } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { useState } from 'react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+import { inspectorStyles as styles } from '../inspectorStyles';
+import {
+ filterLocalDatabaseFields,
+ formatLocalDatabaseFieldValue,
+ type LocalDatabaseTableRow,
+} from './model';
+
+interface RecordDetailsProps {
+ row: LocalDatabaseTableRow | undefined;
+}
+
+const RecordDetails = ({ row }: RecordDetailsProps) => {
+ const [search, setSearch] = useState('');
+ const visibleFields = filterLocalDatabaseFields(row?.fields ?? [], search);
+
+ return (
+ <aside
+ aria-label={'Selected record details'}
+ className={cx(styles.detailsPane, devDockPanelStyles.paneDividerStart)}
+ >
+ <div className={devDockPanelStyles.paneHeader}>Details</div>
+ <div className={devDockPanelStyles.paneSearch}>
+ <Input
+ allowClear
+ className={devDockPanelStyles.searchInput}
+ disabled={!row}
+ placeholder={'Search fields…'}
+ size={'small'}
+ value={search}
+ variant={'borderless'}
+ 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>
+ )}
+ </aside>
+ );
+};
+
+export default RecordDetails;
diff --git a/src/features/DevPanel/LocalDatabase/RecordTable.tsx b/src/features/DevPanel/LocalDatabase/RecordTable.tsx
new file mode 100644
index 00000000000..f248a919dcb
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/RecordTable.tsx
@@ -0,0 +1,150 @@
+'use client';
+
+import { Button, Input } from '@lobehub/ui/base-ui';
+import { RefreshCw } from 'lucide-react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+import { inspectorStyles as styles } from '../inspectorStyles';
+import {
+ formatLocalDatabaseCellValue,
+ type LocalDatabaseColumn,
+ type LocalDatabaseTableRow,
+} from './model';
+
+export const MAX_RENDERED_ROWS = 300;
+
+interface RecordTableProps {
+ columns: LocalDatabaseColumn[];
+ isLoading: boolean;
+ matchingCount: number;
+ onRefresh: () => void;
+ onRowSearchChange: (value: string) => void;
+ onSelect: (key: string) => void;
+ rows: LocalDatabaseTableRow[];
+ rowSearch: string;
+ selectedKey: string | undefined;
+ title: string;
+ totalCount: number;
+}
+
+const columnWidth = ({ label }: LocalDatabaseColumn): number => {
+ if (label === 'key') return 260;
+ if (label === 'resource' || label === 'id' || label === 'query') return 200;
+ if (label === 'scope') return 160;
+ if (label === 'version') return 80;
+ if (label === 'updatedAt') return 200;
+ return 240;
+};
+
+const RecordTable = ({
+ columns,
+ isLoading,
+ matchingCount,
+ onRefresh,
+ onRowSearchChange,
+ onSelect,
+ rowSearch,
+ rows,
+ selectedKey,
+ title,
+ totalCount,
+}: RecordTableProps) => {
+ const tableWidth = columns.reduce((total, column) => total + columnWidth(column), 0);
+ const rowRange = matchingCount === 0 ? '0 rows' : `1–${rows.length} of ${matchingCount} rows`;
+
+ return (
+ <main className={styles.tablePane}>
+ <div className={devDockPanelStyles.toolbar}>
+ <span className={styles.tableName} title={title}>
+ {title}
+ </span>
+ <Input
+ allowClear
+ className={styles.toolbarSearch}
+ placeholder={'Search rows…'}
+ size={'small'}
+ style={{ flex: 1 }}
+ value={rowSearch}
+ onChange={(event) => onRowSearchChange(event.target.value)}
+ />
+ <span className={styles.toolbarMeta}>{totalCount} rows</span>
+ <span className={styles.toolbarMeta}>read-only</span>
+ <Button
+ icon={RefreshCw}
+ loading={isLoading}
+ size={'small'}
+ type={'text'}
+ onClick={onRefresh}
+ >
+ Refresh
+ </Button>
+ </div>
+ <div className={styles.tableScroll}>
+ <table
+ className={styles.table}
+ style={{ minWidth: '100%', width: Math.max(tableWidth, 640) }}
+ >
+ <colgroup>
+ {columns.map((column) => (
+ <col key={column.id} style={{ width: columnWidth(column) }} />
+ ))}
+ </colgroup>
+ <thead>
+ <tr>
+ {columns.map((column) => (
+ <th key={column.id} scope={'col'} title={column.label}>
+ {column.label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row) => {
+ const active = row.entry.key === selectedKey;
+
+ return (
+ <tr
+ aria-label={row.entry.key}
+ aria-selected={active}
+ className={active ? styles.rowActive : undefined}
+ key={row.entry.key}
+ tabIndex={0}
+ onClick={() => onSelect(row.entry.key)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onSelect(row.entry.key);
+ }
+ }}
+ >
+ {columns.map((column) => {
+ const field = row.fields.find(({ id }) => id === column.id);
+ const text = formatLocalDatabaseCellValue(field?.value);
+
+ return (
+ <td key={column.id} title={text}>
+ {text}
+ </td>
+ );
+ })}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {rows.length === 0 && (
+ <div className={styles.tableEmpty}>
+ {rowSearch ? `No rows 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>}
+ </div>
+ </main>
+ );
+};
+
+export default RecordTable;
diff --git a/src/features/DevPanel/LocalDatabase/index.tsx b/src/features/DevPanel/LocalDatabase/index.tsx
new file mode 100644
index 00000000000..82c93c766e8
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/index.tsx
@@ -0,0 +1,120 @@
+'use client';
+
+import { Button, Spin } from '@lobehub/ui/base-ui';
+import { useMemo, useState } from 'react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+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 { useLocalDatabaseInspector } from './useLocalDatabaseInspector';
+
+const EMPTY_COLUMNS: LocalDatabaseColumn[] = [
+ { id: '__key', label: 'key' },
+ { id: 'value', label: 'value' },
+];
+
+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 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);
+ };
+
+ if (error) {
+ return (
+ <div className={devDockPanelStyles.root}>
+ <div className={styles.error}>
+ <span>Could not read the local database: {error}</span>
+ <Button size={'small'} onClick={() => void refresh()}>
+ Retry
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (isLoading && collections.length === 0) {
+ return (
+ <div className={devDockPanelStyles.root}>
+ <div className={styles.empty}>
+ <Spin />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={devDockPanelStyles.root}>
+ <div className={styles.workspace}>
+ <CollectionList
+ collections={collections}
+ resources={resources}
+ selectedCollection={selectedCollection}
+ selectedResource={activeResource}
+ onSelectCollection={(name) => {
+ resetSelection();
+ setSelectedResource(null);
+ void selectCollection(name);
+ }}
+ onSelectResource={(resource) => {
+ resetSelection();
+ setSelectedResource(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}
+ onRefresh={() => void refresh()}
+ onRowSearchChange={setRowSearch}
+ onSelect={setSelectedKey}
+ />
+ <RecordDetails key={selectedCollection ?? ''} row={selectedRow} />
+ </div>
+ </div>
+ );
+};
+
+export default LocalDatabasePanel;
diff --git a/src/features/DevPanel/LocalDatabase/model.test.ts b/src/features/DevPanel/LocalDatabase/model.test.ts
new file mode 100644
index 00000000000..d73117d1141
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/model.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest';
+
+import type { LocalDatabaseEntry } from '@/libs/localDatabase';
+
+import {
+ createLocalDatabaseTableRows,
+ filterLocalDatabaseFields,
+ filterLocalDatabaseRows,
+ filterRowsByResource,
+ formatLocalDatabaseFieldValue,
+ getLocalDatabaseColumns,
+ getReplicaResourceGroups,
+ parseReplicaStorageKey,
+} from './model';
+
+const replicaKey = (resource: string, scope: string, queryKey: string, version = 1) =>
+ `replica:${resource}:v${version}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;
+
+describe('Local Database table model', () => {
+ const entries: LocalDatabaseEntry[] = [
+ {
+ key: replicaKey('topicList', 'user-a:ws-1', 'agent_1?{"sortBy":"updatedAt"}'),
+ value: { data: { items: [{ id: 't1', title: 'Storage review' }], total: 1 }, updatedAt: 0 },
+ },
+ {
+ key: replicaKey('agentDetail', 'user-a:ws-1', 'agent_1', 3),
+ value: { data: { id: 'agent_1', title: 'Alpha' }, updatedAt: 1000 },
+ },
+ ];
+
+ it('decodes replica storage keys into resource, version, scope and query', () => {
+ expect(parseReplicaStorageKey(entries[0].key)).toEqual({
+ query: 'agent_1?{"sortBy":"updatedAt"}',
+ resource: 'topicList',
+ scope: 'user-a:ws-1',
+ version: 1,
+ });
+ expect(parseReplicaStorageKey(replicaKey('a:b', 's', '__replica:index'))).toEqual({
+ query: '__replica:index',
+ resource: 'a:b',
+ scope: 's',
+ version: 1,
+ });
+ expect(parseReplicaStorageKey('swr:message:list')).toBeUndefined();
+ });
+
+ it('expands timestamped envelopes into replica columns before the data fields', () => {
+ const rows = createLocalDatabaseTableRows(entries);
+
+ expect(getLocalDatabaseColumns(rows).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),
+ );
+ });
+
+ 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' } },
+ ]);
+
+ expect(row.fields.map(({ label }) => label)).toEqual([
+ 'key',
+ 'version',
+ 'updatedAt',
+ 'data.key',
+ 'data.version',
+ ]);
+ });
+
+ 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);
+
+ expect(filterLocalDatabaseRows(rows, 'storage')).toEqual([rows[0]]);
+ expect(filterLocalDatabaseRows(rows, 'alpha')).toEqual([rows[1]]);
+ expect(filterLocalDatabaseFields(rows[0].fields, 'array').map(({ label }) => label)).toEqual([
+ 'items',
+ ]);
+ });
+
+ it('formats diagnostic values without failing on BigInt or circular references', () => {
+ const value: { count: bigint; self?: unknown } = { count: 2n };
+ value.self = value;
+
+ expect(formatLocalDatabaseFieldValue(value)).toContain('"count": "2n"');
+ expect(formatLocalDatabaseFieldValue(value)).toContain('"self": "[Circular]"');
+ });
+});
diff --git a/src/features/DevPanel/LocalDatabase/model.ts b/src/features/DevPanel/LocalDatabase/model.ts
new file mode 100644
index 00000000000..2e8df9173ce
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/model.ts
@@ -0,0 +1,245 @@
+import type { LocalDatabaseEntry } from '@/libs/localDatabase';
+
+export interface LocalDatabaseField {
+ id: string;
+ label: string;
+ type: string;
+ value: unknown;
+}
+
+export interface LocalDatabaseColumn {
+ id: string;
+ label: string;
+}
+
+export interface LocalDatabaseTableRow {
+ entry: LocalDatabaseEntry;
+ fields: LocalDatabaseField[];
+ replica?: ReplicaStorageKey;
+}
+
+export interface ReplicaStorageKey {
+ query: string;
+ resource: string;
+ scope: string;
+ version: number;
+}
+
+export interface ReplicaResourceGroup {
+ entryCount: number;
+ name: string;
+}
+
+const FIELD_PRIORITY = new Map([
+ ['key', 0],
+ ['resource', 1],
+ ['version', 2],
+ ['scope', 3],
+ ['query', 4],
+ ['updatedAt', 5],
+ ['id', 6],
+]);
+
+// encodeURIComponent escapes ':', so only the resource name can contain one.
+const REPLICA_KEY_PATTERN = /^replica:(.+):v(\d+):([^:]*):([^:]*)$/;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);
+
+const isTimestampEnvelope = (
+ value: unknown,
+): value is Record<string, unknown> & { data: unknown; updatedAt: number } =>
+ isRecord(value) && 'data' in value && typeof value.updatedAt === 'number';
+
+const decode = (value: string): string => {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+};
+
+export const parseReplicaStorageKey = (key: string): ReplicaStorageKey | undefined => {
+ const match = REPLICA_KEY_PATTERN.exec(key);
+ if (!match) return undefined;
+
+ const [, resource, version, scope, query] = match;
+ return { query: decode(query), resource, scope: decode(scope), version: Number(version) };
+};
+
+const serialize = (value: unknown, indent?: number): string => {
+ const seen = new WeakSet<object>();
+
+ try {
+ const result = JSON.stringify(
+ value,
+ (_key, item) => {
+ if (typeof item === 'bigint') return `${item}n`;
+ if (typeof item === 'object' && item !== null) {
+ if (seen.has(item)) return '[Circular]';
+ seen.add(item);
+ }
+ return item;
+ },
+ indent,
+ );
+
+ return result ?? String(value);
+ } catch (error) {
+ return `[Unable to serialize: ${error instanceof Error ? error.message : String(error)}]`;
+ }
+};
+
+export const getLocalDatabaseValueType = (value: unknown): string => {
+ if (value === null) return 'null';
+ if (Array.isArray(value)) return `array[${value.length}]`;
+ if (value instanceof Date) return 'date';
+ return typeof value;
+};
+
+export const formatLocalDatabaseCellValue = (value: unknown): string => {
+ if (value === null) return 'NULL';
+ if (value === undefined) return '—';
+ if (typeof value === 'string') return value;
+ if (value instanceof Date) return value.toISOString();
+ if (typeof value === 'object') return serialize(value);
+ return String(value);
+};
+
+export const formatLocalDatabaseFieldValue = (value: unknown): string => {
+ if (value === null) return 'NULL';
+ if (value === undefined) return '—';
+ if (typeof value === 'string') return value;
+ if (value instanceof Date) return value.toISOString();
+ return serialize(value, 2);
+};
+
+const createField = (id: string, label: string, value: unknown): LocalDatabaseField => ({
+ id,
+ label,
+ type: getLocalDatabaseValueType(value),
+ value,
+});
+
+const byPriority = <T>(items: T[], labelOf: (item: T) => string): T[] =>
+ items
+ .map((item, index) => ({ index, item }))
+ .sort(
+ (a, b) =>
+ (FIELD_PRIORITY.get(labelOf(a.item)) ?? Number.POSITIVE_INFINITY) -
+ (FIELD_PRIORITY.get(labelOf(b.item)) ?? Number.POSITIVE_INFINITY) || a.index - b.index,
+ )
+ .map(({ item }) => item);
+
+const pushValueFields = (fields: LocalDatabaseField[], prefix: string, value: unknown) => {
+ if (!isRecord(value)) {
+ fields.push(createField(prefix, prefix, value));
+ return;
+ }
+
+ for (const [name, fieldValue] of Object.entries(value)) {
+ const label = FIELD_PRIORITY.has(name) && name !== 'id' ? `${prefix}.${name}` : name;
+ fields.push(createField(`${prefix}.${name}`, label, fieldValue));
+ }
+};
+
+export const getLocalDatabaseFields = (
+ entry: LocalDatabaseEntry,
+ replica?: ReplicaStorageKey,
+): LocalDatabaseField[] => {
+ const fields = [createField('__key', 'key', entry.key)];
+
+ if (replica) {
+ fields.push(
+ createField('__replica.resource', 'resource', replica.resource),
+ createField('__replica.version', 'version', replica.version),
+ createField('__replica.scope', 'scope', replica.scope),
+ createField('__replica.query', 'query', replica.query),
+ );
+ }
+
+ const { value } = entry;
+
+ if (isTimestampEnvelope(value)) {
+ fields.push(createField('__updatedAt', 'updatedAt', new Date(value.updatedAt)));
+ pushValueFields(fields, 'data', value.data);
+ for (const [name, fieldValue] of Object.entries(value)) {
+ if (name === 'data' || name === 'updatedAt') continue;
+ fields.push(createField(`envelope.${name}`, name, fieldValue));
+ }
+ } else {
+ pushValueFields(fields, 'value', value);
+ }
+
+ 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 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>();
+
+ for (const row of rows) {
+ for (const field of row.fields) {
+ if (!columns.has(field.id)) columns.set(field.id, { id: field.id, label: field.label });
+ }
+ }
+
+ return byPriority([...columns.values()], (column) => column.label);
+};
+
+export const filterLocalDatabaseRows = (
+ rows: LocalDatabaseTableRow[],
+ 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[] => {
+ const term = search.trim().toLowerCase();
+ if (!term) return fields;
+
+ return fields.filter(
+ ({ label, type, value }) =>
+ label.toLowerCase().includes(term) ||
+ type.toLowerCase().includes(term) ||
+ formatLocalDatabaseCellValue(value).toLowerCase().includes(term),
+ );
+};
diff --git a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts
new file mode 100644
index 00000000000..2254097464a
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.test.ts
@@ -0,0 +1,65 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useLocalDatabaseInspector } from './useLocalDatabaseInspector';
+
+const mocks = vi.hoisted(() => ({
+ entriesByPrefix: vi.fn(),
+ listCollections: vi.fn(),
+}));
+
+vi.mock('@/libs/localDatabase', () => ({
+ localDatabase: mocks,
+}));
+
+describe('useLocalDatabaseInspector', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listCollections.mockResolvedValue([
+ { entryCount: 2, name: 'query-projections' },
+ { entryCount: 1, name: 'swr-cache' },
+ ]);
+ mocks.entriesByPrefix.mockImplementation(async (collection: string) =>
+ collection === 'query-projections'
+ ? [
+ { key: 'agent::1', value: { id: '1' } },
+ { key: 'topic::2', value: { id: '2' } },
+ ]
+ : [{ key: 'message:list', value: { data: [] } }],
+ );
+ });
+
+ it('discovers collections and opens the first collection as a readable snapshot', 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', '');
+ });
+
+ it('switches collections and preserves the selected collection 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: [] } }]);
+
+ 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'] } },
+ ]);
+
+ await act(() => result.current.refresh());
+
+ expect(result.current.selectedCollection).toBe('swr-cache');
+ expect(result.current.entries).toHaveLength(2);
+ expect(result.current.collections[1].entryCount).toBe(2);
+ });
+});
diff --git a/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts
new file mode 100644
index 00000000000..6ff96917cd4
--- /dev/null
+++ b/src/features/DevPanel/LocalDatabase/useLocalDatabaseInspector.ts
@@ -0,0 +1,87 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import {
+ localDatabase,
+ type LocalDatabaseCollectionInfo,
+ type LocalDatabaseEntry,
+} from '@/libs/localDatabase';
+
+interface LocalDatabaseInspectorState {
+ collections: LocalDatabaseCollectionInfo[];
+ entries: LocalDatabaseEntry[];
+ error: string | null;
+ isLoading: boolean;
+ selectedCollection: string | null;
+}
+
+const INITIAL_STATE: LocalDatabaseInspectorState = {
+ collections: [],
+ entries: [],
+ error: null,
+ isLoading: true,
+ selectedCollection: null,
+};
+
+const errorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error);
+
+export const useLocalDatabaseInspector = () => {
+ const [state, setState] = useState<LocalDatabaseInspectorState>(INITIAL_STATE);
+ const requestIdRef = useRef(0);
+
+ const loadSnapshot = useCallback(async (preferredCollection: string | null) => {
+ const requestId = ++requestIdRef.current;
+ setState((current) => ({ ...current, error: null, isLoading: true }));
+
+ 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, '')
+ : [];
+
+ if (requestId !== requestIdRef.current) return;
+ setState({ collections, entries, error: null, isLoading: false, selectedCollection });
+ } 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;
+ setState((current) => ({
+ ...current,
+ entries: [],
+ error: null,
+ isLoading: true,
+ selectedCollection,
+ }));
+
+ try {
+ const entries = await localDatabase.entriesByPrefix(selectedCollection, '');
+ if (requestId !== requestIdRef.current) return;
+ setState((current) => ({ ...current, entries, isLoading: false }));
+ } catch (error) {
+ if (requestId !== requestIdRef.current) return;
+ setState((current) => ({ ...current, error: errorMessage(error), isLoading: false }));
+ }
+ }, []);
+
+ useEffect(() => {
+ void loadSnapshot(null);
+ return () => {
+ requestIdRef.current += 1;
+ };
+ }, [loadSnapshot]);
+
+ const refresh = useCallback(
+ () => loadSnapshot(state.selectedCollection),
+ [loadSnapshot, state.selectedCollection],
+ );
+
+ return { ...state, refresh, selectCollection };
+};
diff --git a/src/features/DevPanel/Replica/EntryDetails.tsx b/src/features/DevPanel/Replica/EntryDetails.tsx
new file mode 100644
index 00000000000..6d7cd615ed6
--- /dev/null
+++ b/src/features/DevPanel/Replica/EntryDetails.tsx
@@ -0,0 +1,143 @@
+'use client';
+
+import { Button, Switch, TextArea } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { Pencil, RefreshCw, Trash2 } from 'lucide-react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+import type { ReplicaDevtoolsEntry } from '@/libs/replica/devtools';
+
+import { inspectorStyles as styles } from '../inspectorStyles';
+import { type ReplicaEntryRow, serializeReplicaDraft } from './model';
+import { replicaStyles } from './styles';
+import { useEntryEditor } from './useEntryEditor';
+
+const MAX_PREVIEW_LENGTH = 100_000;
+
+interface EntryDetailsProps {
+ entry: ReplicaDevtoolsEntry | undefined;
+ onPin: (key: string) => void;
+ row: ReplicaEntryRow | undefined;
+}
+
+const preview = (value: unknown): string => {
+ if (value === undefined) return '—';
+ try {
+ const text = serializeReplicaDraft(value);
+ return text.length > MAX_PREVIEW_LENGTH
+ ? `${text.slice(0, MAX_PREVIEW_LENGTH)}\n… truncated (${text.length} chars); use Edit to see all`
+ : text;
+ } catch (error) {
+ return `[Unable to serialize: ${error instanceof Error ? error.message : String(error)}]`;
+ }
+};
+
+const Field = ({ label, type, value }: { label: string; type?: string; value: string }) => (
+ <div className={styles.detailField}>
+ <div className={styles.detailLabel}>
+ <span>{label}</span>
+ {type && <span className={styles.detailType}>{type}</span>}
+ </div>
+ <pre className={styles.detailValue}>{value}</pre>
+ </div>
+);
+
+const EntryDetails = ({ entry, onPin, row }: EntryDetailsProps) => {
+ const editor = useEntryEditor(entry, row?.key);
+
+ return (
+ <aside
+ aria-label={'Selected entry details'}
+ className={cx(styles.detailsPane, devDockPanelStyles.paneDividerStart)}
+ >
+ <div className={devDockPanelStyles.paneHeader}>Entry</div>
+ {entry && row ? (
+ <>
+ <div className={replicaStyles.actions}>
+ <Button
+ disabled={editor.isEditing}
+ icon={Pencil}
+ size={'small'}
+ type={'text'}
+ onClick={() => {
+ onPin(row.key);
+ editor.start();
+ }}
+ >
+ Edit
+ </Button>
+ <Button
+ icon={RefreshCw}
+ size={'small'}
+ title={'Re-run the mounted useSync query of this entry'}
+ type={'text'}
+ onClick={() => void entry.revalidate(row.key)}
+ >
+ Revalidate
+ </Button>
+ <Button
+ danger
+ icon={Trash2}
+ size={'small'}
+ title={'slice.remove: drops the entry and every persisted query variant of the key'}
+ type={'text'}
+ onClick={() => entry.remove(row.key)}
+ >
+ Remove
+ </Button>
+ </div>
+ {editor.isEditing ? (
+ <div className={replicaStyles.editor}>
+ <TextArea
+ resize
+ aria-label={`Edit ${row.key} as JSON`}
+ className={replicaStyles.editorInput}
+ spellCheck={false}
+ value={editor.draft ?? ''}
+ onChange={(event) => editor.setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') editor.cancel();
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) editor.apply();
+ }}
+ />
+ {editor.error && <div className={replicaStyles.editorError}>{editor.error}</div>}
+ <div className={replicaStyles.editorFooter}>
+ <label className={replicaStyles.persistToggle}>
+ <Switch checked={editor.persist} size={'small'} onChange={editor.setPersist} />
+ Persist
+ </label>
+ <span>
+ <Button size={'small'} type={'text'} onClick={editor.cancel}>
+ Cancel
+ </Button>
+ <Button size={'small'} type={'primary'} onClick={editor.apply}>
+ Apply
+ </Button>
+ </span>
+ </div>
+ </div>
+ ) : (
+ <div className={styles.detailFields}>
+ {editor.error && <Field label={'error'} value={editor.error} />}
+ <Field label={'key'} value={row.key} />
+ <Field label={'source'} value={row.source} />
+ <Field label={'query'} value={row.query ?? '—'} />
+ <Field
+ label={'pending'}
+ type={row.hasBase ? 'over base' : undefined}
+ value={String(row.pending)}
+ />
+ <Field label={'updatedAt'} value={row.updatedAt?.toISOString() ?? '—'} />
+ {row.params !== undefined && <Field label={'params'} value={preview(row.params)} />}
+ <Field label={'value'} value={preview(row.data)} />
+ </div>
+ )}
+ </>
+ ) : (
+ <div className={styles.empty}>Select an entry to inspect it.</div>
+ )}
+ </aside>
+ );
+};
+
+export default EntryDetails;
diff --git a/src/features/DevPanel/Replica/EntryTable.tsx b/src/features/DevPanel/Replica/EntryTable.tsx
new file mode 100644
index 00000000000..df8cecbdc3a
--- /dev/null
+++ b/src/features/DevPanel/Replica/EntryTable.tsx
@@ -0,0 +1,141 @@
+'use client';
+
+import { Button, Input } from '@lobehub/ui/base-ui';
+import { RefreshCw } from 'lucide-react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+import { inspectorStyles as styles } from '../inspectorStyles';
+import { describeReplicaValue, type ReplicaEntryRow } from './model';
+import { MAX_RENDERED_ENTRIES } from './useReplicaInspector';
+
+interface EntryTableProps {
+ matchingCount: number;
+ onRevalidate: (() => void) | undefined;
+ onSearchChange: (value: string) => void;
+ onSelect: (key: string) => void;
+ rows: ReplicaEntryRow[];
+ search: string;
+ selectedKey: string | undefined;
+ title: string;
+ totalCount: number;
+}
+
+const COLUMNS = [
+ { label: 'key', width: 240 },
+ { label: 'source', width: 80 },
+ { label: 'pending', width: 72 },
+ { label: 'query', width: 200 },
+ { label: 'updatedAt', width: 200 },
+ { label: 'value', width: 200 },
+] as const;
+
+const TABLE_WIDTH = COLUMNS.reduce((total, { width }) => total + width, 0);
+
+const cellsOf = (row: ReplicaEntryRow): string[] => [
+ row.key,
+ row.source,
+ String(row.pending),
+ row.query ?? '—',
+ row.updatedAt?.toISOString() ?? '—',
+ describeReplicaValue(row.data),
+];
+
+const EntryTable = ({
+ matchingCount,
+ onRevalidate,
+ onSearchChange,
+ onSelect,
+ rows,
+ search,
+ selectedKey,
+ title,
+ totalCount,
+}: EntryTableProps) => (
+ <main className={styles.tablePane}>
+ <div className={devDockPanelStyles.toolbar}>
+ <span className={styles.tableName} title={title}>
+ {title}
+ </span>
+ <Input
+ allowClear
+ className={styles.toolbarSearch}
+ placeholder={'Search key, query, source…'}
+ size={'small'}
+ style={{ flex: 1 }}
+ value={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ />
+ <span className={styles.toolbarMeta}>{totalCount} entries · live</span>
+ <Button
+ disabled={!onRevalidate}
+ icon={RefreshCw}
+ size={'small'}
+ title={'Re-run the mounted useSync queries of this resource'}
+ type={'text'}
+ onClick={onRevalidate}
+ >
+ Revalidate
+ </Button>
+ </div>
+ <div className={styles.tableScroll}>
+ <table className={styles.table} style={{ minWidth: '100%', width: TABLE_WIDTH }}>
+ <colgroup>
+ {COLUMNS.map(({ label, width }) => (
+ <col key={label} style={{ width }} />
+ ))}
+ </colgroup>
+ <thead>
+ <tr>
+ {COLUMNS.map(({ label }) => (
+ <th key={label} scope={'col'}>
+ {label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row) => {
+ const active = row.key === selectedKey;
+
+ return (
+ <tr
+ aria-label={row.key}
+ aria-selected={active}
+ className={active ? styles.rowActive : undefined}
+ key={row.key}
+ tabIndex={0}
+ onClick={() => onSelect(row.key)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onSelect(row.key);
+ }
+ }}
+ >
+ {cellsOf(row).map((text, index) => (
+ <td key={COLUMNS[index].label} title={text}>
+ {text}
+ </td>
+ ))}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {rows.length === 0 && (
+ <div className={styles.tableEmpty}>
+ {search ? `No entries match “${search}”.` : 'This replica holds no entries.'}
+ </div>
+ )}
+ </div>
+ <div className={devDockPanelStyles.statusBar}>
+ <span>{matchingCount === 0 ? '0 entries' : `1–${rows.length} of ${matchingCount}`}</span>
+ {matchingCount > MAX_RENDERED_ENTRIES && (
+ <span>Refine the search to inspect later entries.</span>
+ )}
+ </div>
+ </main>
+);
+
+export default EntryTable;
diff --git a/src/features/DevPanel/Replica/ResourceList.tsx b/src/features/DevPanel/Replica/ResourceList.tsx
new file mode 100644
index 00000000000..cfb6bbc8926
--- /dev/null
+++ b/src/features/DevPanel/Replica/ResourceList.tsx
@@ -0,0 +1,83 @@
+'use client';
+
+import { Input } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { Boxes } from 'lucide-react';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+import { inspectorStyles as styles } from '../inspectorStyles';
+import type { ReplicaResourceSummary } from './model';
+import { replicaStyles } from './styles';
+
+interface ResourceListProps {
+ onSearchChange: (value: string) => void;
+ onSelect: (namespace: string) => void;
+ resources: ReplicaResourceSummary[];
+ search: string;
+ selectedNamespace: string | undefined;
+}
+
+const ResourceList = ({
+ onSearchChange,
+ onSelect,
+ resources,
+ search,
+ selectedNamespace,
+}: ResourceListProps) => (
+ <aside
+ aria-label={'Replica resources'}
+ className={cx(styles.sidePane, devDockPanelStyles.paneDividerEnd)}
+ >
+ <div className={devDockPanelStyles.paneHeader}>Resources</div>
+ <div className={devDockPanelStyles.paneSearch}>
+ <Input
+ allowClear
+ className={devDockPanelStyles.searchInput}
+ placeholder={'Search resources…'}
+ size={'small'}
+ value={search}
+ variant={'borderless'}
+ onChange={(event) => onSearchChange(event.target.value)}
+ />
+ </div>
+ <div className={styles.list}>
+ {resources.length === 0 ? (
+ <div className={styles.empty}>
+ {search ? 'No resources match.' : 'No replica has been created yet.'}
+ </div>
+ ) : (
+ resources.map(
+ ({ entryCount, name, namespace, paged, pendingCount, persisted, version }) => {
+ const active = namespace === selectedNamespace;
+
+ return (
+ <button
+ aria-pressed={active}
+ className={cx(styles.listItem, active && styles.listItemActive)}
+ key={namespace}
+ title={`${namespace}${persisted ? '' : ' · memory only'}${paged ? ' · paged' : ''}`}
+ type={'button'}
+ onClick={() => onSelect(namespace)}
+ >
+ <Boxes className={styles.listIcon} size={14} />
+ <span className={styles.listName}>{name}</span>
+ <span className={replicaStyles.resourceMeta}>
+ {pendingCount > 0 && (
+ <span className={cx(replicaStyles.badge, replicaStyles.badgePending)}>
+ {pendingCount}↺
+ </span>
+ )}
+ <span className={replicaStyles.badge}>v{version}</span>
+ <span className={styles.listCount}>{entryCount}</span>
+ </span>
+ </button>
+ );
+ },
+ )
+ )}
+ </div>
+ </aside>
+);
+
+export default ResourceList;
diff --git a/src/features/DevPanel/Replica/index.tsx b/src/features/DevPanel/Replica/index.tsx
new file mode 100644
index 00000000000..07f19236309
--- /dev/null
+++ b/src/features/DevPanel/Replica/index.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { devDockPanelStyles } from '@/features/DevDock/panelStyles';
+
+import { inspectorStyles as styles } from '../inspectorStyles';
+import EntryDetails from './EntryDetails';
+import EntryTable from './EntryTable';
+import ResourceList from './ResourceList';
+import { useReplicaInspector } from './useReplicaInspector';
+
+const ReplicaPanel = () => {
+ const {
+ entrySearch,
+ matchingCount,
+ renderedRows,
+ resourceSearch,
+ selectEntry,
+ selectResource,
+ selected,
+ selectedRow,
+ setEntrySearch,
+ setResourceSearch,
+ totalCount,
+ visibleResources,
+ } = useReplicaInspector();
+ const namespace = selected?.resource.namespace;
+
+ return (
+ <div className={devDockPanelStyles.root}>
+ <div className={styles.workspace}>
+ <ResourceList
+ resources={visibleResources}
+ search={resourceSearch}
+ selectedNamespace={namespace}
+ onSearchChange={setResourceSearch}
+ onSelect={selectResource}
+ />
+ <EntryTable
+ matchingCount={matchingCount}
+ rows={renderedRows}
+ search={entrySearch}
+ selectedKey={selectedRow?.key}
+ title={selected?.resource.name ?? 'Replica'}
+ totalCount={totalCount}
+ onRevalidate={selected ? () => void selected.revalidate() : undefined}
+ onSearchChange={setEntrySearch}
+ onSelect={selectEntry}
+ />
+ <EntryDetails
+ entry={selected}
+ key={`${namespace}\u0000${selectedRow?.key}`}
+ row={selectedRow}
+ onPin={selectEntry}
+ />
+ </div>
+ </div>
+ );
+};
+
+export default ReplicaPanel;
diff --git a/src/features/DevPanel/Replica/model.test.ts b/src/features/DevPanel/Replica/model.test.ts
new file mode 100644
index 00000000000..5bb985fc6cf
--- /dev/null
+++ b/src/features/DevPanel/Replica/model.test.ts
@@ -0,0 +1,95 @@
+import type { ReplicaState } from '@lobechat/replica';
+import { describe, expect, it } from 'vitest';
+
+import type { ReplicaDevtoolsEntry } from '@/libs/replica/devtools';
+
+import {
+ createReplicaEntryRows,
+ describeReplicaValue,
+ filterReplicaEntryRows,
+ parseReplicaDraft,
+ serializeReplicaDraft,
+ summarizeReplicaResource,
+} from './model';
+
+const createEntry = (
+ state: ReplicaState<unknown>,
+ view: Record<string, unknown>,
+ paged = false,
+): ReplicaDevtoolsEntry =>
+ ({
+ keys: () => [...new Set([...Object.keys(state.entries), ...Object.keys(view)])],
+ read: (key: string) => view[key],
+ remove: () => true,
+ resource: {
+ name: 'topicList',
+ namespace: 'replica:topicList:v2',
+ paging: paged ? {} : undefined,
+ persisted: true,
+ version: 2,
+ },
+ revalidate: async () => undefined,
+ state: () => state,
+ update: () => undefined,
+ }) as unknown as ReplicaDevtoolsEntry;
+
+const state: ReplicaState<unknown> = {
+ entries: {
+ agent_1: {
+ base: { items: [], total: 0 },
+ pending: [{ apply: (data) => data, id: 1 }],
+ query: '{"sortBy":"updatedAt"}',
+ source: 'server',
+ updatedAt: 2000,
+ },
+ agent_2: { pending: [], source: 'storage', updatedAt: 1000 },
+ },
+ scope: 'user-1:personal',
+};
+
+describe('Replica inspector model', () => {
+ it('summarizes a resource from its bookkeeping and loaded view keys', () => {
+ const entry = createEntry(state, { agent_1: {}, agent_2: {}, seeded: {} }, true);
+
+ expect(summarizeReplicaResource(entry)).toEqual({
+ entryCount: 3,
+ name: 'topicList',
+ namespace: 'replica:topicList:v2',
+ paged: true,
+ pendingCount: 1,
+ persisted: true,
+ scope: 'user-1:personal',
+ version: 2,
+ });
+ });
+
+ it('lists entries newest first, including view keys the engine has no meta for', () => {
+ const rows = createReplicaEntryRows(createEntry(state, { agent_1: 1, seeded: 2 }));
+
+ expect(rows.map(({ key, pending, source }) => [key, source, pending])).toEqual([
+ ['agent_1', 'server', 1],
+ ['agent_2', 'storage', 0],
+ ['seeded', '—', 0],
+ ]);
+ expect(rows[0].hasBase).toBe(true);
+ expect(rows[0].updatedAt).toEqual(new Date(2000));
+ expect(filterReplicaEntryRows(rows, 'sortby').map(({ key }) => key)).toEqual(['agent_1']);
+ expect(filterReplicaEntryRows(rows, 'storage').map(({ key }) => key)).toEqual(['agent_2']);
+ });
+
+ it('describes values compactly for the table', () => {
+ expect(describeReplicaValue({ items: [1, 2], total: 2 })).toBe('page · 2 items');
+ expect(describeReplicaValue({ id: 'a', title: 'b' })).toBe('object{2}');
+ expect(describeReplicaValue([1])).toBe('array[1]');
+ expect(describeReplicaValue(undefined)).toBe('—');
+ });
+
+ it('round-trips dates through an edit draft', () => {
+ const value = { createdAt: new Date('2026-10-16T00:00:00.000Z'), tags: ['a'], title: 'T' };
+ const draft = serializeReplicaDraft(value);
+
+ expect(draft).toContain('"$date": "2026-10-16T00:00:00.000Z"');
+ expect(parseReplicaDraft(draft)).toEqual(value);
+ expect(parseReplicaDraft('{"$date":"x","other":1}')).toEqual({ $date: 'x', other: 1 });
+ });
+});
diff --git a/src/features/DevPanel/Replica/model.ts b/src/features/DevPanel/Replica/model.ts
new file mode 100644
index 00000000000..c6696514628
--- /dev/null
+++ b/src/features/DevPanel/Replica/model.ts
@@ -0,0 +1,119 @@
+import type { ReplicaDevtoolsEntry } from '@/libs/replica/devtools';
+
+export interface ReplicaResourceSummary {
+ entryCount: number;
+ name: string;
+ namespace: string;
+ paged: boolean;
+ pendingCount: number;
+ persisted: boolean;
+ scope: string | undefined;
+ version: number;
+}
+
+export interface ReplicaEntryRow {
+ data: unknown;
+ hasBase: boolean;
+ key: string;
+ params: unknown;
+ pending: number;
+ query: string | undefined;
+ source: string;
+ updatedAt: Date | undefined;
+}
+
+const DATE_TAG = '$date';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);
+
+export const summarizeReplicaResource = (entry: ReplicaDevtoolsEntry): ReplicaResourceSummary => {
+ const { resource } = entry;
+ const state = entry.state();
+ const metas = Object.values(state?.entries ?? {});
+
+ return {
+ entryCount: entry.keys().length,
+ name: resource.name,
+ namespace: resource.namespace,
+ paged: Boolean(resource.paging),
+ pendingCount: metas.reduce((total, meta) => total + meta.pending.length, 0),
+ persisted: resource.persisted,
+ scope: state?.scope,
+ version: resource.version,
+ };
+};
+
+export const createReplicaEntryRows = (entry: ReplicaDevtoolsEntry): ReplicaEntryRow[] => {
+ const metas = entry.state()?.entries ?? {};
+
+ return entry
+ .keys()
+ .map((key) => {
+ const meta = metas[key];
+ return {
+ data: entry.read(key),
+ hasBase: meta?.base !== undefined,
+ key,
+ params: meta?.params,
+ pending: meta?.pending.length ?? 0,
+ query: meta?.query,
+ source: meta?.source ?? '—',
+ updatedAt: meta?.updatedAt ? new Date(meta.updatedAt) : undefined,
+ };
+ })
+ .sort((a, b) => (b.updatedAt?.getTime() ?? 0) - (a.updatedAt?.getTime() ?? 0));
+};
+
+export const filterReplicaResources = (
+ resources: ReplicaResourceSummary[],
+ search: string,
+): ReplicaResourceSummary[] => {
+ const term = search.trim().toLowerCase();
+ return term ? resources.filter(({ name }) => name.toLowerCase().includes(term)) : resources;
+};
+
+export const filterReplicaEntryRows = (
+ rows: ReplicaEntryRow[],
+ search: string,
+): ReplicaEntryRow[] => {
+ const term = search.trim().toLowerCase();
+ if (!term) return rows;
+
+ return rows.filter(({ key, query, source }) =>
+ [key, query ?? '', source].some((text) => text.toLowerCase().includes(term)),
+ );
+};
+
+export const describeReplicaValue = (value: unknown): string => {
+ if (value === undefined) return '—';
+ if (value === null) return 'null';
+ if (value instanceof Date) return value.toISOString();
+ if (Array.isArray(value)) return `array[${value.length}]`;
+ if (isRecord(value)) {
+ if (Array.isArray(value.items)) return `page · ${value.items.length} items`;
+ return `object{${Object.keys(value).length}}`;
+ }
+ if (typeof value === 'string') return value.length > 80 ? `${value.slice(0, 80)}…` : value;
+ return String(value);
+};
+
+// Dates are tagged instead of left to toJSON so an edit round-trips them as
+// Date objects; selectors call date methods on these fields.
+export const serializeReplicaDraft = (value: unknown): string =>
+ JSON.stringify(
+ value,
+ function (this: Record<string, unknown>, key, item) {
+ const raw = this[key];
+ if (raw instanceof Date) return { [DATE_TAG]: raw.toISOString() };
+ return item;
+ },
+ 2,
+ ) ?? 'null';
+
+export const parseReplicaDraft = (text: string): unknown =>
+ JSON.parse(text, (_key, item) =>
+ isRecord(item) && Object.keys(item).length === 1 && typeof item[DATE_TAG] === 'string'
+ ? new Date(item[DATE_TAG])
+ : item,
+ );
diff --git a/src/features/DevPanel/Replica/styles.ts b/src/features/DevPanel/Replica/styles.ts
new file mode 100644
index 00000000000..71f5d566839
--- /dev/null
+++ b/src/features/DevPanel/Replica/styles.ts
@@ -0,0 +1,68 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+
+export const replicaStyles = createStaticStyles(({ css }) => ({
+ actions: css`
+ display: flex;
+ flex-shrink: 0;
+ flex-wrap: wrap;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ badge: css`
+ padding-inline: 4px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusXS};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 10px;
+ line-height: 16px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ badgePending: css`
+ border-color: ${cssVar.colorWarningBorder};
+ color: ${cssVar.colorWarning};
+ `,
+ editor: css`
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: 8px;
+
+ min-height: 0;
+ padding: 12px;
+ `,
+ editorFooter: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextTertiary};
+ `,
+ editorError: css`
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorError};
+ overflow-wrap: anywhere;
+ `,
+ editorInput: css`
+ flex: 1;
+ min-height: 200px;
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ `,
+ persistToggle: css`
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ `,
+ resourceMeta: css`
+ display: flex;
+ flex-shrink: 0;
+ gap: 4px;
+ `,
+}));
diff --git a/src/features/DevPanel/Replica/useEntryEditor.ts b/src/features/DevPanel/Replica/useEntryEditor.ts
new file mode 100644
index 00000000000..3940b911387
--- /dev/null
+++ b/src/features/DevPanel/Replica/useEntryEditor.ts
@@ -0,0 +1,57 @@
+import { useState } from 'react';
+
+import type { ReplicaDevtoolsEntry } from '@/libs/replica/devtools';
+
+import { parseReplicaDraft, serializeReplicaDraft } from './model';
+
+const errorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error);
+
+export const useEntryEditor = (
+ entry: ReplicaDevtoolsEntry | undefined,
+ key: string | undefined,
+) => {
+ const [draft, setDraft] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [persist, setPersist] = useState(true);
+
+ const start = () => {
+ if (!entry || key === undefined) return;
+ try {
+ setDraft(serializeReplicaDraft(entry.read(key)));
+ setError(null);
+ } catch (cause) {
+ setError(`Cannot edit this value as JSON: ${errorMessage(cause)}`);
+ }
+ };
+
+ const cancel = () => {
+ setDraft(null);
+ setError(null);
+ };
+
+ const apply = () => {
+ if (!entry || key === undefined || draft === null) return;
+ try {
+ entry.update(key, parseReplicaDraft(draft), { persist });
+ cancel();
+ } catch (cause) {
+ setError(errorMessage(cause));
+ }
+ };
+
+ return {
+ apply,
+ cancel,
+ draft,
+ error,
+ isEditing: draft !== null,
+ persist,
+ setDraft: (value: string) => {
+ setDraft(value);
+ setError(null);
+ },
+ setPersist,
+ start,
+ };
+};
diff --git a/src/features/DevPanel/Replica/useReplicaInspector.test.ts b/src/features/DevPanel/Replica/useReplicaInspector.test.ts
new file mode 100644
index 00000000000..919e11eb160
--- /dev/null
+++ b/src/features/DevPanel/Replica/useReplicaInspector.test.ts
@@ -0,0 +1,92 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ defineReplica,
+ recordLens,
+ type ReplicaState,
+} from '@/libs/replica';
+
+import { useEntryEditor } from './useEntryEditor';
+import { useReplicaInspector } from './useReplicaInspector';
+
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));
+
+interface Topic {
+ createdAt: Date;
+ title: string;
+}
+
+interface TestState {
+ topics: Record<string, Topic>;
+ topicsReplica: ReplicaState<Topic>;
+}
+
+const resource = defineReplica<{ id: string }, Topic>({
+ key: ({ id }) => id,
+ name: 'inspectorTopic',
+ scope: { canPersist: () => false, get: () => 'user-1:personal', use: () => 'user-1:personal' },
+ storage: 'memory',
+ version: 1,
+});
+const store = createStore<TestState>()(() => ({
+ topics: {},
+ topicsReplica: createReplicaState(),
+}));
+const slice = createReplicaSlice<TestState, { id: string }, Topic>(resource, {
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'topicsReplica',
+ view: recordLens('topics'),
+});
+
+const createdAt = new Date('2026-10-16T00:00:00.000Z');
+
+describe('useReplicaInspector', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('follows replica commits live and writes edits back through the slice', () => {
+ slice.update('t1', () => ({ createdAt, title: 'Draft' }));
+
+ const { result } = renderHook(() => useReplicaInspector());
+ act(() => result.current.selectResource(resource.namespace));
+
+ expect(result.current.selected?.resource).toBe(resource);
+ expect(result.current.selectedRow).toMatchObject({ key: 't1', source: 'local' });
+
+ act(() => {
+ slice.update('t2', () => ({ createdAt, title: 'Second' }));
+ vi.advanceTimersByTime(200);
+ });
+ expect(result.current.totalCount).toBe(2);
+
+ const editor = renderHook(() => useEntryEditor(result.current.selected, 't1'));
+ act(() => editor.result.current.start());
+ act(() =>
+ editor.result.current.setDraft(editor.result.current.draft!.replace('"Draft"', '"Renamed"')),
+ );
+ act(() => editor.result.current.apply());
+
+ expect(editor.result.current.isEditing).toBe(false);
+ expect(store.getState().topics.t1).toEqual({ createdAt, title: 'Renamed' });
+ });
+
+ it('keeps the draft open and reports invalid JSON', () => {
+ slice.update('t3', () => ({ createdAt, title: 'Keep' }));
+ const { result } = renderHook(() => useReplicaInspector());
+ act(() => result.current.selectResource(resource.namespace));
+
+ const editor = renderHook(() => useEntryEditor(result.current.selected, 't3'));
+ act(() => editor.result.current.start());
+ act(() => editor.result.current.setDraft('{ not json'));
+ act(() => editor.result.current.apply());
+
+ expect(editor.result.current.isEditing).toBe(true);
+ expect(editor.result.current.error).toBeTruthy();
+ expect(store.getState().topics.t3.title).toBe('Keep');
+ });
+});
diff --git a/src/features/DevPanel/Replica/useReplicaInspector.ts b/src/features/DevPanel/Replica/useReplicaInspector.ts
new file mode 100644
index 00000000000..98568432a27
--- /dev/null
+++ b/src/features/DevPanel/Replica/useReplicaInspector.ts
@@ -0,0 +1,65 @@
+import { useMemo, useState, useSyncExternalStore } from 'react';
+
+import {
+ getReplicaDevtoolsVersion,
+ listReplicaDevtools,
+ subscribeReplicaDevtools,
+} from '@/libs/replica/devtools';
+
+import {
+ createReplicaEntryRows,
+ filterReplicaEntryRows,
+ filterReplicaResources,
+ summarizeReplicaResource,
+} from './model';
+
+export const MAX_RENDERED_ENTRIES = 300;
+
+export const useReplicaInspector = () => {
+ const version = useSyncExternalStore(
+ subscribeReplicaDevtools,
+ getReplicaDevtoolsVersion,
+ getReplicaDevtoolsVersion,
+ );
+ const [resourceSearch, setResourceSearch] = useState('');
+ const [entrySearch, setEntrySearch] = useState('');
+ const [requestedNamespace, setRequestedNamespace] = useState<string | null>(null);
+ const [requestedKey, setRequestedKey] = useState<string | null>(null);
+
+ const snapshot = useMemo(() => ({ registry: listReplicaDevtools(), version }), [version]);
+ const { registry } = snapshot;
+ const resources = useMemo(() => registry.map(summarizeReplicaResource), [registry]);
+ const visibleResources = filterReplicaResources(resources, resourceSearch);
+
+ const selected =
+ registry.find(({ resource }) => resource.namespace === requestedNamespace) ??
+ registry.find((entry) => entry.keys().length > 0) ??
+ registry.at(0);
+ const rows = useMemo(
+ () => (selected ? createReplicaEntryRows(selected) : []),
+ [selected, snapshot],
+ );
+ const matchingRows = filterReplicaEntryRows(rows, entrySearch);
+ const renderedRows = matchingRows.slice(0, MAX_RENDERED_ENTRIES);
+ const selectedRow = renderedRows.find(({ key }) => key === requestedKey) ?? renderedRows.at(0);
+
+ return {
+ entrySearch,
+ matchingCount: matchingRows.length,
+ renderedRows,
+ resourceSearch,
+ resources,
+ selectEntry: setRequestedKey,
+ selectResource: (namespace: string) => {
+ setRequestedNamespace(namespace);
+ setRequestedKey(null);
+ setEntrySearch('');
+ },
+ selected,
+ selectedRow,
+ setEntrySearch,
+ setResourceSearch,
+ totalCount: rows.length,
+ visibleResources,
+ };
+};
diff --git a/src/features/DevPanel/inspectorStyles.ts b/src/features/DevPanel/inspectorStyles.ts
new file mode 100644
index 00000000000..3cfadfd9ac8
--- /dev/null
+++ b/src/features/DevPanel/inspectorStyles.ts
@@ -0,0 +1,295 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+
+export const inspectorStyles = createStaticStyles(({ css }) => ({
+ listCount: css`
+ flex-shrink: 0;
+
+ min-width: 24px;
+ padding-inline: 4px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusXS};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ listIcon: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ listItem: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ width: 100%;
+ height: 32px;
+ padding-inline: 12px;
+ border: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextSecondary};
+ text-align: start;
+
+ background: transparent;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: -2px;
+ }
+ `,
+ listItemActive: css`
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ `,
+ list: css`
+ overflow: auto;
+ flex: 1;
+ min-height: 0;
+ padding-block: 4px;
+ `,
+ listName: css`
+ overflow: hidden;
+ flex: 1;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ sidePane: css`
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ min-width: 0;
+ min-height: 0;
+ `,
+ detailField: css`
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+
+ padding: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ detailFields: css`
+ overflow: auto;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+
+ min-height: 0;
+ `,
+ detailLabel: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextSecondary};
+ `,
+ detailType: css`
+ font-family: ${cssVar.fontFamilyCode};
+ color: ${cssVar.colorTextTertiary};
+ `,
+ detailValue: css`
+ overflow: auto;
+
+ min-height: 28px;
+ max-height: 180px;
+ margin: 0;
+ padding-block: 4px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ line-height: 1.6;
+ color: ${cssVar.colorText};
+ overflow-wrap: anywhere;
+ white-space: pre-wrap;
+ `,
+ detailsPane: css`
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ min-width: 0;
+ min-height: 0;
+
+ @media (width <= 900px) {
+ display: none;
+ }
+ `,
+ empty: css`
+ display: flex;
+ flex: 1;
+ align-items: center;
+ justify-content: center;
+
+ min-height: 0;
+ padding: 24px;
+
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ error: css`
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: 12px;
+ align-items: center;
+ justify-content: center;
+
+ min-height: 0;
+ padding: 24px;
+
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorError};
+ text-align: center;
+ `,
+ listItemNested: css`
+ height: 28px;
+ padding-inline-start: 34px;
+ `,
+ rowActive: css`
+ background: ${cssVar.colorFillSecondary};
+ `,
+ table: css`
+ table-layout: fixed;
+ border-spacing: 0;
+ border-collapse: separate;
+
+ th,
+ td {
+ overflow: hidden;
+
+ height: 32px;
+ padding-inline: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ border-inline-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextSecondary};
+ text-align: start;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ th {
+ position: sticky;
+ z-index: 1;
+ inset-block-start: 0;
+
+ font-family: ${cssVar.fontFamily};
+ font-weight: 600;
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorBgContainer};
+ }
+
+ th:last-child,
+ td:last-child {
+ border-inline-end: 0;
+ }
+
+ tbody tr {
+ cursor: pointer;
+ outline: none;
+ }
+
+ tbody tr:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ tbody tr:focus-visible {
+ box-shadow: inset 0 0 0 2px ${cssVar.colorPrimary};
+ }
+ `,
+ tableEmpty: css`
+ position: absolute;
+ inset-block: 32px 0;
+ inset-inline: 0;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ padding: 24px;
+
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ tableName: css`
+ overflow: hidden;
+ flex-shrink: 1;
+
+ min-width: 100px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ tablePane: css`
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ min-width: 0;
+ min-height: 0;
+ `,
+ tableScroll: css`
+ position: relative;
+ overflow: auto;
+ flex: 1;
+ min-height: 0;
+ `,
+ toolbarMeta: css`
+ flex-shrink: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: ${cssVar.fontSizeSM};
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+
+ @media (width <= 1100px) {
+ display: none;
+ }
+ `,
+ toolbarSearch: css`
+ min-width: 120px;
+ max-width: 300px;
+ `,
+ workspace: css`
+ overflow: hidden;
+ display: grid;
+ grid-template-columns: 220px minmax(360px, 1fr) 300px;
+ flex: 1;
+
+ min-height: 0;
+
+ @media (width <= 1200px) {
+ grid-template-columns: 190px minmax(360px, 1fr) 260px;
+ }
+
+ @media (width <= 900px) {
+ grid-template-columns: 170px minmax(0, 1fr);
+ }
+
+ @media (width <= 560px) {
+ grid-template-columns: 140px minmax(0, 1fr);
+ }
+ `,
+}));
diff --git a/src/features/HomeSidebar/Body/Project/index.tsx b/src/features/HomeSidebar/Body/Project/index.tsx
index a70fb526b36..78ebc5be2dc 100644
--- a/src/features/HomeSidebar/Body/Project/index.tsx
+++ b/src/features/HomeSidebar/Body/Project/index.tsx
@@ -18,8 +18,9 @@ import AsyncError from '@/components/AsyncError';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { openCreateProjectModal } from '@/features/Projects/CreateProjectModal';
+import { resolveProjectListState } from '@/features/Projects/projectListState';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useLoadedProjectList, useProjectStore } from '@/store/project';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
@@ -33,12 +34,11 @@ const Project = memo<ProjectProps>(({ itemKey }) => {
const { t } = useTranslation('project');
const enabled = useUserStore(labPreferSelectors.enableProjects);
const navigate = useWorkspaceAwareNavigate();
- const projects = useCurrentProjectList();
+ const projects = useLoadedProjectList();
const { error, isHydrated, isValidating, revalidate } = useProjectStore(
(s) => s.useFetchProjectList,
)(enabled);
- // Rows come from the store; the hook only reports fetch progress.
- const isLoading = !isHydrated || isValidating;
+ const state = resolveProjectListState({ error, isHydrated, isValidating, projects });
if (!enabled) return null;
@@ -66,18 +66,18 @@ const Project = memo<ProjectProps>(({ itemKey }) => {
</div>
</AccordionHeader>
<AccordionPanel>
- {error && projects.length === 0 ? (
+ {state === 'error' ? (
<AsyncError error={error} variant="inline" onRetry={() => revalidate()} />
- ) : isLoading && projects.length === 0 ? (
+ ) : state === 'loading' ? (
<SkeletonList rows={3} />
- ) : projects.length === 0 ? (
+ ) : state === 'empty' ? (
<NavItem
icon={PlusIcon}
title={t('sidebar.emptyAction')}
onClick={() => openCreateProjectModal()}
/>
) : (
- projects.map((project) => <ProjectItem key={project.id} project={project} />)
+ projects?.map((project) => <ProjectItem key={project.id} project={project} />)
)}
</AccordionPanel>
</AccordionItem>
diff --git a/src/features/Projects/Layout/ProjectHeader.tsx b/src/features/Projects/Layout/ProjectHeader.tsx
index d05874b5060..334ebbeb07a 100644
--- a/src/features/Projects/Layout/ProjectHeader.tsx
+++ b/src/features/Projects/Layout/ProjectHeader.tsx
@@ -14,7 +14,9 @@ import type { SwitcherItem } from '@/features/NavPanel/switcher/switcherItems';
import SwitcherMenu from '@/features/NavPanel/switcher/SwitcherMenu';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { ProjectDetail } from '@/store/project';
-import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useLoadedProjectList, useProjectStore } from '@/store/project';
+
+import { resolveProjectListState } from '../projectListState';
interface ProjectHeaderProps {
project?: ProjectDetail['project'];
@@ -23,16 +25,15 @@ interface ProjectHeaderProps {
const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {
const { t } = useTranslation(['project', 'common']);
const navigate = useWorkspaceAwareNavigate();
- const projects = useCurrentProjectList();
+ const projects = useLoadedProjectList();
const { error, isHydrated, isValidating, revalidate } = useProjectStore(
(s) => s.useFetchProjectList,
)(true);
- // Rows come from the store; the hook only reports fetch progress.
- const isLoading = !isHydrated || isValidating;
+ const listState = resolveProjectListState({ error, isHydrated, isValidating, projects });
const items = useMemo<SwitcherItem[]>(
() =>
- projects.map((item) => ({
+ (projects ?? []).map((item) => ({
avatar: item.avatar || undefined,
id: item.slug ?? item.id,
private: item.visibility === 'private',
@@ -54,8 +55,8 @@ const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {
content={
<SwitcherMenu
activeId={project?.slug ?? project?.id}
- error={items.length === 0 ? error : undefined}
- isLoading={isLoading && items.length === 0}
+ error={listState === 'error' ? error : undefined}
+ isLoading={listState === 'loading'}
items={items}
kind={'project'}
searchPlaceholder={t('navPanel.searchProject', { ns: 'common' })}
diff --git a/src/features/Projects/List/index.tsx b/src/features/Projects/List/index.tsx
index 7b5871f058a..8653d49032c 100644
--- a/src/features/Projects/List/index.tsx
+++ b/src/features/Projects/List/index.tsx
@@ -33,11 +33,13 @@ import TopicCreatorAvatar from '@/features/TopicCreatorAvatar';
import UserAvatar from '@/features/User/UserAvatar';
import WideScreenContainer from '@/features/WideScreenContainer';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
-import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useLoadedProjectList, useProjectStore } from '@/store/project';
import type { ProjectListItem } from '@/store/project/store';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { resolveProjectListState } from '../projectListState';
+
const styles = createStaticStyles(({ css, cssVar }) => ({
actions: css`
flex: none;
@@ -196,15 +198,15 @@ const ProjectListPage = memo(() => {
const { t } = useTranslation('project');
const [keyword, setKeyword] = useState('');
const enabled = useUserStore(labPreferSelectors.enableProjects);
- const projects = useCurrentProjectList();
+ const projects = useLoadedProjectList();
const { error, isHydrated, isValidating, revalidate } = useProjectStore(
(s) => s.useFetchProjectList,
)(enabled);
- // Rows come from the store; the hook only reports fetch progress.
- const isLoading = !isHydrated || isValidating;
+ const listState = resolveProjectListState({ error, isHydrated, isValidating, projects });
const filteredProjects = useMemo(() => {
const normalizedKeyword = keyword.trim().toLocaleLowerCase();
+ if (!projects) return [];
return normalizedKeyword
? projects.filter((project) =>
[project.name, project.identifier, project.description]
@@ -238,9 +240,9 @@ const ProjectListPage = memo(() => {
{t('create.action')}
</Button>
</Flexbox>
- {error && projects.length === 0 ? (
+ {listState === 'error' ? (
<AsyncError error={error} onRetry={() => revalidate()} />
- ) : isLoading && projects.length === 0 ? (
+ ) : listState === 'loading' ? (
<SkeletonList rows={8} />
) : filteredProjects.length === 0 ? (
<Center flex={1} padding={48}>
diff --git a/src/features/Projects/projectListState.test.ts b/src/features/Projects/projectListState.test.ts
new file mode 100644
index 00000000000..c2b4dbea95c
--- /dev/null
+++ b/src/features/Projects/projectListState.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ProjectListItem } from '@/store/project';
+
+import { resolveProjectListState } from './projectListState';
+
+const project = { id: 'prj_1' } as ProjectListItem;
+const idle = { error: undefined, isHydrated: true, isValidating: false };
+
+describe('resolveProjectListState', () => {
+ it('shows the empty action, not a skeleton, while a confirmed-empty list revalidates', () => {
+ expect(resolveProjectListState({ ...idle, isValidating: true, projects: [] })).toBe('empty');
+ });
+
+ it('keeps rendering rows while they revalidate', () => {
+ expect(resolveProjectListState({ ...idle, isValidating: true, projects: [project] })).toBe(
+ 'ready',
+ );
+ });
+
+ it('shows the skeleton only until the list first loads', () => {
+ expect(resolveProjectListState({ ...idle, isHydrated: false, projects: undefined })).toBe(
+ 'loading',
+ );
+ expect(resolveProjectListState({ ...idle, isValidating: true, projects: undefined })).toBe(
+ 'loading',
+ );
+ });
+
+ it('surfaces a failed fetch when no rows are on screen', () => {
+ const error = new Error('offline');
+
+ expect(resolveProjectListState({ ...idle, error, projects: undefined })).toBe('error');
+ expect(resolveProjectListState({ ...idle, error, projects: [] })).toBe('error');
+ expect(resolveProjectListState({ ...idle, error, projects: [project] })).toBe('ready');
+ });
+});
diff --git a/src/features/Projects/projectListState.ts b/src/features/Projects/projectListState.ts
new file mode 100644
index 00000000000..41c6356d281
--- /dev/null
+++ b/src/features/Projects/projectListState.ts
@@ -0,0 +1,22 @@
+import type { ProjectListItem } from '@/store/project';
+
+export type ProjectListState = 'empty' | 'error' | 'loading' | 'ready';
+
+interface ResolveProjectListStateParams {
+ error: unknown;
+ isHydrated: boolean;
+ isValidating: boolean;
+ projects: ProjectListItem[] | undefined;
+}
+
+export const resolveProjectListState = ({
+ error,
+ isHydrated,
+ isValidating,
+ projects,
+}: ResolveProjectListStateParams): ProjectListState => {
+ if (projects && projects.length > 0) return 'ready';
+ if (error) return 'error';
+ if (projects === undefined && (!isHydrated || isValidating)) return 'loading';
+ return 'empty';
+};
diff --git a/src/libs/localDatabase/electronAdapter.test.ts b/src/libs/localDatabase/electronAdapter.test.ts
index 97f5738ae80..9607913a0c5 100644
--- a/src/libs/localDatabase/electronAdapter.test.ts
+++ b/src/libs/localDatabase/electronAdapter.test.ts
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
entriesByPrefix: vi.fn(),
get: vi.fn(),
initialize: vi.fn(),
+ listCollections: vi.fn(),
set: vi.fn(),
}));
@@ -31,6 +32,7 @@ describe('createElectronLocalDatabaseAdapter', () => {
vi.clearAllMocks();
mocks.initialize.mockResolvedValue(undefined);
+ mocks.listCollections.mockResolvedValue([{ entryCount: 2, name: 'cache' }]);
mocks.get.mockImplementation(async ({ collection, key }: DesktopLocalDatabaseKey) =>
records.get(recordKey(collection, key)),
);
@@ -90,5 +92,6 @@ describe('createElectronLocalDatabaseAdapter', () => {
{ key: 'scope::1', value: { id: 1 } },
{ key: 'scope::2', value: { id: 2 } },
]);
+ await expect(adapter.listCollections()).resolves.toEqual([{ entryCount: 2, name: 'cache' }]);
});
});
diff --git a/src/libs/localDatabase/electronAdapter.ts b/src/libs/localDatabase/electronAdapter.ts
index 643a26311f7..60d141197b3 100644
--- a/src/libs/localDatabase/electronAdapter.ts
+++ b/src/libs/localDatabase/electronAdapter.ts
@@ -39,6 +39,7 @@ export const createElectronLocalDatabaseAdapter = (): LocalDatabaseAdapter => ({
initialize: async () => {
await ensureElectronIpc().localDatabase.initialize();
},
+ listCollections: async () => ensureElectronIpc().localDatabase.listCollections(),
set: async (collection, key, value) => {
await ensureElectronIpc().localDatabase.set({
collection,
diff --git a/src/libs/localDatabase/index.test.ts b/src/libs/localDatabase/index.test.ts
index 7e0c6dcf35b..8da6e8f093f 100644
--- a/src/libs/localDatabase/index.test.ts
+++ b/src/libs/localDatabase/index.test.ts
@@ -40,6 +40,21 @@ describe('localDatabase', () => {
]);
});
+ it('discovers populated collections with current entry counts', async () => {
+ await localDatabase.batch([
+ { collection, key: 'first', type: 'set', value: 1 },
+ { collection, key: 'second', type: 'set', value: 2 },
+ { collection: otherCollection, key: 'only', type: 'set', value: 3 },
+ ]);
+
+ const collections = await localDatabase.listCollections();
+
+ expect(collections.filter(({ name }) => name.startsWith('database-test'))).toEqual([
+ { entryCount: 2, name: collection },
+ { entryCount: 1, name: otherCollection },
+ ]);
+ });
+
it('commits mixed writes and deletes as one batch', async () => {
await localDatabase.set(collection, 'legacy', { value: 'old' });
await localDatabase.batch([
@@ -59,15 +74,20 @@ describe('localDatabase', () => {
entriesByPrefix: vi.fn().mockResolvedValue([]),
get: vi.fn().mockResolvedValue({ source: 'electron' }),
initialize: vi.fn().mockResolvedValue(undefined),
+ listCollections: vi.fn().mockResolvedValue([{ entryCount: 1, name: 'runtime' }]),
set: vi.fn().mockResolvedValue(undefined),
};
const unregister = registerLocalDatabaseAdapter(adapter);
try {
await expect(localDatabase.get('runtime', 'key')).resolves.toEqual({ source: 'electron' });
+ await expect(localDatabase.listCollections()).resolves.toEqual([
+ { entryCount: 1, name: 'runtime' },
+ ]);
await localDatabase.set('runtime', 'key', { value: 1 });
expect(adapter.get).toHaveBeenCalledWith('runtime', 'key');
+ expect(adapter.listCollections).toHaveBeenCalledOnce();
expect(adapter.set).toHaveBeenCalledWith('runtime', 'key', { value: 1 });
} finally {
unregister();
diff --git a/src/libs/localDatabase/index.ts b/src/libs/localDatabase/index.ts
index 0d26a87598f..931a2b8eb4f 100644
--- a/src/libs/localDatabase/index.ts
+++ b/src/libs/localDatabase/index.ts
@@ -4,6 +4,7 @@ import type { LocalDatabaseAdapter, LocalDatabaseBatchOperation } from './types'
export type {
LocalDatabaseAdapter,
LocalDatabaseBatchOperation,
+ LocalDatabaseCollectionInfo,
LocalDatabaseEntry,
} from './types';
@@ -34,6 +35,7 @@ export const localDatabase = {
get: <T>(collection: string, key: string): Promise<T | undefined> =>
activeAdapter.get<T>(collection, key),
initialize: (): Promise<void> => activeAdapter.initialize(),
+ 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 3fbffe035c1..62548ee4705 100644
--- a/src/libs/localDatabase/indexedDBAdapter.ts
+++ b/src/libs/localDatabase/indexedDBAdapter.ts
@@ -7,6 +7,7 @@ import {
import type {
LocalDatabaseAdapter,
LocalDatabaseBatchOperation,
+ LocalDatabaseCollectionInfo,
LocalDatabaseEntry,
} from './types';
@@ -19,6 +20,11 @@ const COLLECTION_SEPARATOR = '\u0000';
const collectionPrefix = (collection: string) => `${collection}${COLLECTION_SEPARATOR}`;
const storageKey = (collection: string, key: string) => `${collectionPrefix(collection)}${key}`;
+const collectionFromStorageKey = (key: IDBValidKey): string | undefined => {
+ if (typeof key !== 'string') return undefined;
+ const separatorIndex = key.indexOf(COLLECTION_SEPARATOR);
+ return separatorIndex < 0 ? undefined : key.slice(0, separatorIndex);
+};
const storageRange = (collection: string, prefix: string) => {
const lowerBound = storageKey(collection, prefix);
return IDBKeyRange.bound(lowerBound, `${lowerBound}\uFFFF`);
@@ -172,6 +178,21 @@ export const createIndexedDBLocalDatabaseAdapter = (): LocalDatabaseAdapter => {
await getDatabase();
},
+ listCollections: async (): Promise<LocalDatabaseCollectionInfo[]> => {
+ const keys = await runTransaction<IDBValidKey[]>('readonly', (store) => store.getAllKeys());
+ const counts = new Map<string, number>();
+
+ for (const key of keys) {
+ const collection = collectionFromStorageKey(key);
+ if (collection === undefined) continue;
+ counts.set(collection, (counts.get(collection) ?? 0) + 1);
+ }
+
+ return [...counts.entries()]
+ .map(([name, entryCount]) => ({ entryCount, name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ },
+
set: async (collection: string, key: string, value: unknown): Promise<void> => {
await runTransaction('readwrite', (store) =>
store.put({ key: storageKey(collection, key), value } satisfies IndexedDBRecord),
diff --git a/src/libs/localDatabase/types.ts b/src/libs/localDatabase/types.ts
index 07eaa526386..0d5debfab10 100644
--- a/src/libs/localDatabase/types.ts
+++ b/src/libs/localDatabase/types.ts
@@ -3,6 +3,11 @@ export interface LocalDatabaseEntry<T = unknown> {
value: T;
}
+export interface LocalDatabaseCollectionInfo {
+ entryCount: number;
+ name: string;
+}
+
export type LocalDatabaseBatchOperation =
| {
collection: string;
@@ -29,5 +34,6 @@ export interface LocalDatabaseAdapter {
entriesByPrefix: <T>(collection: string, prefix: string) => Promise<LocalDatabaseEntry<T>[]>;
get: <T>(collection: string, key: string) => Promise<T | undefined>;
initialize: () => Promise<void>;
+ listCollections: () => Promise<LocalDatabaseCollectionInfo[]>;
set: (collection: string, key: string, value: unknown) => Promise<void>;
}
diff --git a/src/libs/replica/devtools.test.ts b/src/libs/replica/devtools.test.ts
new file mode 100644
index 00000000000..f9403f7a490
--- /dev/null
+++ b/src/libs/replica/devtools.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import {
+ getReplicaDevtoolsVersion,
+ listReplicaDevtools,
+ subscribeReplicaDevtools,
+} from './devtools';
+import {
+ createReplicaSlice,
+ createReplicaState,
+ defineReplica,
+ recordLens,
+ type ReplicaState,
+} from './index';
+
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));
+
+interface TestState {
+ lists: Record<string, string[]>;
+ listsReplica: ReplicaState<string[]>;
+}
+
+const createFixture = (name: string) => {
+ const resource = defineReplica<{ id: string }, string[]>({
+ key: ({ id }) => id,
+ name,
+ scope: { canPersist: () => false, get: () => 'user-1:personal', use: () => 'user-1:personal' },
+ storage: 'memory',
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+ const entry = () => listReplicaDevtools().find((item) => item.resource === resource)!;
+ return { entry, slice, store };
+};
+
+describe('replica devtools registry', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('exposes every app slice with its live entries and writes back through the slice', () => {
+ const { entry, slice, store } = createFixture('devtoolsList');
+
+ slice.update('a', () => ['one']);
+
+ expect(entry().keys()).toEqual(['a']);
+ expect(entry().read('a')).toEqual(['one']);
+ expect(entry().state()?.entries.a?.source).toBe('local');
+
+ entry().update('a', ['two'], { persist: false });
+ expect(store.getState().lists.a).toEqual(['two']);
+
+ entry().remove('a');
+ expect(entry().keys()).toEqual([]);
+ });
+
+ it('replaces the registration when a store is rebuilt for the same resource', () => {
+ createFixture('devtoolsRebuilt');
+ const { entry, slice } = createFixture('devtoolsRebuilt');
+
+ slice.update('b', () => ['fresh']);
+
+ expect(
+ listReplicaDevtools().filter(({ resource }) => resource.name === 'devtoolsRebuilt'),
+ ).toHaveLength(1);
+ expect(entry().read('b')).toEqual(['fresh']);
+ });
+
+ it('coalesces commits into one notification per interval, only while subscribed', () => {
+ const { slice } = createFixture('devtoolsNotify');
+ const idleVersion = getReplicaDevtoolsVersion();
+
+ slice.update('a', () => ['unobserved']);
+ vi.runAllTimers();
+ expect(getReplicaDevtoolsVersion()).toBe(idleVersion);
+
+ const listener = vi.fn();
+ const unsubscribe = subscribeReplicaDevtools(listener);
+
+ slice.update('a', () => ['one']);
+ slice.update('a', () => ['two']);
+ slice.update('b', () => ['three']);
+ expect(listener).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(200);
+ expect(listener).toHaveBeenCalledOnce();
+ expect(getReplicaDevtoolsVersion()).toBe(idleVersion + 1);
+
+ unsubscribe();
+ });
+});
diff --git a/src/libs/replica/devtools.ts b/src/libs/replica/devtools.ts
new file mode 100644
index 00000000000..b5e82e441e8
--- /dev/null
+++ b/src/libs/replica/devtools.ts
@@ -0,0 +1,85 @@
+import type { ReplicaResource, ReplicaState } from '@lobechat/replica';
+import type { ReplicaLens } from '@lobechat/replica/zustand';
+
+export interface ReplicaDevtoolsEntry {
+ keys: () => string[];
+ read: (key: string) => unknown;
+ remove: (key: string) => boolean;
+ resource: ReplicaResource<any, any, any>;
+ revalidate: (key?: string) => Promise<unknown>;
+ state: () => ReplicaState<unknown> | undefined;
+ update: (key: string, data: unknown, options: { persist: boolean }) => void;
+}
+
+interface DevtoolsSlice<TData> {
+ remove: (key: string) => boolean;
+ revalidate: (key?: string) => Promise<unknown>;
+ update: (
+ key: string,
+ apply: (data: TData | undefined) => TData | undefined,
+ options?: { persist?: boolean },
+ ) => unknown;
+}
+
+interface DevtoolsBinding<TStore, TData> {
+ get: () => TStore;
+ slice: DevtoolsSlice<TData>;
+ stateKey: keyof TStore & string;
+ view: ReplicaLens<TStore, TData>;
+}
+
+const NOTIFY_INTERVAL = 200;
+
+const entries = new Map<string, ReplicaDevtoolsEntry>();
+const listeners = new Set<() => void>();
+let version = 0;
+let timer: ReturnType<typeof setTimeout> | undefined;
+
+const flush = () => {
+ timer = undefined;
+ version += 1;
+ for (const listener of listeners) listener();
+};
+
+// Replica commits can fire many times per frame while a transcript streams, so
+// the inspector is told at most once per interval, and never while it is closed.
+export const notifyReplicaDevtools = () => {
+ if (listeners.size === 0 || timer) return;
+ timer = setTimeout(flush, NOTIFY_INTERVAL);
+};
+
+export const subscribeReplicaDevtools = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+export const getReplicaDevtoolsVersion = () => version;
+
+export const listReplicaDevtools = (): ReplicaDevtoolsEntry[] =>
+ [...entries.values()].sort((a, b) => a.resource.name.localeCompare(b.resource.name));
+
+// Keyed by namespace (name + version), which storage already requires to be
+// unique, so a store rebuilt by HMR or a test replaces its old registration.
+export const registerReplicaDevtools = <TStore, TData>(
+ resource: ReplicaResource<any, TData, any>,
+ { get, slice, stateKey, view }: DevtoolsBinding<TStore, TData>,
+) => {
+ const state = () => get()[stateKey] as unknown as ReplicaState<unknown> | undefined;
+
+ entries.set(resource.namespace, {
+ keys: () => [
+ ...new Set([...Object.keys(state()?.entries ?? {}), ...(view.keys?.(get()) ?? [])]),
+ ],
+ read: (key) => view.get(get(), key),
+ remove: (key) => slice.remove(key),
+ resource,
+ revalidate: (key) => slice.revalidate(key),
+ state,
+ update: (key, data, { persist }) => {
+ slice.update(key, () => data as TData, { persist });
+ },
+ });
+ notifyReplicaDevtools();
+};
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
index 7bd97200e2f..36a88e1f1b0 100644
--- a/src/libs/replica/index.ts
+++ b/src/libs/replica/index.ts
@@ -23,6 +23,8 @@ import {
import { mutate, useClientDataSWR } from '@/libs/swr';
import { getCacheScope, isScopeTrusted, useCacheScope } from '@/libs/swr/useCacheScope';
+import { notifyReplicaDevtools, registerReplicaDevtools } from './devtools';
+
/**
* LobeHub wiring of `@lobechat/replica`: replicas are partitioned like the SWR
* cache (`${userId}:${workspaceId}`), persist to IndexedDB by default and
@@ -157,7 +159,20 @@ export const readReplicaStoredKeys = async (
export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
resource: ReplicaResource<TParams, TData, TFetched>,
options: Omit<CreateReplicaSliceOptions<TStore, TParams, TData, TFetched>, 'driver'>,
-) => createCoreReplicaSlice(resource, { driver: replicaSWRDriver, ...options });
+) => {
+ const { get, set, stateKey, view } = options;
+ const slice = createCoreReplicaSlice(resource, {
+ driver: replicaSWRDriver,
+ ...options,
+ set: (partial, replace, action) => {
+ set(partial, replace, action);
+ notifyReplicaDevtools();
+ },
+ });
+
+ registerReplicaDevtools(resource, { get, slice, stateKey, view });
+ return slice;
+};
export * from '@lobechat/replica';
export {