dsh-whale-whispers 1.21.0 → 2.0.8

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, convFiles: convFilesProp = [], 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,7 +626,7 @@ 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),
629
+ h('div', { style: { ...S.dim, fontSize: 11.5, marginBottom: 8 } }, (conv ? '当前这本:' + conv + ' · ' : '') + '文件:' + source),
630
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
632
  Array.from(new Set([].concat(convs || [], (convFilesProp || []).filter((n) => removedList.indexOf(n) < 0)))).sort((a, b) => String(a).localeCompare(String(b))).map((name) => {
@@ -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,
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')
@@ -591,7 +637,7 @@ async function sessionTitleOf(sessionId) {
591
637
  const hit = names.indexOf(want) >= 0 ? want : names.find((n) => n.startsWith(String(sessionId)))
592
638
  if (!hit) return ''
593
639
  const raw = await readFile(dir + '/' + hit, 'utf8')
594
- const parsed = JSON.parse(raw)
640
+ const parsed = JSON.parse(stripBom(raw))
595
641
  const rows = (parsed && parsed.record && parsed.record.rows) || parsed || {}
596
642
  const t = rows && rows.title && (rows.title.val !== undefined ? rows.title.val : rows.title)
597
643
  return typeof t === 'string' ? t.trim() : ''
@@ -672,41 +718,62 @@ async function sessionTitleOf(sessionId) {
672
718
  }),
673
719
  )
674
720
 
675
- 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) => {
676
752
  const cfgNow = (await readJson(configCandidates()[0])) || {}
677
753
  const dir = await quotesDir()
678
754
  const convs = await listConvFiles(dir)
679
- const active = conv ? await aliasOf(conv) : ''
680
- const meta = await resolveTarget()
755
+ const sidKey = String(sid || '').trim()
756
+ const wantAll = mode === 'all' || (!mode && !conv && !sidKey)
757
+ let active = ''
681
758
  let path = ''
682
- let source = ''
683
759
  let items = []
684
- if (active) {
685
- let useSid = false
686
- if (sid) {
687
- const ownTitle = await sessionTitleOf(sid)
688
- useSid = !active || !ownTitle || safeConvName(ownTitle) === active
689
- }
690
- path = (useSid ? await findBySid(dir, sid) : '') || (await ensureConvFile(dir, active))
691
- if (useSid) await tagSid(path, sid)
692
- source = await readSource(path)
760
+
761
+ const readBookSource = async (file, label) => {
762
+ let source = await readSource(file)
693
763
  const repaired = repairOrphans(source)
694
764
  if (repaired !== source) {
695
- await writeAtomic(path, repaired)
765
+ await writeAtomic(file, repaired)
696
766
  source = repaired
697
767
  }
698
768
  const real = parseQuotes(source).filter((it) => it.text && it.text.trim() && it.text.trim() !== PLACEHOLDER)
699
769
  if (!real.length) {
700
- const migrated = await migrateLegacy(dir, active)
770
+ const migrated = await migrateLegacy(dir, label)
701
771
  if (migrated) source = migrated
702
772
  }
703
- const favs = new Set((await readFavs(path)).map((x) => normalise(String(x))))
704
- items = parseQuotes(source).map((it) => ({
705
- ...it,
706
- conversation: String(it.conversation || '').trim() || active,
707
- fav: favs.has(normalise(it.text)),
708
- }))
709
- } else {
773
+ return source
774
+ }
775
+
776
+ if (wantAll) {
710
777
  // 「全部对话」:把所有对话文件聚起来(跳过占位句),按时间倒序
711
778
  const seen = new Set()
712
779
  const favsAll = new Set((await readFavs(join(dir, '_'))).map((x) => normalise(String(x))))
@@ -730,14 +797,56 @@ async function sessionTitleOf(sessionId) {
730
797
  }
731
798
  items.sort((a, b) => (b.ts || 0) - (a.ts || 0))
732
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)
733
842
  }
734
843
  return {
735
844
  ok: true,
736
- title: meta.title,
845
+ title,
737
846
  source: path,
738
847
  dir,
739
848
  conv: active,
740
- convs,
849
+ convs: listed,
741
850
  items,
742
851
  captureLevel: CAPTURE_RULES[cfgNow.captureLevel] ? cfgNow.captureLevel : 'normal',
743
852
  captureRule: typeof cfgNow.captureRule === 'string' ? cfgNow.captureRule : '',
@@ -768,12 +877,18 @@ async function sessionTitleOf(sessionId) {
768
877
  const path = target.path
769
878
  const title = target.title
770
879
  const label = convName || title
771
- const source = await readSource(path)
772
- 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
773
889
  const added = inserted.added
774
890
  const reason = inserted.reason
775
- const content = added ? dropPlaceholder(inserted.content) : inserted.content
776
- if (added) await writeAtomic(path, content)
891
+ const content = written.content
777
892
  return {
778
893
  ok: true,
779
894
  added,
@@ -788,19 +903,32 @@ async function sessionTitleOf(sessionId) {
788
903
  const removeQuote = async (text, conv) => {
789
904
  const wanted = normalise(text)
790
905
  if (!wanted) return { ok: false, error: 'text 不能为空' }
791
- const { path } = await targetFor(conv)
792
- 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
+ }
793
913
  const eol = source.includes('\r\n') ? '\r\n' : '\n'
794
- const lines = source.split(/\r?\n/)
795
- 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
796
916
  if (at === -1) {
797
- // 句子可能写在别的对话文件里(例如早期按 sid 落盘但没带对话名),再扫一遍所有文件
917
+ // 句子可能写在别的对话文件里(例如早期按 sid 落盘但没带对话名),再扫一遍所有文件。
918
+ // 不带 conv 时 append 写的是 config 里的 legacy 文件(resolveTarget),所以先认它;目录也要用 quotesDir()(会读 config),不能写死 DEFAULT_DIR。
919
+ const quoteDir = await quotesDir()
920
+ const legacyPath = (await resolveTarget()).path
921
+ const altPaths = []
922
+ if (legacyPath && legacyPath !== path) altPaths.push(legacyPath)
798
923
  let altNames = []
799
- try { altNames = (await readdir(DEFAULT_DIR)).filter((n) => n.endsWith('.md')) } catch { altNames = [] }
924
+ try { altNames = (await readdir(quoteDir)).filter((n) => n.endsWith('.md')) } catch { altNames = [] }
800
925
  for (const name of altNames) {
801
- const alt = DEFAULT_DIR + '/' + name
802
- if (alt === path) continue
803
- const altSource = await readSource(alt)
926
+ const alt = quoteDir + '/' + name
927
+ if (alt !== path && altPaths.indexOf(alt) === -1) altPaths.push(alt)
928
+ }
929
+ for (const alt of altPaths) {
930
+ let altSource = ''
931
+ try { altSource = await readFile(alt, 'utf8') } catch { continue }
804
932
  const altLines = altSource.split(/\r?\n/)
805
933
  const hit = altLines.findIndex((l) => l.trim().startsWith('- ') && normalise(splitLine(l)) === wanted)
806
934
  if (hit === -1) continue
@@ -868,20 +996,23 @@ async function sessionTitleOf(sessionId) {
868
996
  }
869
997
 
870
998
  /** Rename one conversation's own file (per-conversation mode). */
871
- const renameConvFile = async (from, to) => {
872
- const srcName = safeConvName(from)
999
+ const renameConvFile = async (from, to, sid) => {
873
1000
  const dstName = safeConvName(to)
874
- if (!srcName || !dstName) return { ok: false, error: '新旧名字都要填' }
875
- if (srcName === dstName) return { ok: true, changed: 0 }
1001
+ if (!dstName) return { ok: false, error: '新名字要填' }
876
1002
  const dir = await quotesDir()
877
- const srcFile = dir + '/' + srcName + '.md'
878
- const dstFile = dir + '/' + dstName + '.md'
1003
+ let srcName = safeConvName(from)
1004
+ let srcFile = srcName ? dir + '/' + srcName + '.md' : ''
879
1005
  let body = ''
880
- try {
1006
+ try { body = await readFile(srcFile, 'utf8') } catch {
1007
+ // 名字对不上(会话改过名、语录早先也改过名)→ 按 sid 找真正的那本
1008
+ const bySid = sid ? await findBySid(dir, sid) : ''
1009
+ if (!bySid) return { ok: false, error: '没有这个对话的语录文件' }
1010
+ srcFile = bySid
1011
+ srcName = srcFile.slice(dir.length + 1).replace(/\.md$/i, '')
881
1012
  body = await readFile(srcFile, 'utf8')
882
- } catch {
883
- return { ok: false, error: '没有这个对话的语录文件' }
884
1013
  }
1014
+ if (srcName === dstName) return { ok: true, changed: 0 }
1015
+ const dstFile = dir + '/' + dstName + '.md'
885
1016
  try {
886
1017
  await stat(dstFile)
887
1018
  return { ok: false, error: '已经有同名目录了' }
@@ -896,7 +1027,12 @@ async function sessionTitleOf(sessionId) {
896
1027
  const cfgPath = configCandidates()[0]
897
1028
  const cfg = (await readJson(cfgPath)) || {}
898
1029
  const alias = (cfg && cfg.convAlias && typeof cfg.convAlias === 'object') ? cfg.convAlias : {}
899
- alias[srcName] = dstName
1030
+ // 旧名字、真实文件名、当前会话标题,统统指向新名字,免得下次又建一本空的
1031
+ let titleKey = ''
1032
+ if (sid) { try { titleKey = safeConvName(await sessionTitleOf(sid)) } catch { titleKey = '' } }
1033
+ for (const k of [srcName, safeConvName(from), titleKey]) {
1034
+ if (k && k !== dstName) alias[k] = dstName
1035
+ }
900
1036
  cfg.convAlias = alias
901
1037
  await writeJson(cfgPath, cfg)
902
1038
  } catch { /* 记不住别名也不影响改名本身 */ }
@@ -1021,8 +1157,9 @@ async function sessionTitleOf(sessionId) {
1021
1157
  const rawSid = cq.get('b64sid')
1022
1158
  sid = rawSid ? Buffer.from(rawSid, 'base64').toString('utf8') : (cq.get('sid') || '')
1023
1159
  } catch { sid = '' }
1160
+ const mode = cq.get('mode') || ''
1024
1161
  try {
1025
- payload = await listQuotes(conv, sid)
1162
+ payload = await listQuotes(conv, sid, mode)
1026
1163
  } catch (error) {
1027
1164
  payload = { ok: false, items: [], error: String((error && error.message) || error) }
1028
1165
  }
@@ -1105,7 +1242,7 @@ async function sessionTitleOf(sessionId) {
1105
1242
  if (!title && !pathValue && !captureLevel && !hasRule && manualAdd === null && msgAction === null && trashAuto === null && trashDays === null) return jsonSend(res, 400, { ok: false, error: '没有要改的字段' })
1106
1243
  if (title && title.length > 40) return jsonSend(res, 400, { ok: false, error: '标题太长(最多 40 字)' })
1107
1244
  if (pathValue && !/^([a-zA-Z]:[\\/]|\\\\|\/)/.test(pathValue)) {
1108
- return jsonSend(res, 400, { ok: false, error: '请填绝对路径,例如 D:/dsh work/self/quotes.md' })
1245
+ return jsonSend(res, 400, { ok: false, error: '请填绝对路径,例如 C:/Users/me/.dsh/whale-whispers/quotes.md' })
1109
1246
  }
1110
1247
 
1111
1248
  try {
@@ -1183,7 +1320,7 @@ async function sessionTitleOf(sessionId) {
1183
1320
  } catch { /* 单个文件读不到就算了 */ }
1184
1321
  }
1185
1322
  if (!best) return ''
1186
- const data = JSON.parse(readFileSync(join(dir, best), 'utf8'))
1323
+ const data = JSON.parse(stripBom(readFileSync(join(dir, best), 'utf8')))
1187
1324
  const t = data && data.record && data.record.rows && data.record.rows.title
1188
1325
  return t && typeof t.val === 'string' ? t.val.trim() : ''
1189
1326
  } catch {
@@ -1196,7 +1333,7 @@ async function sessionTitleOf(sessionId) {
1196
1333
  let rule = ''
1197
1334
  try {
1198
1335
  const cfgPath = join(homedir(), '.dsh', 'quotes.config.json')
1199
- const parsed = JSON.parse(readFileSync(cfgPath, 'utf8'))
1336
+ const parsed = JSON.parse(stripBom(readFileSync(cfgPath, 'utf8')))
1200
1337
  if (parsed && CAPTURE_RULES[parsed.captureLevel]) level = parsed.captureLevel
1201
1338
  if (parsed && typeof parsed.captureRule === 'string') rule = parsed.captureRule.trim()
1202
1339
  if (parsed && parsed.captureRules && typeof parsed.captureRules === 'object') {
@@ -1208,7 +1345,7 @@ async function sessionTitleOf(sessionId) {
1208
1345
  }
1209
1346
  try {
1210
1347
  const cfgPath = join(homedir(), '.dsh', 'quotes.config.json')
1211
- const parsed2 = JSON.parse(readFileSync(cfgPath, 'utf8'))
1348
+ const parsed2 = JSON.parse(stripBom(readFileSync(cfgPath, 'utf8')))
1212
1349
  const cur2 = currentConvSync()
1213
1350
  if (cur2 && parsed2 && Array.isArray(parsed2.disabledConversations) && parsed2.disabledConversations.includes(cur2)) return ''
1214
1351
  } catch {
@@ -1253,14 +1390,23 @@ async function sessionTitleOf(sessionId) {
1253
1390
  }
1254
1391
  if (!text) return jsonSend(res, 400, { ok: false, error: 'text 不能为空' })
1255
1392
 
1393
+ let convArg = fixMojibake(q.get('conv') || '')
1394
+ if (!convArg) {
1395
+ try {
1396
+ const body = JSON.parse(raw || '{}') || {}
1397
+ convArg = fixMojibake(typeof body.conv === 'string' ? body.conv : '')
1398
+ } catch { convArg = '' }
1399
+ }
1256
1400
  try {
1257
- const conv = fixMojibake(q.get('conv') || '')
1258
- const out = await removeQuote(text, conv)
1259
- if (out && out.ok && Array.isArray(out.block) && out.block.length) {
1260
- try {
1401
+ const out = await removeQuote(text, convArg)
1402
+ try {
1403
+ if (out && out.ok && Array.isArray(out.block) && out.block.length) {
1261
1404
  await writeAtomic(DEFAULT_DIR + '/.undo.json', JSON.stringify({ file: out.source, block: out.block }))
1262
- } catch { /* 快照失败不影响删除 */ }
1263
- }
1405
+ } else if (out && out.ok) {
1406
+ /* 没抓到整块(例如跨文件删到的旧格式行),就不要留着上一次的快照误导人 */
1407
+ await writeAtomic(DEFAULT_DIR + '/.undo.json', '')
1408
+ }
1409
+ } catch { /* 快照失败不影响删除 */ }
1264
1410
  jsonSend(res, 200, out)
1265
1411
  } catch (error) {
1266
1412
  jsonSend(res, 500, { ok: false, error: String((error && error.message) || error) })
@@ -1276,6 +1422,12 @@ async function sessionTitleOf(sessionId) {
1276
1422
  kind: 'exact',
1277
1423
  path: UNDO_ROUTE,
1278
1424
  handler: async (req, res) => {
1425
+ if (req.method === 'GET') {
1426
+ let peek = null
1427
+ try { peek = await readJson(DEFAULT_DIR + '/.undo.json') } catch (e) { peek = null }
1428
+ const hasPeek = !!(peek && Array.isArray(peek.block) && peek.block.length)
1429
+ return jsonSend(res, 200, { ok: true, has: hasPeek, text: hasPeek ? splitLine(peek.block[0] || '') : '' })
1430
+ }
1279
1431
  if (req.method !== 'POST') return jsonSend(res, 405, { ok: false, error: 'POST only' })
1280
1432
  try {
1281
1433
  const snap = await readJson(DEFAULT_DIR + '/.undo.json')
@@ -1318,23 +1470,26 @@ async function sessionTitleOf(sessionId) {
1318
1470
  }
1319
1471
  let text = dec(q.get('b64text'))
1320
1472
  let conversation = dec(q.get('b64conv'))
1321
- if (!text) {
1473
+ let sidArg = dec(q.get('b64sid'))
1474
+ if (!text || !conversation || !sidArg) {
1322
1475
  try {
1323
1476
  const body = JSON.parse(raw || '{}') || {}
1324
- text = fixMojibake(typeof body.text === 'string' ? body.text : '').trim()
1325
- conversation = fixMojibake(typeof body.conversation === 'string' ? body.conversation : conversation).trim()
1477
+ if (!text) text = fixMojibake(typeof body.text === 'string' ? body.text : '').trim()
1478
+ if (!conversation) conversation = fixMojibake(typeof body.conversation === 'string' ? body.conversation : conversation).trim()
1479
+ if (!sidArg) {
1480
+ const bs = body.sid || body.sessionId
1481
+ if (typeof bs === 'string' && bs.trim()) sidArg = bs.trim()
1482
+ }
1326
1483
  } catch { /* 忽略 */ }
1327
1484
  }
1328
1485
  if (!text) return jsonSend(res, 400, { ok: false, error: 'text 不能为空' })
1329
- if (!conversation) {
1330
- const sid = dec(q.get('b64sid'))
1331
- if (sid) conversation = await sessionTitleOf(sid)
1332
- }
1486
+ const convGiven = conversation
1487
+ if (!conversation && sidArg) conversation = await sessionTitleOf(sidArg)
1333
1488
  // 目录改过名之后,用别名回到真实目录,免得又写出一个同名目录
1334
1489
  if (conversation) conversation = await aliasOf(conversation)
1335
1490
  // 按 messageId 回源到会话事件,拿真正那一条回复的文本
1336
1491
  {
1337
- const sid2 = dec(q.get('b64sid'))
1492
+ const sid2 = sidArg
1338
1493
  const mid = dec(q.get('b64mid'))
1339
1494
  if (sid2 && mid) {
1340
1495
  const exact = messageTextOf(sid2, mid)
@@ -1344,15 +1499,31 @@ async function sessionTitleOf(sessionId) {
1344
1499
  if (text.length > 500) return jsonSend(res, 400, { ok: false, error: '太长了(最多 500 字)' })
1345
1500
 
1346
1501
  try {
1347
- const target = await targetFor(conversation, true)
1502
+ let target
1503
+ if (sidArg && !convGiven) {
1504
+ // 没指定书名 = 「本对话」:严格按 sessionId 找那本
1505
+ const dirNow = await quotesDir()
1506
+ const book = await sessionBook(dirNow, sidArg, conversation)
1507
+ if (book.blocked || !book.path) {
1508
+ return jsonSend(res, 400, { ok: false, error: '这本在回收站里,先在设置里点「恢复」收回来再记' })
1509
+ }
1510
+ target = { path: book.path, conv: book.conv, title: conversation }
1511
+ } else {
1512
+ // 明确指定了某一本:按书名写,别被当前会话的 sid 抢走
1513
+ target = await targetFor(conversation, true)
1514
+ }
1348
1515
  const path = target.path
1349
1516
  if (!path) {
1350
1517
  return jsonSend(res, 400, { ok: false, error: '这本在回收站里,先在设置里点「恢复」收回来再记' })
1351
1518
  }
1352
- const source = await readSource(path)
1353
- const result = insertQuote(source, text, '', '', safeConvName(conversation))
1354
- if (!result || !result.added) return jsonSend(res, 200, { ok: true, duplicate: true, conv: target.conv })
1355
- await writeFile(path, dropPlaceholder(result.content), 'utf8')
1519
+ const done = await withQuoteLock(path, async () => {
1520
+ const source = await readSource(path)
1521
+ const result = insertQuote(source, text, '', '', safeConvName(conversation))
1522
+ if (!result || !result.added) return { added: false }
1523
+ await writeAtomic(path, dropPlaceholder(result.content))
1524
+ return { added: true }
1525
+ })
1526
+ if (!done.added) return jsonSend(res, 200, { ok: true, duplicate: true, conv: target.conv })
1356
1527
  jsonSend(res, 200, { ok: true, conv: target.conv })
1357
1528
  } catch (error) {
1358
1529
  jsonSend(res, 500, { ok: false, error: String((error && error.message) || error) })
@@ -1425,8 +1596,9 @@ async function sessionTitleOf(sessionId) {
1425
1596
  }
1426
1597
  const from = dec(q.get('b64from'))
1427
1598
  const to = dec(q.get('b64to'))
1599
+ const rsid = dec(q.get('b64sid'))
1428
1600
  try {
1429
- jsonSend(res, 200, await renameConvFile(from, to))
1601
+ jsonSend(res, 200, await renameConvFile(from, to, rsid))
1430
1602
  } catch (error) {
1431
1603
  jsonSend(res, 500, { ok: false, error: String((error && error.message) || error) })
1432
1604
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-whale-whispers",
3
- "version": "1.21.0",
3
+ "version": "2.0.8",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",