dsh-memu-memory 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -279,7 +279,7 @@ window.__ModuleLoader__.load({
279
279
  poolReview: '待复核',
280
280
  poolInactive: '已失效',
281
281
  wallReadError: '部分记忆库读取失败',
282
- wallLimit: '仅展示最近 300 条',
282
+ wallLimit: '超出单次读取上限,其余未显示',
283
283
  wallScopePrivate: '私有',
284
284
  wallScopeGlobal: '全局',
285
285
  wallFilterScope: '范围',
@@ -727,6 +727,8 @@ window.__ModuleLoader__.load({
727
727
  browseSearch: '搜索本库',
728
728
  browseSearchPlaceholder: '按标题、正文、ID 或标签过滤当前记忆库…',
729
729
  browseSearchClear: '清空',
730
+ browseLoadMore: '显示更多',
731
+ browseLoadingFull: '正在加载完整正文…',
730
732
  // Enum display labels. Stored values stay English; only these flip with locale.
731
733
  layerLongTerm: '长期记忆',
732
734
  layerAnchor: '锚点记忆',
@@ -1268,7 +1270,7 @@ window.__ModuleLoader__.load({
1268
1270
  poolReview: 'Review',
1269
1271
  poolInactive: 'Inactive',
1270
1272
  wallReadError: 'Some libraries could not be read',
1271
- wallLimit: 'Showing the latest 300 entries',
1273
+ wallLimit: 'Beyond the single-read cap; the rest is not shown',
1272
1274
  wallScopePrivate: 'Private',
1273
1275
  wallScopeGlobal: 'Global',
1274
1276
  wallFilterScope: 'Scope',
@@ -1716,6 +1718,8 @@ window.__ModuleLoader__.load({
1716
1718
  browseSearch: 'Search this library',
1717
1719
  browseSearchPlaceholder: 'Filter the current library by title, body, id or tags…',
1718
1720
  browseSearchClear: 'Clear',
1721
+ browseLoadMore: 'Show more',
1722
+ browseLoadingFull: 'Loading full text…',
1719
1723
  layerLongTerm: 'Long-term',
1720
1724
  layerAnchor: 'Anchor',
1721
1725
  layerMustRemember: 'Permanent',
@@ -3193,6 +3197,127 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
3193
3197
  item.hidden ? null : h('figcaption', null, item.caption || '[图片]')))) : null)
3194
3198
  }
3195
3199
 
3200
+ // 一张可编辑的记忆卡。draft 下沉到卡片内部:浏览页可能有几百张卡,输入时
3201
+ // 若把草稿放在父级 state,每敲一个字都要重渲染整个列表(2026-11-28 的卡顿
3202
+ // 现场)。memo 之后只有被编辑的那一张会重画。
3203
+ const BrowserMemoryCard = React.memo(function BrowserMemoryCard({ file: f, t, busy, browseBusy, onSave, onArchive, onResolve, onLoadFull }) {
3204
+ const [draft, setDraft] = React.useState({})
3205
+ // 列表只带截断后的正文。第一次聚焦正文输入框时补拉全文,否则用户改一个字
3206
+ // 保存就会把尾部写丢。拉取期间输入框只读,避免在截断版上先打字。
3207
+ const [fullContent, setFullContent] = React.useState(null)
3208
+ const [loadingFull, setLoadingFull] = React.useState(false)
3209
+ const set = (key, value) => setDraft((prev) => ({ ...prev, [key]: value }))
3210
+ const ensureFull = async () => {
3211
+ if (!f.truncated || fullContent !== null || loadingFull) return
3212
+ setLoadingFull(true)
3213
+ try {
3214
+ const text = await onLoadFull(f)
3215
+ if (typeof text === 'string') setFullContent(text)
3216
+ } catch (error) {
3217
+ // 拉不到就退回截断显示;至少留一条可查的信号,不静默。
3218
+ try { console.warn('dsh-memu-memory: full body load failed', f.id, error?.message || error) } catch {}
3219
+ } finally { setLoadingFull(false) }
3220
+ }
3221
+ // 有构成就讲构成;没有就回到旧的单值标签,老条目照旧可读。
3222
+ const moodText = emotionTagText(f.emotion)
3223
+ || (typeof f.moodValence === 'number' && f.moodValence !== 0 ? f.moodValence.toFixed(2) : '')
3224
+ return h('div', { style: S.item },
3225
+ h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center' } },
3226
+ h('div', { style: S.row },
3227
+ h(Tag, null, enumText(t, LAYER_LABELS, f.layer || 'long_term')),
3228
+ f.marginalized ? h(Tag, null, t('marginalizedTag')) : null,
3229
+ f.openLoop ? h(Tag, null, t('openLoopTag')) : null,
3230
+ // What the memory is allowed to do with itself. Hiding these in the data
3231
+ // meant the only way to notice a misfiled "never say out loud" was to
3232
+ // open the JSON.
3233
+ f.disclosure && f.disclosure !== 'can_tell'
3234
+ ? h(Tag, { tone: f.disclosure === 'never_say' ? 'warn' : 'info' }, enumText(t, DISCLOSURE_LABELS, f.disclosure))
3235
+ : null,
3236
+ f.visibility === 'secret' ? h(Tag, { tone: 'warn' }, enumText(t, VISIBILITY_LABELS, 'secret')) : null,
3237
+ // Provenance, always shown here: the browser is where you audit a memory,
3238
+ // so "where did this come from" is not an optional detail. A quote and an
3239
+ // inference read identically once injected — this tag is the difference.
3240
+ h(Tag, { tone: f.source === 'imagined' ? 'warn' : (f.source === 'user_said' ? 'info' : undefined) },
3241
+ enumText(t, SOURCE_LABELS, f.source || 'inferred')),
3242
+ f.owner === 'about_user' ? h(Tag, { tone: 'info' }, enumText(t, OWNER_LABELS, 'about_user')) : null,
3243
+ // Keep the year: a deadline sliced from offset 5 reads "10-29 14:30", which
3244
+ // is indistinguishable from a stale entry once the year turns over.
3245
+ f.expiresAt ? h(Tag, null, `${t('shortTermExpires')} ${String(f.expiresAt).slice(0, 16).replace('T', ' ')}`) : null,
3246
+ f.peak ? h(Tag, null, t('peakTag')) : null,
3247
+ // A dated memory is an appointment, not an anniversary; the tag has to
3248
+ // say which, because only one of them means "this happens every year".
3249
+ f.salientDate
3250
+ ? h(Tag, null, `${/^\d{4}-\d{2}-\d{2}$/.test(f.salientDate) ? t('dueDateTag') : t('anniversaryTag')} ${f.salientDate}`)
3251
+ : null,
3252
+ // 四轴构成放在 Tag 里;激活/掌控/来源直接可见,不再只藏在悬停提示里。
3253
+ moodText ? h(Tag, null, `${t('moodTag')} ${moodText}`) : null,
3254
+ emotionMetaText(f, t) ? h('span', { style: S.muted }, emotionMetaText(f, t)) : null,
3255
+ typeof f.accuracy === 'number' && typeof f.confidence === 'number' && f.accuracy <= 0.6 && f.accuracy < f.confidence - 0.1
3256
+ ? h(Tag, { tone: 'warn' }, `${t('accuracyTag')} ${f.accuracy}`) : null,
3257
+ h(Tag, null, enumText(t, STATUS_LABELS, f.status || 'active'))),
3258
+ h('div', { style: { display: 'flex', gap: 6, flexShrink: 0 } },
3259
+ // 待复核条目在这里就能拍板,不必绕去全局页的复核队列;
3260
+ // resolution 沿用复核草稿(缺省 replace),与全局队列同一 RPC。
3261
+ f.status === 'pending_review'
3262
+ ? h(Button, { onClick: () => onResolve(f.id, 'accept'), disabled: busy || browseBusy, primary: true }, t('accept'))
3263
+ : null,
3264
+ f.status === 'pending_review'
3265
+ ? h(Button, { onClick: () => onResolve(f.id, 'reject'), disabled: busy || browseBusy, style: S.ghost }, t('reject'))
3266
+ : null,
3267
+ h(Button, { onClick: () => onSave(f.id, draft), disabled: busy || browseBusy }, t('save')),
3268
+ h(Button, { onClick: () => onArchive(f.id), disabled: busy || browseBusy, style: S.ghost }, t('archive')))),
3269
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, margin: '8px 0 4px' } },
3270
+ h('span', { style: { ...S.muted, minWidth: 72 } }, t('decay')),
3271
+ h(Bar, { value: f.decay, title: `${Math.round((Number(f.decay) || 0) * 100)}%` }),
3272
+ h('span', { style: S.muted }, f.lastAccessAt
3273
+ ? `${t('accessed')}: ${String(f.lastAccessAt).slice(0, 10)}`
3274
+ : t('neverAccessed'))),
3275
+ h(MemoryAttachments, { items: f.attachments, t }),
3276
+ h('input', {
3277
+ style: { ...S.input, width: '100%', marginTop: 8 },
3278
+ value: draft.title ?? f.title ?? '', placeholder: t('name'),
3279
+ onChange: (e) => set('title', e.target.value),
3280
+ }),
3281
+ h('textarea', {
3282
+ style: { ...S.textarea, marginTop: 6, minHeight: 90 },
3283
+ value: draft.content ?? fullContent ?? f.content ?? '',
3284
+ readOnly: loadingFull,
3285
+ title: loadingFull ? t('browseLoadingFull') : undefined,
3286
+ onFocus: () => { void ensureFull() },
3287
+ onChange: (e) => set('content', e.target.value),
3288
+ }),
3289
+ h('input', {
3290
+ style: { ...S.input, width: '100%', marginTop: 6 },
3291
+ value: (draft.tags ?? f.tags ?? []).join(', '), placeholder: 'tag1, tag2',
3292
+ onChange: (e) => set('tags', e.target.value.split(',').map((x) => x.trim()).filter(Boolean)),
3293
+ }),
3294
+ h('div', { style: { display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' } },
3295
+ h('select', {
3296
+ style: { ...S.input, flex: '1 1 120px', minWidth: 0 },
3297
+ title: t('disclosureLabel'),
3298
+ value: draft.disclosure ?? f.disclosure ?? 'can_tell',
3299
+ onChange: (e) => set('disclosure', e.target.value),
3300
+ }, ['can_tell', 'only_if_asked', 'never_say'].map((v) => h('option', { key: v, value: v }, enumText(t, DISCLOSURE_LABELS, v)))),
3301
+ h('select', {
3302
+ style: { ...S.input, flex: '1 1 110px', minWidth: 0 },
3303
+ title: t('ownerLabel'),
3304
+ value: draft.owner ?? f.owner ?? 'me',
3305
+ onChange: (e) => set('owner', e.target.value),
3306
+ }, ['me', 'us', 'about_user', 'about_project'].map((v) => h('option', { key: v, value: v }, enumText(t, OWNER_LABELS, v)))),
3307
+ h('select', {
3308
+ style: { ...S.input, flex: '1 1 110px', minWidth: 0 },
3309
+ title: t('visibilityLabel'),
3310
+ value: draft.visibility ?? f.visibility ?? 'shared',
3311
+ onChange: (e) => set('visibility', e.target.value),
3312
+ }, ['shared', 'secret'].map((v) => h('option', { key: v, value: v }, enumText(t, VISIBILITY_LABELS, v)))),
3313
+ h('select', {
3314
+ style: { ...S.input, flex: '1 1 110px', minWidth: 0 },
3315
+ title: t('sourceLabel'),
3316
+ value: draft.source ?? f.source ?? 'inferred',
3317
+ onChange: (e) => set('source', e.target.value),
3318
+ }, ['user_said', 'inferred', 'imagined', 'told'].map((v) => h('option', { key: v, value: v }, enumText(t, SOURCE_LABELS, v))))))
3319
+ })
3320
+
3196
3321
  function VisionConfigPanel({ call, config, t }) {
3197
3322
  const [message, setMessage] = React.useState('')
3198
3323
  const [busy, setBusy] = React.useState(false)
@@ -4602,12 +4727,38 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4602
4727
  let alive = true
4603
4728
  const requestId = ++browseRequest.current
4604
4729
  const current = () => alive && requestId === browseRequest.current
4605
- const load = async () => {
4606
- try {
4607
- const value = await call('browseWall', { libraryId: libraryId || null, limit: 300, domain: wallDomain || undefined })
4730
+ // 整库流式读取:首批立即上屏,之后逐批追加。记忆墙原先在 300 条处截断,
4731
+ // 读者看到的是“最近 300 条”而不是自己的库(2026-11-28)。每批之间让出
4732
+ // 一帧,卡片一批批出现,而不是最后一起跳出来。
4733
+ const stream = async (targetLibraryId) => {
4734
+ let items = []
4735
+ let total = 0
4736
+ let batches = 0
4737
+ for (;;) {
4738
+ // 活锁保护:库在读取过程中被持续写入时 total 会一直变大,没有这条上限
4739
+ // 这个循环可以永远转下去。40 批 × 300 = 12000 条,远超正常库规模,
4740
+ // 真的到顶就停在这里(界面会显示「超出单次读取上限」)。
4741
+ if (++batches > 40) return
4742
+ const value = await call('browseWall', {
4743
+ libraryId: targetLibraryId || null,
4744
+ limit: 300,
4745
+ offset: items.length,
4746
+ domain: wallDomain || undefined,
4747
+ })
4608
4748
  if (!current()) return
4609
- setData(value)
4749
+ const batch = Array.isArray(value?.items) ? value.items : []
4750
+ items = items.concat(batch)
4751
+ total = Number(value?.total) || items.length
4752
+ setData({ ...value, items, total })
4610
4753
  setError('')
4754
+ if (!batch.length || items.length >= total) return
4755
+ await new Promise(resolve => setTimeout(resolve, 0))
4756
+ if (!current()) return
4757
+ }
4758
+ }
4759
+ const load = async () => {
4760
+ try {
4761
+ await stream(libraryId)
4611
4762
  } catch (failure) {
4612
4763
  if (!current()) return
4613
4764
  const message = String(failure?.message || failure)
@@ -4616,12 +4767,10 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4616
4767
  // 不再整页空。用户可手动切换库;多库选项保留为禁用。
4617
4768
  if (!libraryId && firstLibraryId && /forbidden|403/i.test(message)) {
4618
4769
  try {
4619
- const value = await call('browseWall', { libraryId: firstLibraryId, limit: 300, domain: wallDomain || undefined })
4770
+ await stream(firstLibraryId)
4620
4771
  // A newer selection owns the wall now; do not force the reader
4621
4772
  // back to the first library from a fallback they did not ask for.
4622
4773
  if (!current()) return
4623
- setData(value)
4624
- setError('')
4625
4774
  setMultiBlocked(true)
4626
4775
  setLibraryId(firstLibraryId)
4627
4776
  return
@@ -5813,7 +5962,13 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5813
5962
  const browseLibraryRequest = React.useRef(0)
5814
5963
  const reviewsRequest = React.useRef(0)
5815
5964
  const statsRequest = React.useRef(0)
5816
- const [browseDraft, setBrowseDraft] = React.useState({})
5965
+ // 浏览页一次挂载多少张卡:先 60 张,滚到底自动追加。几百张卡一次性建完
5966
+ // 会明显卡(每张卡有 6 个可编辑控件),而它们之间没有共享状态。
5967
+ const [browseShown, setBrowseShown] = React.useState(60)
5968
+ const browseMoreRef = React.useRef(null)
5969
+ // 渲染期写入、effect 只读:archShown 在 loading 分支之后才定义,而 hook
5970
+ // 顺序契约要求 effect 必须放在那之前(见下方 Hook order 注释)。
5971
+ const browseTotalRef = React.useRef(0)
5817
5972
  const [browseBusy, setBrowseBusy] = React.useState(false)
5818
5973
  // 'active' | 'archived'. Archiving used to be a one-way door in the UI: the entry
5819
5974
  // stayed in the same list with a different tag, so the mess you were trying to
@@ -5821,6 +5976,19 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5821
5976
  const [browseView, setBrowseView] = React.useState('active')
5822
5977
  // 当前库内的即时过滤:列表本来就已取回(browseLibrary),不再加一次 RPC。
5823
5978
  const [browseQuery, setBrowseQuery] = React.useState('')
5979
+ // 滚到底部自动追加下一批卡片(依赖排在 browseView/browseQuery 之后,否则
5980
+ // 依赖数组会踩到 TDZ)。IntersectionObserver 不可用时退回「显示更多」按钮。
5981
+ React.useEffect(() => {
5982
+ const node = browseMoreRef.current
5983
+ if (!node || typeof IntersectionObserver !== 'function') return undefined
5984
+ const observer = new IntersectionObserver((entries) => {
5985
+ if (entries.some((entry) => entry.isIntersecting)) {
5986
+ setBrowseShown((count) => Math.min(count + 120, browseTotalRef.current || count + 120))
5987
+ }
5988
+ }, { rootMargin: '600px 0px' })
5989
+ observer.observe(node)
5990
+ return () => observer.disconnect()
5991
+ }, [browseShown, browseView, browseQuery, browseLibId])
5824
5992
  // Permanent deletion is two clicks, and only for the row that was armed.
5825
5993
  const [deleteArmed, setDeleteArmed] = React.useState('')
5826
5994
  React.useEffect(() => {
@@ -6429,7 +6597,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
6429
6597
  if (requestId !== browseLibraryRequest.current) return
6430
6598
  setBrowseFiles(res?.files || [])
6431
6599
  setBrowseSource(res?.source || 'engine')
6432
- setBrowseDraft({})
6600
+ setBrowseShown(60)
6433
6601
  setDeleteArmed('')
6434
6602
  } catch (e) { if (requestId === browseLibraryRequest.current) setError(String(e?.message || e)) } finally { if (requestId === browseLibraryRequest.current) setBrowseBusy(false) }
6435
6603
  }
@@ -6493,9 +6661,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
6493
6661
  await openBrowser(browseLibId)
6494
6662
  } catch (e) { setError(String(e?.message || e)) } finally { setBrowseBusy(false) }
6495
6663
  }
6496
- const saveMemory = async (id) => {
6497
- const patch = browseDraft[id] || {}
6498
- if (Object.keys(patch).length === 0) return
6664
+ const saveMemory = async (id, patch) => {
6665
+ if (!patch || Object.keys(patch).length === 0) return
6499
6666
  setBrowseBusy(true)
6500
6667
  try {
6501
6668
  await call('updateMemory', { libraryId: browseLibId, id, patch })
@@ -6551,6 +6718,23 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
6551
6718
  if (item.libraryId && browseLibId === item.libraryId) await openBrowser(item.libraryId)
6552
6719
  } catch (e) { setError(String(e?.message || e)) } finally { setBusy(false) }
6553
6720
  }
6721
+ // 卡片回调必须引用稳定,否则 React.memo 在每次父渲染时都会失效。动作实现
6722
+ // 放在 ref 里(它们依赖本轮闭包中的 call / browseLibId),组件只拿恒定的转发器。
6723
+ const cardActionsRef = React.useRef({})
6724
+ cardActionsRef.current = {
6725
+ save: saveMemory,
6726
+ archive: archiveMemory,
6727
+ resolve: (id, kind) => resolveReview({ id, libraryId: browseLibId }, kind),
6728
+ // 列表只带截断正文,编辑前按需补全文(getMemory 读 sidecar 索引,不起引擎)。
6729
+ loadFull: async (file) => {
6730
+ const res = await call('getMemory', { libraryId: file.libraryId || browseLibId, id: file.id })
6731
+ return res?.entry?.content ?? ''
6732
+ },
6733
+ }
6734
+ const cardSave = React.useCallback((id, patch) => cardActionsRef.current.save(id, patch), [])
6735
+ const cardArchive = React.useCallback((id) => cardActionsRef.current.archive(id), [])
6736
+ const cardResolve = React.useCallback((id, kind) => cardActionsRef.current.resolve(id, kind), [])
6737
+ const cardLoadFull = React.useCallback((file) => cardActionsRef.current.loadFull(file), [])
6554
6738
  // 撤销集合合并(spec §4.11 undo-absorb / §6.7 UI):全局元数据动作,不带
6555
6739
  // libraryId;两段确认由 actionLabel/confirmAction 承担。成功后刷新全局列表。
6556
6740
  const undoAbsorb = async (id) => {
@@ -7816,108 +8000,6 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
7816
8000
  : null),
7817
8001
  promptPageBody))
7818
8002
 
7819
- const renderBrowserItem = (f) => {
7820
- const draft = browseDraft[f.id] || {}
7821
- const set = (key, value) => setBrowseDraft((prev) => ({
7822
- ...prev, [f.id]: { ...(prev[f.id] || {}), [key]: value },
7823
- }))
7824
- // 有构成就讲构成;没有就回到旧的单值标签,老条目照旧可读。
7825
- const moodText = emotionTagText(f.emotion)
7826
- || (typeof f.moodValence === 'number' && f.moodValence !== 0 ? f.moodValence.toFixed(2) : '')
7827
- return h('div', { key: f.id, style: S.item },
7828
- h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center' } },
7829
- h('div', { style: S.row },
7830
- h(Tag, null, enumText(t, LAYER_LABELS, f.layer || 'long_term')),
7831
- f.marginalized ? h(Tag, null, t('marginalizedTag')) : null,
7832
- f.openLoop ? h(Tag, null, t('openLoopTag')) : null,
7833
- // What the memory is allowed to do with itself. Hiding these in the data
7834
- // meant the only way to notice a misfiled "never say out loud" was to
7835
- // open the JSON.
7836
- f.disclosure && f.disclosure !== 'can_tell'
7837
- ? h(Tag, { tone: f.disclosure === 'never_say' ? 'warn' : 'info' }, enumText(t, DISCLOSURE_LABELS, f.disclosure))
7838
- : null,
7839
- f.visibility === 'secret' ? h(Tag, { tone: 'warn' }, enumText(t, VISIBILITY_LABELS, 'secret')) : null,
7840
- // Provenance, always shown here: the browser is where you audit a memory,
7841
- // so "where did this come from" is not an optional detail. A quote and an
7842
- // inference read identically once injected — this tag is the difference.
7843
- h(Tag, { tone: f.source === 'imagined' ? 'warn' : (f.source === 'user_said' ? 'info' : undefined) },
7844
- enumText(t, SOURCE_LABELS, f.source || 'inferred')),
7845
- f.owner === 'about_user' ? h(Tag, { tone: 'info' }, enumText(t, OWNER_LABELS, 'about_user')) : null,
7846
- // Keep the year: a deadline sliced from offset 5 reads "10-29 14:30", which
7847
- // is indistinguishable from a stale entry once the year turns over.
7848
- f.expiresAt ? h(Tag, null, `${t('shortTermExpires')} ${String(f.expiresAt).slice(0, 16).replace('T', ' ')}`) : null,
7849
- f.peak ? h(Tag, null, t('peakTag')) : null,
7850
- // A dated memory is an appointment, not an anniversary; the tag has to
7851
- // say which, because only one of them means "this happens every year".
7852
- f.salientDate
7853
- ? h(Tag, null, `${/^\d{4}-\d{2}-\d{2}$/.test(f.salientDate) ? t('dueDateTag') : t('anniversaryTag')} ${f.salientDate}`)
7854
- : null,
7855
- // 四轴构成放在 Tag 里;激活/掌控/来源直接可见,不再只藏在悬停提示里。
7856
- moodText ? h(Tag, null, `${t('moodTag')} ${moodText}`) : null,
7857
- emotionMetaText(f, t) ? h('span', { style: S.muted }, emotionMetaText(f, t)) : null,
7858
- typeof f.accuracy === 'number' && typeof f.confidence === 'number' && f.accuracy <= 0.6 && f.accuracy < f.confidence - 0.1
7859
- ? h(Tag, { tone: 'warn' }, `${t('accuracyTag')} ${f.accuracy}`) : null,
7860
- h(Tag, null, enumText(t, STATUS_LABELS, f.status || 'active'))),
7861
- h('div', { style: { display: 'flex', gap: 6, flexShrink: 0 } },
7862
- // 待复核条目在这里就能拍板,不必绕去全局页的复核队列;
7863
- // resolution 沿用复核草稿(缺省 replace),与全局队列同一 RPC。
7864
- f.status === 'pending_review'
7865
- ? h(Button, { onClick: () => resolveReview({ id: f.id, libraryId: browseLibId }, 'accept'), disabled: busy || browseBusy, primary: true }, t('accept'))
7866
- : null,
7867
- f.status === 'pending_review'
7868
- ? h(Button, { onClick: () => resolveReview({ id: f.id, libraryId: browseLibId }, 'reject'), disabled: busy || browseBusy, style: S.ghost }, t('reject'))
7869
- : null,
7870
- h(Button, { onClick: () => saveMemory(f.id), disabled: busy || browseBusy }, t('save')),
7871
- h(Button, { onClick: () => archiveMemory(f.id), disabled: busy || browseBusy, style: S.ghost }, t('archive')))),
7872
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, margin: '8px 0 4px' } },
7873
- h('span', { style: { ...S.muted, minWidth: 72 } }, t('decay')),
7874
- h(Bar, { value: f.decay, title: `${Math.round((Number(f.decay) || 0) * 100)}%` }),
7875
- h('span', { style: S.muted }, f.lastAccessAt
7876
- ? `${t('accessed')}: ${String(f.lastAccessAt).slice(0, 10)}`
7877
- : t('neverAccessed'))),
7878
- h(MemoryAttachments, { items: f.attachments, t }),
7879
- h('input', {
7880
- style: { ...S.input, width: '100%', marginTop: 8 },
7881
- value: draft.title ?? f.title ?? '', placeholder: t('name'),
7882
- onChange: (e) => set('title', e.target.value),
7883
- }),
7884
- h('textarea', {
7885
- style: { ...S.textarea, marginTop: 6, minHeight: 90 },
7886
- value: draft.content ?? f.content ?? '',
7887
- onChange: (e) => set('content', e.target.value),
7888
- }),
7889
- h('input', {
7890
- style: { ...S.input, width: '100%', marginTop: 6 },
7891
- value: (draft.tags ?? f.tags ?? []).join(', '), placeholder: 'tag1, tag2',
7892
- onChange: (e) => set('tags', e.target.value.split(',').map((x) => x.trim()).filter(Boolean)),
7893
- }),
7894
- h('div', { style: { display: 'flex', gap: 6, marginTop: 6, flexWrap: 'wrap' } },
7895
- h('select', {
7896
- style: { ...S.input, flex: '1 1 120px', minWidth: 0 },
7897
- title: t('disclosureLabel'),
7898
- value: draft.disclosure ?? f.disclosure ?? 'can_tell',
7899
- onChange: (e) => set('disclosure', e.target.value),
7900
- }, ['can_tell', 'only_if_asked', 'never_say'].map((v) => h('option', { key: v, value: v }, enumText(t, DISCLOSURE_LABELS, v)))),
7901
- h('select', {
7902
- style: { ...S.input, flex: '1 1 110px', minWidth: 0 },
7903
- title: t('ownerLabel'),
7904
- value: draft.owner ?? f.owner ?? 'me',
7905
- onChange: (e) => set('owner', e.target.value),
7906
- }, ['me', 'us', 'about_user', 'about_project'].map((v) => h('option', { key: v, value: v }, enumText(t, OWNER_LABELS, v)))),
7907
- h('select', {
7908
- style: { ...S.input, flex: '1 1 110px', minWidth: 0 },
7909
- title: t('visibilityLabel'),
7910
- value: draft.visibility ?? f.visibility ?? 'shared',
7911
- onChange: (e) => set('visibility', e.target.value),
7912
- }, ['shared', 'secret'].map((v) => h('option', { key: v, value: v }, enumText(t, VISIBILITY_LABELS, v)))),
7913
- h('select', {
7914
- style: { ...S.input, flex: '1 1 110px', minWidth: 0 },
7915
- title: t('sourceLabel'),
7916
- value: draft.source ?? f.source ?? 'inferred',
7917
- onChange: (e) => set('source', e.target.value),
7918
- }, ['user_said', 'inferred', 'imagined', 'told'].map((v) => h('option', { key: v, value: v }, enumText(t, SOURCE_LABELS, v))))))
7919
- }
7920
-
7921
8003
  const browsePool = file => file.status === 'pending_review' ? 'review' : file.status === 'archived' ? 'archived'
7922
8004
  : ['suppressed', 'expired', 'superseded'].includes(file.status) || file.expiresAt && Date.parse(file.expiresAt) <= Date.now() ? 'inactive' : 'active'
7923
8005
  const browseQueryText = browseQuery.trim().toLowerCase()
@@ -7925,6 +8007,9 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
7925
8007
  || [file.title, file.content, file.id, ...(Array.isArray(file.tags) ? file.tags : [])]
7926
8008
  .some(value => String(value || '').toLowerCase().includes(browseQueryText))
7927
8009
  const archShown = browseFiles.filter(file => browsePool(file) === browseView && browseMatched(file))
8010
+ // 供滚到底部自动追加用(effect 在 loading 分支之前,拿不到这里的局部值)。
8011
+ browseTotalRef.current = archShown.length
8012
+ const browseVisible = browseView === 'archived' ? archShown : archShown.slice(0, browseShown)
7928
8013
  // An archived row is a body you are deciding about, not a draft you are editing:
7929
8014
  // no title/content/tag fields, just enough to recognise it plus the two exits.
7930
8015
  const renderArchivedMemory = (f) => h('div', { key: f.id, style: S.item },
@@ -7990,14 +8075,14 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
7990
8075
  h('select', {
7991
8076
  style: { ...S.input, flex: 1 }, value: browseLibId,
7992
8077
  title: (state.libraries || []).find((lib) => lib.id === browseLibId)?.scopeKey || t('currentLibrary'),
7993
- onChange: (e) => { setBrowseLibId(e.target.value); setBrowseQuery('') },
8078
+ onChange: (e) => { setBrowseLibId(e.target.value); setBrowseQuery(''); setBrowseShown(60) },
7994
8079
  }, (state.libraries || []).map((l) => h('option', { key: l.id, value: l.id }, libraryOptionLabel(l, state.libraries || []))))),
7995
8080
  browseView === 'relations' ? null : h('div', { style: S.row },
7996
8081
  h('span', { style: S.label }, t('browseSearch')),
7997
8082
  h('input', {
7998
8083
  style: { ...S.input, flex: 1 }, type: 'search', value: browseQuery,
7999
8084
  placeholder: t('browseSearchPlaceholder'), 'aria-label': t('browseSearch'),
8000
- onChange: (e) => setBrowseQuery(e.target.value),
8085
+ onChange: (e) => { setBrowseQuery(e.target.value); setBrowseShown(60) },
8001
8086
  }),
8002
8087
  browseQuery
8003
8088
  ? h('span', { style: S.muted, role: 'status' },
@@ -8019,7 +8104,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
8019
8104
  role: 'tab',
8020
8105
  'aria-selected': browseView === value,
8021
8106
  className: `dshm-nav-item${browseView === value ? ' on' : ''}`,
8022
- onClick: () => { setBrowseView(value); setDeleteArmed('') },
8107
+ onClick: () => { setBrowseView(value); setBrowseShown(60); setDeleteArmed('') },
8023
8108
  }, value === 'relations' ? pair[1] : pair[1] + ' (' + count + ')')
8024
8109
  })),
8025
8110
  browseView === 'archived' && archShown.length > 0
@@ -8030,7 +8115,25 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
8030
8115
  : archShown.length === 0
8031
8116
  ? h(Empty, null, browseView === 'archived' ? t('browseArchivedEmpty') : t('noMemoriesView'))
8032
8117
  : h('div', { style: { ...S.list, marginTop: 10 } },
8033
- archShown.map(browseView === 'archived' ? renderArchivedMemory : renderBrowserItem))))
8118
+ browseVisible.map(browseView === 'archived' ? renderArchivedMemory : (file) => h(BrowserMemoryCard, {
8119
+ key: file.id,
8120
+ file,
8121
+ t,
8122
+ busy,
8123
+ browseBusy,
8124
+ onSave: cardSave,
8125
+ onArchive: cardArchive,
8126
+ onResolve: cardResolve,
8127
+ onLoadFull: cardLoadFull,
8128
+ })),
8129
+ browseView !== 'archived' && archShown.length > browseShown
8130
+ ? h('div', { ref: browseMoreRef, style: { ...S.muted, marginTop: 10 }, role: 'status' },
8131
+ h(Button, {
8132
+ onClick: () => setBrowseShown((count) => count + 120),
8133
+ style: S.ghost,
8134
+ title: t('browseLoadMore'),
8135
+ }, t('browseLoadMore') + ` (${browseVisible.length}/${archShown.length})`))
8136
+ : null)))
8034
8137
 
8035
8138
  const renderFolderItem = (folder) => {
8036
8139
  const disabled = folderBusy === folder.scopeKey
package/lib/engine.js CHANGED
@@ -29,6 +29,13 @@ const VERSION_CACHE_MS = 5 * 60 * 1000
29
29
  const PERSISTED_TTL_MS = 24 * 60 * 60 * 1000
30
30
  let versionCache = { at: 0, value: null }
31
31
 
32
+ // 本进程是否正在装引擎。`engineStatus` 每次轮询都会跑一次中断收尾,必须能把
33
+ // 「自己正在跑的安装」和「上次死掉的安装」分开,否则会把自己判成中断。
34
+ let installInFlight = false
35
+ // 多久没有进展就认定安装已死。与 acquireLock 的过期锁阈值保持一致(30 分钟),
36
+ // 这样一个僵死安装会在状态、锁、界面三处同时被判定为过期。
37
+ const STALE_INSTALL_MS = 30 * 60 * 1000
38
+
32
39
  // Compare PEP 440-ish versions without a dependency. A plain release is newer
33
40
  // than a pre-release of the same number (`0.11.0` > `0.11.0b3`).
34
41
  export function compareVersions(a, b) {
@@ -628,7 +635,61 @@ export function engineVersionSizes() {
628
635
  return sizes
629
636
  }
630
637
 
638
+ /**
639
+ * 清掉中断安装留下的临时 venv。只动 `venv.tmp-*`:正式目录(`venv-*`)可能正是
640
+ * current.json 指向的可用引擎,绝不能误删。
641
+ */
642
+ function removeTempVenvs() {
643
+ let removed = 0
644
+ let names = []
645
+ try { names = fs.readdirSync(engineDir(ENGINE_VERSION)) } catch { return removed }
646
+ for (const name of names) {
647
+ if (!name.startsWith('venv.tmp-')) continue
648
+ try {
649
+ fs.rmSync(path.join(engineDir(ENGINE_VERSION), name), { recursive: true, force: true })
650
+ removed += 1
651
+ } catch {}
652
+ }
653
+ return removed
654
+ }
655
+
656
+ /**
657
+ * 给一次被中断的安装收尾。
658
+ *
659
+ * 安装进程被杀(宿主重启、断电、任务管理器结束进程)时,`state.json` 会永久停在
660
+ * `installing`:没有 error、没有 current、临时 venv 留在盘上。界面只能显示
661
+ * 「installing」,而实际上没有任何进程在装——2026-11-26 那次就这样卡了两天,语义
662
+ * 召回一直静默降级成关键词,没有人看得出它其实已经死了。
663
+ *
664
+ * 三条判据同时成立才动手(全部满足才算「死掉」):
665
+ * 1. `state.status === 'installing'`
666
+ * 2. 本进程没有在装(`installInFlight`),且 `install.lock` 不存在
667
+ * 3. `updatedAt` 超过 `staleMs` 没变
668
+ * 动作:落成 `failed` 并写清原因,同时清理 `venv.tmp-*` 残骸,让重装从干净状态开始。
669
+ *
670
+ * 幂等:收尾一次后 status 不再是 installing,后续轮询直接返回。
671
+ */
672
+ export function reconcileInterruptedInstall({ now = Date.now(), staleMs = STALE_INSTALL_MS } = {}) {
673
+ const state = readState()
674
+ if (state.status !== 'installing') return { changed: false, state }
675
+ if (installInFlight) return { changed: false, state }
676
+ if (fs.existsSync(LOCK_FILE())) return { changed: false, state }
677
+ const updated = Date.parse(state.updatedAt || state.startedAt || '')
678
+ if (!Number.isFinite(updated) || now - updated < staleMs) return { changed: false, state }
679
+ const removed = removeTempVenvs()
680
+ const minutes = Math.round((now - updated) / 60_000)
681
+ const next = writeState({
682
+ status: 'failed',
683
+ step: 'interrupted',
684
+ error: `安装在「${state.step || '未知步骤'}」中断,已 ${minutes} 分钟无进展;已清理 ${removed} 个未完成的 venv,请重新安装`,
685
+ })
686
+ logLine(`interrupted install reconciled: step=${state.step || '?'} idle=${minutes}min removed=${removed}`)
687
+ return { changed: true, state: next, removed }
688
+ }
689
+
631
690
  export function engineStatus({ withSize = false } = {}) {
691
+ // 每次查询先收尾一次中断安装:界面读状态时就能自愈,不必等用户点安装。
692
+ reconcileInterruptedInstall()
632
693
  const current = readCurrent()
633
694
  const state = readState()
634
695
  return {
@@ -669,6 +730,9 @@ function acquireLock() {
669
730
  const fd = fs.openSync(file, 'wx')
670
731
  fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: stamp() }), 'utf8')
671
732
  fs.closeSync(fd)
733
+ // 三个受锁流程(安装 / 切版本 / 删版本)都会走到这里,标志放在锁上最稳:
734
+ // reconcile 只看「本进程有没有持锁」就能区分活干和尸体。
735
+ installInFlight = true
672
736
  return true
673
737
  } catch (error) {
674
738
  if (error?.code !== 'EEXIST') throw error
@@ -691,6 +755,7 @@ function acquireLock() {
691
755
  }
692
756
 
693
757
  function releaseLock() {
758
+ installInFlight = false
694
759
  try { fs.rmSync(LOCK_FILE(), { force: true }) } catch {}
695
760
  }
696
761
 
@@ -1021,6 +1086,9 @@ export async function installEngine({ force = false, log = null, beforeSwitch =
1021
1086
  }
1022
1087
 
1023
1088
  export async function ensureEngine({ force = false, log = null, beforeSwitch = null } = {}) {
1089
+ // 带着一次死掉的安装开始新一轮,会先撞上 installing 中间态和 venv.tmp 残骸;
1090
+ // 先收尾再读 current,重装才能从干净状态起跑。
1091
+ reconcileInterruptedInstall()
1024
1092
  const current = readCurrent()
1025
1093
  if (!force && current?.version === ENGINE_VERSION) {
1026
1094
  const verified = await verifyEngineRepaired(current.python, { log })