Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(memory): browse processed episodes in Search (#1442)

rkrkrkkd230bb4417b0
diff --git a/docs/MEMORY.md b/docs/MEMORY.md
index ed9c90dae..d22a27d24 100644
--- a/docs/MEMORY.md
+++ b/docs/MEMORY.md
@@ -26,6 +26,12 @@ provider's opaque entry id as a future inspection handle. Listing does not add
Search/Get payloads to provider diagnostics and does not invoke LLM, embedding,
or reranking providers.
+In **Settings > Memory > Search**, leave the query empty to browse these
+episodes newest first. Choose one project or **All my projects**, use the page
+controls below the episode excerpts, then select a row to open its full detail.
+The **Entry ID** chip copies the provider's opaque identifier. Entering any
+non-empty query switches the same tab back to relevance-ordered search.
+
## Optional reranking endpoint
The third processing endpoint in **Settings > Memory** is optional. Configure
diff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.md
index 77684152c..b8180a79d 100644
--- a/docs/MEMORY_ZH.md
+++ b/docs/MEMORY_ZH.md
@@ -12,6 +12,11 @@ cursor 聚合同一用户的多个项目;Agent CLI 不能请求 `all`。JSON
entry id,作为未来检查入口。列表读取不会把 Search/Get 负载写入提供方诊断,也不会调用
LLM、Embedding 或重排序服务。
+在**设置 > 记忆 > 搜索**中留空查询,即可按最新优先浏览这些事件。可以选择单个项目或
+**我的全部项目**,通过事件摘要下方的页码切换页面,再选择一行打开完整详情。点击
+**条目 ID** 芯片会复制提供方的不透明标识符。输入任意非空查询后,同一标签页会切回按
+相关性排序的搜索结果。
+
## 处理预检与可选重排序端点
确认更改 Embedding 端点标识或重试待处理的重建前,Avibe 会分别执行一次有界的聊天
diff --git a/docs/plans/memory-list-1427.md b/docs/plans/memory-list-1427.md
index 70bf95c45..8a1de6fba 100644
--- a/docs/plans/memory-list-1427.md
+++ b/docs/plans/memory-list-1427.md
@@ -75,7 +75,28 @@ Failures produce `memory_list_partial`; deadline/provider-window limits produce
single-project listing, and focused unit/contract tests.
2. PR2 (after PR1 review pass): scoped internal route/client, CLI/i18n/docs,
UI-only aggregate cursor, parser contracts, and closed-loop scenarios.
-3. Browse UI remains out of scope until its design mockup is approved.
+3. PR3 (after PR2 review pass): extend the existing Search tab with the approved
+ browse state, UI API types, i18n, and component contracts.
+
+## Search tab browse state
+
+The owner-approved UI keeps the existing Processing Record / Profile / Search /
+Settings tabs. `MemorySearchPanel` switches by trimmed query value:
+
+- empty query: browse processed episodes in timestamp-descending order
+- non-empty query: retain the existing relevance-ordered search behavior
+
+Browse uses the same project catalog as search, including the UI-only `all`
+aggregate. Single-project pages use EverOS page numbers. For `all`, the client
+keeps the opaque cursor returned for each visited page so Previous, known page
+numbers, and Next remain navigable without interpreting the token. Project
+changes reset browse pagination.
+
+Each browse row shows its project, timestamp, and a bounded excerpt. Selecting a
+row opens a detail view with the episode body and a copy affordance for the
+opaque entry id. Loading, empty, partial/truncated, disabled, and closed-error
+states remain explicit. The sort control is fixed to Newest first because v1's
+provider-neutral contract exposes only timestamp ordering.
Scenario IDs are catalogued under `tests/scenarios/memory_list/`; the closed-loop
evidence captures processed episodes in one scoped project, lists them through
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 5bf1773a4..ff966b82d 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -65,6 +65,8 @@ capabilities:
- tests/test_internal_server.py
- tests/test_internal_client.py
- tests/test_memory_cli.py
+ - ui/src/components/settings/memory/MemorySearchPanel.test.tsx
+ - ui/src/context/ApiContext.memoryList.test.tsx
- id: memory_repair
name: Live Memory index repair via admitted artifact sync
status: active
diff --git a/tests/scenarios/memory_list/catalog.yaml b/tests/scenarios/memory_list/catalog.yaml
index 3756aa947..a52a6e15d 100644
--- a/tests/scenarios/memory_list/catalog.yaml
+++ b/tests/scenarios/memory_list/catalog.yaml
@@ -7,6 +7,8 @@ capability:
- tests/test_memory_runtime.py
- tests/test_internal_server.py
- tests/test_memory_cli.py
+ - ui/src/components/settings/memory/MemorySearchPanel.test.tsx
+ - ui/src/context/ApiContext.memoryList.test.tsx
status_legend:
covered: executable evidence exists
partial: contract coverage exists
@@ -41,3 +43,15 @@ scenarios:
kind: degradation
layer: contract
test: tests/test_memory_runtime.py::test_list_all_episodes_marks_partial_results_and_omits_total
+ - id: MEMORY-LIST-006
+ name: Empty Search query browses episodes with detail and a copyable entry id
+ status: covered
+ kind: happy_path
+ layer: contract
+ test: ui/src/components/settings/memory/MemorySearchPanel.test.tsx
+ - id: MEMORY-LIST-007
+ name: Non-empty Search query preserves relevance search behavior
+ status: covered
+ kind: compatibility
+ layer: contract
+ test: ui/src/components/settings/memory/MemorySearchPanel.test.tsx
diff --git a/tests/scenarios/memory_list/observations.yaml b/tests/scenarios/memory_list/observations.yaml
index cf2244af8..6a8aa55cc 100644
--- a/tests/scenarios/memory_list/observations.yaml
+++ b/tests/scenarios/memory_list/observations.yaml
@@ -15,3 +15,10 @@ observations:
scenarios:
- MEMORY-LIST-005
observation: Aggregate reads retain healthy project items while surfacing a closed warning and nullable total when another project fails.
+ - id: MEMORY-LIST-OBS-004
+ scenarios:
+ - MEMORY-LIST-003
+ - MEMORY-LIST-004
+ - MEMORY-LIST-006
+ - MEMORY-LIST-007
+ observation: The existing Search tab selects browse or relevance search solely from the trimmed query, while UI-only aggregate cursors remain opaque and entry ids are exposed only through a copy affordance.
diff --git a/ui/src/components/settings/memory/MemorySearchPanel.test.tsx b/ui/src/components/settings/memory/MemorySearchPanel.test.tsx
new file mode 100644
index 000000000..6b25b9a7c
--- /dev/null
+++ b/ui/src/components/settings/memory/MemorySearchPanel.test.tsx
@@ -0,0 +1,390 @@
+/* @vitest-environment jsdom */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import type { MemoryListItem, MemoryListWarning } from '../../../context/ApiContext';
+import { MemorySearchPanel } from './MemorySearchPanel';
+
+const apiHarness = vi.hoisted(() => {
+ const initial = {
+ listMemoryEpisodes: vi.fn(),
+ listMemoryProjects: vi.fn(),
+ searchMemory: vi.fn(),
+ };
+ return { current: initial, initial };
+});
+const api = apiHarness.initial;
+const copyTextToClipboard = vi.hoisted(() => vi.fn());
+const translate = vi.hoisted(() => (
+ key: string,
+ options?: Record<string, string | number>,
+) => {
+ if (options?.page != null && options?.total != null) {
+ return `${key}:${options.page}/${options.total}`;
+ }
+ if (options?.page != null) return `${key}:${options.page}`;
+ if (options?.count != null) return `${key}:${options.count}`;
+ if (options?.title != null) return `${key}:${options.title}`;
+ return key;
+});
+
+vi.mock('../../../context/ApiContext', async (loadOriginal) => {
+ const original = await loadOriginal<typeof import('../../../context/ApiContext')>();
+ return { ...original, useApi: () => apiHarness.current };
+});
+
+vi.mock('../../../lib/utils', async (loadOriginal) => {
+ const original = await loadOriginal<typeof import('../../../lib/utils')>();
+ return { ...original, copyTextToClipboard };
+});
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: translate }),
+}));
+
+const episode = (overrides: Partial<MemoryListItem> = {}): MemoryListItem => ({
+ id: 'entry-001',
+ kind: 'episode',
+ subject: 'Release planning',
+ summary: 'Compared the rollout options.',
+ body: 'Compared the rollout options and selected the staged release.',
+ timestamp: '2026-08-14T09:30:00Z',
+ project: 'default',
+ ...overrides,
+});
+
+const listResult = (
+ items: MemoryListItem[],
+ overrides: Partial<{
+ total_count: number | null;
+ next_cursor: string | null;
+ warnings: MemoryListWarning[];
+ }> = {},
+) => ({
+ status: 'ok' as const,
+ items,
+ count: items.length,
+ total_count: 0,
+ warnings: [],
+ page: 1,
+ page_size: 20,
+ next_cursor: null,
+ ...overrides,
+});
+
+beforeEach(() => {
+ apiHarness.current = api;
+ api.listMemoryProjects.mockResolvedValue({
+ status: 'ok',
+ projects: [
+ { id: 'default', kind: 'default' },
+ { id: 'all', kind: 'all' },
+ { id: 'notes', kind: 'named' },
+ ],
+ });
+ api.listMemoryEpisodes.mockResolvedValue(listResult([]));
+ api.searchMemory.mockResolvedValue({ status: 'ok', items: [], warnings: [] });
+ copyTextToClipboard.mockResolvedValue(true);
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('MemorySearchPanel browse and search modes', () => {
+ it('[MEMORY-LIST-004][MEMORY-LIST-006] browses a page boundary and copies the selected entry ID', async () => {
+ const first = episode();
+ const second = episode({ id: 'entry-021', subject: 'Follow-up', summary: '', body: 'Second page body.' });
+ api.listMemoryEpisodes.mockImplementation((_project: string, options: { page: number }) =>
+ Promise.resolve(options.page === 1
+ ? listResult([first], { total_count: 21 })
+ : listResult([second], { total_count: 21 })),
+ );
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+
+ expect(await screen.findByText(first.summary)).toBeTruthy();
+ expect(screen.getByLabelText('memory.search.browse.sortLabel')).toHaveProperty('value', 'newest');
+ expect(screen.getByLabelText('memory.search.browse.sortLabel')).toHaveProperty('disabled', false);
+ expect(api.listMemoryEpisodes).toHaveBeenCalledWith('default', {
+ page: 1,
+ cursor: null,
+ limit: 20,
+ });
+ expect(screen.queryByRole('button', { name: 'memory.search.browse.copyEntryId' })).toBeNull();
+ const firstRow = screen.getByRole('button', {
+ name: 'memory.search.browse.openDetail:Release planning',
+ });
+ expect(firstRow.getAttribute('aria-pressed')).toBe('false');
+ await user.click(firstRow);
+ expect(firstRow.getAttribute('aria-pressed')).toBe('true');
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.copyEntryId' }));
+ expect(copyTextToClipboard).toHaveBeenCalledWith(first.id);
+ expect(await screen.findByRole('button', { name: 'memory.search.browse.entryIdCopied' })).toBeTruthy();
+
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.next' }));
+ expect(await screen.findByText(second.subject)).toBeTruthy();
+ expect(screen.queryByText(second.body)).toBeNull();
+ await user.click(screen.getByRole('button', {
+ name: 'memory.search.browse.openDetail:Follow-up',
+ }));
+ expect(await screen.findByText(second.body)).toBeTruthy();
+ expect(api.listMemoryEpisodes).toHaveBeenLastCalledWith('default', {
+ page: 2,
+ cursor: null,
+ limit: 20,
+ });
+ expect((screen.getByRole('button', { name: 'memory.search.browse.next' }) as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it('[MEMORY-LIST-003] resumes the all-project aggregate with the opaque cursor', async () => {
+ const first = episode({ id: 'all-001', project: 'notes' });
+ const second = episode({ id: 'all-002', project: 'default', summary: 'Older aggregate episode.' });
+ api.listMemoryEpisodes.mockImplementation((project: string, options: { cursor: string | null }) => {
+ if (project !== 'all') return Promise.resolve(listResult([]));
+ return Promise.resolve(options.cursor === 'cursor-page-2'
+ ? listResult([second], { total_count: 21 })
+ : listResult([first], { total_count: 21, next_cursor: 'cursor-page-2' }));
+ });
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+
+ expect(await screen.findByText(first.summary)).toBeTruthy();
+ expect(api.listMemoryEpisodes).toHaveBeenLastCalledWith('all', {
+ page: 1,
+ cursor: null,
+ limit: 20,
+ });
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.next' }));
+ expect(await screen.findByText(second.summary)).toBeTruthy();
+ expect(api.listMemoryEpisodes).toHaveBeenLastCalledWith('all', {
+ page: 2,
+ cursor: 'cursor-page-2',
+ limit: 20,
+ });
+
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.previous' }));
+ await waitFor(() => expect(api.listMemoryEpisodes).toHaveBeenLastCalledWith('all', {
+ page: 1,
+ cursor: null,
+ limit: 20,
+ }));
+ });
+
+ it('[MEMORY-LIST-004] refetches the displayed page when the API identity changes', async () => {
+ const first = episode({ id: 'page-1', summary: 'Original first page.' });
+ const second = episode({ id: 'page-2', summary: 'Original second page.' });
+ api.listMemoryEpisodes.mockImplementation((_project: string, options: { page: number }) =>
+ Promise.resolve(options.page === 1
+ ? listResult([first], { total_count: 21 })
+ : listResult([second], { total_count: 21 })),
+ );
+ const user = userEvent.setup();
+ const view = render(<MemorySearchPanel enabled />);
+
+ await screen.findByText('Original first page.');
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.next' }));
+ await screen.findByText('Original second page.');
+
+ const replacementList = vi.fn().mockResolvedValue(listResult([
+ episode({ id: 'replacement-page-2', summary: 'Replacement second page.' }),
+ ], { total_count: 21 }));
+ apiHarness.current = { ...api, listMemoryEpisodes: replacementList };
+ view.rerender(<MemorySearchPanel enabled />);
+
+ expect(await screen.findByText('Replacement second page.')).toBeTruthy();
+ expect(replacementList).toHaveBeenCalledWith('default', {
+ page: 2,
+ cursor: null,
+ limit: 20,
+ });
+ expect(screen.getByText('memory.search.browse.pageSummary:2/2')).toBeTruthy();
+ });
+
+ it('[MEMORY-LIST-003] invalidates descendant aggregate cursors when an earlier page changes', async () => {
+ let pageOneReads = 0;
+ api.listMemoryEpisodes.mockImplementation((project: string, options: { cursor: string | null }) => {
+ if (project !== 'all') return Promise.resolve(listResult([]));
+ if (options.cursor === 'cursor-page-2') {
+ return Promise.resolve(listResult([
+ episode({ id: 'page-2', summary: 'Aggregate page two.' }),
+ ], { total_count: 60, next_cursor: 'cursor-page-3' }));
+ }
+ pageOneReads += 1;
+ return Promise.resolve(listResult([
+ episode({ id: `page-1-${pageOneReads}`, summary: 'Aggregate page one.' }),
+ ], {
+ total_count: 60,
+ next_cursor: pageOneReads === 1 ? 'cursor-page-2' : null,
+ }));
+ });
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+ await screen.findByText('Aggregate page one.');
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.next' }));
+ await screen.findByText('Aggregate page two.');
+ expect((screen.getByRole('button', { name: 'memory.search.browse.page:3' }) as HTMLButtonElement).disabled).toBe(false);
+
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.page:1' }));
+ await waitFor(() => expect(pageOneReads).toBe(2));
+ expect((screen.getByRole('button', { name: 'memory.search.browse.page:2' }) as HTMLButtonElement).disabled).toBe(true);
+ expect((screen.getByRole('button', { name: 'memory.search.browse.page:3' }) as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it('[MEMORY-LIST-003] keeps duplicate aggregate IDs distinct by project', async () => {
+ const defaultEpisode = episode({
+ id: 'shared-id',
+ project: 'default',
+ subject: 'Default episode',
+ summary: 'Default excerpt.',
+ body: 'Default detail body.',
+ });
+ const notesEpisode = episode({
+ id: 'shared-id',
+ project: 'notes',
+ subject: 'Notes episode',
+ summary: 'Notes excerpt.',
+ body: 'Notes detail body.',
+ });
+ api.listMemoryEpisodes.mockImplementation((project: string) => Promise.resolve(
+ project === 'all'
+ ? listResult([defaultEpisode, notesEpisode], { total_count: 2 })
+ : listResult([]),
+ ));
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+ const defaultRow = await screen.findByRole('button', {
+ name: 'memory.search.browse.openDetail:Default episode',
+ });
+ const notesRow = screen.getByRole('button', {
+ name: 'memory.search.browse.openDetail:Notes episode',
+ });
+ await user.click(notesRow);
+
+ expect(await screen.findByText('Notes detail body.')).toBeTruthy();
+ expect(screen.queryByText('Default detail body.')).toBeNull();
+ expect(defaultRow.getAttribute('aria-pressed')).toBe('false');
+ expect(notesRow.getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('[MEMORY-LIST-005] preserves retry and navigation controls after a page failure', async () => {
+ let pageTwoAttempts = 0;
+ api.listMemoryEpisodes.mockImplementation((project: string, options: { cursor: string | null }) => {
+ if (project !== 'all') return Promise.resolve(listResult([]));
+ if (options.cursor === 'cursor-page-2') {
+ pageTwoAttempts += 1;
+ return Promise.resolve(pageTwoAttempts === 1
+ ? { status: 'failed', error: 'memory_provider_timeout' }
+ : listResult([episode({ id: 'recovered-page', summary: 'Recovered page.' })], {
+ total_count: 21,
+ }));
+ }
+ return Promise.resolve(listResult([episode({ summary: 'First aggregate page.' })], {
+ total_count: 21,
+ next_cursor: 'cursor-page-2',
+ }));
+ });
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+ await screen.findByText('First aggregate page.');
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.next' }));
+
+ const retry = await screen.findByRole('button', { name: 'memory.search.browse.retry' });
+ expect((screen.getByRole('button', { name: 'memory.search.browse.previous' }) as HTMLButtonElement).disabled).toBe(false);
+ await user.click(retry);
+ expect(await screen.findByText('Recovered page.')).toBeTruthy();
+ expect(pageTwoAttempts).toBe(2);
+ });
+
+ it('[MEMORY-LIST-005] keeps an empty partial aggregate page resumable', async () => {
+ api.listMemoryEpisodes.mockImplementation((project: string, options: { cursor: string | null }) => {
+ if (project !== 'all') return Promise.resolve(listResult([]));
+ return Promise.resolve(options.cursor === 'retry-cursor'
+ ? listResult([episode({ id: 'recovered-entry', project: 'notes' })], { total_count: null })
+ : listResult([], {
+ total_count: null,
+ next_cursor: 'retry-cursor',
+ warnings: ['memory_list_partial'],
+ }));
+ });
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+
+ expect(await screen.findByText('memory.search.browse.partialEmpty')).toBeTruthy();
+ expect(screen.queryByText('memory.search.browse.empty')).toBeNull();
+ expect(screen.getByText('memory.search.browse.partial')).toBeTruthy();
+ await user.click(screen.getByRole('button', { name: 'memory.search.browse.next' }));
+
+ expect(await screen.findByText('Compared the rollout options.')).toBeTruthy();
+ expect(api.listMemoryEpisodes).toHaveBeenLastCalledWith('all', {
+ page: 2,
+ cursor: 'retry-cursor',
+ limit: 20,
+ });
+ });
+
+ it('[MEMORY-LIST-005] treats an empty truncated aggregate page as incomplete', async () => {
+ api.listMemoryEpisodes.mockImplementation((project: string) => Promise.resolve(
+ project === 'all'
+ ? listResult([], {
+ total_count: null,
+ next_cursor: 'retry-cursor',
+ warnings: ['memory_list_truncated'],
+ })
+ : listResult([]),
+ ));
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+
+ expect(await screen.findByText('memory.search.browse.partialEmpty')).toBeTruthy();
+ expect(screen.queryByText('memory.search.browse.empty')).toBeNull();
+ expect(screen.getByText('memory.search.browse.truncated')).toBeTruthy();
+ expect((screen.getByRole('button', { name: 'memory.search.browse.next' }) as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it('[MEMORY-LIST-007] keeps non-empty queries on the existing relevance search path', async () => {
+ api.searchMemory.mockResolvedValue({
+ status: 'ok',
+ items: [{
+ kind: 'episode',
+ text: 'The matching relevance-ranked memory.',
+ date: '2026-08-14',
+ project: 'notes',
+ }],
+ warnings: [],
+ });
+ const user = userEvent.setup();
+
+ render(<MemorySearchPanel enabled />);
+ await user.type(screen.getByPlaceholderText('memory.search.placeholder'), ' release plan ');
+ await user.selectOptions(await screen.findByLabelText('memory.search.projectLabel'), 'all');
+ await user.click(screen.getByRole('button', { name: 'memory.search.button' }));
+
+ expect(await screen.findByText('The matching relevance-ranked memory.')).toBeTruthy();
+ expect(api.searchMemory).toHaveBeenCalledWith('release plan', 20, 'all');
+ });
+
+ it('shows the Memory-closed state without issuing list calls', () => {
+ render(<MemorySearchPanel enabled={false} />);
+
+ expect(screen.getByText('memory.search.browse.closedTitle')).toBeTruthy();
+ expect(screen.getByText('memory.search.browse.closedDescription')).toBeTruthy();
+ expect(api.listMemoryEpisodes).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/settings/memory/MemorySearchPanel.tsx b/ui/src/components/settings/memory/MemorySearchPanel.tsx
index 1f1c8adf1..827ac3b0f 100644
--- a/ui/src/components/settings/memory/MemorySearchPanel.tsx
+++ b/ui/src/components/settings/memory/MemorySearchPanel.tsx
@@ -1,43 +1,131 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Loader2, Search as SearchIcon } from 'lucide-react';
+import {
+ Check,
+ ChevronLeft,
+ ChevronRight,
+ Copy,
+ Loader2,
+ RotateCw,
+ Search as SearchIcon,
+} from 'lucide-react';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
+import { Card, CardContent } from '../../ui/card';
import { Input } from '../../ui/input';
import { Select } from '../../ui/select';
import { useApi } from '../../../context/ApiContext';
-import type { MemoryRecallResult } from '../../../context/ApiContext';
+import type {
+ MemoryListItem,
+ MemoryListResult,
+ MemoryRecallResult,
+} from '../../../context/ApiContext';
+import { copyTextToClipboard } from '../../../lib/utils';
import { useMemoryResource } from './useMemoryResource';
type MemoryItemsOk = Extract<MemoryRecallResult, { status: 'ok' }>;
+type MemoryListOk = Extract<MemoryListResult, { status: 'ok' }>;
+
+const PAGE_SIZE = 20;
+const FALLBACK_PROJECTS = [
+ { id: 'default', kind: 'default' as const },
+ { id: 'all', kind: 'all' as const },
+];
+
+function episodeExcerpt(item: MemoryListItem): string {
+ return item.summary || item.subject || item.body;
+}
+
+function episodeTitle(item: MemoryListItem): string {
+ return item.subject || item.summary || item.body;
+}
+
+function episodeIdentity(item: MemoryListItem): string {
+ return JSON.stringify([item.project, item.id]);
+}
+
+function formatEpisodeTimestamp(value: string): string {
+ const instant = new Date(value);
+ if (Number.isNaN(instant.getTime())) return value;
+ const pad = (part: number) => String(part).padStart(2, '0');
+ return `${instant.getFullYear()}-${pad(instant.getMonth() + 1)}-${pad(instant.getDate())} · ${pad(instant.getHours())}:${pad(instant.getMinutes())}`;
+}
+
+function visiblePageNumbers(current: number, total: number): number[] {
+ const width = Math.min(5, total);
+ const start = Math.max(1, Math.min(current - 2, total - width + 1));
+ return Array.from({ length: width }, (_, index) => start + index);
+}
export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) => {
const { t } = useTranslation();
const api = useApi();
const [query, setQuery] = useState('');
const [project, setProject] = useState('default');
- const [projects, setProjects] = useState<Array<{ id: string; kind: string }>>([
- { id: 'default', kind: 'default' },
- { id: 'all', kind: 'all' },
- ]);
- const read = useCallback(
- (text: string, selected: string) => api.searchMemory(text, 20, selected),
+ const [projects, setProjects] = useState<Array<{ id: string; kind: string }>>(
+ FALLBACK_PROJECTS,
+ );
+ const [browsePage, setBrowsePage] = useState(1);
+ const [cursorByPage, setCursorByPage] = useState<Record<number, string | null>>({ 1: null });
+ const browseRequestRef = useRef(0);
+ const browsePositionRef = useRef({ project: 'default', page: 1, cursor: null as string | null });
+ const [selectedEpisodeKey, setSelectedEpisodeKey] = useState<string | null>(null);
+ const [copiedEpisodeKey, setCopiedEpisodeKey] = useState<string | null>(null);
+ const browseMode = !query.trim();
+
+ const searchRead = useCallback(
+ (text: string, selected: string) => api.searchMemory(text, PAGE_SIZE, selected),
[api],
);
const {
- data,
- error,
+ data: searchData,
+ error: searchError,
loading: searching,
loaded: searched,
reload: search,
} = useMemoryResource<MemoryItemsOk, [string, string]>({
- read,
+ read: searchRead,
failureMessageKey: 'memory.search.searchFailed',
clearErrorOnReload: true,
resetDataOnError: true,
});
+ const browseRead = useCallback(
+ async (selected: string, page: number, cursor: string | null) => {
+ const request = ++browseRequestRef.current;
+ const result = await api.listMemoryEpisodes(selected, { page, cursor, limit: PAGE_SIZE });
+ if (
+ request === browseRequestRef.current
+ && selected === 'all'
+ && result.status === 'ok'
+ ) {
+ setCursorByPage((current) => {
+ const next = Object.fromEntries(
+ Object.entries(current).filter(([knownPage]) => Number(knownPage) <= page),
+ );
+ if (result.next_cursor) next[page + 1] = result.next_cursor;
+ return next;
+ });
+ }
+ return result;
+ },
+ [api],
+ );
+ const {
+ data: browseData,
+ error: browseError,
+ loading: browsing,
+ loaded: browsed,
+ reload: browse,
+ } = useMemoryResource<MemoryListOk, [string, number, string | null]>({
+ read: browseRead,
+ failureMessageKey: 'memory.search.browse.loadFailed',
+ enabled,
+ clearErrorOnReload: true,
+ resetDataOnError: true,
+ });
+
useEffect(() => {
if (!enabled) return;
void api
@@ -47,36 +135,155 @@ export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) =
setProjects(result.projects);
}
})
- .catch(() => {
- setProjects([
- { id: 'default', kind: 'default' },
- { id: 'all', kind: 'all' },
- ]);
- });
+ .catch(() => setProjects(FALLBACK_PROJECTS));
}, [api, enabled]);
+ useEffect(() => {
+ if (!enabled || !browseMode) return;
+ const position = browsePositionRef.current;
+ const page = position.project === project ? position.page : 1;
+ const cursor = position.project === project ? position.cursor : null;
+ browsePositionRef.current = { project, page, cursor };
+ void browse(project, page, cursor);
+ }, [browse, browseMode, enabled, project]);
+
+ const resetBrowseNavigation = (selectedProject = project) => {
+ browseRequestRef.current += 1;
+ browsePositionRef.current = { project: selectedProject, page: 1, cursor: null };
+ setCursorByPage({ 1: null });
+ setBrowsePage(1);
+ setSelectedEpisodeKey(null);
+ setCopiedEpisodeKey(null);
+ };
+
const runSearch = () => {
const trimmed = query.trim();
if (!trimmed) return;
void search(trimmed, project);
};
+ const goToBrowsePage = (nextPage: number) => {
+ if (nextPage < 1 || nextPage === browsePage) return;
+ const cursor = project === 'all' ? cursorByPage[nextPage] : null;
+ if (project === 'all' && cursor === undefined) return;
+ browsePositionRef.current = { project, page: nextPage, cursor };
+ setBrowsePage(nextPage);
+ setSelectedEpisodeKey(null);
+ setCopiedEpisodeKey(null);
+ void browse(project, nextPage, cursor);
+ };
+
+ const retryBrowsePage = () => {
+ const cursor = project === 'all' ? cursorByPage[browsePage] : null;
+ if (project === 'all' && cursor === undefined) return;
+ browsePositionRef.current = { project, page: browsePage, cursor };
+ setSelectedEpisodeKey(null);
+ setCopiedEpisodeKey(null);
+ void browse(project, browsePage, cursor);
+ };
+
+ const searchItems = searchData?.items ?? null;
+ const searchWarnings = searchData?.warnings ?? [];
+ const browseItems = browseData?.items ?? [];
+ const browseIncomplete = browseData?.warnings.some(
+ (warning) => warning === 'memory_list_partial' || warning === 'memory_list_truncated',
+ ) ?? false;
+ const selectedEpisode = selectedEpisodeKey
+ ? (browseItems.find((item) => episodeIdentity(item) === selectedEpisodeKey) ?? null)
+ : null;
+ const knownPageCount = Math.max(1, ...Object.keys(cursorByPage).map(Number));
+ const totalPages = browseData?.total_count != null
+ ? Math.max(1, Math.ceil(browseData.total_count / PAGE_SIZE))
+ : Math.max(knownPageCount, browsePage + (browseData?.next_cursor ? 1 : 0));
+ const hasNextBrowsePage = project === 'all'
+ ? Boolean(browseData?.next_cursor)
+ : browsePage < totalPages;
+ const pageNumbers = useMemo(
+ () => visiblePageNumbers(browsePage, totalPages),
+ [browsePage, totalPages],
+ );
+ const browsePagination = (
+ <nav className="flex flex-wrap items-center justify-center gap-1.5" aria-label={t('memory.search.browse.episodes')}>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => goToBrowsePage(browsePage - 1)}
+ disabled={browsePage <= 1 || browsing}
+ aria-label={t('memory.search.browse.previous')}
+ >
+ <ChevronLeft className="size-3.5" />
+ </Button>
+ {pageNumbers.map((page) => {
+ const available = project !== 'all' || cursorByPage[page] !== undefined;
+ return (
+ <Button
+ key={page}
+ variant={page === browsePage ? 'default' : 'secondary'}
+ size="icon"
+ className="text-[13px]"
+ onClick={() => goToBrowsePage(page)}
+ disabled={!available || browsing}
+ aria-current={page === browsePage ? 'page' : undefined}
+ aria-label={t('memory.search.browse.page', { page })}
+ >
+ {page}
+ </Button>
+ );
+ })}
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => goToBrowsePage(browsePage + 1)}
+ disabled={!hasNextBrowsePage || browsing}
+ aria-label={t('memory.search.browse.next')}
+ >
+ <ChevronRight className="size-3.5" />
+ </Button>
+ </nav>
+ );
+
if (!enabled) {
- return <div className="rounded-2xl border border-dashed border-border bg-surface p-8 text-center text-sm text-muted">{t('memory.search.disabledHint')}</div>;
+ return (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-5 py-4">
+ <p className="text-[13px] font-semibold text-destructive-ink">
+ {t('memory.search.browse.closedTitle')}
+ </p>
+ <p className="mt-1 text-[12.5px] text-muted">
+ {t('memory.search.browse.closedDescription')}
+ </p>
+ </div>
+ );
}
- const items = data?.items ?? null;
- const warnings = data?.warnings ?? [];
-
return (
- <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-4">
<p className="text-[12.5px] text-muted">{t('memory.search.description')}</p>
- <div className="flex flex-col gap-2 sm:flex-row">
+ <div className="flex flex-col gap-2 lg:flex-row">
+ <div className="relative min-w-0 flex-1">
+ <SearchIcon size={15} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted" />
+ <Input
+ value={query}
+ onChange={(event) => {
+ const nextQuery = event.target.value;
+ if (!nextQuery.trim() && !browseMode) resetBrowseNavigation();
+ setQuery(nextQuery);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') runSearch();
+ }}
+ placeholder={t('memory.search.placeholder')}
+ className="pl-9 text-[13px]"
+ />
+ </div>
<Select
value={project}
- onChange={(event) => setProject(event.target.value)}
+ onChange={(event) => {
+ const nextProject = event.target.value;
+ if (browseMode) resetBrowseNavigation(nextProject);
+ setProject(nextProject);
+ }}
aria-label={t('memory.search.projectLabel')}
- wrapperClassName="sm:w-52"
+ wrapperClassName="lg:w-52"
>
{projects.map((row) => (
<option key={row.id} value={row.id}>
@@ -88,53 +295,189 @@ export const MemorySearchPanel: React.FC<{ enabled: boolean }> = ({ enabled }) =
</option>
))}
</Select>
- <div className="relative flex-1">
- <SearchIcon size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted" />
- <Input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') runSearch();
- }}
- placeholder={t('memory.search.placeholder')}
- className="pl-9 text-[13px]"
- />
- </div>
- <Button onClick={runSearch} disabled={searching || !query.trim()}>
- {searching ? <Loader2 className="size-3.5 animate-spin" /> : null}
- {searching ? t('memory.search.searching') : t('memory.search.button')}
- </Button>
+ {browseMode ? (
+ <Select
+ value="newest"
+ onChange={() => undefined}
+ aria-label={t('memory.search.browse.sortLabel')}
+ wrapperClassName="lg:w-44"
+ >
+ <option value="newest">{t('memory.search.browse.newestFirst')}</option>
+ </Select>
+ ) : (
+ <Button onClick={runSearch} disabled={searching || !query.trim()}>
+ {searching ? <Loader2 className="size-3.5 animate-spin" /> : <SearchIcon className="size-3.5" />}
+ {searching ? t('memory.search.searching') : t('memory.search.button')}
+ </Button>
+ )}
</div>
- {warnings.includes('memory_search_partial') ? (
- <div className="rounded-xl border border-border bg-surface px-4 py-3 text-sm text-muted">{t('memory.search.partial')}</div>
- ) : null}
- {warnings.includes('memory_search_truncated') ? (
- <div className="rounded-xl border border-border bg-surface px-4 py-3 text-sm text-muted">{t('memory.search.truncated')}</div>
- ) : null}
- {error ? (
- <div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">{error}</div>
- ) : !searched ? null : !items || items.length === 0 ? (
- <div className="rounded-2xl border border-dashed border-border bg-surface p-8 text-center text-sm text-muted">
- {t('memory.search.empty')}
- </div>
- ) : (
- <div className="flex flex-col gap-2">
- {items.map((item, idx) => (
- <div key={idx} className="rounded-xl border border-border bg-surface px-4 py-3">
- <div className="mb-1 flex items-center gap-2">
- <Badge variant="secondary">{t(`memory.kind.${item.kind}`)}</Badge>
- {item.project && (project === 'all' || item.project !== 'default') ? (
- <Badge variant="outline">
- {item.project === 'default' ? t('memory.search.projectDefault') : item.project}
- </Badge>
- ) : null}
- {item.date ? <span className="font-mono text-[10.5px] text-muted">{item.date}</span> : null}
+
+ {browseMode ? (
+ <>
+ {browseData?.warnings.includes('memory_list_partial') ? (
+ <div className="rounded-lg border border-border bg-surface px-4 py-3 text-sm text-muted">
+ {t('memory.search.browse.partial')}
+ </div>
+ ) : null}
+ {browseData?.warnings.includes('memory_list_truncated') ? (
+ <div className="rounded-lg border border-border bg-surface px-4 py-3 text-sm text-muted">
+ {t('memory.search.browse.truncated')}
+ </div>
+ ) : null}
+ {browseError ? (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">
+ {browseError}
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ <Button variant="secondary" size="sm" onClick={retryBrowsePage}>
+ <RotateCw className="size-3.5" />
+ {t('memory.search.browse.retry')}
+ </Button>
+ {browsePagination}
</div>
- <p className="whitespace-pre-wrap text-[13px] leading-relaxed text-foreground">{item.text}</p>
</div>
- ))}
- <p className="px-1 text-[11px] text-muted">{t('memory.search.sourceNote')}</p>
- </div>
+ ) : browsing || !browsed ? (
+ <div className="flex min-h-32 items-center justify-center gap-2 rounded-lg border border-border bg-surface text-sm text-muted">
+ <Loader2 className="size-4 animate-spin text-mint-ink" />
+ {t('memory.search.browse.loading')}
+ </div>
+ ) : browseItems.length === 0 ? (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-lg border border-dashed border-border bg-surface p-8 text-center text-sm text-muted">
+ {project === 'all' && browseIncomplete
+ ? t('memory.search.browse.partialEmpty')
+ : t('memory.search.browse.empty')}
+ </div>
+ {browsePage > 1 || hasNextBrowsePage ? browsePagination : null}
+ </div>
+ ) : (
+ <section className="flex flex-col gap-3" aria-labelledby="memory-browse-title">
+ <div className="flex flex-wrap items-end justify-between gap-2">
+ <h3 id="memory-browse-title" className="text-[14px] font-semibold text-foreground">
+ {t('memory.search.browse.episodes')}
+ </h3>
+ <div className="flex items-center gap-2 font-mono text-[10.5px] uppercase text-muted">
+ {browseData?.total_count != null ? (
+ <span>{t('memory.search.browse.total', { count: browseData.total_count })}</span>
+ ) : null}
+ <span>{t('memory.search.browse.pageSummary', { page: browsePage, total: totalPages })}</span>
+ </div>
+ </div>
+ <div className="overflow-hidden rounded-lg border border-border bg-surface">
+ {browseItems.map((item) => {
+ const itemKey = episodeIdentity(item);
+ const selected = itemKey === selectedEpisodeKey;
+ return (
+ <button
+ key={itemKey}
+ type="button"
+ onClick={() => {
+ setSelectedEpisodeKey(itemKey);
+ setCopiedEpisodeKey(null);
+ }}
+ aria-pressed={selected}
+ aria-label={t('memory.search.browse.openDetail', { title: episodeTitle(item) })}
+ className={`block w-full border-b border-border px-4 py-3 text-left last:border-b-0 hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring ${selected ? 'bg-mint/[0.06]' : ''}`}
+ >
+ <div className="mb-1.5 flex items-center justify-between gap-3">
+ <Badge variant={selected ? 'success' : 'outline'} className="max-w-[60%] truncate font-mono text-[9.5px] uppercase">
+ {item.project === 'default' ? t('memory.search.projectDefault') : item.project}
+ </Badge>
+ <time dateTime={item.timestamp} className="shrink-0 font-mono text-[10.5px] text-muted">
+ {formatEpisodeTimestamp(item.timestamp)}
+ </time>
+ </div>
+ <p className="line-clamp-2 text-[13px] leading-relaxed text-foreground">
+ {episodeExcerpt(item)}
+ </p>
+ </button>
+ );
+ })}
+ </div>
+
+ {browsePagination}
+
+ {selectedEpisode ? (
+ <Card aria-labelledby="memory-episode-detail-title">
+ <CardContent className="flex flex-col gap-3 p-4">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <p id="memory-episode-detail-title" className="text-[13px] font-semibold text-foreground">
+ {t('memory.search.browse.detailTitle')}
+ </p>
+ <p className="mt-1 text-[11px] text-muted">{episodeTitle(selectedEpisode)}</p>
+ </div>
+ <time dateTime={selectedEpisode.timestamp} className="font-mono text-[10.5px] text-muted">
+ {formatEpisodeTimestamp(selectedEpisode.timestamp)}
+ </time>
+ </div>
+ <p className="whitespace-pre-wrap text-[13px] leading-relaxed text-foreground">
+ {selectedEpisode.body}
+ </p>
+ <div className="flex flex-wrap items-center gap-2 border-t border-border pt-3">
+ <span className="font-mono text-[10px] uppercase text-muted">
+ {t('memory.search.browse.entryId')}
+ </span>
+ <Button
+ variant="secondary"
+ size="xs"
+ className="max-w-full font-mono"
+ onClick={() => {
+ void copyTextToClipboard(selectedEpisode.id).then((copied) => {
+ if (copied) setCopiedEpisodeKey(episodeIdentity(selectedEpisode));
+ });
+ }}
+ aria-label={copiedEpisodeKey === episodeIdentity(selectedEpisode)
+ ? t('memory.search.browse.entryIdCopied')
+ : t('memory.search.browse.copyEntryId')}
+ >
+ <span className="max-w-[min(60vw,28rem)] truncate">{selectedEpisode.id}</span>
+ {copiedEpisodeKey === episodeIdentity(selectedEpisode)
+ ? <Check className="size-3.5 text-mint-ink" />
+ : <Copy className="size-3.5" />}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ ) : null}
+ </section>
+ )}
+ </>
+ ) : (
+ <>
+ {searchWarnings.includes('memory_search_partial') ? (
+ <div className="rounded-lg border border-border bg-surface px-4 py-3 text-sm text-muted">{t('memory.search.partial')}</div>
+ ) : null}
+ {searchWarnings.includes('memory_search_truncated') ? (
+ <div className="rounded-lg border border-border bg-surface px-4 py-3 text-sm text-muted">{t('memory.search.truncated')}</div>
+ ) : null}
+ {searchError ? (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">{searchError}</div>
+ ) : !searched ? null : !searchItems || searchItems.length === 0 ? (
+ <div className="rounded-lg border border-dashed border-border bg-surface p-8 text-center text-sm text-muted">
+ {t('memory.search.empty')}
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {searchItems.map((item, index) => (
+ <div key={index} className="rounded-lg border border-border bg-surface px-4 py-3">
+ <div className="mb-1 flex items-center gap-2">
+ <Badge variant="secondary">{t(`memory.kind.${item.kind}`)}</Badge>
+ {item.project && (project === 'all' || item.project !== 'default') ? (
+ <Badge variant="outline">
+ {item.project === 'default' ? t('memory.search.projectDefault') : item.project}
+ </Badge>
+ ) : null}
+ {item.date ? <span className="font-mono text-[10.5px] text-muted">{item.date}</span> : null}
+ </div>
+ <p className="whitespace-pre-wrap text-[13px] leading-relaxed text-foreground">{item.text}</p>
+ </div>
+ ))}
+ <p className="px-1 text-[11px] text-muted">{t('memory.search.sourceNote')}</p>
+ </div>
+ )}
+ </>
)}
</div>
);
diff --git a/ui/src/context/ApiContext.memoryList.test.tsx b/ui/src/context/ApiContext.memoryList.test.tsx
new file mode 100644
index 000000000..d79dea400
--- /dev/null
+++ b/ui/src/context/ApiContext.memoryList.test.tsx
@@ -0,0 +1,74 @@
+/* @vitest-environment jsdom */
+
+import { useEffect } from 'react';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/apiFetch', () => ({ apiFetch }));
+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { ApiProvider, useApi } from './ApiContext';
+
+let capturedApi: ReturnType<typeof useApi> | null = null;
+
+const CaptureApi = () => {
+ const api = useApi();
+ useEffect(() => {
+ capturedApi = api;
+ }, [api]);
+ return null;
+};
+
+beforeEach(() => {
+ capturedApi = null;
+ window.localStorage.clear();
+ apiFetch.mockReset();
+ apiFetch.mockResolvedValue(new Response(JSON.stringify({
+ status: 'ok',
+ items: [],
+ count: 0,
+ total_count: 0,
+ warnings: [],
+ }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }));
+});
+
+afterEach(() => {
+ cleanup();
+ window.localStorage.clear();
+});
+
+describe('ApiProvider Memory listing transport', () => {
+ it('[MEMORY-LIST-003][MEMORY-LIST-004] keeps page and aggregate cursor payloads distinct', async () => {
+ render(<ApiProvider><CaptureApi /></ApiProvider>);
+ await waitFor(() => expect(capturedApi).not.toBeNull());
+
+ await capturedApi!.listMemoryEpisodes('notes', {
+ page: 3,
+ cursor: 'ignored-for-single-project',
+ limit: 7,
+ });
+ await capturedApi!.listMemoryEpisodes('all', {
+ page: 9,
+ cursor: 'opaque-page-2',
+ limit: 20,
+ });
+ await capturedApi!.listMemoryEpisodes('all');
+
+ expect(apiFetch.mock.calls.map(([path, init]) => ({
+ path,
+ body: JSON.parse(String(init?.body)),
+ }))).toEqual([
+ { path: '/api/memory/list', body: { project: 'notes', limit: 7, page: 3 } },
+ { path: '/api/memory/list', body: { project: 'all', limit: 20, cursor: 'opaque-page-2' } },
+ { path: '/api/memory/list', body: { project: 'all', limit: 20 } },
+ ]);
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 7967323bb..424135643 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -566,6 +566,10 @@ export type ApiContextType = {
getMemoryMaintenance: () => Promise<MemoryMaintenanceResult>;
getMemoryProfile: () => Promise<MemoryItemsResult>;
searchMemory: (query: string, limit?: number, project?: string) => Promise<MemoryRecallResult>;
+ listMemoryEpisodes: (
+ project: string,
+ options?: { page?: number; cursor?: string | null; limit?: number },
+ ) => Promise<MemoryListResult>;
listMemoryProjects: () => Promise<{ status: 'ok'; projects: Array<{ id: string; kind: 'default' | 'named' | 'all' }> } | { status: 'failed'; error?: string }>;
getMemoryLog: (cursor?: string | null, limit?: number) => Promise<MemoryLogListResult>;
getMemoryLogEntry: (memcellId: string) => Promise<MemoryLogDetailResult>;
@@ -2031,6 +2035,31 @@ export type MemoryRecallResult =
}
| MemoryFailure;
+export type MemoryListWarning = 'memory_list_partial' | 'memory_list_truncated';
+
+export type MemoryListItem = {
+ id: string;
+ kind: 'episode';
+ subject: string;
+ summary: string;
+ body: string;
+ timestamp: string;
+ project: string;
+};
+
+export type MemoryListResult =
+ | {
+ status: 'ok';
+ items: MemoryListItem[];
+ count: number;
+ total_count: number | null;
+ warnings: MemoryListWarning[];
+ page?: number;
+ page_size?: number;
+ next_cursor?: string | null;
+ }
+ | MemoryFailure;
+
export type MemoryLogSourceStatus = {
status: 'available' | 'partial' | 'stale' | 'unknown' | 'unavailable';
observed_at: string | null;
@@ -3330,6 +3359,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
},
...(project ? { project } : {}),
}, { handleError: false }),
+ listMemoryEpisodes: (project, options = {}) => {
+ const limit = options.limit ?? 20;
+ return postJson('/api/memory/list', {
+ project,
+ limit,
+ ...(project === 'all'
+ ? (options.cursor ? { cursor: options.cursor } : {})
+ : { page: options.page ?? 1 }),
+ }, { handleError: false });
+ },
listMemoryProjects: () => getJson('/api/memory/projects', { handleError: false }),
getMemoryLog: (cursor = null, limit = 20) => {
const query = new URLSearchParams({ limit: String(limit) });
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fc1a658d2..78b456a39 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4264,19 +4264,43 @@
"sourceNote": "Distilled from your conversation history, plus any notes your Agent recorded."
},
"search": {
- "description": "Search your Memory. Conversations are stored in Default unless an Agent saved a fact to a named project.",
- "placeholder": "Search your memory…",
+ "description": "Search your Memory, or leave the query empty to browse processed episodes. Conversations are stored in Default unless an Agent saved a fact to a named project.",
+ "placeholder": "Search memories — empty shows everything",
"button": "Search",
"searching": "Searching…",
"empty": "No results.",
"searchFailed": "Search failed.",
- "disabledHint": "Enable Memory to search.",
+ "disabledHint": "Enable Memory to search or browse.",
"sourceNote": "Distilled from your conversation history, plus any notes your Agent recorded.",
"projectLabel": "Memory project",
"projectDefault": "Default",
"projectAll": "All my projects",
"partial": "Some projects could not be searched. These results may be incomplete.",
- "truncated": "Search stopped before every project was checked. These results may be incomplete."
+ "truncated": "Search stopped before every project was checked. These results may be incomplete.",
+ "browse": {
+ "sortLabel": "Episode order",
+ "newestFirst": "Newest first",
+ "episodes": "Episodes",
+ "loading": "Loading episodes…",
+ "empty": "No processed episodes in this project yet.",
+ "partialEmpty": "Episodes may exist in projects that could not be loaded. Continue or retry this page.",
+ "loadFailed": "Couldn't load episodes.",
+ "retry": "Retry page",
+ "closedTitle": "Memory closed",
+ "closedDescription": "Memory is unavailable. Enable it from Settings and try again.",
+ "partial": "Some projects could not be loaded. This page may be incomplete.",
+ "truncated": "Listing stopped before every episode was checked. This page may be incomplete.",
+ "total": "{{count}} episodes",
+ "pageSummary": "Page {{page}} of {{total}}",
+ "previous": "Previous page",
+ "next": "Next page",
+ "page": "Page {{page}}",
+ "detailTitle": "Episode detail",
+ "entryId": "Entry ID",
+ "copyEntryId": "Copy entry ID",
+ "entryIdCopied": "Entry ID copied",
+ "openDetail": "Open episode: {{title}}"
+ }
},
"log": {
"description": "See the processing history for created Memory entries across every user and project on this installation.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 188cc3b78..15eff596c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4264,19 +4264,43 @@
"sourceNote": "由你的对话历史,以及 Agent 记录的内容(如有)提炼而来。"
},
"search": {
- "description": "搜索你的记忆。对话默认写入 Default;只有 Agent 显式指定时才会进命名项目。",
- "placeholder": "搜索你的记忆…",
+ "description": "搜索你的记忆,或留空查询以浏览已处理的记忆片段。对话默认写入 Default;只有 Agent 显式指定时才会写入命名项目。",
+ "placeholder": "搜索记忆——留空显示全部",
"button": "搜索",
"searching": "搜索中…",
"empty": "没有结果。",
"searchFailed": "搜索失败。",
- "disabledHint": "启用记忆后即可搜索。",
+ "disabledHint": "启用记忆后即可搜索或浏览。",
"sourceNote": "由你的对话历史,以及 Agent 记录的内容(如有)提炼而来。",
"projectLabel": "记忆项目",
"projectDefault": "默认",
"projectAll": "我的全部项目",
"partial": "部分项目未能搜索,结果可能不完整。",
- "truncated": "搜索在查完所有项目前停止,结果可能不完整。"
+ "truncated": "搜索在查完所有项目前停止,结果可能不完整。",
+ "browse": {
+ "sortLabel": "记忆片段排序",
+ "newestFirst": "最新优先",
+ "episodes": "记忆片段",
+ "loading": "正在加载记忆片段…",
+ "empty": "此项目还没有已处理的记忆片段。",
+ "partialEmpty": "未能加载的项目中可能仍有记忆片段。请继续翻页或重试本页。",
+ "loadFailed": "无法加载记忆片段。",
+ "retry": "重试本页",
+ "closedTitle": "记忆已关闭",
+ "closedDescription": "记忆当前不可用。请在设置中启用后重试。",
+ "partial": "部分项目未能加载,本页内容可能不完整。",
+ "truncated": "列表在检查完所有记忆片段前停止,本页内容可能不完整。",
+ "total": "{{count}} 条记忆片段",
+ "pageSummary": "第 {{page}} 页,共 {{total}} 页",
+ "previous": "上一页",
+ "next": "下一页",
+ "page": "第 {{page}} 页",
+ "detailTitle": "记忆片段详情",
+ "entryId": "条目 ID",
+ "copyEntryId": "复制条目 ID",
+ "entryIdCopied": "条目 ID 已复制",
+ "openDetail": "打开记忆片段:{{title}}"
+ }
},
"log": {
"description": "查看本安装中所有用户和项目的已创建记忆条目的处理记录。",