dsh-aurorix-agentbook 1.5.1 → 1.6.0
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 +2 -2
- package/lib/abook.js +32 -15
- package/lib/backend.js +57 -22
- package/lib/host.js +27 -9
- package/lib/index.js +157 -23
- package/lib/view.js +82 -41
- package/lib/web.js +512 -208
- package/lib/words.js +26 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
| 位置 | 是什么 |
|
|
11
11
|
|---|---|
|
|
12
|
-
| 输入框上方状态条 | `记忆
|
|
12
|
+
| 输入框上方状态条 | `记忆 560 条 · 7 个平面`,每 60 秒刷新,点开就是面板 |
|
|
13
13
|
| 输入框上方胶囊「查记忆」 | 拿输入框里正在打的词去检索,命中结果插回输入框(不会自动发送) |
|
|
14
14
|
| 助手消息长按菜单「记进记忆」 | 把这条回复存成 explicit 要点,标题取首行 |
|
|
15
15
|
| 面板「记忆库」 | 七个平面的条数、关键词召回、详情页、写入表单、凭据保险箱 |
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
|
|
30
30
|
`rules` 有保底档:即使排名靠后也会给摘要,不会只剩标题。
|
|
31
31
|
|
|
32
|
-
当前库(约
|
|
32
|
+
当前库(约 560 条)的快照约 60 KB,默认上限 96 KB,不会被截断。
|
|
33
33
|
|
|
34
34
|
## 怎么工作
|
|
35
35
|
|
package/lib/abook.js
CHANGED
|
@@ -38,10 +38,15 @@ export function locate() {
|
|
|
38
38
|
*/
|
|
39
39
|
function run(bin, args, input, timeoutMs = TIMEOUT_MS) {
|
|
40
40
|
return new Promise((resolve) => {
|
|
41
|
-
|
|
41
|
+
let child
|
|
42
|
+
try { child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] }) }
|
|
43
|
+
catch (error) {
|
|
44
|
+
resolve({ ok: false, code: 'spawn', stdout: '', stderr: String(error.message), json: undefined })
|
|
45
|
+
return
|
|
46
|
+
}
|
|
42
47
|
const out = []
|
|
43
48
|
const err = []
|
|
44
|
-
let
|
|
49
|
+
let bytes = 0
|
|
45
50
|
let settled = false
|
|
46
51
|
const finish = (result) => {
|
|
47
52
|
if (settled) return
|
|
@@ -54,18 +59,23 @@ function run(bin, args, input, timeoutMs = TIMEOUT_MS) {
|
|
|
54
59
|
finish({ ok: false, code: 'timeout', stdout: '', stderr: `abook ${Math.round(timeoutMs / 1000)} 秒没有返回`, json: undefined })
|
|
55
60
|
}, timeoutMs)
|
|
56
61
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
62
|
+
const collect = (target) => (chunk) => {
|
|
63
|
+
if (settled) return
|
|
64
|
+
bytes += chunk.length
|
|
65
|
+
if (bytes > MAX_OUTPUT) {
|
|
60
66
|
try { child.kill('SIGKILL') } catch {}
|
|
61
67
|
finish({ ok: false, code: 'too-large', stdout: '', stderr: '输出超过 8 MB', json: undefined })
|
|
62
68
|
return
|
|
63
69
|
}
|
|
64
|
-
|
|
65
|
-
}
|
|
66
|
-
child.
|
|
70
|
+
target.push(chunk)
|
|
71
|
+
}
|
|
72
|
+
child.stdout.on('data', collect(out))
|
|
73
|
+
child.stderr.on('data', collect(err))
|
|
74
|
+
// 子进程提前退出时 stdin 可能报 EPIPE;以退出码和 stderr 为准。
|
|
75
|
+
child.stdin.on('error', () => {})
|
|
67
76
|
child.on('error', (error) => finish({ ok: false, code: 'spawn', stdout: '', stderr: String(error?.message ?? error), json: undefined }))
|
|
68
77
|
child.on('close', (code) => {
|
|
78
|
+
if (settled) return
|
|
69
79
|
const stdout = Buffer.concat(out).toString('utf8')
|
|
70
80
|
const stderr = Buffer.concat(err).toString('utf8')
|
|
71
81
|
let json
|
|
@@ -140,17 +150,14 @@ export function createBackend(options = {}) {
|
|
|
140
150
|
if (typeof bin === 'string' && bin !== '' && existsSync(bin)) return Promise.resolve(bin)
|
|
141
151
|
if (installing !== undefined) return installing
|
|
142
152
|
installing = (async () => {
|
|
143
|
-
if (explicit !== ''
|
|
153
|
+
if (explicit !== '') return (bin = (await ensureBackend({ configured: explicit })).bin)
|
|
144
154
|
const own = installedPath(home)
|
|
145
155
|
if (existsSync(own)) return (bin = own)
|
|
146
156
|
const legacy = locate()
|
|
147
157
|
if (legacy !== undefined) return (bin = legacy)
|
|
148
158
|
const r = await ensureBackend({ configured: '', home, version, autoInstall })
|
|
149
159
|
return (bin = r.bin)
|
|
150
|
-
})().
|
|
151
|
-
installing = undefined
|
|
152
|
-
throw err
|
|
153
|
-
})
|
|
160
|
+
})().finally(() => { installing = undefined })
|
|
154
161
|
return installing
|
|
155
162
|
}
|
|
156
163
|
|
|
@@ -178,6 +185,9 @@ export function createBackend(options = {}) {
|
|
|
178
185
|
get bin() {
|
|
179
186
|
return bin
|
|
180
187
|
},
|
|
188
|
+
get root() {
|
|
189
|
+
return root
|
|
190
|
+
},
|
|
181
191
|
ensure: ensureBin,
|
|
182
192
|
|
|
183
193
|
/** 各平面条数与总数;credentials=vault 表示凭据平面由独立保险箱承载。 */
|
|
@@ -211,10 +221,17 @@ export function createBackend(options = {}) {
|
|
|
211
221
|
async raw(argv, options = {}) {
|
|
212
222
|
if (!Array.isArray(argv) || argv.length === 0) return { ok: false, reason: 'argv 不能为空' }
|
|
213
223
|
const args = argv.map((x) => String(x))
|
|
214
|
-
if (args.
|
|
224
|
+
if (args.some((arg) => arg === '--root' || arg === '-r' || arg.startsWith('--root=') || arg.startsWith('-r='))) {
|
|
215
225
|
return { ok: false, reason: '不要自带 --root:库根由插件配置固定' }
|
|
216
226
|
}
|
|
217
|
-
|
|
227
|
+
let b
|
|
228
|
+
try {
|
|
229
|
+
b = await ensureBin()
|
|
230
|
+
await ensureLib()
|
|
231
|
+
} catch (err) {
|
|
232
|
+
return { ok: false, reason: String(err?.message ?? err) }
|
|
233
|
+
}
|
|
234
|
+
const r = await run(b, root === '' ? args : [...args, '--root', root], options.stdin, options.timeoutMs ?? 60_000)
|
|
218
235
|
return {
|
|
219
236
|
ok: r.ok,
|
|
220
237
|
code: r.code,
|
package/lib/backend.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// 1. 不碰系统目录、不改 PATH、不写 shell 配置——二进制只放在插件自己的数据目录里。
|
|
5
5
|
// 2. 程序与数据分离:二进制在 cache,记忆库本体仍在 ~/AgentsBook。
|
|
6
6
|
// 3. 失败要能说清:网络断了、平台不支持、校验不过,各自给不同的错误。
|
|
7
|
-
import { createHash } from 'node:crypto'
|
|
7
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
8
8
|
import {
|
|
9
9
|
accessSync,
|
|
10
10
|
chmodSync,
|
|
@@ -128,37 +128,63 @@ export async function ensureBackend(options = {}) {
|
|
|
128
128
|
if (asset === undefined) {
|
|
129
129
|
throw backendError('unsupported-platform', `没有适配 ${process.platform}/${process.arch} 的 abook 构建。`)
|
|
130
130
|
}
|
|
131
|
-
const
|
|
132
|
-
const url = `https://github.com/${REPO}/releases/download/${version}/${asset}`
|
|
131
|
+
const release = await releaseInfo(want)
|
|
132
|
+
const url = `https://github.com/${REPO}/releases/download/${encodeURIComponent(release.version)}/${asset}`
|
|
133
133
|
const buf = await download(url)
|
|
134
134
|
if (!looksExecutable(buf)) {
|
|
135
135
|
throw backendError('bad-download', `${url} 返回的不是可执行文件(前 4 字节 ${[...buf.subarray(0, 4)].map((b) => b.toString(16)).join(' ')})。`)
|
|
136
136
|
}
|
|
137
|
+
const digest = createHash('sha256').update(buf).digest('hex')
|
|
138
|
+
if (digest !== release.digest) {
|
|
139
|
+
throw backendError('checksum-mismatch', `${asset} 校验失败:期望 ${release.digest},实际 ${digest}。`)
|
|
140
|
+
}
|
|
137
141
|
|
|
138
142
|
const dir = backendDir(home)
|
|
139
143
|
mkdirSync(dir, { recursive: true })
|
|
140
144
|
const target = installedPath(home)
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
renameSync(tmp, target)
|
|
145
|
-
writeFileSync(versionFile(home), version)
|
|
145
|
+
const suffix = `${process.pid}-${randomBytes(8).toString('hex')}`
|
|
146
|
+
const tmp = `${target}.tmp-${suffix}`
|
|
147
|
+
const versionTmp = `${versionFile(home)}.tmp-${suffix}`
|
|
146
148
|
try {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
+
writeFileSync(tmp, buf, { mode: 0o755 })
|
|
150
|
+
if (process.platform !== 'win32') chmodSync(tmp, 0o755)
|
|
151
|
+
writeFileSync(versionTmp, `${release.version}\n`, { mode: 0o600 })
|
|
152
|
+
renameSync(tmp, target)
|
|
153
|
+
renameSync(versionTmp, versionFile(home))
|
|
154
|
+
} finally {
|
|
155
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
156
|
+
try { rmSync(versionTmp, { force: true }) } catch {}
|
|
157
|
+
}
|
|
149
158
|
|
|
150
159
|
linkCli(target)
|
|
151
|
-
return { bin: target, version, source: 'downloaded', bytes: buf.length, sha256:
|
|
160
|
+
return { bin: target, version: release.version, source: 'downloaded', bytes: buf.length, sha256: digest }
|
|
152
161
|
}
|
|
153
162
|
|
|
154
|
-
async function
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
163
|
+
async function releaseInfo(version) {
|
|
164
|
+
const endpoint = version === undefined || version === ''
|
|
165
|
+
? `https://api.github.com/repos/${REPO}/releases/latest`
|
|
166
|
+
: `https://api.github.com/repos/${REPO}/releases/tags/${encodeURIComponent(version)}`
|
|
167
|
+
let r
|
|
168
|
+
try {
|
|
169
|
+
r = await fetch(endpoint, {
|
|
170
|
+
headers: { 'user-agent': 'dsh-aurorix-agentbook', accept: 'application/vnd.github+json' },
|
|
171
|
+
})
|
|
172
|
+
} catch (err) {
|
|
173
|
+
throw backendError('network', `查 abook 发布信息失败:${err?.message ?? err}`)
|
|
174
|
+
}
|
|
175
|
+
if (!r.ok) throw backendError('catalog-failed', `查 abook 发布信息失败:HTTP ${r.status}`)
|
|
159
176
|
const d = await r.json()
|
|
160
|
-
|
|
161
|
-
|
|
177
|
+
const tag = typeof d.tag_name === 'string' ? d.tag_name : ''
|
|
178
|
+
if (!/^v?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(tag)) {
|
|
179
|
+
throw backendError('catalog-failed', 'GitHub 返回了无效的 abook 版本标识')
|
|
180
|
+
}
|
|
181
|
+
const asset = assetName()
|
|
182
|
+
const entry = Array.isArray(d.assets) ? d.assets.find((x) => x?.name === asset) : undefined
|
|
183
|
+
const digest = typeof entry?.digest === 'string' && /^sha256:[0-9a-f]{64}$/.test(entry.digest)
|
|
184
|
+
? entry.digest.slice('sha256:'.length)
|
|
185
|
+
: ''
|
|
186
|
+
if (digest === '') throw backendError('catalog-failed', `GitHub 没有提供 ${asset} 的 SHA-256 摘要`)
|
|
187
|
+
return { version: tag, digest }
|
|
162
188
|
}
|
|
163
189
|
|
|
164
190
|
async function download(url) {
|
|
@@ -206,11 +232,20 @@ export function linkCli(bin, options = {}) {
|
|
|
206
232
|
if (!existsSync(dir)) continue
|
|
207
233
|
accessSync(dir, fsConstants.W_OK)
|
|
208
234
|
const target = joinPath(dir, name)
|
|
235
|
+
// Never replace an existing PATH command: it may belong to the user or another package.
|
|
209
236
|
try {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
237
|
+
symlinkSync(bin, target)
|
|
238
|
+
return { ok: true, linked: target, reason: 'created' }
|
|
239
|
+
} catch (err) {
|
|
240
|
+
if (err?.code === 'EEXIST') {
|
|
241
|
+
try {
|
|
242
|
+
if (realpathSync(target) === realpathSync(bin)) {
|
|
243
|
+
return { ok: true, linked: target, reason: 'already' }
|
|
244
|
+
}
|
|
245
|
+
} catch {}
|
|
246
|
+
}
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
214
249
|
} catch {
|
|
215
250
|
continue
|
|
216
251
|
}
|
package/lib/host.js
CHANGED
|
@@ -7,11 +7,20 @@
|
|
|
7
7
|
// 时,那一块就不装,其余部分照常工作,整个插件不会因此起不来。
|
|
8
8
|
import { spawn } from 'node:child_process'
|
|
9
9
|
import { delimiter, dirname } from 'node:path'
|
|
10
|
+
const ATTACH_ACTIONS = ['list', 'add', 'get', 'rm', 'path', 'sync', 'refs']
|
|
11
|
+
|
|
12
|
+
function sanitizeShellEnv(base, binDir, root) {
|
|
13
|
+
const env = {}
|
|
14
|
+
const blocked = /^(?:BASH_ENV|ENV|NODE_OPTIONS|PYTHONSTARTUP|RUBYOPT|PERL5OPT)$|(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|COOKIE|AUTH|PRIVATE[_-]?KEY|SIGNING[_-]?KEY)/i
|
|
15
|
+
for (const [key, value] of Object.entries(base ?? {})) {
|
|
16
|
+
if (blocked.test(key)) continue
|
|
17
|
+
env[key] = value
|
|
18
|
+
}
|
|
19
|
+
if (binDir !== '') env.PATH = `${binDir}${delimiter}${base?.PATH ?? ''}`
|
|
20
|
+
if (root !== '') env.ABOOK_ROOT = root
|
|
21
|
+
return env
|
|
22
|
+
}
|
|
10
23
|
|
|
11
|
-
/**
|
|
12
|
-
* 当前能用的 shell。不同平台差得远,命令语法完全不同,所以要让模型知道自己在哪套里。
|
|
13
|
-
* Windows 上没有 bash:有 PowerShell 就用它,再不行退回 cmd。
|
|
14
|
-
*/
|
|
15
24
|
function detectShell() {
|
|
16
25
|
if (process.platform !== 'win32') {
|
|
17
26
|
return { kind: 'posix', name: 'bash', build: (c) => ['-c', c] }
|
|
@@ -77,6 +86,7 @@ export function planeWord(plane) {
|
|
|
77
86
|
*/
|
|
78
87
|
export function attachHost(ctx, deps) {
|
|
79
88
|
const backend = deps.backend
|
|
89
|
+
const root = typeof backend?.root === 'string' ? backend.root : ''
|
|
80
90
|
const cfg = () => readConfig(deps.config)
|
|
81
91
|
const access = createAccessStore(resolveStatePath(cfg().statePath))
|
|
82
92
|
|
|
@@ -441,11 +451,7 @@ export function attachHost(ctx, deps) {
|
|
|
441
451
|
return await new Promise((resolve) => {
|
|
442
452
|
// PATH 只对这个子进程前置,不动系统环境;这样无论哪个平台,`abook` 都能直接打。
|
|
443
453
|
const binDir = typeof backend?.bin === 'string' && backend.bin !== '' ? dirname(backend.bin) : ''
|
|
444
|
-
const env =
|
|
445
|
-
...process.env,
|
|
446
|
-
...(binDir !== '' ? { PATH: `${binDir}${delimiter}${process.env.PATH ?? ''}` } : {}),
|
|
447
|
-
...(typeof root === 'string' && root !== '' ? { ABOOK_ROOT: root } : {}),
|
|
448
|
-
}
|
|
454
|
+
const env = sanitizeShellEnv(process.env, binDir, root)
|
|
449
455
|
const child = spawn(SHELL.name, SHELL.build(command), { cwd, env })
|
|
450
456
|
const out = []
|
|
451
457
|
const err = []
|
|
@@ -522,6 +528,18 @@ export function attachHost(ctx, deps) {
|
|
|
522
528
|
const action = String(args.action ?? '').trim()
|
|
523
529
|
const record = String(args.record ?? '').trim()
|
|
524
530
|
if (action === '' || record === '') return { ok: false, text: 'action 与 record 都必须给。' }
|
|
531
|
+
// action 落在 argv 的参数位上:不是白名单里的子命令就直接拒,别让 --help 之类被当成动作。
|
|
532
|
+
if (!ATTACH_ACTIONS.includes(action)) {
|
|
533
|
+
return { ok: false, text: `不支持的动作:${action}。可用:${ATTACH_ACTIONS.join(' / ')}` }
|
|
534
|
+
}
|
|
535
|
+
// 记录选择器与附件名以 - 开头会被 abook 当成选项解析,这里挡在调用之前。
|
|
536
|
+
if (record.startsWith('-')) {
|
|
537
|
+
return { ok: false, text: '记录标识不能以 - 开头(会被当成命令行选项)。' }
|
|
538
|
+
}
|
|
539
|
+
// 记录选择器也当路径用,含 .. 或绝对路径就会跑到库外面写附件目录。
|
|
540
|
+
if (record.includes('..') || record.startsWith('/') || record.includes('\\')) {
|
|
541
|
+
return { ok: false, text: '记录标识只能是记录 ID、文件名或库内相对路径,不能带 .. 或绝对路径。' }
|
|
542
|
+
}
|
|
525
543
|
|
|
526
544
|
const argv = ['attach', action, record]
|
|
527
545
|
const file = typeof args.file === 'string' ? args.file.trim() : ''
|
package/lib/index.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { createBackend, PLANES } from './abook.js'
|
|
9
9
|
import { attachWeb } from './web.js'
|
|
10
10
|
import { attachHost } from './host.js'
|
|
11
|
-
import { memoryData, memoryView,
|
|
11
|
+
import { joinPages, memoryData, memoryView, PAGE_CHARS, pageSlice, splitPages, stripData } from './view.js'
|
|
12
12
|
import { planeLabel, words } from './words.js'
|
|
13
13
|
|
|
14
14
|
export const name = 'dsh-aurorix-agentbook'
|
|
@@ -75,7 +75,9 @@ export function apply(ctx, config) {
|
|
|
75
75
|
vaultDraftNote: '',
|
|
76
76
|
detail: undefined,
|
|
77
77
|
detailEditing: false,
|
|
78
|
-
|
|
78
|
+
detailPage: 0,
|
|
79
|
+
detailPages: undefined,
|
|
80
|
+
detailDraft: { title: '', body: '', readWhen: '', purpose: '', append: '' },
|
|
79
81
|
})
|
|
80
82
|
|
|
81
83
|
// 详情缓存:abook 每次调用要起子进程(实测 230ms),反复进出同一条记录没必要重读。
|
|
@@ -186,8 +188,10 @@ export function apply(ctx, config) {
|
|
|
186
188
|
if (!read.ok) return { ok: false, reason: read.reason }
|
|
187
189
|
const record = read.record ?? {}
|
|
188
190
|
if (cached === undefined) cacheDetail(id, record)
|
|
189
|
-
const
|
|
191
|
+
const pager = pageSlice(record.content, 0)
|
|
190
192
|
update(scope, {
|
|
193
|
+
detailPage: 0,
|
|
194
|
+
detailEditing: false,
|
|
191
195
|
detail: {
|
|
192
196
|
kind: 'memory',
|
|
193
197
|
id: String(record.id ?? id),
|
|
@@ -197,9 +201,7 @@ export function apply(ctx, config) {
|
|
|
197
201
|
updated: record.updated_at === undefined ? '' : formatTime(record.updated_at),
|
|
198
202
|
body: String(record.content ?? ''),
|
|
199
203
|
revision: record.revision,
|
|
200
|
-
|
|
201
|
-
shown: body.shown,
|
|
202
|
-
total: body.total,
|
|
204
|
+
pages: pager.pages,
|
|
203
205
|
},
|
|
204
206
|
})
|
|
205
207
|
return { ok: true }
|
|
@@ -212,8 +214,10 @@ export function apply(ctx, config) {
|
|
|
212
214
|
if (!read.ok) return { ok: false, reason: read.reason }
|
|
213
215
|
const record = read.record
|
|
214
216
|
const item = (stateOf(scope).vault?.items ?? []).find((x) => x.ident === ident)
|
|
215
|
-
const
|
|
217
|
+
const pager = pageSlice(record.body, 0)
|
|
216
218
|
update(scope, {
|
|
219
|
+
detailPage: 0,
|
|
220
|
+
detailEditing: false,
|
|
217
221
|
detail: {
|
|
218
222
|
kind: 'vault',
|
|
219
223
|
id: ident,
|
|
@@ -223,9 +227,7 @@ export function apply(ctx, config) {
|
|
|
223
227
|
updated: item === undefined ? '' : item.when,
|
|
224
228
|
verified: item === undefined ? undefined : item.verified,
|
|
225
229
|
body: record.body,
|
|
226
|
-
|
|
227
|
-
shown: body.shown,
|
|
228
|
-
total: body.total,
|
|
230
|
+
pages: pager.pages,
|
|
229
231
|
},
|
|
230
232
|
})
|
|
231
233
|
return { ok: true }
|
|
@@ -248,7 +250,16 @@ export function apply(ctx, config) {
|
|
|
248
250
|
}
|
|
249
251
|
|
|
250
252
|
const patchOf = (scope, locale) => memoryData(stateOf(scope), { locale })
|
|
251
|
-
|
|
253
|
+
/** 当前详情一共有多少页:编辑态看页数组,阅读态按正文长度算。 */
|
|
254
|
+
const totalPagesOf = (state) => {
|
|
255
|
+
if (Array.isArray(state.detailPages) && state.detailPages.length > 0) return state.detailPages.length
|
|
256
|
+
return pageSlice(state.detail?.body ?? '', 0).pages
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const closeDetail = (scope) => update(scope, {
|
|
260
|
+
detail: undefined, detailEditing: false, detailPage: 0, detailPages: undefined,
|
|
261
|
+
detailDraft: { title: '', body: '', readWhen: '', purpose: '', append: '' },
|
|
262
|
+
})
|
|
252
263
|
|
|
253
264
|
ctx.inject(['dshGo'], (ctx) => {
|
|
254
265
|
// 加载时留一行:插件是不是真的被宿主装上了,看日志就能判断,不必猜。
|
|
@@ -315,28 +326,50 @@ export function apply(ctx, config) {
|
|
|
315
326
|
},
|
|
316
327
|
|
|
317
328
|
// 详情页 → 编辑态。字段的初值从当前详情页带过去,不用重新读库。
|
|
329
|
+
// 正文一律可编辑:长记录按页改,手机端不设字数门槛。
|
|
318
330
|
'detail-edit': (scope) => {
|
|
319
331
|
const current = stateOf(scope)
|
|
320
332
|
const d = current.detail
|
|
321
333
|
if (d === undefined || d === null) return { toast: '没有可编辑的详情' }
|
|
322
334
|
update(scope, {
|
|
323
335
|
detailEditing: true,
|
|
336
|
+
detailPage: 0,
|
|
337
|
+
// 编辑期间正文按固定页数组改,页与页互不影响。
|
|
338
|
+
detailPages: splitPages(d.body ?? ''),
|
|
324
339
|
detailDraft: {
|
|
325
340
|
title: String(d.title ?? ''),
|
|
326
341
|
body: String(d.body ?? ''),
|
|
327
342
|
readWhen: String(d.readWhen ?? ''),
|
|
328
343
|
purpose: String(d.purpose ?? ''),
|
|
344
|
+
append: '',
|
|
329
345
|
},
|
|
330
346
|
})
|
|
331
347
|
return { refresh: 'memory-home' }
|
|
332
348
|
},
|
|
333
349
|
|
|
334
350
|
'detail-cancel': (scope) => {
|
|
335
|
-
update(scope, { detailEditing: false })
|
|
351
|
+
update(scope, { detailEditing: false, detailPage: 0, detailPages: undefined })
|
|
352
|
+
return { refresh: 'memory-home' }
|
|
353
|
+
},
|
|
354
|
+
|
|
355
|
+
// 阅读时翻页:正文按页看完全文,不改内容。
|
|
356
|
+
'detail-page-prev': (scope) => {
|
|
357
|
+
const current = stateOf(scope)
|
|
358
|
+
const page = Math.max(0, (Number(current.detailPage) || 0) - 1)
|
|
359
|
+
update(scope, { detailPage: page })
|
|
360
|
+
return { refresh: 'memory-home' }
|
|
361
|
+
},
|
|
362
|
+
|
|
363
|
+
'detail-page-next': (scope) => {
|
|
364
|
+
const current = stateOf(scope)
|
|
365
|
+
const pages = totalPagesOf(current)
|
|
366
|
+
const page = Math.min(Math.max(0, pages - 1), (Number(current.detailPage) || 0) + 1)
|
|
367
|
+
update(scope, { detailPage: page })
|
|
336
368
|
return { refresh: 'memory-home' }
|
|
337
369
|
},
|
|
338
370
|
|
|
339
|
-
//
|
|
371
|
+
// 保存:一页一存。改的是固定页数组里的这一页,存完自动翻到下一页。
|
|
372
|
+
// 页数组在进编辑态时就切好了,所以某页变长不会挪动其他页的边界。
|
|
340
373
|
'detail-save': async (scope, event) => {
|
|
341
374
|
const odd = w(event?.locale)
|
|
342
375
|
const current = stateOf(scope)
|
|
@@ -346,35 +379,134 @@ export function apply(ctx, config) {
|
|
|
346
379
|
const field = (path) => (typeof values[path] === 'string' ? values[path] : '')
|
|
347
380
|
const isVault = d.kind === 'vault'
|
|
348
381
|
|
|
382
|
+
const draft = current.detailDraft ?? {}
|
|
383
|
+
// 进编辑态时切好的页数组必须一直在;缺了就用当前完整正文重新切一次,
|
|
384
|
+
// 绝不能拿「这一页的新文字」去拼整篇——那会把其余页吞掉。
|
|
385
|
+
const pages = Array.isArray(current.detailPages) && current.detailPages.length > 0
|
|
386
|
+
? [...current.detailPages]
|
|
387
|
+
: splitPages(draft.body ?? d.body ?? '')
|
|
388
|
+
const pageNo = Math.min(Math.max(0, Math.trunc(Number(current.detailPage) || 0)), pages.length - 1)
|
|
389
|
+
pages[pageNo] = field('data.detailDraft.body')
|
|
390
|
+
const merged = joinPages(pages)
|
|
391
|
+
const more = pageNo < pages.length - 1
|
|
392
|
+
|
|
349
393
|
if (isVault) {
|
|
350
394
|
const purpose = field('data.detailDraft.purpose').trim()
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
const r = await backend.vaultPut({ ident: String(d.id ?? ''), purpose, body })
|
|
395
|
+
if (merged === '') return { toast: odd.editFailed + '正文不能为空' }
|
|
396
|
+
const r = await backend.vaultPut({ ident: String(d.id ?? ''), purpose, body: merged })
|
|
354
397
|
if (!r.ok) return { toast: `${odd.editFailed}${r.reason}`.slice(0, 60) }
|
|
398
|
+
update(scope, {
|
|
399
|
+
detailEditing: more,
|
|
400
|
+
detailPage: more ? pageNo + 1 : 0,
|
|
401
|
+
detailPages: more ? pages : undefined,
|
|
402
|
+
detailDraft: { ...draft, purpose, body: merged, append: '' },
|
|
403
|
+
detail: { ...d, body: merged, purpose, bytes: Buffer.byteLength(merged, 'utf8') },
|
|
404
|
+
})
|
|
405
|
+
if (more) return { refresh: 'memory-home' }
|
|
355
406
|
const reopened = await openVault(scope, String(d.id ?? ''))
|
|
356
|
-
update(scope, { detailEditing: false })
|
|
357
407
|
if (!reopened.ok) return { toast: odd.editedOk }
|
|
358
408
|
return { refresh: 'memory-home' }
|
|
359
409
|
}
|
|
360
410
|
|
|
361
411
|
const title = field('data.detailDraft.title').trim()
|
|
362
412
|
if (title === '') return { toast: odd.editFailed + '标题不能为空' }
|
|
413
|
+
const readWhen = field('data.detailDraft.readWhen').trim()
|
|
363
414
|
const r = await backend.update({
|
|
364
415
|
id: String(d.id ?? ''),
|
|
365
416
|
title,
|
|
366
|
-
body:
|
|
367
|
-
readWhen
|
|
417
|
+
body: merged,
|
|
418
|
+
readWhen,
|
|
368
419
|
revision: d.revision,
|
|
369
420
|
})
|
|
370
421
|
if (!r.ok) return { toast: `${odd.editFailed}${r.reason}`.slice(0, 60) }
|
|
371
422
|
detailCache.clear()
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
423
|
+
const record = r.record ?? {}
|
|
424
|
+
// 存完换成新的 revision:接着改下一页还要用它防覆盖。
|
|
425
|
+
update(scope, {
|
|
426
|
+
detail: {
|
|
427
|
+
...d,
|
|
428
|
+
title,
|
|
429
|
+
readWhen,
|
|
430
|
+
body: merged,
|
|
431
|
+
revision: record.revision ?? d.revision,
|
|
432
|
+
updated: record.updated_at === undefined ? d.updated : formatTime(record.updated_at),
|
|
433
|
+
pages: pages.length,
|
|
434
|
+
},
|
|
435
|
+
detailEditing: more,
|
|
436
|
+
detailPage: more ? pageNo + 1 : 0,
|
|
437
|
+
detailPages: more ? pages : undefined,
|
|
438
|
+
detailDraft: { ...draft, title, readWhen, body: merged, append: '' },
|
|
439
|
+
})
|
|
375
440
|
return { refresh: 'memory-home' }
|
|
376
441
|
},
|
|
377
442
|
|
|
443
|
+
// 末尾追加:正文继续往上写,这条路没有长度上限。
|
|
444
|
+
'detail-append': async (scope, event) => {
|
|
445
|
+
const odd = w(event?.locale)
|
|
446
|
+
const current = stateOf(scope)
|
|
447
|
+
const d = current.detail
|
|
448
|
+
if (d === undefined || d === null) return { toast: odd.editFailed + '无详情' }
|
|
449
|
+
const values = event?.value?.values ?? {}
|
|
450
|
+
const extra = typeof values['data.detailDraft.append'] === 'string' ? values['data.detailDraft.append'] : ''
|
|
451
|
+
if (extra.trim() === '') return { toast: odd.bodyEmpty }
|
|
452
|
+
const draft = current.detailDraft ?? {}
|
|
453
|
+
const pages = Array.isArray(current.detailPages) && current.detailPages.length > 0
|
|
454
|
+
? [...current.detailPages]
|
|
455
|
+
: splitPages(draft.body ?? d.body ?? '')
|
|
456
|
+
// 追加落在最后一页;写满 600 字再自动续页,单页始终在输入框上限内。
|
|
457
|
+
let tail = (pages[pages.length - 1] ?? '') + extra
|
|
458
|
+
while (tail.length > PAGE_CHARS) {
|
|
459
|
+
pages[pages.length - 1] = tail.slice(0, PAGE_CHARS)
|
|
460
|
+
tail = tail.slice(PAGE_CHARS)
|
|
461
|
+
pages.push(tail)
|
|
462
|
+
}
|
|
463
|
+
pages[pages.length - 1] = tail
|
|
464
|
+
const merged = joinPages(pages)
|
|
465
|
+
const isVault = d.kind === 'vault'
|
|
466
|
+
|
|
467
|
+
if (isVault) {
|
|
468
|
+
const purpose = String(draft.purpose ?? d.purpose ?? '').trim()
|
|
469
|
+
const r = await backend.vaultPut({ ident: String(d.id ?? ''), purpose, body: merged })
|
|
470
|
+
if (!r.ok) return { toast: `${odd.editFailed}${r.reason}`.slice(0, 60) }
|
|
471
|
+
update(scope, {
|
|
472
|
+
detail: { ...d, body: merged, purpose, bytes: Buffer.byteLength(merged, 'utf8') },
|
|
473
|
+
detailDraft: { ...draft, purpose, body: merged, append: '' },
|
|
474
|
+
detailPages: pages,
|
|
475
|
+
detailPage: pages.length - 1,
|
|
476
|
+
})
|
|
477
|
+
return { toast: odd.appendedOk, refresh: 'memory-home' }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const title = String(draft.title ?? d.title ?? '').trim()
|
|
481
|
+
if (title === '') return { toast: odd.editFailed + '标题不能为空' }
|
|
482
|
+
const readWhen = String(draft.readWhen ?? d.readWhen ?? '').trim()
|
|
483
|
+
const r = await backend.update({
|
|
484
|
+
id: String(d.id ?? ''),
|
|
485
|
+
title,
|
|
486
|
+
body: merged,
|
|
487
|
+
readWhen,
|
|
488
|
+
revision: d.revision,
|
|
489
|
+
})
|
|
490
|
+
if (!r.ok) return { toast: `${odd.editFailed}${r.reason}`.slice(0, 60) }
|
|
491
|
+
detailCache.clear()
|
|
492
|
+
const record = r.record ?? {}
|
|
493
|
+
update(scope, {
|
|
494
|
+
detail: {
|
|
495
|
+
...d,
|
|
496
|
+
title,
|
|
497
|
+
readWhen,
|
|
498
|
+
body: merged,
|
|
499
|
+
revision: record.revision ?? d.revision,
|
|
500
|
+
updated: record.updated_at === undefined ? d.updated : formatTime(record.updated_at),
|
|
501
|
+
pages: pages.length,
|
|
502
|
+
},
|
|
503
|
+
detailDraft: { ...draft, title, readWhen, body: merged, append: '' },
|
|
504
|
+
detailPages: pages,
|
|
505
|
+
detailPage: pages.length - 1,
|
|
506
|
+
})
|
|
507
|
+
return { toast: odd.appendedOk, refresh: 'memory-home' }
|
|
508
|
+
},
|
|
509
|
+
|
|
378
510
|
// 点召回结果的一行:读出正文,切到详情页。
|
|
379
511
|
// 详情页要换掉整棵视图,只能用 refresh;而 refresh 不在延后结果允许的效果里,
|
|
380
512
|
// 所以这里是当场做的:读一条本地记录实测 0.25 秒,3 秒的处理器窗口够用。
|
|
@@ -448,7 +580,9 @@ export function apply(ctx, config) {
|
|
|
448
580
|
if (detail === undefined) return { toast: odd.readFailed }
|
|
449
581
|
const body = String(detail.body ?? '')
|
|
450
582
|
if (body === '') return { toast: odd.bodyEmpty }
|
|
451
|
-
|
|
583
|
+
// 剪贴板一次最多 8000 字(宿主协议上限),超了就复制前 8000 字并说清楚。
|
|
584
|
+
if (body.length > COPY_LIMIT) return { copy: body.slice(0, COPY_LIMIT), toast: odd.copiedPartial(COPY_LIMIT) }
|
|
585
|
+
return { copy: body, toast: odd.copied }
|
|
452
586
|
},
|
|
453
587
|
|
|
454
588
|
// 重新读库:结构不变,只回写数据。
|