dsh-whale-whispers 1.20.4 → 2.0.7

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/README.md CHANGED
@@ -52,9 +52,10 @@
52
52
  | 搜句子 | 顶部搜索框,句子、批注、上文都能命中;「搜本对话 / 搜全对话」切换范围 |
53
53
  | 只看收藏 | 句子右边的星标,点一下收藏;「只看收藏」过滤 |
54
54
  | 按时间筛 | 全部 / 近一周 / 近一月 |
55
- | 翻一句 | 随机翻一条旧的出来看看 |
55
+ | 翻一句 | 随机翻一条旧的出来看看;卡片上能复制、能看批注与上文 |
56
56
  | 复制一句 | 句子左边的复制图标 |
57
57
  | 删一句 | 句子右边的 ✕,两下确认 |
58
+ | 撤销删除 | 删完工具条右边会出现;刷新页面也还在,直到你撤它或又删了别的 |
58
59
  | 备份 / 下载 | 设置里「这本(.md)」或「全部(.md)」;工具条上的「匿名版」去掉批注与上文 |
59
60
  | 恢复 | 选一份之前备份的 .md 覆盖当前文件(旧文件另存 `.before-restore-`) |
60
61
  | 回收站自动清理 | 开关 + 保留天数(默认关,关了就一直留着) |
@@ -0,0 +1,148 @@
1
+ # 鲸语 · dsh-whale-whispers
2
+
3
+ > 装了的话麻烦点个 ⭐(仓库右上角),让我知道有人在用;
4
+ > 装不上、用着别扭、想要什么功能,直接在市场页的评论区留言,或开一个 [Issue](https://github.com/heiyedehen/dsh-whale-whispers/issues)——都会看到。
5
+
6
+ 鲸鱼的声音能穿过整片海。
7
+
8
+ 你随口说的那句话,说完就沉下去了——鲸语把它捞回来,收进会话头部的「鲸语」标签页,不催你,也不提醒你。等哪天想再听,点开就是。
9
+
10
+ ## 三处入口
11
+
12
+ - **会话头部的「鲸语」标签**:句子都在里面,最新的在上;能搜、能筛、能翻。
13
+ - **每条回复下面那个书签图标**:点一下,这一条回复就收进去(设置里可以关掉)。
14
+ - **设置 → 鲸语**:改名、备份、恢复、规则、回收站,都在那儿。
15
+
16
+ ## 每个对话一本
17
+
18
+ 默认按会话名分本:你在「鱼搭子」里记的句子,只进 `鱼搭子.md`;换到别的对话,看到的是别的本子。
19
+
20
+ - 顶部下拉可以切「全部对话」(汇总看)或某一本;
21
+ - 右上角「改名」改的是**这本的文件名**,会话再打开还是它;
22
+ - 设置里那一行开关是**这个对话**的启用状态:停用后它不再自动记,也不建新本;手动加一句仍然可以。
23
+
24
+ ## 不想让它写的时候
25
+
26
+ 三种状态,别混着理解:
27
+
28
+ | 操作 | 效果 |
29
+ |---|---|
30
+ | 关掉「对话」开关 | 不再自动记;手动「加一句」还能用;进对话不建新本 |
31
+ | 「把这本移走」 | 移到 `quotes/.trash`,下拉里不再出现;不自动记、不能手写、进对话不建本 |
32
+ | 回收站里「清空」 | 文件真删、删了不能恢复;对话保持隐藏,不会自己回来 |
33
+
34
+ 移出过的对话想回来,去设置最下面点「重新启用这本」,会新建一本空的。
35
+
36
+ ## 让它记什么
37
+
38
+ 默认规则写在系统提示里:**判断、比喻、认输、承认**这类才记,寒暄和进度不记。
39
+
40
+ 嫌不够,可以在设置里补:
41
+
42
+ - **全局**:所有对话都用这一条;
43
+ - **本对话**:只给当前这一本用,优先级高于全局;
44
+ - **频率**:保守(只记明说的)/ 正常(一段对话一两句)/ 积极(遇到像样就记),对新会话生效。
45
+
46
+ 留空就是默认规则,最多 400 字。
47
+
48
+ ## 面板上还能做什么
49
+
50
+ | 想做什么 | 在哪儿 |
51
+ |---|---|
52
+ | 搜句子 | 顶部搜索框,句子、批注、上文都能命中;「搜本对话 / 搜全对话」切换范围 |
53
+ | 只看收藏 | 句子右边的星标,点一下收藏;「只看收藏」过滤 |
54
+ | 按时间筛 | 全部 / 近一周 / 近一月 |
55
+ | 翻一句 | 随机翻一条旧的出来看看 |
56
+ | 复制一句 | 句子左边的复制图标 |
57
+ | 删一句 | 句子右边的 ✕,两下确认 |
58
+ | 备份 / 下载 | 设置里「这本(.md)」或「全部(.md)」;工具条上的「匿名版」去掉批注与上文 |
59
+ | 恢复 | 选一份之前备份的 .md 覆盖当前文件(旧文件另存 `.before-restore-`) |
60
+ | 回收站自动清理 | 开关 + 保留天数(默认关,关了就一直留着) |
61
+
62
+ ## 给 agent 的工具
63
+
64
+ | 工具 | 作用 |
65
+ |---|---|
66
+ | `whale_whisper_append` | 收一句;重复的自动跳过 |
67
+ | `whale_whisper_list` | 读回最近的句子(查重、看自己收过什么) |
68
+ | `whale_whisper_remove` | 删掉一句(整句匹配,不会误伤旁边那条) |
69
+ | `whale_whisper_merge` | 合并重复句,只留最早那条,返回删了几条 |
70
+
71
+ 写进去是原子的(临时文件 + rename),格式跟文件里原有的一样:`- 「句子」(批注)`。
72
+
73
+ 想让它主动收,在 agent 的规矩里写一句:
74
+
75
+ > 觉得某句话值得留,就调 `whale_whisper_append` 收进鲸语,别问。
76
+
77
+ ## 文件长什么样
78
+
79
+ ```
80
+ ~/.dsh/whale-whispers/quotes.md # 默认位置
81
+ ```
82
+
83
+ `##` 写日期,`-` 写句子,句尾 `(批注)` 显示成灰色小字:
84
+
85
+ ```markdown
86
+ # 我的鲸语
87
+
88
+ ## 2026-11-03
89
+
90
+ - 「这句话是我想说的。」
91
+ - 「这句后面带个批注。」(为什么记它)
92
+ ↳ 上文:这句话是在什么情形下说的
93
+ ```
94
+
95
+ 按对话分本时,每份文件开头会有 `<!-- sid:… -->` 记它属于哪个会话;句子下面跟一行 `收录自:会话名`。
96
+
97
+ `whale_whisper_append` 只改 `- ` 开头的行,你手写的标题、注释、空行都不会被动。
98
+
99
+ ## 配置
100
+
101
+ `~/.dsh/quotes.config.json`(找不到就退回插件默认:`~/.dsh/whale-whispers/quotes.md` + 标题「鲸语」):
102
+
103
+ ```json
104
+ {
105
+ "path": "C:/Users/you/quotes.md",
106
+ "title": "我的鲸语",
107
+ "captureLevel": "normal",
108
+ "captureRule": "",
109
+ "captureRules": { "鱼搭子": "只记技术结论" },
110
+ "manualAdd": true,
111
+ "msgAction": true,
112
+ "trashAuto": false,
113
+ "trashDays": 30
114
+ }
115
+ ```
116
+
117
+ 也可以用环境变量绕开:`DSH_WHALE_WHISPERS_PATH`、`DSH_WHALE_WHISPERS_TITLE`。
118
+
119
+ ## 它怎么工作
120
+
121
+ - Host:`/dsh-quotes.json`(每次现读文件,不缓存)、几个改配置与收句子的路由、四个工具;
122
+ - Client:注册进会话头部的 `鲸语` 标签、每条回复的 `assistant-actions`、`settings.section`;
123
+ - 面板只在切到它时读一次文件,后台不轮询,不额外花一分钱。
124
+
125
+ ## 安装
126
+
127
+ ```bash
128
+ dsh plugin add dsh-whale-whispers
129
+ ```
130
+
131
+ 或用 Web UI 的插件市场选本地目录。装完刷新页面;改到 host 半边才需要重启。
132
+
133
+ ## 装了却看不到
134
+
135
+ 1. `dsh.client.inject` 里写的客户端包必须本机真有(这份用 `dsh-client-runtime` + `dsh-client-ui-renderer` + `dsh-client-ui-layout`);
136
+ 2. 模块 id 必须等于包名(`dsh-whale-whispers`),错一个字母就静默不挂载;
137
+ 3. 改完刷新页面(client 半边不会自动重载);
138
+ 4. 还空就看开发者控制台有没有 `failed to load module`。
139
+
140
+ ## 版本
141
+
142
+ 版本号在插件页和设置里的「更新」一行都能看到。想升级:
143
+
144
+ ```bash
145
+ dsh plugin add dsh-whale-whispers@latest
146
+ ```
147
+
148
+ 装完刷新页面即可,数据(`quotes.config.json` 与各本 .md)不会动。
package/client.js CHANGED
@@ -24,8 +24,9 @@ window.__ModuleLoader__.load({
24
24
 
25
25
  React.useEffect(() => {
26
26
  let alive = true
27
- const params = []
28
- if (convParam) params.push('conv=' + encodeURIComponent(convParam))
27
+ const mode = convParam === '__all__' ? 'all' : (convParam ? 'name' : 'session')
28
+ const params = ['mode=' + mode]
29
+ if (convParam && convParam !== '__all__') params.push('conv=' + encodeURIComponent(convParam))
29
30
  if (sidParam) params.push('b64sid=' + encodeURIComponent(b64(String(sidParam))))
30
31
  const url = '/dsh-quotes.json' + (params.length ? '?' + params.join('&') : '')
31
32
  fetch(url, { cache: 'no-store' })
@@ -35,6 +36,7 @@ window.__ModuleLoader__.load({
35
36
  setState({
36
37
  loading: false,
37
38
  title: (j && j.title) || '鲸语',
39
+ book: (j && j.conv) || '',
38
40
  source: (j && j.source) || '',
39
41
  items: (j && j.items) || [],
40
42
  disabled: (j && j.disabledConversations) || [],
@@ -58,7 +60,7 @@ window.__ModuleLoader__.load({
58
60
  }
59
61
  })
60
62
  return () => { alive = false }
61
- }, [tick, convParam])
63
+ }, [tick, convParam, sidParam])
62
64
 
63
65
  const reload = React.useCallback(() => setTick((n) => n + 1), [])
64
66
  return { ...state, reload }
@@ -126,7 +128,7 @@ window.__ModuleLoader__.load({
126
128
 
127
129
  /* ---------- 改名 ---------- */
128
130
 
129
- function Rename({ title, conv, onDone }) {
131
+ function Rename({ title, conv, sid, onDone }) {
130
132
  const [open, setOpen] = React.useState(false)
131
133
  const [value, setValue] = React.useState(conv || title)
132
134
  const [busy, setBusy] = React.useState(false)
@@ -139,6 +141,7 @@ window.__ModuleLoader__.load({
139
141
  try {
140
142
  const url = conv
141
143
  ? '/dsh-quotes.renameconv?b64from=' + encodeURIComponent(b64(conv)) + '&b64to=' + encodeURIComponent(b64(next))
144
+ + (sid ? '&b64sid=' + encodeURIComponent(b64(String(sid))) : '')
142
145
  : '/dsh-quotes.config?b64title=' + encodeURIComponent(b64(next))
143
146
  const r = await fetch(url, { method: 'POST' })
144
147
  const j = await r.json()
@@ -206,7 +209,7 @@ window.__ModuleLoader__.load({
206
209
  style: S.inputWide,
207
210
  value,
208
211
  autoFocus: true,
209
- placeholder: 'D:/dsh work/self/quotes.md',
212
+ placeholder: 'C:/Users/me/.dsh/whale-whispers/quotes.md',
210
213
  onChange: (e) => setValue(e.target.value),
211
214
  onKeyDown: (e) => {
212
215
  if (e.key === 'Enter') save()
@@ -494,7 +497,8 @@ window.__ModuleLoader__.load({
494
497
  }, icon)
495
498
  }
496
499
 
497
- function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto: trashAutoProp = false, trashDays: trashDaysProp = 30, items = [], source = '', disabled = [], level: levelProp, version = '', rule: ruleProp = '', convRule: convRuleProp = '', manualAdd: manualAddProp = true, msgAction: msgActionProp = true, onDone = () => {} }) {
500
+ function Settings({ title = '', conv = '', book = '', removed = [], trash = [], trashAuto: trashAutoProp = false, trashDays: trashDaysProp = 30, items = [], source = '', disabled = [], level: levelProp, version = '', rule: ruleProp = '', convRule: convRuleProp = '', manualAdd: manualAddProp = true, msgAction: msgActionProp = true, convFiles: convFilesProp = [], onDone = () => {} }) {
501
+ if (!conv || conv === '__all__') conv = book || ''
498
502
  const LABEL = { conservative: '保守', normal: '正常', eager: '积极' }
499
503
  const [level, setLevel] = React.useState(typeof levelProp === 'string' ? levelProp : 'normal')
500
504
  const [busy, setBusy] = React.useState('')
@@ -519,13 +523,9 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
519
523
  const [msgBusy, setMsgBusy] = React.useState(false)
520
524
  const [manualBusy, setManualBusy] = React.useState(false)
521
525
  const convs = React.useMemo(() => {
522
- const seen = []
523
- ;(items || []).forEach((it) => {
524
- const name = (it && it.conversation) || ''
525
- if (seen.indexOf(name) < 0) seen.push(name)
526
- })
527
- return seen.sort((x, y) => (x || '').localeCompare(y || ''))
528
- }, [items])
526
+ const list = (convFilesProp || []).filter((n) => n && removedList.indexOf(n) < 0)
527
+ return Array.from(new Set(list)).sort((x, y) => String(x).localeCompare(String(y)))
528
+ }, [convFilesProp, removedList])
529
529
  const fileRef = React.useRef(null)
530
530
  const say = (text, where) => {
531
531
  setMsg(text)
@@ -626,10 +626,10 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
626
626
  h('div', { style: { fontSize: 14, fontWeight: 600 } }, '鲸语设置'),
627
627
  h('span', { style: { flex: 1 } }),
628
628
  h('button', { type: 'button', style: S.btn, onClick: onDone }, '关闭')),
629
- h('div', { style: { ...S.dim, fontSize: 11.5, marginBottom: 8 } }, '文件:' + source),
630
- row('对话', convs.length
629
+ h('div', { style: { ...S.dim, fontSize: 11.5, marginBottom: 8 } }, (conv ? '当前这本:' + conv + ' · ' : '') + '文件:' + source),
630
+ row('对话', Array.from(new Set([].concat(convs || [], (convFilesProp || []).filter((n) => removedList.indexOf(n) < 0)))).length
631
631
  ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 170, overflow: 'auto', minWidth: 250 } },
632
- convs.map((name) => {
632
+ Array.from(new Set([].concat(convs || [], (convFilesProp || []).filter((n) => removedList.indexOf(n) < 0)))).sort((a, b) => String(a).localeCompare(String(b))).map((name) => {
633
633
  const on = off.indexOf(name) < 0
634
634
  return h('div', { key: name || '__none', style: { display: 'flex', alignItems: 'center', gap: 8 } },
635
635
  h('span', { style: { fontSize: 12, flex: 1 } },
@@ -979,33 +979,27 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
979
979
  const sessionId = (props && props.sessionId) || ''
980
980
  const [conv, setConv] = React.useState('')
981
981
  const [undoItem, setUndoItem] = React.useState(null)
982
+ const [undoSnap, setUndoSnap] = React.useState('')
983
+ React.useEffect(() => {
984
+ let alive = true
985
+ fetch('/dsh-quotes.undo', { cache: 'no-store' })
986
+ .then((r) => r.json())
987
+ .then((j) => { if (alive && j && j.has) setUndoSnap(String(j.text || '')) })
988
+ .catch(() => { /* 探不到就不显示 */ })
989
+ return () => { alive = false }
990
+ }, [])
982
991
  React.useEffect(() => {
983
992
  if (!undoItem) return undefined
984
993
  const t = setTimeout(() => setUndoItem(null), 12000)
985
994
  return () => clearTimeout(t)
986
995
  }, [undoItem])
987
- const { loading, title, source, items, error, disabled, level, rule, convRule, captureRules, removed, trash, manualAdd, msgAction: msgActionCfg, trashAuto: trashAutoCfg, trashDays: trashDaysCfg, convs: convFiles, reload } = useQuotes(conv, sessionId)
988
- React.useEffect(() => {
989
- let alive = true
990
- const url = '/dsh-quotes.session' + (sessionId ? ('?b64sid=' + encodeURIComponent(b64(String(sessionId)))) : '')
991
- fetch(url, { cache: 'no-store' })
992
- .then((r) => r.json())
993
- .then((j) => {
994
- if (!alive) return
995
- const t = j && typeof j.title === 'string' ? j.title.trim() : ''
996
- if (!t) return
997
- setConv(t)
998
- try { window.localStorage.setItem('dsh-whale-whispers:conv', t) } catch { /* 忽略 */ }
999
- })
1000
- .catch(() => { /* 读不到就按老样子 */ })
1001
- return () => { alive = false }
1002
- }, [sessionId])
996
+ const { loading, title, book, source, items, error, disabled, level, rule, convRule, captureRules, removed, trash, manualAdd, msgAction: msgActionCfg, trashAuto: trashAutoCfg, trashDays: trashDaysCfg, convs: convFiles, reload } = useQuotes(conv, sessionId)
997
+ const allConv = conv === '__all__'
1003
998
 
1004
999
  const [q, setQ] = React.useState('')
1005
1000
  const [span, setSpan] = React.useState('all')
1006
1001
  const [spot, setSpot] = React.useState(null)
1007
1002
  const [onlyFav, setOnlyFav] = React.useState(false)
1008
- const [allConv, setAllConv] = React.useState(false)
1009
1003
  const [asc, setAsc] = React.useState(false)
1010
1004
  const [renaming, setRenaming] = React.useState(false)
1011
1005
  const [addOpen, setAddOpen] = React.useState(false)
@@ -1025,13 +1019,9 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1025
1019
  const [convDraft, setConvDraft] = React.useState('')
1026
1020
 
1027
1021
  const convs = React.useMemo(() => {
1028
- const set = new Set(convFiles || [])
1029
- for (const it of items) {
1030
- const name = String(it.conversation || '').trim()
1031
- if (name) set.add(name)
1032
- }
1022
+ const set = new Set((convFiles || []).filter((n) => n && removed.indexOf(n) < 0))
1033
1023
  return Array.from(set)
1034
- }, [items, convFiles])
1024
+ }, [removed, convFiles])
1035
1025
  const rootRef = useRefreshWhenVisible(reload)
1036
1026
 
1037
1027
  const shown = React.useMemo(() => {
@@ -1043,7 +1033,6 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1043
1033
  const ts = Number(it.ts) || Date.parse(String(it.date || '')) || 0
1044
1034
  if (ts < cutoff) return false
1045
1035
  }
1046
- if (!onlyFav && !allConv && !conv && false) return false
1047
1036
  if (!needle) return true
1048
1037
  return [it.text, it.note, it.context, it.conversation, it.date]
1049
1038
  .filter(Boolean).join(' ').toLowerCase().includes(needle)
@@ -1060,7 +1049,7 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1060
1049
  const g = Array.from(map.entries()).reverse()
1061
1050
  const list = asc ? g.map(([k, v]) => [k, v.slice().reverse()]).reverse() : g
1062
1051
  // 「全部对话」下即使是空书也占一行,不然刚建好的书看起来像不存在
1063
- if (allConv && !conv) {
1052
+ if (allConv) {
1064
1053
  for (const n of (convFiles || [])) {
1065
1054
  if (!list.some(([k]) => k === n)) list.push([n, []])
1066
1055
  }
@@ -1085,15 +1074,16 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1085
1074
  return h('div', { ref: rootRef, style: S.wrap },
1086
1075
  h('div', { style: { ...S.head, justifyContent: 'space-between' } },
1087
1076
  h('div', { style: { display: 'flex', alignItems: 'baseline', gap: 10 } },
1088
- h('h2', { style: S.title }, conv ? conv : '全部对话'),
1077
+ h('h2', { style: S.title }, allConv ? '全部对话' : (book || title)),
1089
1078
  h('span', { style: S.count }, items.length
1090
1079
  ? items.length + ' 句 · 收藏 ' + items.filter((i) => i.fav === true).length
1091
- + (conv ? '' : ' · ' + (convFiles || []).length + ' 本')
1080
+ + (allConv ? ' · ' + (convFiles || []).length + ' 本' : '')
1092
1081
  : '还没有')),
1093
- conv
1082
+ book && conv !== '__all__'
1094
1083
  ? h(Rename, {
1095
- title,
1096
- conv,
1084
+ title: book,
1085
+ conv: book,
1086
+ sid: sessionId,
1097
1087
  onDone: (n) => {
1098
1088
  if (n) {
1099
1089
  try { window.localStorage.setItem('dsh-whale-whispers:conv', n) } catch { /* 忽略 */ }
@@ -1133,10 +1123,10 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1133
1123
  h('button', { type: 'button', style: S.btn, onClick: () => setSpot(null) }, '收起')))
1134
1124
  : null,
1135
1125
  h('div', { style: S.bar },
1136
- h(ExportBar, { title, items, name: conv || '鲸语' }),
1126
+ h(ExportBar, { title, items, name: (conv === '__all__' || !book) ? '鲸语' : book }),
1137
1127
  manualAdd ? h('button', { type: 'button', style: S.btn, onClick: () => { setAddOpen(true); setAddMsg('') } }, '加一句') : null,
1138
1128
  h('select', {
1139
- value: conv,
1129
+ value: conv || book || '',
1140
1130
  title: '按对话筛选',
1141
1131
  onChange: (e) => {
1142
1132
  const v = e.target.value
@@ -1145,7 +1135,7 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1145
1135
  },
1146
1136
  style: { padding: '3px 6px', fontSize: 12, borderRadius: 6, border: '1px solid rgba(0,0,0,.18)', background: 'transparent', maxWidth: 150 },
1147
1137
  },
1148
- h('option', { value: '' }, '全部对话'),
1138
+ h('option', { value: '__all__' }, '全部对话'),
1149
1139
  convs.map((name) => h('option', { key: name, value: name }, name))),
1150
1140
  h('input', {
1151
1141
  type: 'search',
@@ -1156,9 +1146,9 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1156
1146
  }),
1157
1147
  h('button', {
1158
1148
  type: 'button',
1159
- title: allConv ? '现在连全对话一起搜,点一下只搜这本' : '现在只搜这本,点一下连全对话一起搜',
1149
+ title: allConv ? '现在连所有对话一起搜,点一下只看这本' : '现在只看这本,点一下连所有对话一起搜',
1160
1150
  style: { ...S.btn, opacity: allConv ? 1 : 0.6 },
1161
- onClick: () => setAllConv((v) => !v),
1151
+ onClick: () => setConv(allConv ? '' : '__all__'),
1162
1152
  }, allConv ? '搜全对话' : '搜本对话'),
1163
1153
  h('span', { style: { flex: 1 } }),
1164
1154
  h('button', {
@@ -1198,17 +1188,18 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1198
1188
  onClick: () => setSettingsOpen(true),
1199
1189
  }, '设置'),
1200
1190
  h(PathEditor, { source, onDone: reload }),
1201
- undoItem
1191
+ (undoItem || undoSnap)
1202
1192
  ? h('button', {
1203
1193
  type: 'button',
1204
1194
  style: { ...S.btn, color: '#b3261e' },
1205
- title: '撤销上一次删除:' + String(undoItem.text || '').slice(0, 40),
1195
+ title: '撤销上一次删除:' + String((undoItem && undoItem.text) || undoSnap || '').slice(0, 40),
1206
1196
  onClick: async () => {
1207
1197
  try {
1208
1198
  const r = await fetch('/dsh-quotes.undo', { method: 'POST' })
1209
1199
  const j = await r.json()
1210
1200
  if (!j || !j.ok) throw new Error((j && j.error) || '撤销失败')
1211
1201
  setUndoItem(null)
1202
+ setUndoSnap('')
1212
1203
  reload()
1213
1204
  } catch { /* 忽略 */ }
1214
1205
  },
@@ -1232,7 +1223,7 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1232
1223
  style: { width: '100%', fontSize: 13, lineHeight: 1.6, padding: 8, borderRadius: 8, border: '1px solid rgba(0,0,0,.18)', background: 'transparent', resize: 'vertical' },
1233
1224
  }),
1234
1225
  h('div', { style: { ...S.dim, fontSize: 11.5, marginTop: 6 } },
1235
- conv ? ('会记到「' + conv + '」下') : '没选对话,会记成「未标注对话」'),
1226
+ (conv && conv !== '__all__') ? ('会记到「' + conv + '」下') : '会记到当前对话那本'),
1236
1227
  addMsg ? h('div', { style: { fontSize: 12, color: '#1a7f37', marginTop: 6 } }, addMsg) : null,
1237
1228
  h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 12 } },
1238
1229
  h('button', { type: 'button', style: S.btn, onClick: () => setAddOpen(false) }, '取消'),
@@ -1246,7 +1237,7 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1246
1237
  const res = await fetch('/dsh-quotes.add', {
1247
1238
  method: 'POST',
1248
1239
  headers: { 'content-type': 'application/json' },
1249
- body: JSON.stringify({ text, conversation: conv || '' }),
1240
+ body: JSON.stringify({ text, conversation: (conv && conv !== '__all__') ? conv : '', sid: sessionId }),
1250
1241
  })
1251
1242
  const data = await res.json()
1252
1243
  if (!data || !data.ok) throw new Error((data && data.error) || '没写进去')
@@ -1261,6 +1252,7 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1261
1252
  ? h(Boundary, null, h(Settings, { level,
1262
1253
  title,
1263
1254
  conv,
1255
+ book,
1264
1256
  removed,
1265
1257
  trash,
1266
1258
  items,
@@ -1270,6 +1262,7 @@ function Settings({ title = '', conv = '', removed = [], trash = [], trashAuto:
1270
1262
  convRule,
1271
1263
  manualAdd,
1272
1264
  msgAction: msgActionCfg,
1265
+ convFiles,
1273
1266
  trashAuto: trashAutoCfg,
1274
1267
  trashDays: trashDaysCfg,
1275
1268
  onDone: () => { setSettingsOpen(false); reload() },
package/index.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * The tools and the panel resolve the same config through the same function, so one
17
17
  * operation has one implementation (see the plugin-development skill on user actions).
18
18
  */
19
- import { readFile, writeFile, rename, mkdir, readdir, stat, unlink } from 'node:fs/promises'
19
+ import { readFile, writeFile, rename, mkdir, readdir, stat, unlink, open } from 'node:fs/promises'
20
20
  import { readFileSync, readdirSync, statSync } from 'node:fs'
21
21
  import { dirname, join } from 'node:path'
22
22
  import { homedir } from 'node:os'
@@ -43,17 +43,17 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'agents']
43
43
 
44
44
  async function readJson(path) {
45
45
  try {
46
- return JSON.parse(await readFile(path, 'utf8'))
46
+ return JSON.parse(stripBom(await readFile(path, 'utf8')))
47
47
  } catch {
48
48
  return null
49
49
  }
50
50
  }
51
51
 
52
- /** Config candidates, most specific first: the author's spot, then the user's home. */
52
+ /** Config candidates, most specific first: the user's home, then an old author-side legacy spot. */
53
53
  function configCandidates() {
54
54
  return [
55
- 'D:/dsh work/self/quotes.config.json',
56
55
  join(homedir(), '.dsh', 'quotes.config.json'),
56
+ 'D:/dsh work/self/quotes.config.json',
57
57
  ]
58
58
  }
59
59
 
@@ -78,7 +78,7 @@ async function resolveTarget() {
78
78
 
79
79
 
80
80
 
81
- const DEFAULT_DIR = 'D:/dsh work/self/quotes'
81
+ const DEFAULT_DIR = join(homedir(), '.dsh', 'whale-whispers', 'quotes')
82
82
  const PLACEHOLDER = '(这一栏还空着——等我说第一句,或者你手动加一条)'
83
83
 
84
84
  /** 对话名 → 合法文件名。空名回落到 legacy。 */
@@ -132,7 +132,7 @@ async function quotesDir() {
132
132
 
133
133
  async function disabledList() {
134
134
  try {
135
- const parsed = JSON.parse(await readFile(join(homedir(), '.dsh', 'quotes.config.json'), 'utf8'))
135
+ const parsed = JSON.parse(stripBom(await readFile(join(homedir(), '.dsh', 'quotes.config.json'), 'utf8')))
136
136
  return Array.isArray(parsed && parsed.disabledConversations) ? parsed.disabledConversations : []
137
137
  } catch {
138
138
  return []
@@ -468,6 +468,52 @@ async function writeAtomic(path, content) {
468
468
  await rename(tmp, path)
469
469
  }
470
470
 
471
+ /** Windows 记事本爱在开头塞一个 BOM;JSON.parse 见到它必炸,先切掉。 */
472
+ export function stripBom(text) {
473
+ const s = typeof text === 'string' ? text : String(text == null ? '' : text)
474
+ return s.charCodeAt(0) === 0xfeff ? s.slice(1) : s
475
+ }
476
+
477
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
478
+
479
+ /**
480
+ * 同一个句子本可能被两只鱼同时写(宿主里一个进程、另开的 DSH 里一个进程)。
481
+ * 读-改-写之间不加锁,后写的那次会把先写的那句覆盖掉。
482
+ * 用 `<本子>.lock` 排他创建当锁:抢不到就等,锁太旧(进程崩了没删)就当没主。
483
+ */
484
+ export async function withQuoteLock(path, fn, { timeoutMs = 5000, staleMs = 15000 } = {}) {
485
+ const lock = `${path}.lock`
486
+ const started = Date.now()
487
+ let handle = null
488
+ for (;;) {
489
+ try {
490
+ handle = await open(lock, 'wx')
491
+ break
492
+ } catch (error) {
493
+ if (!error || error.code !== 'EEXIST') throw error
494
+ try {
495
+ const info = await stat(lock)
496
+ if (Date.now() - info.mtimeMs > staleMs) {
497
+ await unlink(lock).catch(() => {})
498
+ continue
499
+ }
500
+ } catch {
501
+ continue // 锁刚被别人放掉,重试
502
+ }
503
+ if (Date.now() - started > timeoutMs) {
504
+ throw new Error('本子正被另一个进程写着,等了 5 秒还没放开:' + lock)
505
+ }
506
+ await sleep(20 + Math.floor(Math.random() * 30))
507
+ }
508
+ }
509
+ try {
510
+ return await fn()
511
+ } finally {
512
+ try { await handle.close() } catch { /* 已经关了 */ }
513
+ await unlink(lock).catch(() => {})
514
+ }
515
+ }
516
+
471
517
  async function readSource(path) {
472
518
  try {
473
519
  return await readFile(path, 'utf8')
@@ -484,6 +530,22 @@ async function readSource(path) {
484
530
  }
485
531
 
486
532
  /** 星标是全局的:一本一句都要能看见,所以不跟着单本的 sidecar 走。 */
533
+ /** 解析缓存:同一文件(mtime+size 未变)不重复读盘、不重复 parse。 */
534
+ const __parsedCache = new Map()
535
+ const __PARSED_CACHE_MAX = 500
536
+
537
+ async function readParsedCached(path) {
538
+ let st = null
539
+ try { st = await stat(path) } catch { return { text: '', parsed: [] } }
540
+ const hit = __parsedCache.get(path)
541
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.value
542
+ const text = await readFile(path, 'utf8')
543
+ const value = { text, parsed: parseQuotes(text) }
544
+ if (__parsedCache.size >= __PARSED_CACHE_MAX) __parsedCache.clear()
545
+ __parsedCache.set(path, { mtimeMs: st.mtimeMs, size: st.size, value })
546
+ return value
547
+ }
548
+
487
549
  async function favFile(source) {
488
550
  const dir = await quotesDir()
489
551
  return join(dir, '.favs.json')
@@ -575,7 +637,7 @@ async function sessionTitleOf(sessionId) {
575
637
  const hit = names.indexOf(want) >= 0 ? want : names.find((n) => n.startsWith(String(sessionId)))
576
638
  if (!hit) return ''
577
639
  const raw = await readFile(dir + '/' + hit, 'utf8')
578
- const parsed = JSON.parse(raw)
640
+ const parsed = JSON.parse(stripBom(raw))
579
641
  const rows = (parsed && parsed.record && parsed.record.rows) || parsed || {}
580
642
  const t = rows && rows.title && (rows.title.val !== undefined ? rows.title.val : rows.title)
581
643
  return typeof t === 'string' ? t.trim() : ''
@@ -656,49 +718,70 @@ async function sessionTitleOf(sessionId) {
656
718
  }),
657
719
  )
658
720
 
659
- const listQuotes = async (conv, sid) => {
721
+ const bookNameOf = (dir, file) => file
722
+ ? String(file).slice(String(dir).length + 1).replace(/\.md$/i, '')
723
+ : ''
724
+
725
+ /**
726
+ * 给一个会话找它那本书:先认文件里的 `<!-- sid:... -->`,
727
+ * 找不到才按会话标题(或给定名字)建一本并打上标记。
728
+ * 以后会话改名、书改名都不会再凭名字去认书。
729
+ */
730
+ const sessionBook = async (dir, sidKey, fallbackName) => {
731
+ const key = String(sidKey || '').trim()
732
+ const found = key ? await findBySid(dir, key) : ''
733
+ if (found) return { path: found, conv: bookNameOf(dir, found), blocked: false }
734
+ let name = ''
735
+ if (key) {
736
+ try { name = safeConvName(await sessionTitleOf(key)) } catch { name = '' }
737
+ }
738
+ if (!name && fallbackName) name = safeConvName(fallbackName)
739
+ if (!name) name = '未命名'
740
+ const removedNow = await removedConvList()
741
+ if (removedNow.includes(name)) return { path: '', conv: name, blocked: true }
742
+ const exist = dir + '/' + name + '.md'
743
+ let has = false
744
+ try { await stat(exist); has = true } catch { has = false }
745
+ const file = has ? exist : await ensureConvFile(dir, name, true)
746
+ if (!file) return { path: '', conv: name, blocked: true }
747
+ if (key) await tagSid(file, key)
748
+ return { path: file, conv: name, blocked: false }
749
+ }
750
+
751
+ const listQuotes = async (conv, sid, mode) => {
660
752
  const cfgNow = (await readJson(configCandidates()[0])) || {}
661
753
  const dir = await quotesDir()
662
754
  const convs = await listConvFiles(dir)
663
- const active = conv ? await aliasOf(conv) : ''
664
- const meta = await resolveTarget()
755
+ const sidKey = String(sid || '').trim()
756
+ const wantAll = mode === 'all' || (!mode && !conv && !sidKey)
757
+ let active = ''
665
758
  let path = ''
666
- let source = ''
667
759
  let items = []
668
- if (active) {
669
- let useSid = false
670
- if (sid) {
671
- const ownTitle = await sessionTitleOf(sid)
672
- useSid = !active || !ownTitle || safeConvName(ownTitle) === active
673
- }
674
- path = (useSid ? await findBySid(dir, sid) : '') || (await ensureConvFile(dir, active))
675
- if (useSid) await tagSid(path, sid)
676
- source = await readSource(path)
760
+
761
+ const readBookSource = async (file, label) => {
762
+ let source = await readSource(file)
677
763
  const repaired = repairOrphans(source)
678
764
  if (repaired !== source) {
679
- await writeAtomic(path, repaired)
765
+ await writeAtomic(file, repaired)
680
766
  source = repaired
681
767
  }
682
768
  const real = parseQuotes(source).filter((it) => it.text && it.text.trim() && it.text.trim() !== PLACEHOLDER)
683
769
  if (!real.length) {
684
- const migrated = await migrateLegacy(dir, active)
770
+ const migrated = await migrateLegacy(dir, label)
685
771
  if (migrated) source = migrated
686
772
  }
687
- const favs = new Set((await readFavs(path)).map((x) => normalise(String(x))))
688
- items = parseQuotes(source).map((it) => ({
689
- ...it,
690
- conversation: String(it.conversation || '').trim() || active,
691
- fav: favs.has(normalise(it.text)),
692
- }))
693
- } else {
773
+ return source
774
+ }
775
+
776
+ if (wantAll) {
694
777
  // 「全部对话」:把所有对话文件聚起来(跳过占位句),按时间倒序
695
778
  const seen = new Set()
779
+ const favsAll = new Set((await readFavs(join(dir, '_'))).map((x) => normalise(String(x))))
696
780
  for (const n of convs) {
697
781
  const fp = dir + '/' + n + '.md'
698
- let text = ''
699
- try { text = await readFile(fp, 'utf8') } catch { continue }
700
- const favs = new Set((await readFavs(fp)).map((x) => normalise(String(x))))
701
- for (const it of parseQuotes(text)) {
782
+ const cached = await readParsedCached(fp)
783
+ if (!cached.parsed.length) continue
784
+ for (const it of cached.parsed) {
702
785
  const t = (it.text || '').trim()
703
786
  if (!t || t === PLACEHOLDER) continue
704
787
  const k = normalise(t)
@@ -708,20 +791,62 @@ async function sessionTitleOf(sessionId) {
708
791
  ...it,
709
792
  conv: n,
710
793
  conversation: String(it.conversation || '').trim() || n,
711
- fav: favs.has(k),
794
+ fav: favsAll.has(k),
712
795
  })
713
796
  }
714
797
  }
715
798
  items.sort((a, b) => (b.ts || 0) - (a.ts || 0))
716
799
  path = dir
800
+ } else if (mode === 'name' && conv) {
801
+ active = await aliasOf(safeConvName(conv))
802
+ const file = await ensureConvFile(dir, active)
803
+ if (file) {
804
+ path = file
805
+ const source = await readBookSource(file, active)
806
+ const favs = new Set((await readFavs(file)).map((x) => normalise(String(x))))
807
+ items = parseQuotes(source).map((it) => ({
808
+ ...it,
809
+ conversation: String(it.conversation || '').trim() || active,
810
+ fav: favs.has(normalise(it.text)),
811
+ }))
812
+ }
813
+ } else {
814
+ // 会话视图:sid 才是身份,书名只是标签
815
+ const book = await sessionBook(dir, sidKey, conv)
816
+ active = book.conv
817
+ if (book.path) {
818
+ path = book.path
819
+ const source = await readBookSource(book.path, active)
820
+ const favs = new Set((await readFavs(book.path)).map((x) => normalise(String(x))))
821
+ items = parseQuotes(source).map((it) => ({
822
+ ...it,
823
+ conversation: String(it.conversation || '').trim() || active,
824
+ fav: favs.has(normalise(it.text)),
825
+ }))
826
+ }
827
+ }
828
+
829
+ const title = typeof cfgNow.title === 'string' && cfgNow.title.trim() ? cfgNow.title.trim() : '鲸语'
830
+ // 下拉只列「真写过句子」的书;空壳(只有占位句)不占位置,当前这本例外。
831
+ const listed = []
832
+ for (const n of convs) {
833
+ if (active && n === active) { listed.push(n); continue }
834
+ const f = join(dir, n + '.md')
835
+ const cached = await readParsedCached(f).catch(() => null)
836
+ const rows = (cached && Array.isArray(cached.parsed)) ? cached.parsed : []
837
+ const real = rows.some((it) => {
838
+ const t = String((it && it.text) || '').trim()
839
+ return t && t !== PLACEHOLDER
840
+ })
841
+ if (real) listed.push(n)
717
842
  }
718
843
  return {
719
844
  ok: true,
720
- title: meta.title,
845
+ title,
721
846
  source: path,
722
847
  dir,
723
848
  conv: active,
724
- convs,
849
+ convs: listed,
725
850
  items,
726
851
  captureLevel: CAPTURE_RULES[cfgNow.captureLevel] ? cfgNow.captureLevel : 'normal',
727
852
  captureRule: typeof cfgNow.captureRule === 'string' ? cfgNow.captureRule : '',
@@ -752,12 +877,18 @@ async function sessionTitleOf(sessionId) {
752
877
  const path = target.path
753
878
  const title = target.title
754
879
  const label = convName || title
755
- const source = await readSource(path)
756
- const inserted = insertQuote(source, body, note ? String(note).trim() : '', context ? String(context).trim() : '', label)
880
+ // 读-改-写整段上锁:两只鱼同时记,后写的不会把前一句吞掉
881
+ const written = await withQuoteLock(path, async () => {
882
+ const source = await readSource(path)
883
+ const inserted = insertQuote(source, body, note ? String(note).trim() : '', context ? String(context).trim() : '', label)
884
+ const content = inserted.added ? dropPlaceholder(inserted.content) : inserted.content
885
+ if (inserted.added) await writeAtomic(path, content)
886
+ return { inserted, content }
887
+ })
888
+ const inserted = written.inserted
757
889
  const added = inserted.added
758
890
  const reason = inserted.reason
759
- const content = added ? dropPlaceholder(inserted.content) : inserted.content
760
- if (added) await writeAtomic(path, content)
891
+ const content = written.content
761
892
  return {
762
893
  ok: true,
763
894
  added,
@@ -772,11 +903,16 @@ async function sessionTitleOf(sessionId) {
772
903
  const removeQuote = async (text, conv) => {
773
904
  const wanted = normalise(text)
774
905
  if (!wanted) return { ok: false, error: 'text 不能为空' }
775
- const { path } = await targetFor(conv)
776
- const source = await readSource(path)
906
+ // 删除不能因为「这本还没建」就顺手建出一个空文件来(之前删未标注对话时就发生过)
907
+ let path = ''
908
+ let source = ''
909
+ if (conv) {
910
+ path = (await targetFor(conv)).path
911
+ try { source = await readFile(path, 'utf8') } catch { source = '' }
912
+ }
777
913
  const eol = source.includes('\r\n') ? '\r\n' : '\n'
778
- const lines = source.split(/\r?\n/)
779
- let at = lines.findIndex((l) => l.trim().startsWith('- ') && normalise(splitLine(l)) === wanted)
914
+ const lines = source ? source.split(/\r?\n/) : []
915
+ let at = path ? lines.findIndex((l) => l.trim().startsWith('- ') && normalise(splitLine(l)) === wanted) : -1
780
916
  if (at === -1) {
781
917
  // 句子可能写在别的对话文件里(例如早期按 sid 落盘但没带对话名),再扫一遍所有文件
782
918
  let altNames = []
@@ -784,7 +920,8 @@ async function sessionTitleOf(sessionId) {
784
920
  for (const name of altNames) {
785
921
  const alt = DEFAULT_DIR + '/' + name
786
922
  if (alt === path) continue
787
- const altSource = await readSource(alt)
923
+ let altSource = ''
924
+ try { altSource = await readFile(alt, 'utf8') } catch { continue }
788
925
  const altLines = altSource.split(/\r?\n/)
789
926
  const hit = altLines.findIndex((l) => l.trim().startsWith('- ') && normalise(splitLine(l)) === wanted)
790
927
  if (hit === -1) continue
@@ -852,20 +989,23 @@ async function sessionTitleOf(sessionId) {
852
989
  }
853
990
 
854
991
  /** Rename one conversation's own file (per-conversation mode). */
855
- const renameConvFile = async (from, to) => {
856
- const srcName = safeConvName(from)
992
+ const renameConvFile = async (from, to, sid) => {
857
993
  const dstName = safeConvName(to)
858
- if (!srcName || !dstName) return { ok: false, error: '新旧名字都要填' }
859
- if (srcName === dstName) return { ok: true, changed: 0 }
994
+ if (!dstName) return { ok: false, error: '新名字要填' }
860
995
  const dir = await quotesDir()
861
- const srcFile = dir + '/' + srcName + '.md'
862
- const dstFile = dir + '/' + dstName + '.md'
996
+ let srcName = safeConvName(from)
997
+ let srcFile = srcName ? dir + '/' + srcName + '.md' : ''
863
998
  let body = ''
864
- try {
999
+ try { body = await readFile(srcFile, 'utf8') } catch {
1000
+ // 名字对不上(会话改过名、语录早先也改过名)→ 按 sid 找真正的那本
1001
+ const bySid = sid ? await findBySid(dir, sid) : ''
1002
+ if (!bySid) return { ok: false, error: '没有这个对话的语录文件' }
1003
+ srcFile = bySid
1004
+ srcName = srcFile.slice(dir.length + 1).replace(/\.md$/i, '')
865
1005
  body = await readFile(srcFile, 'utf8')
866
- } catch {
867
- return { ok: false, error: '没有这个对话的语录文件' }
868
1006
  }
1007
+ if (srcName === dstName) return { ok: true, changed: 0 }
1008
+ const dstFile = dir + '/' + dstName + '.md'
869
1009
  try {
870
1010
  await stat(dstFile)
871
1011
  return { ok: false, error: '已经有同名目录了' }
@@ -880,7 +1020,12 @@ async function sessionTitleOf(sessionId) {
880
1020
  const cfgPath = configCandidates()[0]
881
1021
  const cfg = (await readJson(cfgPath)) || {}
882
1022
  const alias = (cfg && cfg.convAlias && typeof cfg.convAlias === 'object') ? cfg.convAlias : {}
883
- alias[srcName] = dstName
1023
+ // 旧名字、真实文件名、当前会话标题,统统指向新名字,免得下次又建一本空的
1024
+ let titleKey = ''
1025
+ if (sid) { try { titleKey = safeConvName(await sessionTitleOf(sid)) } catch { titleKey = '' } }
1026
+ for (const k of [srcName, safeConvName(from), titleKey]) {
1027
+ if (k && k !== dstName) alias[k] = dstName
1028
+ }
884
1029
  cfg.convAlias = alias
885
1030
  await writeJson(cfgPath, cfg)
886
1031
  } catch { /* 记不住别名也不影响改名本身 */ }
@@ -1005,8 +1150,9 @@ async function sessionTitleOf(sessionId) {
1005
1150
  const rawSid = cq.get('b64sid')
1006
1151
  sid = rawSid ? Buffer.from(rawSid, 'base64').toString('utf8') : (cq.get('sid') || '')
1007
1152
  } catch { sid = '' }
1153
+ const mode = cq.get('mode') || ''
1008
1154
  try {
1009
- payload = await listQuotes(conv, sid)
1155
+ payload = await listQuotes(conv, sid, mode)
1010
1156
  } catch (error) {
1011
1157
  payload = { ok: false, items: [], error: String((error && error.message) || error) }
1012
1158
  }
@@ -1089,7 +1235,7 @@ async function sessionTitleOf(sessionId) {
1089
1235
  if (!title && !pathValue && !captureLevel && !hasRule && manualAdd === null && msgAction === null && trashAuto === null && trashDays === null) return jsonSend(res, 400, { ok: false, error: '没有要改的字段' })
1090
1236
  if (title && title.length > 40) return jsonSend(res, 400, { ok: false, error: '标题太长(最多 40 字)' })
1091
1237
  if (pathValue && !/^([a-zA-Z]:[\\/]|\\\\|\/)/.test(pathValue)) {
1092
- return jsonSend(res, 400, { ok: false, error: '请填绝对路径,例如 D:/dsh work/self/quotes.md' })
1238
+ return jsonSend(res, 400, { ok: false, error: '请填绝对路径,例如 C:/Users/me/.dsh/whale-whispers/quotes.md' })
1093
1239
  }
1094
1240
 
1095
1241
  try {
@@ -1167,7 +1313,7 @@ async function sessionTitleOf(sessionId) {
1167
1313
  } catch { /* 单个文件读不到就算了 */ }
1168
1314
  }
1169
1315
  if (!best) return ''
1170
- const data = JSON.parse(readFileSync(join(dir, best), 'utf8'))
1316
+ const data = JSON.parse(stripBom(readFileSync(join(dir, best), 'utf8')))
1171
1317
  const t = data && data.record && data.record.rows && data.record.rows.title
1172
1318
  return t && typeof t.val === 'string' ? t.val.trim() : ''
1173
1319
  } catch {
@@ -1180,7 +1326,7 @@ async function sessionTitleOf(sessionId) {
1180
1326
  let rule = ''
1181
1327
  try {
1182
1328
  const cfgPath = join(homedir(), '.dsh', 'quotes.config.json')
1183
- const parsed = JSON.parse(readFileSync(cfgPath, 'utf8'))
1329
+ const parsed = JSON.parse(stripBom(readFileSync(cfgPath, 'utf8')))
1184
1330
  if (parsed && CAPTURE_RULES[parsed.captureLevel]) level = parsed.captureLevel
1185
1331
  if (parsed && typeof parsed.captureRule === 'string') rule = parsed.captureRule.trim()
1186
1332
  if (parsed && parsed.captureRules && typeof parsed.captureRules === 'object') {
@@ -1192,7 +1338,7 @@ async function sessionTitleOf(sessionId) {
1192
1338
  }
1193
1339
  try {
1194
1340
  const cfgPath = join(homedir(), '.dsh', 'quotes.config.json')
1195
- const parsed2 = JSON.parse(readFileSync(cfgPath, 'utf8'))
1341
+ const parsed2 = JSON.parse(stripBom(readFileSync(cfgPath, 'utf8')))
1196
1342
  const cur2 = currentConvSync()
1197
1343
  if (cur2 && parsed2 && Array.isArray(parsed2.disabledConversations) && parsed2.disabledConversations.includes(cur2)) return ''
1198
1344
  } catch {
@@ -1237,14 +1383,23 @@ async function sessionTitleOf(sessionId) {
1237
1383
  }
1238
1384
  if (!text) return jsonSend(res, 400, { ok: false, error: 'text 不能为空' })
1239
1385
 
1386
+ let convArg = fixMojibake(q.get('conv') || '')
1387
+ if (!convArg) {
1388
+ try {
1389
+ const body = JSON.parse(raw || '{}') || {}
1390
+ convArg = fixMojibake(typeof body.conv === 'string' ? body.conv : '')
1391
+ } catch { convArg = '' }
1392
+ }
1240
1393
  try {
1241
- const conv = fixMojibake(q.get('conv') || '')
1242
- const out = await removeQuote(text, conv)
1243
- if (out && out.ok && Array.isArray(out.block) && out.block.length) {
1244
- try {
1394
+ const out = await removeQuote(text, convArg)
1395
+ try {
1396
+ if (out && out.ok && Array.isArray(out.block) && out.block.length) {
1245
1397
  await writeAtomic(DEFAULT_DIR + '/.undo.json', JSON.stringify({ file: out.source, block: out.block }))
1246
- } catch { /* 快照失败不影响删除 */ }
1247
- }
1398
+ } else if (out && out.ok) {
1399
+ /* 没抓到整块(例如跨文件删到的旧格式行),就不要留着上一次的快照误导人 */
1400
+ await writeAtomic(DEFAULT_DIR + '/.undo.json', '')
1401
+ }
1402
+ } catch { /* 快照失败不影响删除 */ }
1248
1403
  jsonSend(res, 200, out)
1249
1404
  } catch (error) {
1250
1405
  jsonSend(res, 500, { ok: false, error: String((error && error.message) || error) })
@@ -1260,6 +1415,12 @@ async function sessionTitleOf(sessionId) {
1260
1415
  kind: 'exact',
1261
1416
  path: UNDO_ROUTE,
1262
1417
  handler: async (req, res) => {
1418
+ if (req.method === 'GET') {
1419
+ let peek = null
1420
+ try { peek = await readJson(DEFAULT_DIR + '/.undo.json') } catch (e) { peek = null }
1421
+ const hasPeek = !!(peek && Array.isArray(peek.block) && peek.block.length)
1422
+ return jsonSend(res, 200, { ok: true, has: hasPeek, text: hasPeek ? splitLine(peek.block[0] || '') : '' })
1423
+ }
1263
1424
  if (req.method !== 'POST') return jsonSend(res, 405, { ok: false, error: 'POST only' })
1264
1425
  try {
1265
1426
  const snap = await readJson(DEFAULT_DIR + '/.undo.json')
@@ -1302,23 +1463,26 @@ async function sessionTitleOf(sessionId) {
1302
1463
  }
1303
1464
  let text = dec(q.get('b64text'))
1304
1465
  let conversation = dec(q.get('b64conv'))
1305
- if (!text) {
1466
+ let sidArg = dec(q.get('b64sid'))
1467
+ if (!text || !conversation || !sidArg) {
1306
1468
  try {
1307
1469
  const body = JSON.parse(raw || '{}') || {}
1308
- text = fixMojibake(typeof body.text === 'string' ? body.text : '').trim()
1309
- conversation = fixMojibake(typeof body.conversation === 'string' ? body.conversation : conversation).trim()
1470
+ if (!text) text = fixMojibake(typeof body.text === 'string' ? body.text : '').trim()
1471
+ if (!conversation) conversation = fixMojibake(typeof body.conversation === 'string' ? body.conversation : conversation).trim()
1472
+ if (!sidArg) {
1473
+ const bs = body.sid || body.sessionId
1474
+ if (typeof bs === 'string' && bs.trim()) sidArg = bs.trim()
1475
+ }
1310
1476
  } catch { /* 忽略 */ }
1311
1477
  }
1312
1478
  if (!text) return jsonSend(res, 400, { ok: false, error: 'text 不能为空' })
1313
- if (!conversation) {
1314
- const sid = dec(q.get('b64sid'))
1315
- if (sid) conversation = await sessionTitleOf(sid)
1316
- }
1479
+ const convGiven = conversation
1480
+ if (!conversation && sidArg) conversation = await sessionTitleOf(sidArg)
1317
1481
  // 目录改过名之后,用别名回到真实目录,免得又写出一个同名目录
1318
1482
  if (conversation) conversation = await aliasOf(conversation)
1319
1483
  // 按 messageId 回源到会话事件,拿真正那一条回复的文本
1320
1484
  {
1321
- const sid2 = dec(q.get('b64sid'))
1485
+ const sid2 = sidArg
1322
1486
  const mid = dec(q.get('b64mid'))
1323
1487
  if (sid2 && mid) {
1324
1488
  const exact = messageTextOf(sid2, mid)
@@ -1328,15 +1492,31 @@ async function sessionTitleOf(sessionId) {
1328
1492
  if (text.length > 500) return jsonSend(res, 400, { ok: false, error: '太长了(最多 500 字)' })
1329
1493
 
1330
1494
  try {
1331
- const target = await targetFor(conversation, true)
1495
+ let target
1496
+ if (sidArg && !convGiven) {
1497
+ // 没指定书名 = 「本对话」:严格按 sessionId 找那本
1498
+ const dirNow = await quotesDir()
1499
+ const book = await sessionBook(dirNow, sidArg, conversation)
1500
+ if (book.blocked || !book.path) {
1501
+ return jsonSend(res, 400, { ok: false, error: '这本在回收站里,先在设置里点「恢复」收回来再记' })
1502
+ }
1503
+ target = { path: book.path, conv: book.conv, title: conversation }
1504
+ } else {
1505
+ // 明确指定了某一本:按书名写,别被当前会话的 sid 抢走
1506
+ target = await targetFor(conversation, true)
1507
+ }
1332
1508
  const path = target.path
1333
1509
  if (!path) {
1334
1510
  return jsonSend(res, 400, { ok: false, error: '这本在回收站里,先在设置里点「恢复」收回来再记' })
1335
1511
  }
1336
- const source = await readSource(path)
1337
- const result = insertQuote(source, text, '', '', safeConvName(conversation))
1338
- if (!result || !result.added) return jsonSend(res, 200, { ok: true, duplicate: true, conv: target.conv })
1339
- await writeFile(path, dropPlaceholder(result.content), 'utf8')
1512
+ const done = await withQuoteLock(path, async () => {
1513
+ const source = await readSource(path)
1514
+ const result = insertQuote(source, text, '', '', safeConvName(conversation))
1515
+ if (!result || !result.added) return { added: false }
1516
+ await writeAtomic(path, dropPlaceholder(result.content))
1517
+ return { added: true }
1518
+ })
1519
+ if (!done.added) return jsonSend(res, 200, { ok: true, duplicate: true, conv: target.conv })
1340
1520
  jsonSend(res, 200, { ok: true, conv: target.conv })
1341
1521
  } catch (error) {
1342
1522
  jsonSend(res, 500, { ok: false, error: String((error && error.message) || error) })
@@ -1409,8 +1589,9 @@ async function sessionTitleOf(sessionId) {
1409
1589
  }
1410
1590
  const from = dec(q.get('b64from'))
1411
1591
  const to = dec(q.get('b64to'))
1592
+ const rsid = dec(q.get('b64sid'))
1412
1593
  try {
1413
- jsonSend(res, 200, await renameConvFile(from, to))
1594
+ jsonSend(res, 200, await renameConvFile(from, to, rsid))
1414
1595
  } catch (error) {
1415
1596
  jsonSend(res, 500, { ok: false, error: String((error && error.message) || error) })
1416
1597
  }
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Whale Whispers",
4
- "description": "Some words sink the moment they are said. Whale Whispers fishes them back into a small drawer under the composer - open it whenever you want to hear them again."
4
+ "description": "Lines worth keeping, one markdown book per conversation, in a tab of the chat header."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "鲸语",
4
- "description": "有些话说出口就沉下去了。鲸语把它们捞回来,收进输入框下面的小抽屉——等你想再听时,点开就能听到。"
4
+ "description": "有些话说出口就沉下去了。鲸语把它们捞回来,收进会话头部的「鲸语」标签页——每个对话一本,等你想再听时点开就是。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-whale-whispers",
3
- "version": "1.20.4",
3
+ "version": "2.0.7",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",