Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/3114-memory-directory.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The memory dialog has a directory of own and team topics and a search over the entries it already loaded, so finding one memory no longer means scrolling the whole list. (#3114)
186 changes: 152 additions & 34 deletions core/client.js

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions core/src/client/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -1055,6 +1055,12 @@ const ZH = {
'Memory summary': '记忆摘要',
'All entries': '全部记忆',
'Memory options': '记忆选项',
Overview: '总览',
'Memory directory': '记忆目录',
'Search memory': '搜索记忆',
'Main memory': '主记忆',
'No entries match "{query}"': '没有匹配 "{query}" 的记忆',
'Try a different word, or clear the search to see every entry.': '换个词,或清空搜索看全部记忆。',
'Close memory': '关闭记忆',
'Back to the summary': '返回摘要',
'Regenerate summary': '重新生成摘要',
Expand Down
105 changes: 86 additions & 19 deletions core/src/client/memory-panel.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// answers from the entries or changes them. Modeled on ChatGPT's memory summary.
import { createElement as h, Fragment, useCallback, useEffect, useRef, useState } from 'react'
import { useEscape } from './overlay-hooks.js'
import { ArrowUpIcon, CheckIcon, ChevronLeftIcon, ChevronRightIcon, CloseIcon, DotsIcon, MemoryIcon, TrashIcon } from './icons.js'
import { ArrowUpIcon, CheckIcon, ChevronLeftIcon, ChevronRightIcon, CloseIcon, DotsIcon, MemoryIcon, SearchIcon, TrashIcon } from './icons.js'
import { dateLocale, hostText, t } from './i18n.js'
import { memoryBlockedNotice, memoryEmptyNotice } from './memory-empty.js'
import { summaryBlocks } from './text.js'
Expand Down Expand Up @@ -128,6 +128,23 @@ const groupEntries = entries => entries.reduce((groups, entry) => {
return groups
}, [])

// The directory reads the same grouping the list draws, so one topic never appears twice under
// two names. A topic is the scope plus the name: own travel and team travel are two rows.
const navTopics = entries => groupEntries(entries ?? [])
.map(group => ({ scope: group.scope, topic: group.topic ?? null, count: group.entries.length }))
const sameTopic = (a, b) => Boolean(a) && Boolean(b) && a.scope === b.scope && (a.topic ?? null) === (b.topic ?? null)
// Every whitespace-separated term must appear in the entry text, topic, or author; an empty
// query keeps every entry. Local to the loaded view — the host's recall index is a different
// search and is not asked here.
const filterMemoryEntries = (entries, query) => {
const terms = String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean)
if (terms.length === 0) return [...(entries ?? [])]
return (entries ?? []).filter((entry) => {
const hay = `${entry.text ?? ''} ${entry.topic ?? ''} ${entry.by ?? ''}`.toLowerCase()
return terms.every(term => hay.includes(term))
})
}

function EntryRow({ entry, remove }) {
const [confirming, setConfirming] = useState(false)
const [busy, setBusy] = useState(false)
Expand All @@ -153,13 +170,13 @@ function EntryRow({ entry, remove }) {
}, confirming ? t('Remove') : h(TrashIcon)) : null)
}

function Entries({ bot, view, remove }) {
function Entries({ bot, view, remove, subset = false }) {
const groups = groupEntries(view.entries)
const refused = memoryBlockedNotice(view)
const sections = [
{ scope: 'own', title: t("{name}'s memory", { name: bot.name }), size: view.sizes.own },
{ scope: 'team', title: t('Team memory'), hint: t('Every Bot reads it'), size: view.sizes.team },
]
].filter(section => !subset || groups.some(group => group.scope === section.scope))
return h('div', { className: 'bt-mem-entries' },
refused === null ? null : h('div', { className: 'bt-mem-empty-text', role: 'status' }, refused),
sections.map(section => h('section', { key: section.scope, className: 'bt-mem-section' },
Expand Down Expand Up @@ -239,12 +256,40 @@ function useNow(every) {
return now
}

function MemoryNav({ bot, view, page, topic, query, setQuery, openOverview, openTopic, openEntries }) {
const topics = navTopics(view?.entries)
const item = (title, badge, on, current) => h('button', {
type: 'button', className: 'bt-mem-nav-item', 'aria-current': current ? 'page' : undefined, onClick: on,
},
h('span', { className: 'bt-mem-nav-label' }, title),
badge === undefined ? null : h('span', { className: 'bt-mem-nav-count' }, String(badge)))
const block = (title, items) => items.length === 0 ? null : h('div', { className: 'bt-mem-nav-group' },
h('div', { className: 'bt-mem-nav-heading' }, title),
items.map(entry => h(Fragment, { key: `${entry.scope}:${entry.topic ?? ''}` },
item(entry.topic ?? t('Main memory'), entry.count, () => openTopic(entry), page === 'entries' && sameTopic(topic, entry)))))
return h('nav', { className: 'bt-mem-nav', 'aria-label': t('Memory directory') },
h('label', { className: 'bt-mem-search' },
h(SearchIcon),
h('input', {
className: 'bt-mem-search-input', type: 'search', value: query,
placeholder: t('Search memory'), 'aria-label': t('Search memory'),
onChange: event => setQuery(event.target.value),
})),
h('div', { className: 'bt-mem-nav-list' },
item(t('Overview'), undefined, openOverview, page === 'summary' && query.trim() === ''),
item(t('All entries'), view?.entries.length ?? 0, () => openEntries(null), page === 'entries' && !topic && query.trim() === ''),
block(t("{name}'s memory", { name: bot.name }), topics.filter(entry => entry.scope !== 'team')),
block(t('Team memory'), topics.filter(entry => entry.scope === 'team'))))
}

export function MemoryDialog({ bot, actions, roster, leaving = false }) {
const { view, error, load, show } = useMemoryView(bot.id, actions)
// A read-only window refuses both writes below at the host, so the panel draws neither and
// says why in the host's own sentence — the same one the sidebar and the Settings header carry.
const locked = typeof roster?.readOnly === 'string' && roster.readOnly.trim() !== ''
const [page, setPage] = useState('summary')
const [topic, setTopic] = useState(null)
const [query, setQuery] = useState('')
const [menu, setMenu] = useState(false)
const [menuShown, menuLeaving] = useLinger(menu, MENU_EXIT_MS)
const [text, setText] = useState('')
Expand All @@ -269,9 +314,10 @@ export function MemoryDialog({ bot, actions, roster, leaving = false }) {
window.removeEventListener('keydown', onKey, true)
}
}, [menu])
const regenerate = () => { setMenu(false); setPage('summary'); void load({ regenerate: true }) }
const openEntries = () => { setMenu(false); setPage('entries') }
const backToSummary = () => { setPage('summary'); void load({ summarize: true }) }
const regenerate = () => { setMenu(false); setPage('summary'); setTopic(null); setQuery(''); void load({ regenerate: true }) }
const openEntries = (nextTopic = null) => { setMenu(false); setPage('entries'); setTopic(nextTopic); setQuery('') }
const openOverview = () => { setMenu(false); setPage('summary'); setTopic(null); setQuery(''); void load({ summarize: true }) }
const backToSummary = () => openOverview()
const remove = async (entry) => {
try {
show(await actions.memoryForget(bot.id, entry))
Expand Down Expand Up @@ -300,8 +346,18 @@ export function MemoryDialog({ bot, actions, roster, leaving = false }) {

const count = view?.entries.length ?? 0
const when = view?.summary ? ago(view.summary.at, now) : null
const searching = query.trim() !== ''
const filtered = view === null ? []
: searching ? filterMemoryEntries(view.entries, query)
: topic ? view.entries.filter(entry => sameTopic(entry, topic))
: view.entries
const listed = view === null ? null : { ...view, entries: filtered }
const showEntries = searching || page === 'entries'
const title = searching ? t('Search memory')
: page === 'entries' ? (topic ? (topic.topic ?? t('Main memory')) : t('All entries'))
: t('Memory summary')
const status = view === null ? ''
: page === 'entries' ? (count === 1 ? t('1 entry') : t('{count} entries', { count }))
: showEntries ? (filtered.length === 1 ? t('1 entry') : t('{count} entries', { count: filtered.length }))
: view.summarizing && view.summary ? t('Updating…')
: view.summary && view.fresh ? (when ? t('Updated {time}', { time: when }) : t('Updated just now'))
: ''
Expand All @@ -310,24 +366,35 @@ export function MemoryDialog({ bot, actions, roster, leaving = false }) {
h('div', { className: 'bt-scrim bt-mem-scrim', onMouseDown: close }),
h('div', { className: 'bt-mem', role: 'dialog', 'aria-modal': true, 'aria-label': t("{name}'s memory", { name: bot.name }) },
h('div', { className: 'bt-mem-head' },
page === 'entries' ? h('button', { type: 'button', className: 'bt-icon-btn', 'aria-label': t('Back to the summary'), onClick: backToSummary }, h(ChevronLeftIcon)) : null,
h('h2', null, page === 'entries' ? t('All entries') : t('Memory summary')),
h('span', { className: 'bt-mem-status' }, page === 'summary' ? [bot.name, status].filter(Boolean).join(' · ') : status),
showEntries ? h('button', { type: 'button', className: 'bt-icon-btn', 'aria-label': t('Back to the summary'), onClick: backToSummary }, h(ChevronLeftIcon)) : null,
h('h2', null, title),
h('span', { className: 'bt-mem-status' }, page === 'summary' && !searching ? [bot.name, status].filter(Boolean).join(' · ') : status),
h('span', { className: 'bt-mem-head-gap' }),
h('button', { ref: dotsRef, type: 'button', className: 'bt-icon-btn', 'aria-label': t('Memory options'), 'aria-haspopup': 'menu', 'aria-expanded': menu, onClick: () => setMenu(value => !value) }, h(DotsIcon)),
h('button', { type: 'button', className: 'bt-icon-btn', 'aria-label': t('Close memory'), onClick: close }, h(CloseIcon)),
menuShown ? h('div', { ref: menuRef, className: 'bt-menu bt-mem-menu', role: 'menu', 'aria-label': t('Memory options'), 'data-leaving': menuLeaving || undefined },
h('button', { type: 'button', role: 'menuitem', onClick: openEntries },
h('button', { type: 'button', role: 'menuitem', onClick: () => openEntries(null) },
h('span', { className: 'bt-menu-label' }, t('All entries')), h('span', { className: 'bt-menu-hint' }, String(count))),
h('button', { type: 'button', role: 'menuitem', disabled: count === 0 || view?.summarizing, onClick: regenerate },
h('span', { className: 'bt-menu-label' }, t('Regenerate summary')))) : null),
h('div', { className: 'bt-mem-body' },
readOnlyLine(h, roster, actions),
error ? h('div', { className: 'bt-error', role: 'alert', style: { padding: 0 } }, hostText(error)) : null,
view === null ? (error ? null : h(Skeleton))
: page === 'entries' ? h(Entries, { bot, view, remove: locked ? null : remove })
: h(Summary, { bot, view, regenerate })),
h('div', { className: 'bt-mem-foot' },
h('div', { className: 'bt-mem-shell' },
h(MemoryNav, {
bot, view, page, topic, query, setQuery, openOverview, openEntries,
openTopic: next => openEntries(next),
}),
h('div', { className: 'bt-mem-main' },
h('div', { className: 'bt-mem-body' },
readOnlyLine(h, roster, actions),
error ? h('div', { className: 'bt-error', role: 'alert', style: { padding: 0 } }, hostText(error)) : null,
view === null ? (error ? null : h(Skeleton))
: showEntries
? (searching && filtered.length === 0
? h('div', { className: 'bt-mem-empty' },
h('div', { className: 'bt-mem-empty-title' }, t('No entries match "{query}"', { query: query.trim() })),
h('div', { className: 'bt-mem-empty-text' }, t('Try a different word, or clear the search to see every entry.')))
: h(Entries, { bot, view: listed, remove: locked ? null : remove, subset: searching || Boolean(topic) }))
: h(Summary, { bot, view, regenerate })),
h('div', { className: 'bt-mem-foot' },
answer ? h(Reply, { answer, dismiss: () => setAnswer(null) }) : null,
locked ? null : h('form', { className: 'bt-mem-ask', onSubmit: ask },
h('input', {
Expand All @@ -336,5 +403,5 @@ export function MemoryDialog({ bot, actions, roster, leaving = false }) {
onChange: event => setText(event.target.value),
}),
h('button', { type: 'submit', className: 'bt-mem-send', disabled: busy || text.trim() === '', 'aria-label': t('Send') },
busy ? h('span', { className: 'bt-mem-spin', 'aria-hidden': true }) : h(ArrowUpIcon))))))
busy ? h('span', { className: 'bt-mem-spin', 'aria-hidden': true }) : h(ArrowUpIcon))))))))
}
14 changes: 14 additions & 0 deletions core/src/client/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,20 @@ body[data-ds-dark-theme] .bt-theme-chip i{background:var(--da)}
.bt-mem-head-gap{flex:1}
.bt-mem-menu{position:absolute;top:52px;right:50px;min-width:220px;--bt-origin:top right}
.bt-mem-menu button:disabled{opacity:.4;cursor:default;background:none}
.bt-mem-shell{flex:1;min-height:0;display:flex}
.bt-mem-main{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column}
.bt-mem-nav{flex:none;width:200px;display:flex;flex-direction:column;gap:10px;padding:12px 10px 16px;border-right:.5px solid var(--bt-line);background:var(--bt-sidebar);min-height:0}
.bt-mem-search{display:flex;align-items:center;gap:8px;margin:0 4px;padding:0 8px;height:32px;border-radius:8px;background:var(--bt-main);border:.5px solid var(--bt-line-2);color:var(--bt-ink-2)}
.bt-mem-search svg{flex:none;width:14px;height:14px}
.bt-mem-search-input{flex:1;min-width:0;border:0;background:none;color:var(--bt-ink);font:inherit;font-size:13px;outline:none}
.bt-mem-nav-list{display:flex;flex-direction:column;gap:2px;min-height:0;overflow:auto;padding:0 2px}
.bt-mem-nav-group{display:flex;flex-direction:column;gap:2px;margin-top:10px}
.bt-mem-nav-heading{padding:4px 8px 2px;font-size:11px;line-height:14px;font-weight:600;color:var(--bt-ink-3);text-transform:uppercase;letter-spacing:.04em}
.bt-mem-nav-item{display:flex;align-items:center;gap:8px;width:100%;margin:0;padding:6px 8px;border:0;border-radius:8px;background:none;color:var(--bt-ink);font:inherit;font-size:13px;line-height:18px;text-align:left;cursor:pointer}
.bt-mem-nav-item:hover{background:var(--bt-hover)}
.bt-mem-nav-item[aria-current=page]{background:var(--bt-selected,var(--bt-active));font-weight:600}
.bt-mem-nav-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.bt-mem-nav-count{flex:none;font-size:11px;line-height:14px;color:var(--bt-ink-3);font-variant-numeric:tabular-nums}
.bt-mem-body{flex:1;overflow-y:auto;padding:22px 28px 24px;scrollbar-width:thin;display:flex;flex-direction:column;gap:12px}
.bt-mem-summary{transition:opacity .3s ease}
.bt-mem-summary[data-stale]{opacity:.55}
Expand Down
82 changes: 82 additions & 0 deletions core/test/memory-panel-readonly.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,85 @@ test('P-475: the dialog is handed the roster, or the panel cannot know the windo
const overlays = readFileSync(new URL('../src/client/overlays.js', import.meta.url), 'utf8')
assert.match(overlays, /h\(MemoryDialog, \{ key: memory, bot: roster\.byId\[memory\], roster, actions, leaving: memoryLeaving \}\)/)
})

// #3114: the directory and the search read the view the host already returned; four entries
// across both scopes, one untagged, so a topic row, an untagged row, and a shared topic name
// (travel in own and team) are all on screen at once.
const catalogView = () => ({
entries: [
{ text: 'Prefers the window seat on flights', scope: 'own', topic: 'travel', source: 'memory panel', added: 'today' },
{ text: 'Allergic to peanuts', scope: 'own', source: 'memory panel', added: 'today' },
{ text: 'Standup is at 10:00', scope: 'team', topic: 'rituals', by: 'Chief', added: 'yesterday' },
{ text: 'The travel budget is tight this quarter', scope: 'team', topic: 'travel', by: 'Writer', added: 'yesterday' },
],
sizes: { own: 40, team: 60 },
limits: { main: 4000 },
blocked: [],
summary: { at: Date.now() - 60_000, text: 'One saved fact' },
fresh: true,
summarizing: false,
})
const catalogActions = () => ({ ...actions(), memoryView: async () => catalogView() })

// Opening the summary page is enough: the directory is drawn beside it, so no ⋯ walk is needed.
async function openCatalog(roster = {}) {
reset()
const props = { bot: { id: 'bot1', name: 'Scout' }, actions: catalogActions(), roster }
let tree = render(props)
await flush()
tree = render(props)
return { props, tree }
}
const navItems = tree => byClass(tree, 'bt-mem-nav-item')
const searchField = tree => all(tree).find(node => node.type === 'input' && node.props?.['aria-label'] === 'Search memory')

test('#3114: the memory panel names a directory and offers a search over loaded entries', async () => {
const { tree } = await openCatalog()
assert.ok(all(tree).some(node => node.props?.['aria-label'] === 'Memory directory'), 'the directory is named')
assert.ok(searchField(tree), 'the directory holds a search field')
// Overview, All entries, own: travel + Main memory, team: rituals + travel — the directory
// keeps the order the list draws its groups in, so a row never moves when an entry is added.
assert.equal(navItems(tree).length, 6)
const labels = byClass(tree, 'bt-mem-nav-label').map(node => textOf(node))
assert.deepEqual(labels, ['Overview', 'All entries', 'travel', 'Main memory', 'rituals', 'travel'])
// All entries carries the count the view already gave, and two travel rows stay separate.
assert.equal(textOf(navItems(tree)[1]), 'All entries4')
assert.deepEqual(byClass(tree, 'bt-mem-nav-count').map(node => textOf(node)), ['4', '1', '1', '1', '1'])
})

test('#3114: search keeps entries that hold every term, and says when none does', async () => {
const { props, tree } = await openCatalog()
searchField(tree).props.onChange({ target: { value: 'travel budget' } })
const searched = render(props)
assert.match(textOf(searched), /The travel budget is tight this quarter/)
// "travel" alone is the topic of the window-seat entry, but "budget" is not in its text.
assert.doesNotMatch(textOf(searched), /Prefers the window seat on flights/)
assert.doesNotMatch(textOf(searched), /Allergic to peanuts/)
// The title says what the list is, and the count follows the filter, not the view.
assert.match(textOf(searched), /Search memory/)
assert.equal(textOf(byClass(searched, 'bt-mem-status')[0]), '1 entry')
searchField(searched).props.onChange({ target: { value: 'nothing here' } })
const empty = render(props)
assert.match(textOf(empty), /No entries match "nothing here"/)
assert.match(textOf(empty), /Try a different word, or clear the search to see every entry\./)
assert.equal(byClass(empty, 'bt-mem-entry').length, 0)
})

test('#3114: a directory topic filters the list, and All entries clears it', async () => {
const { props, tree } = await openCatalog()
// Index 2 is the own "travel" row; the own block is drawn before the team block.
const ownTravel = navItems(tree)[2]
assert.equal(textOf(ownTravel), 'travel1')
ownTravel.props.onClick()
const filtered = render(props)
assert.match(textOf(filtered), /Prefers the window seat on flights/)
// Team travel holds the same topic name and must not leak into the own list.
assert.doesNotMatch(textOf(filtered), /The travel budget is tight this quarter/)
assert.doesNotMatch(textOf(filtered), /Allergic to peanuts/)
assert.equal(byClass(filtered, 'bt-mem-topic').length, 1)
assert.equal(navItems(filtered)[2].props['aria-current'], 'page')
navItems(filtered)[1].props.onClick()
const all = render(props)
assert.equal(byClass(all, 'bt-mem-entry').length, 4)
assert.equal(navItems(all)[2].props['aria-current'], undefined)
})
Loading
Loading