dsh-engramory 1.3.0 → 1.4.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.
Files changed (5) hide show
  1. package/README.en.md +271 -254
  2. package/README.md +145 -141
  3. package/client.js +1376 -1202
  4. package/index.js +3495 -3402
  5. package/package.json +79 -79
package/client.js CHANGED
@@ -1,1202 +1,1376 @@
1
- /**
2
- * dsh-engramory, browser half: the settings on the package's own page in the Plugins page,
3
- * and the sidebar's Memory entry — a page listing the memory stores by name, with the two
4
- * settings that matter most at its top. The settings go through the route index.js
5
- * registers for them (the memory's language follows dsh's); the page lists the stores and
6
- * opens a note in the desktop's own app through the memory route, so no note's text is
7
- * ever read into the page.
8
- *
9
- * Plain script, no build step, like index.js: React comes from the page's module table,
10
- * no Harness client package is loaded as a module (dsh's guidance — they change without
11
- * notice), and the colours are the host's theme tokens, so light, dark and third-party themes
12
- * follow — but for the memory page's banner, in the project's own navy and mint on any theme,
13
- * that mint again in an index's fill bar and a clean check-up's tick, and the note types'
14
- * marks, each a muted colour of its own leaned toward the theme's text.
15
- * Visible text goes through the locale service.
16
- */
17
- window.__ModuleLoader__.load({
18
- id: 'dsh-engramory',
19
- factory(require) {
20
- const React = require('react')
21
- const h = React.createElement
22
- const { useCallback, useEffect, useRef, useState } = React
23
-
24
- const NS = 'engramory'
25
- /** The Plugins page keys a package's own settings by its package name. */
26
- const PACKAGE = 'dsh-engramory'
27
- /** The sidebar entry and the main-column page it opens share this id. */
28
- const PANEL = 'engramory'
29
- /** Relative to the page, as dsh's own pages fetch, so a mounted deployment keeps its prefix. */
30
- const SETTINGS_API = 'api/engramory/settings'
31
- const MEMORY_API = 'api/engramory/memory'
32
- /** This plugin's version, for the feedback footer; a test keeps it equal to package.json's. */
33
- const VERSION = '1.3.0'
34
- /** Where feedback goes: a new issue on the repository, or the project's mailbox. Opening
35
- * the link is the browser's (the desktop app hands it to the system's); the footer submits
36
- * nothing by itself. */
37
- const ISSUES = 'https://github.com/tinqiao-oss/engramory/issues/new'
38
- const EMAIL = 'engramory@agent.qq.com'
39
- /** The how-to's lines, in order. */
40
- const HOW_TO = ['howToSay', 'howToRecall', 'howToEdit', 'howToMove', 'howToSocial']
41
- /** A note past this is almost always a timeline under one slug (SKILL.md: "A note has a size
42
- * too"); the doctor warns at the same size (ENGRAMORY_NOTE_WARN_BYTES). */
43
- const LARGE_NOTE = 12 * 1024
44
- /** An `upcoming` note named with its date: `2026-10-31-interview`, `2026-10-31面试` (SKILL.md §2.2). */
45
- const DATED = /^(\d{4})-(\d{2})-(\d{2})(?!\d)/
46
- const DEFAULT_LINES = 200
47
- const DEFAULT_BYTES = 25600
48
- /** The order the memory page shows note types in (SKILL.md §2, §2.2). */
49
- const TYPES = ['user', 'feedback', 'project', 'reference', 'moment', 'upcoming', 'self', 'other']
50
-
51
- const zh = {
52
- summary: '大肥鱼模式和记忆权限、索引上限。',
53
- loading: '正在读取设置…',
54
- loadFailed: '读不到设置。',
55
- retry: '重试',
56
- unavailable: '这个 dsh 不能在页面里保存这些设置(没有配置编辑服务)。请改配置文件 cordis.patch.yml,写法见插件说明。',
57
- expression: '配置文件里有设置是用 !!js 表达式写的,这里显示不了它的实际值,所以只读。请直接改 cordis.patch.yml。',
58
- companion: '大肥鱼模式',
59
- companionHint: '多记三类:经历、约定、我自己,用角色口吻回忆。',
60
- audience: '记忆权限',
61
- audiencePrivate: '专属',
62
- audienceSocial: '社交',
63
- audiencePrivateHint: '只有你用这个 dsh:每个对话都能用记忆。',
64
- audienceSocialHint: '别人也能跟你的 AI 聊(接了 QQ、微信等):只有你本人聊、没有别人插过话的对话能用记忆。',
65
- cap: '索引上限',
66
- capHint: '默认 200 行 / 25600 字节,超过后 AI 要先压缩才能再写。',
67
- capLines: '行',
68
- capBytes: '字节',
69
- save: '保存',
70
- saving: '保存中…',
71
- discard: '放弃修改',
72
- reloading: '已保存,插件正在用新设置重新加载…',
73
- saved: '已保存。',
74
- savedUnconfirmed: '已保存,但重新读到的设置和刚才填的不一样(或者插件还没加载好)。请刷新页面看看。',
75
- stale: '设置在别处被改过,已重新读取。请再改一次。',
76
- overridden: '更高一层的配置覆盖了这些值,这里保存不了。',
77
- invalid: '有一项填得不对:',
78
- failed: '保存失败:',
79
- panel: '记忆',
80
- panelTitle: 'Engramory 记忆',
81
- refresh: '刷新',
82
- stripNote: '说明和索引上限在「插件 → Engramory 记忆」。',
83
- stripReadOnly: '这里改不了,见「插件 → Engramory 记忆」。',
84
- listing: '正在读取记忆…',
85
- listFailed: '读不到记忆库。',
86
- listTimeout: '读取超时了,可能有工作区在连不上的网络盘上。稍后点刷新再试。',
87
- empty: '还没有记忆。AI 第一次存记忆时会自动建好记忆库。',
88
- pinnedRelative: '配置里固定的索引(indexPath)是相对路径,跟着每个会话的目录走,这里列不出来。改成绝对路径就能在这里看到。',
89
- storeUser: '全局记忆',
90
- storePinned: '固定的记忆库',
91
- usage: '索引 {lines} / {maxLines} 行 · {size} / {maxSize}',
92
- usageOver: '索引 {size} / {maxSize},超出上限',
93
- usageSize: '索引 {size} / {maxSize}',
94
- sizeBytes: '{n} B',
95
- sizeKB: '{n} KB',
96
- overHint: '超出上限了,AI 只读得到前面一部分,该压缩了。',
97
- noIndex: '还没有索引',
98
- openIndex: '打开索引',
99
- openFolder: '打开文件夹',
100
- opened: '已打开 {name}。',
101
- openUnavailable: '这台 dsh 不能在本机打开文件(比如远程访问时)。文件在上面写的位置。',
102
- openMissing: '找不到这个文件了,可能刚被改名或删掉。点刷新看看。',
103
- openBusy: '还在打开上一个,稍等一下再点。',
104
- openFailed: '打不开:{reason}',
105
- typeUser: '用户',
106
- typeFeedback: '反馈',
107
- typeProject: '项目',
108
- typeReference: '参考',
109
- typeMoment: '经历',
110
- typeUpcoming: '约定',
111
- typeSelf: '我自己',
112
- typeOther: '其他',
113
- archive: '归档 {count} 份',
114
- more: '文件太多,这里只列出了一部分。',
115
- healthOk: '体检:没发现问题。',
116
- healthBroken: '索引里指向不存在的文件({count})',
117
- healthBrokenMore: '索引里指向不存在的文件({count} 个以上)',
118
- healthBrokenUnlisted: '索引里有指向不存在的文件,太多了,这里没列出。',
119
- healthUnindexed: '不在索引里({count}):AI 回忆从索引开始,这些它通常找不到,除非别的笔记链到它们。',
120
- healthUntyped: '没写类型或类型不认识({count}),列在「其他」里。',
121
- healthFix: '完整检查可以用 engramory_doctor.py。',
122
- healthLarge: '要核对的太多,没做体检。',
123
- healthUnreadable: '有文件读不了,没做体检。',
124
- healthPartial: '文件太多没列全,没做体检。',
125
- howTo: '怎么用',
126
- howToSay: '想让 AI 记住什么,直接跟它说,比如「记住:我习惯用 pnpm」「把这个决定记下来」。平时它也会尽量自己挑值得长期记住的记下来,比如你纠正过它的做法。',
127
- howToRecall: '默认每次对话都会带上记忆的目录(索引),AI 用到细节时再打开那条笔记,不用你提醒。',
128
- howToEdit: '这里列出读得到的记忆,打开笔记就能直接改;想让 AI 忘掉什么,跟它说「忘掉……」就行。',
129
- howToMove: '记忆是存在运行 dsh 那台电脑上的普通 markdown 文件,位置写在每个库的标题下面。换电脑时把那个文件夹拷到新电脑的同一位置;在配置里指定过位置的,配置也一起带过去。',
130
- howToSocial: '接了 QQ、微信等、别人也能跟你的 AI 聊的话,在上面打开「大肥鱼模式」,再把「记忆权限」改成「社交」:只有认得出是你本人的对话才拿得到记忆。这不是安全隔离,详见插件说明。',
131
- feedbackLead: '遇到问题或有建议:',
132
- feedbackIssue: '到 GitHub 提 issue',
133
- feedbackMail: ',或发邮件到',
134
- copy: '复制',
135
- copied: '已复制',
136
- copyFailed: '复制不了,请手动选中上面的地址。',
137
- feedbackNote: '邮件会由 AI 助手协助整理,issue 是公开的,两处都别把记忆内容原样贴上去。插件版本 {version}。',
138
- issueBody: '(写下遇到的问题或建议)\n\n---\ndsh-engramory {version}\n打开这个页面的电脑:{os}\ndsh 版本:',
139
- statNote: '条记忆',
140
- statNotes: '条记忆',
141
- statStore: '个记忆库',
142
- statStores: '个记忆库',
143
- statArchive: '份归档',
144
- statsReadAt: '读取于 {time},约定的天数按这时算',
145
- statsPartial: '列表太长,只列出了一部分,这些数字偏少。',
146
- statsUnreadable: '有 {count} 处可能存放记忆库的位置没读到(读不了或查不了),没算在内。',
147
- statsIncomplete: '有的库里有文件读不了,这些数字可能偏少。',
148
- typeAll: '全部',
149
- typeLabel: '按类型筛选',
150
- storeCount: '{count} 条',
151
- storeCountOne: '{count} 条',
152
- noteMeta: '{type} · {size}',
153
- noteUnread: '读不了',
154
- archived: '已归档',
155
- monthDay: '{m}月{d}日',
156
- yearMonthDay: '{y}年{m}月{d}日',
157
- badgePast: '{date} · 日期已过,待确认',
158
- badgeToday: '就是今天',
159
- badgeTomorrow: '{date} · 明天',
160
- badgeSoon: '{date} · 还有 {days} 天',
161
- badgeUndated: '未定日期',
162
- badgeLarge: '偏大,建议拆分',
163
- badgeUnindexed: '不在索引里',
164
- attnTitle: '可以整理一下',
165
- attnLarge: '超过 12 KB 的笔记 {count} 篇:一条笔记该只记一件事,可以让 AI 拆成几篇。',
166
- filterLabel: '筛选笔记',
167
- filterPlaceholder: '按名字筛选',
168
- filterCount: '匹配 {count} 条(只在已列出的笔记里找)',
169
- filterNone: '这个库里没有匹配的笔记。',
170
- tidyCopy: '复制整理指令',
171
- tidyCopied: '已复制,粘贴进对话发给 AI',
172
- tidyFailed: '复制不了,请手动选中下面的指令:',
173
- tidyPrompt: '请按 Engramory 的记忆规则整理这个记忆库:{dir}\n- 索引里指向不存在文件的链接:找得到对应笔记的就改对,确实没有了的只删这个链接;一行里没有别的有效链接了,才删掉整行。\n- 不在索引里的笔记:以后回忆用得上的补进索引,过时的移进 archive/ 或删掉;不要为了补齐全部加进去。\n- 没写类型的笔记补上 type。\n- 索引超出上限就先压缩:合并重复,细节挪回笔记,索引只留指针。\n- 超过约 12 KB 的笔记,按规则拆成几篇。\n- 日期已过的约定别删,问到结果再改写成经历。\n改完再看一遍索引有没有超出上限,然后告诉我改了什么。',
174
- }
175
- const en = {
176
- summary: 'Companion mode and memory access, and the index cap.',
177
- loading: 'Reading the settings…',
178
- loadFailed: 'Could not read the settings.',
179
- retry: 'Retry',
180
- unavailable: 'This dsh cannot save these settings from a page (it has no config editor). Edit cordis.patch.yml instead; the plugin README shows how.',
181
- expression: 'A setting in the config is written as a !!js expression, whose value this page cannot show, so it is read-only. Edit cordis.patch.yml directly.',
182
- companion: 'Companion mode (大肥鱼模式)',
183
- companionHint: 'Keeps three more kinds of note — moments, plans, the character itself — and recalls in character.',
184
- audience: 'Memory access',
185
- audiencePrivate: 'Private',
186
- audienceSocial: 'Social',
187
- audiencePrivateHint: 'Only you use this dsh: every conversation gets the memory.',
188
- audienceSocialHint: 'Others can talk to your AI too (through QQ, WeChat…): only conversations you alone have written in get the memory.',
189
- cap: 'Index cap',
190
- capHint: 'Default 200 lines / 25600 bytes; past it the AI must compact before writing more.',
191
- capLines: 'lines',
192
- capBytes: 'bytes',
193
- save: 'Save',
194
- saving: 'Saving…',
195
- discard: 'Discard changes',
196
- reloading: 'Saved; the plugin is reloading with the new settings…',
197
- saved: 'Saved.',
198
- savedUnconfirmed: 'Saved, but the settings read back differ from what you entered (or the plugin has not finished loading). Reload the page to check.',
199
- stale: 'The settings changed elsewhere and were read again. Make your change once more.',
200
- overridden: 'A higher configuration layer overrides these values, so they cannot be saved here.',
201
- invalid: 'One field is not acceptable: ',
202
- failed: 'Saving failed: ',
203
- panel: 'Memory',
204
- panelTitle: 'Engramory memory',
205
- refresh: 'Refresh',
206
- stripNote: 'Explanations and the index cap: Plugins → Engramory memory.',
207
- stripReadOnly: 'Cannot be changed here; see Plugins → Engramory memory.',
208
- listing: 'Reading the memory…',
209
- listFailed: 'Could not read the memory stores.',
210
- listTimeout: 'Reading took too long — a workspace may be on a network drive that does not answer. Refresh to try again.',
211
- empty: 'No memory yet. The store is created the first time the AI saves something.',
212
- pinnedRelative: 'The pinned index (indexPath) is a relative path, which follows each conversation\'s directory, so it cannot be listed here. Pin an absolute path to see it here.',
213
- storeUser: 'Global memory',
214
- storePinned: 'Pinned store',
215
- usage: 'Index {lines} / {maxLines} lines · {size} / {maxSize}',
216
- usageOver: 'Index {size} / {maxSize}, over the cap',
217
- usageSize: 'Index {size} / {maxSize}',
218
- sizeBytes: '{n} B',
219
- sizeKB: '{n} KB',
220
- overHint: 'Over the cap: the AI reads only the first part. Time to compact it.',
221
- noIndex: 'No index yet',
222
- openIndex: 'Open the index',
223
- openFolder: 'Open the folder',
224
- opened: 'Opened {name}.',
225
- openUnavailable: 'This dsh cannot open files on its own computer (when reached remotely, say). The files are where the path above says.',
226
- openMissing: 'That file is gone — renamed or deleted just now, perhaps. Refresh to see.',
227
- openBusy: 'Still opening the previous one — click again in a moment.',
228
- openFailed: 'Could not open it: {reason}',
229
- typeUser: 'User',
230
- typeFeedback: 'Feedback',
231
- typeProject: 'Project',
232
- typeReference: 'Reference',
233
- typeMoment: 'Moments',
234
- typeUpcoming: 'Coming up',
235
- typeSelf: 'Myself',
236
- typeOther: 'Other',
237
- archive: 'Archive ({count})',
238
- more: 'Too many files: only some are listed here.',
239
- healthOk: 'Check-up: nothing to fix.',
240
- healthBroken: 'The index points to files that are not there ({count})',
241
- healthBrokenMore: 'The index points to files that are not there (over {count})',
242
- healthBrokenUnlisted: 'The index points to files that are not there: too many to list here.',
243
- healthUnindexed: 'Not in the index ({count}): recall starts from the index, so the AI will not find these unless another note links to them.',
244
- healthUntyped: 'No type, or one it does not know ({count}), listed under Other.',
245
- healthFix: 'For a full check, run engramory_doctor.py.',
246
- healthLarge: 'Too much to check here, so no check-up.',
247
- healthUnreadable: 'Some files could not be read, so no check-up.',
248
- healthPartial: 'Too many files to list them all, so no check-up here.',
249
- howTo: 'How to use it',
250
- howToSay: 'To have the AI remember something, just tell it: "remember that I use pnpm", "note this decision down". It also tries to keep what is worth keeping on its own, such as a way of working you corrected.',
251
- howToRecall: 'By default every conversation carries the memory\'s table of contents (the index), and the AI opens a note when it needs the details; you do not have to remind it.',
252
- howToEdit: 'The memory this page can read is listed here; open a note to edit it. To have the AI forget something, tell it "forget …".',
253
- howToMove: 'The memory is plain markdown files on the computer dsh runs on, in the folder shown under each store\'s title. On a new computer, copy that folder to the same place, and if your configuration names where the store is, bring that setting along.',
254
- howToSocial: 'If others can talk to your AI too (through QQ, WeChat and the like), turn on Companion mode above and set Memory access to Social: only conversations it can tell are yours get the memory. This is not a security boundary; see the plugin\'s README.',
255
- feedbackLead: 'Found a problem or have an idea? ',
256
- feedbackIssue: 'Open an issue on GitHub',
257
- feedbackMail: ', or email ',
258
- copy: 'Copy',
259
- copied: 'Copied',
260
- copyFailed: 'Could not copy; select the address above by hand.',
261
- feedbackNote: 'Emails are sorted with the help of an AI assistant, and issues are public: do not paste your memory notes into either. Plugin version {version}.',
262
- issueBody: '(What happened, or your idea)\n\n---\ndsh-engramory {version}\nComputer this page was opened on: {os}\ndsh version: ',
263
- statNote: 'note',
264
- statNotes: 'notes',
265
- statStore: 'store',
266
- statStores: 'stores',
267
- statArchive: 'archived',
268
- statsReadAt: 'Read at {time}; days to a plan count from then',
269
- statsPartial: 'The listing was too long to finish, so these numbers fall short.',
270
- statsUnreadable: '{count} places that may hold a memory store could not be read and are not counted.',
271
- statsIncomplete: 'Some files in a store could not be read, so these numbers may fall short.',
272
- typeAll: 'All',
273
- typeLabel: 'Filter by type',
274
- storeCount: '{count} notes',
275
- storeCountOne: '{count} note',
276
- noteMeta: '{type} · {size}',
277
- noteUnread: 'Could not be read',
278
- archived: 'Archived',
279
- monthDay: '{m}/{d}',
280
- yearMonthDay: '{y}/{m}/{d}',
281
- badgePast: '{date} · passed, outcome to confirm',
282
- badgeToday: 'Today',
283
- badgeTomorrow: '{date} · tomorrow',
284
- badgeSoon: '{date} · in {days} days',
285
- badgeUndated: 'No date yet',
286
- badgeLarge: 'Large: worth splitting',
287
- badgeUnindexed: 'Not in the index',
288
- attnTitle: 'Worth tidying up',
289
- attnLarge: 'Notes past 12 KB: {count}. A note should hold one fact, and the AI can split these.',
290
- filterLabel: 'Filter notes',
291
- filterPlaceholder: 'Filter by name',
292
- filterCount: '{count} matching (among the notes listed)',
293
- filterNone: 'No matching notes in this store.',
294
- tidyCopy: 'Copy tidy-up instructions',
295
- tidyCopied: 'Copied; paste it into a conversation',
296
- tidyFailed: 'Could not copy; select the instructions below by hand:',
297
- tidyPrompt: 'Tidy up this memory store by the Engramory rules: {dir}\n- Links in the index to files that are not there: fix the ones whose note you can find; where there is none, remove that link alone, and the line only when it has no other live link left.\n- Notes the index does not name: add the ones recall will need, move the outdated ones into archive/ or delete them; do not add them all just to be complete.\n- Notes with no type: give them one.\n- An index over its cap: compact it first by merging duplicates and moving detail back into the notes, so the index holds pointers only.\n- Notes past about 12 KB: split them as the rules say.\n- Plans whose date has passed: do not delete them; rewrite them as what happened once you learn the outcome.\nThen check the index is within its cap, and tell me what you changed.',
298
- }
299
-
300
- const CSS = `
301
- .eng-page{display:flex;flex-direction:column;gap:18px;font-size:13px;line-height:1.55;color:var(--dsw-alias-label-primary);max-width:760px;}
302
- .eng-section{display:flex;flex-direction:column;gap:8px;}
303
- .eng-title{font-size:14px;font-weight:600;margin:0;}
304
- .eng-heading{display:flex;align-items:center;gap:10px;}
305
- .eng-hint{margin:0;font-size:12px;color:var(--dsw-alias-label-secondary);}
306
- .eng-note{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary);}
307
- .eng-banner{padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);font-size:12px;}
308
- .eng-banner[data-tone="error"]{color:var(--dsw-alias-state-error-primary);}
309
- .eng-banner[data-tone="ok"]{color:var(--dsw-alias-state-success-primary);}
310
- .eng-segment{display:inline-flex;gap:2px;padding:2px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-interactive-bg-hover);align-self:flex-start;}
311
- .eng-segment button{border:0;background:transparent;color:var(--dsw-alias-label-secondary);border-radius:6px;padding:4px 12px;font:inherit;font-size:12px;cursor:pointer;}
312
- .eng-segment button[aria-pressed="true"]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.12);}
313
- .eng-segment button:disabled{cursor:default;}
314
- .eng-switch{position:relative;width:32px;height:18px;border-radius:999px;border:0;padding:0;cursor:pointer;background:var(--dsw-alias-border-l2);flex:none;}
315
- .eng-switch[aria-checked="true"]{background:var(--dsw-alias-brand-primary);}
316
- .eng-switch:disabled{opacity:.5;cursor:default;}
317
- .eng-switch::after{content:"";position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:var(--dsw-alias-switch-thumb,#fff);transition:transform .15s ease;}
318
- .eng-switch[aria-checked="true"]::after{transform:translateX(14px);}
319
- .eng-input{border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:inherit;padding:5px 9px;font:inherit;font-size:12px;outline:none;min-width:0;}
320
- .eng-input:focus{border-color:var(--dsw-alias-brand-primary);}
321
- .eng-input[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary);}
322
- .eng-cap{display:flex;gap:12px;align-items:center;flex-wrap:wrap;}
323
- .eng-cap label{display:flex;align-items:center;gap:6px;color:var(--dsw-alias-label-secondary);font-size:12px;}
324
- .eng-cap input{width:110px;}
325
- .eng-btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);border-radius:8px;padding:5px 14px;font:inherit;font-size:12px;line-height:18px;cursor:pointer;white-space:nowrap;}
326
- .eng-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);}
327
- .eng-btn:disabled{opacity:.5;cursor:default;}
328
- .eng-btn-primary{background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary));border-color:transparent;color:var(--dsw-alias-label-primary-foreground,#fff);}
329
- .eng-btn-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary));opacity:.9;}
330
- .eng-btn-ghost{border-color:transparent;background:transparent;color:var(--dsw-alias-label-secondary);padding:4px 8px;}
331
- .eng-btn-small{padding:1px 8px;font-size:11.5px;}
332
- .eng-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
333
- .eng-memory{box-sizing:border-box;height:100%;overflow:auto;display:flex;flex-direction:column;align-items:center;gap:20px;padding:28px clamp(24px,4vw,48px) 48px;color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px;}
334
- [data-platform=darwin] .eng-memory{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px));}
335
- .eng-memory>*{box-sizing:border-box;width:100%;max-width:960px;flex:none;}
336
- .eng-memory svg{display:block;flex:none;}
337
- .eng-hero{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:24px 40px;padding:30px 32px;border-radius:24px;color:#e8f3f0;background:radial-gradient(120% 140% at 100% 0%,#1f4a5a 0%,rgba(31,74,90,0) 55%),linear-gradient(135deg,#0f1b2d 0%,#14263f 100%);box-shadow:0 12px 32px rgba(15,27,45,.18);}
338
- .eng-hero-main{display:flex;flex-direction:column;gap:24px;flex:1 1 340px;min-width:0;}
339
- .eng-brand{display:flex;align-items:center;gap:14px;}
340
- .eng-logo{border-radius:12px;box-shadow:0 0 0 1px rgba(110,231,200,.35);}
341
- .eng-hero-title{margin:0;font-size:21px;font-weight:600;line-height:28px;letter-spacing:.01em;}
342
- .eng-stats{display:flex;align-items:baseline;flex-wrap:wrap;gap:6px 0;}
343
- .eng-stat{display:inline-flex;align-items:baseline;gap:6px;}
344
- .eng-stat+.eng-stat{margin-left:18px;padding-left:18px;border-left:1px solid rgba(232,243,240,.18);}
345
- .eng-stat b{font-size:40px;line-height:44px;font-weight:600;color:#6ee7c8;font-variant-numeric:tabular-nums;letter-spacing:-.02em;}
346
- .eng-stat span{font-size:13px;color:rgba(232,243,240,.75);}
347
- .eng-hero-foot{display:flex;align-items:center;flex-wrap:wrap;gap:8px 10px;}
348
- .eng-hero-read{display:inline-flex;align-items:center;gap:6px;margin:0;padding:3px 10px;border-radius:999px;background:rgba(255,255,255,.06);font-size:12px;line-height:18px;color:rgba(232,243,240,.62);}
349
- .eng-hero-side{display:flex;flex-direction:column;flex:0 1 300px;min-width:260px;}
350
- .eng-hero .eng-strip{display:flex;flex-direction:column;gap:14px;padding:18px 20px;border-radius:18px;background:rgba(255,255,255,.06);box-shadow:inset 0 0 0 1px rgba(255,255,255,.08);}
351
- .eng-hero .eng-strip-item{display:flex;align-items:center;justify-content:space-between;gap:20px;min-height:30px;font-size:13px;color:rgba(232,243,240,.8);}
352
- .eng-hero .eng-strip-item:first-child{font-weight:600;color:#e8f3f0;}
353
- .eng-hero .eng-strip-note{margin:0;font-size:11.5px;line-height:17px;color:rgba(232,243,240,.74);}
354
- .eng-hero .eng-switch{width:46px;height:26px;background:rgba(255,255,255,.24);}
355
- .eng-hero .eng-switch::after{top:3px;left:3px;width:20px;height:20px;}
356
- .eng-hero .eng-switch[aria-checked="true"]::after{transform:translateX(20px);}
357
- .eng-hero .eng-switch[aria-checked="true"]{background:#6ee7c8;}
358
- .eng-hero .eng-switch[aria-checked="true"]::after{background:#0f1b2d;}
359
- .eng-hero .eng-segment{border:0;border-radius:999px;background:rgba(0,0,0,.25);}
360
- .eng-hero .eng-segment button{border-radius:999px;padding:3px 14px;font-size:12.5px;line-height:18px;color:rgba(232,243,240,.62);}
361
- .eng-hero .eng-segment button[aria-pressed="true"]{background:#6ee7c8;color:#0f1b2d;box-shadow:none;}
362
- .eng-hero .eng-btn,.eng-hero-btn{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border:1px solid rgba(232,243,240,.22);border-radius:999px;background:transparent;color:#e8f3f0;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap;}
363
- .eng-hero .eng-btn:hover:not(:disabled),.eng-hero-btn:hover{background:rgba(255,255,255,.08);}
364
- .eng-hero :focus-visible{outline:2px solid #6ee7c8;outline-offset:2px;}
365
- .eng-caveat{display:flex;align-items:flex-start;gap:8px;margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
366
- .eng-caveat svg{margin-top:2px;color:var(--dsw-alias-state-warn-label);}
367
- .eng-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin-top:6px;}
368
- .eng-tabs{display:flex;flex-wrap:wrap;gap:2px;flex:1 1 auto;min-width:0;}
369
- .eng-tab{display:inline-flex;align-items:center;gap:5px;height:30px;padding:0 10px;border:0;border-radius:9px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;cursor:pointer;}
370
- .eng-tab:hover{background:var(--dsw-alias-interactive-bg-hover);}
371
- .eng-tab[aria-pressed="true"]{background:var(--dsw-alias-interactive-bg-active);color:var(--dsw-alias-label-primary);font-weight:500;}
372
- .eng-tab-count{font-size:11.5px;font-weight:400;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;}
373
- .eng-search{position:relative;display:flex;align-items:center;flex:0 1 240px;min-width:160px;color:var(--dsw-alias-label-caption);}
374
- .eng-search svg{position:absolute;left:10px;pointer-events:none;}
375
- .eng-search .eng-input{width:100%;height:34px;padding-left:32px;border-radius:10px;font-size:13px;}
376
- .eng-filter-count,.eng-filter-none{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary);}
377
- .eng-store{display:flex;flex-direction:column;gap:10px;margin-top:10px;}
378
- .eng-store-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 10px;}
379
- .eng-store-title{margin:0;font-size:15px;font-weight:600;line-height:22px;}
380
- .eng-store-count{font-size:12px;color:var(--dsw-alias-label-tertiary);}
381
- .eng-meter{display:inline-block;width:56px;height:4px;margin-left:4px;border-radius:999px;background:var(--dsw-alias-border-l2);overflow:hidden;}
382
- .eng-meter-fill{display:block;height:100%;border-radius:999px;background:#2bb894;background:color-mix(in srgb,#2bb894 76%,var(--dsw-alias-label-primary));}
383
- .eng-meter[data-over="true"] .eng-meter-fill{background:var(--dsw-alias-state-error-primary);}
384
- .eng-usage{font-size:11.5px;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;}
385
- .eng-usage[data-over="true"]{color:var(--dsw-alias-state-error-primary);}
386
- .eng-store-actions{margin-left:auto;display:inline-flex;flex-wrap:wrap;gap:2px;}
387
- .eng-path{margin:-8px 0 0;font-family:var(--ds-font-family-code,ui-monospace,monospace);font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;}
388
- .eng-store-ok{display:flex;align-items:center;gap:6px;margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary);}
389
- .eng-store-ok svg{color:#2bb894;color:color-mix(in srgb,#2bb894 76%,var(--dsw-alias-label-primary));}
390
- .eng-attn{display:flex;align-items:flex-start;gap:10px;padding:10px 10px 10px 14px;border-radius:14px;background:var(--dsw-alias-state-warn-tertiary);background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 11%,transparent);}
391
- .eng-attn>svg{margin-top:2px;color:var(--dsw-alias-state-warn-label);}
392
- .eng-attn-body{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0;}
393
- .eng-attn-title{margin:0;font-size:12.5px;font-weight:600;line-height:20px;color:var(--dsw-alias-state-warn-label);}
394
- .eng-attn-item{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
395
- .eng-broken{display:flex;flex-wrap:wrap;gap:4px;margin:4px 0 0;padding:0;list-style:none;}
396
- .eng-broken code{padding:0 6px;border-radius:6px;background:var(--dsw-alias-interactive-bg-hover);font-family:var(--ds-font-family-code,ui-monospace,monospace);font-size:11px;line-height:18px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;}
397
- .eng-attn>.eng-btn{flex:none;}
398
- .eng-tidy{display:flex;flex-direction:column;gap:6px;}
399
- .eng-tidy p{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
400
- .eng-tidy textarea{box-sizing:border-box;width:100%;min-height:150px;resize:vertical;font:inherit;font-size:12px;line-height:18px;}
401
- .eng-list{display:flex;flex-direction:column;padding:4px;border:.5px solid var(--dsw-alias-border-l3);border-radius:16px;}
402
- .eng-rows{display:flex;flex-direction:column;margin:0;padding:0;list-style:none;}
403
- .eng-row{box-sizing:border-box;display:flex;align-items:center;gap:12px;width:100%;min-height:52px;padding:6px 10px;border:0;border-radius:12px;background:transparent;color:inherit;font:inherit;text-align:left;}
404
- button.eng-row{cursor:pointer;}
405
- button.eng-row:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);}
406
- .eng-row[data-type="user"]{--eng-type:#6f86c6;}
407
- .eng-row[data-type="feedback"]{--eng-type:#b39a45;}
408
- .eng-row[data-type="project"]{--eng-type:#4e9a78;}
409
- .eng-row[data-type="reference"]{--eng-type:#8b78c4;}
410
- .eng-row[data-type="moment"]{--eng-type:#c07193;}
411
- .eng-row[data-type="upcoming"]{--eng-type:#c9735c;}
412
- .eng-row[data-type="self"]{--eng-type:#3f9aa6;}
413
- .eng-mark{display:grid;place-items:center;width:32px;height:32px;flex:none;border-radius:10px;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l4);color:var(--eng-type,var(--dsw-alias-label-tertiary));color:color-mix(in srgb,var(--eng-type,var(--dsw-alias-label-tertiary)) 80%,var(--dsw-alias-label-primary));}
414
- .eng-row-text{display:flex;flex-direction:column;flex:1;min-width:0;}
415
- .eng-name{font-size:13.5px;font-weight:500;line-height:19px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
416
- .eng-row-meta{font-size:11.5px;line-height:16px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
417
- .eng-badges{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:6px;max-width:55%;}
418
- .eng-badge{padding:0 8px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);font-size:11.5px;line-height:20px;white-space:nowrap;}
419
- .eng-badge[data-tone="warn"]{background:var(--dsw-alias-state-warn-tertiary);background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 14%,transparent);color:var(--dsw-alias-state-warn-label);}
420
- .eng-badge[data-tone="quiet"]{background:transparent;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3);color:var(--dsw-alias-label-tertiary);}
421
- .eng-row-go{color:var(--dsw-alias-label-caption);}
422
- .eng-archive{border-top:.5px dashed var(--dsw-alias-border-l2);margin-top:4px;padding-top:4px;}
423
- .eng-list>.eng-archive:first-child{border-top:0;margin-top:0;padding-top:0;}
424
- .eng-archive>summary{display:flex;align-items:center;gap:12px;min-height:44px;padding:4px 14px 4px 18px;border-radius:12px;cursor:pointer;font-size:12.5px;color:var(--dsw-alias-label-secondary);list-style:none;}
425
- .eng-archive>summary::-webkit-details-marker{display:none;}
426
- .eng-archive>summary::after,.eng-howto>summary::after{content:"";margin-left:auto;width:6px;height:6px;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:rotate(-45deg);opacity:.55;}
427
- .eng-archive[open]>summary::after,.eng-howto[open]>summary::after{transform:rotate(45deg);}
428
- .eng-archive>summary:hover{background:var(--dsw-alias-interactive-bg-hover);}
429
- .eng-howto{box-sizing:border-box;padding:12px 14px;border:.5px solid var(--dsw-alias-border-l3);border-radius:14px;}
430
- .eng-howto>summary{display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;font-weight:500;line-height:20px;list-style:none;}
431
- .eng-howto>summary::-webkit-details-marker{display:none;}
432
- .eng-howto ul{display:flex;flex-direction:column;gap:4px;margin:10px 0 2px;padding-left:18px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
433
- .eng-feedback{display:flex;flex-direction:column;gap:2px;padding-top:14px;border-top:.5px solid var(--dsw-alias-border-l2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);}
434
- .eng-feedback p{display:flex;align-items:center;flex-wrap:wrap;margin:0;}
435
- .eng-feedback p svg{margin-right:6px;color:var(--dsw-alias-label-tertiary);}
436
- .eng-link{color:var(--dsw-alias-brand-primary);text-decoration:underline;text-underline-offset:2px;}
437
- .eng-link:hover{opacity:.8;}
438
- .eng-email{margin:0 8px 0 2px;font-family:var(--ds-font-family-code,ui-monospace,monospace);user-select:all;color:var(--dsw-alias-label-primary);}
439
- .eng-feedback-note{color:var(--dsw-alias-label-tertiary);}
440
- .eng-name:focus-visible,.eng-row:focus-visible,.eng-btn:focus-visible,.eng-tab:focus-visible,.eng-link:focus-visible,.eng-howto>summary:focus-visible,.eng-archive>summary:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary));outline-offset:1px;}
441
- `
442
-
443
- /** The settings the page edits, in the order the host computes its revision from. */
444
- const settingsOf = (data) => ({
445
- companion: data.companion === true,
446
- audience: data.audience === 'social' ? 'social' : 'private',
447
- maxLines: data.maxLines,
448
- maxBytes: data.maxBytes,
449
- })
450
- const revisionOf = (settings) => JSON.stringify(settings)
451
- const capOf = (text, max) => {
452
- const value = Number(text)
453
- return /^\s*\d+\s*$/.test(String(text)) && Number.isInteger(value) && value >= 1 && value <= max
454
- ? value
455
- : undefined
456
- }
457
-
458
- /** fetch with a deadline: a request the host never answers must not hold the page busy. */
459
- async function request(url, init = {}) {
460
- const deadline = new AbortController()
461
- const timer = setTimeout(() => deadline.abort(), 15000)
462
- try {
463
- const response = await fetch(url, { cache: 'no-store', ...init, signal: deadline.signal,
464
- headers: { accept: 'application/json', ...(init.headers ?? {}) } })
465
- // the body is read under the same deadline: headers alone do not finish a request
466
- const body = await response.json().catch(() => undefined)
467
- return { ok: response.ok, status: response.status, body }
468
- } finally {
469
- clearTimeout(timer)
470
- }
471
- }
472
-
473
- async function fetchSettings() {
474
- const response = await request(SETTINGS_API)
475
- if (!response.ok || response.body === undefined) throw new Error(`HTTP ${response.status}`)
476
- return response.body
477
- }
478
-
479
- /**
480
- * The settings as the host has them, and a save that waits for the reloaded plugin to
481
- * read them back. `onAdopt` hears every settings read, a save's included.
482
- */
483
- function useSettings(t, onAdopt) {
484
- const [state, setState] = useState({ phase: 'loading' })
485
- const [busy, setBusy] = useState(false)
486
- const [banner, setBanner] = useState(undefined)
487
- const alive = useRef(true)
488
- // a second click before the page re-renders as busy must not send a second save
489
- const saving = useRef(false)
490
- useEffect(() => () => { alive.current = false }, [])
491
-
492
- const adopt = useCallback((data) => {
493
- const settings = settingsOf(data)
494
- setState({ phase: 'ready', data, settings })
495
- onAdopt?.(settings)
496
- }, [onAdopt])
497
- const load = useCallback(async () => {
498
- setState((s) => (s.phase === 'ready' ? s : { phase: 'loading' }))
499
- try {
500
- const data = await fetchSettings()
501
- if (alive.current) adopt(data)
502
- } catch {
503
- if (alive.current) setState({ phase: 'error' })
504
- }
505
- }, [adopt])
506
- useEffect(() => { load() }, [load])
507
-
508
- const save = async (next) => {
509
- if (saving.current) return
510
- saving.current = true
511
- setBusy(true)
512
- setBanner(undefined)
513
- try {
514
- let result
515
- try {
516
- const response = await request(SETTINGS_API, {
517
- method: 'POST',
518
- headers: { 'content-type': 'application/json' },
519
- body: JSON.stringify({ revision: state.data.revision, ...next }),
520
- })
521
- result = response.body ?? { ok: false, error: 'failed', message: `HTTP ${response.status}` }
522
- } catch (error) {
523
- result = { ok: false, error: 'failed', message: String(error?.message ?? error) }
524
- }
525
- if (!alive.current) return
526
- if (result.ok) {
527
- // The plugin reloads with the new config; its route comes back with it.
528
- setBanner({ tone: 'ok', text: t('reloading') })
529
- const wanted = revisionOf(next)
530
- let fresh
531
- for (let i = 0; i < 20 && alive.current; i++) {
532
- await new Promise((resolve) => setTimeout(resolve, 400))
533
- try {
534
- fresh = await fetchSettings()
535
- if (revisionOf(settingsOf(fresh)) === wanted) break
536
- } catch { /* still reloading */ }
537
- }
538
- if (!alive.current) return
539
- if (fresh !== undefined) adopt(fresh)
540
- // The save landed either way; say so plainly when what came back differs.
541
- setBanner(fresh !== undefined && revisionOf(settingsOf(fresh)) === wanted
542
- ? { tone: 'ok', text: t('saved') }
543
- : { tone: 'error', text: t('savedUnconfirmed') })
544
- } else if (result.error === 'stale') {
545
- await load()
546
- if (alive.current) setBanner({ tone: 'error', text: t('stale') })
547
- } else if (result.error === 'expression') {
548
- // the profile changed under the page: read it again, which makes the page read-only
549
- await load()
550
- if (alive.current) setBanner({ tone: 'error', text: t('expression') })
551
- } else if (result.error === 'overridden') {
552
- setBanner({ tone: 'error', text: t('overridden') })
553
- } else if (result.error === 'invalid') {
554
- setBanner({ tone: 'error', text: t('invalid') + (result.field ?? '') })
555
- } else if (result.error === 'unavailable') {
556
- setBanner({ tone: 'error', text: t('unavailable') })
557
- } else {
558
- setBanner({ tone: 'error', text: t('failed') + (result.message ?? '') })
559
- }
560
- } finally {
561
- saving.current = false
562
- if (alive.current) setBusy(false)
563
- }
564
- }
565
- return { state, busy, banner, setBanner, load, save }
566
- }
567
-
568
- /** A host-styled switch: role=switch with aria-checked, as the host's own. */
569
- function Switch({ checked, disabled, label, onChange }) {
570
- return h('button', {
571
- type: 'button', role: 'switch', className: 'eng-switch', 'aria-checked': checked,
572
- 'aria-label': label, disabled, onClick: () => onChange(!checked),
573
- })
574
- }
575
-
576
- /** A host-styled two-way choice: buttons with aria-pressed in one group. */
577
- function Segment({ label, value, options, disabled, onChange }) {
578
- return h('div', { className: 'eng-segment', role: 'group', 'aria-label': label },
579
- options.map(([key, text]) => h('button', {
580
- type: 'button', key, 'aria-pressed': value === key, disabled, onClick: () => onChange(key),
581
- }, text)))
582
- }
583
-
584
- function CompanionSection({ draft, t, disabled, update }) {
585
- return h('section', { className: 'eng-section' },
586
- h('div', { className: 'eng-heading' },
587
- h('h3', { className: 'eng-title' }, t('companion')),
588
- h(Switch, { checked: draft.companion, disabled, label: t('companion'),
589
- onChange: (on) => update({ companion: on }) })),
590
- h('p', { className: 'eng-hint' }, t('companionHint')))
591
- }
592
-
593
- function AudienceSection({ draft, t, disabled, update }) {
594
- return h('section', { className: 'eng-section' },
595
- h('h3', { className: 'eng-title' }, t('audience')),
596
- h(Segment, { label: t('audience'), value: draft.audience, disabled,
597
- options: [['private', t('audiencePrivate')], ['social', t('audienceSocial')]],
598
- onChange: (audience) => update({ audience }) }),
599
- h('p', { className: 'eng-hint' }, t(draft.audience === 'social' ? 'audienceSocialHint' : 'audiencePrivateHint')))
600
- }
601
-
602
- function CapSection({ caps, t, disabled, setCaps }) {
603
- const field = (key, label, max) => h('label', null,
604
- h('input', { className: 'eng-input', inputMode: 'numeric', value: caps[key], disabled,
605
- 'aria-invalid': capOf(caps[key], max) === undefined,
606
- onChange: (e) => setCaps({ ...caps, [key]: e.target.value }) }),
607
- label)
608
- return h('section', { className: 'eng-section' },
609
- h('h3', { className: 'eng-title' }, t('cap')),
610
- h('div', { className: 'eng-cap' },
611
- field('maxLines', t('capLines'), Number.MAX_SAFE_INTEGER), field('maxBytes', t('capBytes'), Number.MAX_SAFE_INTEGER)),
612
- h('p', { className: 'eng-hint' }, t('capHint')))
613
- }
614
-
615
- /** The whole form, with what each setting means: the package's page in the Plugins page. */
616
- function SettingsForm({ t }) {
617
- const [draft, setDraft] = useState(undefined)
618
- const [caps, setCaps] = useState({ maxLines: String(DEFAULT_LINES), maxBytes: String(DEFAULT_BYTES) })
619
- const onAdopt = useCallback((settings) => {
620
- setDraft(settings)
621
- setCaps({ maxLines: String(settings.maxLines), maxBytes: String(settings.maxBytes) })
622
- }, [])
623
- const { state, busy, banner, setBanner, load, save } = useSettings(t, onAdopt)
624
-
625
- if (state.phase === 'loading' || draft === undefined && state.phase !== 'error') {
626
- return h('p', { className: 'eng-note' }, t('loading'))
627
- }
628
- if (state.phase === 'error') {
629
- return h('div', { className: 'eng-page' },
630
- h('div', { className: 'eng-banner', 'data-tone': 'error' }, t('loadFailed')),
631
- h('div', { className: 'eng-actions' }, h('button', { type: 'button', className: 'eng-btn', onClick: load }, t('retry'))))
632
- }
633
-
634
- const { data, settings } = state
635
- const editable = data.editable === true
636
- const disabled = !editable || busy
637
- const maxLines = capOf(caps.maxLines, Number.MAX_SAFE_INTEGER)
638
- const maxBytes = capOf(caps.maxBytes, Number.MAX_SAFE_INTEGER)
639
- const next = { ...draft, maxLines: maxLines ?? draft.maxLines, maxBytes: maxBytes ?? draft.maxBytes }
640
- const valid = maxLines !== undefined && maxBytes !== undefined
641
- const dirty = revisionOf(next) !== revisionOf(settings)
642
- const update = (patch) => { setDraft({ ...draft, ...patch }); setBanner(undefined) }
643
- const discard = () => {
644
- setDraft(settings)
645
- setCaps({ maxLines: String(settings.maxLines), maxBytes: String(settings.maxBytes) })
646
- setBanner(undefined)
647
- }
648
-
649
- return h('div', { className: 'eng-page' },
650
- editable ? null : h('div', { className: 'eng-banner' },
651
- t(data.readOnly === 'expression' ? 'expression' : 'unavailable')),
652
- h(CompanionSection, { draft, t, disabled, update }),
653
- // memory access is a choice inside companion mode: off, it changes nothing
654
- draft.companion ? h(AudienceSection, { draft, t, disabled, update }) : null,
655
- h(CapSection, { caps, t, disabled, setCaps }),
656
- banner ? h('div', { className: 'eng-banner', 'data-tone': banner.tone, role: 'status' }, banner.text) : null,
657
- editable ? h('div', { className: 'eng-actions' },
658
- h('button', { type: 'button', className: 'eng-btn eng-btn-primary', disabled: busy || !dirty || !valid, onClick: () => save(next) },
659
- busy ? t('saving') : t('save')),
660
- h('button', { type: 'button', className: 'eng-btn', disabled: busy || !dirty, onClick: discard }, t('discard')))
661
- : null)
662
- }
663
-
664
- function SettingsPage(props) {
665
- if (props.view === 'summary') return props.t('summary')
666
- return h(SettingsForm, props)
667
- }
668
-
669
- /**
670
- * The two settings that matter most, atop the memory page, each saved as it is switched;
671
- * what they mean, and the index cap, stay on the package's page.
672
- */
673
- function SettingsStrip({ t }) {
674
- const { state, busy, banner, load, save } = useSettings(t)
675
- if (state.phase === 'error') {
676
- return h('section', { className: 'eng-strip' },
677
- h('p', { className: 'eng-strip-note' }, t('loadFailed')),
678
- h('button', { type: 'button', className: 'eng-btn', onClick: load }, t('retry')))
679
- }
680
- if (state.phase !== 'ready') return null
681
- const { data, settings } = state
682
- const disabled = data.editable !== true || busy
683
- const change = (patch) => save({ ...settings, ...patch })
684
- return h('section', { className: 'eng-strip' },
685
- h('div', { className: 'eng-strip-item' },
686
- h('span', null, t('companion')),
687
- h(Switch, { checked: settings.companion, disabled, label: t('companion'),
688
- onChange: (on) => change({ companion: on }) })),
689
- // memory access is a choice inside companion mode: off, it changes nothing
690
- settings.companion ? h('div', { className: 'eng-strip-item' },
691
- h('span', null, t('audience')),
692
- h(Segment, { label: t('audience'), value: settings.audience, disabled,
693
- options: [['private', t('audiencePrivate')], ['social', t('audienceSocial')]],
694
- onChange: (audience) => { if (audience !== settings.audience) change({ audience }) } })) : null,
695
- h('p', { className: 'eng-strip-note', role: banner ? 'status' : undefined },
696
- busy ? t('saving') : banner ? banner.text : t(data.editable === true ? 'stripNote' : 'stripReadOnly')))
697
- }
698
-
699
- /** The memory route's listing, read again on `load`; a reply that a later read overtook is dropped. */
700
- function useMemory() {
701
- const [state, setState] = useState({ phase: 'loading' })
702
- const alive = useRef(true)
703
- const generation = useRef(0)
704
- useEffect(() => () => { alive.current = false }, [])
705
- const load = useCallback(async () => {
706
- const mine = ++generation.current
707
- setState((s) => (s.phase === 'ready' ? s : { phase: 'loading' }))
708
- let next
709
- try {
710
- const response = await request(MEMORY_API)
711
- next = response.ok && Array.isArray(response.body?.stores)
712
- ? { phase: 'ready', data: response.body, at: Date.now() }
713
- : { phase: 'error', reason: response.status === 503 ? 'listTimeout' : 'listFailed' }
714
- } catch {
715
- next = { phase: 'error', reason: 'listFailed' }
716
- }
717
- if (alive.current && mine === generation.current) setState(next)
718
- }, [])
719
- useEffect(() => { load() }, [load])
720
- return { state, load }
721
- }
722
-
723
- /** What the page says for each way the memory route declines to open a file. */
724
- const OPEN_FAILURES = {
725
- unavailable: 'openUnavailable', missing: 'openMissing', busy: 'openBusy', timeout: 'listTimeout',
726
- }
727
- const nameOf = (file) => file.replace(/\.md$/i, '')
728
- const sizeOf = (t, bytes) => (bytes < 1024 ? t('sizeBytes', { n: bytes }) : t('sizeKB', { n: (bytes / 1024).toFixed(1) }))
729
- const typeKey = (type) => `type${type[0].toUpperCase()}${type.slice(1)}`
730
- const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
731
- const byName = (a, b) => collator.compare(a, b)
732
- /** Notes in the protocol's order of types, then by name. */
733
- const byTypeThenName = (a, b) => TYPES.indexOf(a.type) - TYPES.indexOf(b.type) || byName(a.name, b.name)
734
-
735
- /** Put `text` on the clipboard; false where there is none (a page over plain http) or it is refused. */
736
- async function copyText(text) {
737
- try {
738
- await globalThis.navigator.clipboard.writeText(text)
739
- return true
740
- } catch {
741
- return false
742
- }
743
- }
744
-
745
- /** The date an `upcoming` note is named with, if it is a real day: `YYYY-MM-DD`, else undefined. */
746
- function dateOf(file) {
747
- const m = DATED.exec(nameOf(file))
748
- if (m === null) return undefined
749
- const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]
750
- const day = new Date(Date.UTC(y, mo - 1, d))
751
- return day.getUTCFullYear() === y && day.getUTCMonth() === mo - 1 && day.getUTCDate() === d
752
- ? `${m[1]}-${m[2]}-${m[3]}` : undefined
753
- }
754
- /** A `YYYY-MM-DD` day as a number of days, to subtract one from another. */
755
- const dayNumber = (date) => Date.UTC(Number(date.slice(0, 4)), Number(date.slice(5, 7)) - 1,
756
- Number(date.slice(8, 10))) / 86400000
757
- /** Today on this computer's calendar, as `YYYY-MM-DD`. */
758
- function todayOf(now) {
759
- const d = new Date(now)
760
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
761
- }
762
-
763
- /**
764
- * Where an `upcoming` note stands against today on this computer: a date passed only says
765
- * the outcome is yet to be asked about (SKILL.md §2.2 keeps the note until it is known),
766
- * so nothing here is called late or stale. No date, or no real one, is undated.
767
- */
768
- function planOf(file, now) {
769
- const date = dateOf(file)
770
- if (date === undefined) return { status: 'undated' }
771
- const days = dayNumber(date) - dayNumber(todayOf(now))
772
- return { status: days < 0 ? 'past' : days === 0 ? 'today' : 'ahead', days, date }
773
- }
774
-
775
- /** A note's name as listed: a plan's date is in its badge, so it is not said again before the name. */
776
- function shownName(file, plan) {
777
- const name = nameOf(file)
778
- if (plan?.date === undefined) return name
779
- const rest = name.slice(10).replace(/^[\s_-]+/, '')
780
- return rest === '' ? name : rest
781
- }
782
-
783
- /** How full an index is, the nearer of its two caps; its lines only when they were counted. */
784
- function fillOf(index, cap) {
785
- const lines = index.lines === undefined ? 0 : index.lines / cap.maxLines
786
- return Math.max(lines, index.bytes / cap.maxBytes)
787
- }
788
-
789
- /** Line icons on a 24-unit grid, in the current colour: [element, attributes] each. One per
790
- * note type (TYPES), drawn alike, so the type's colour tells them apart before the shape does. */
791
- const ICONS = {
792
- refresh: [['path', { d: 'M20 11a8 8 0 1 0-2.3 5.7' }], ['path', { d: 'M20 4v7h-7' }]],
793
- search: [['circle', { cx: 11, cy: 11, r: 7 }], ['path', { d: 'm20 20-3.5-3.5' }]],
794
- copy: [['rect', { x: 9, y: 9, width: 11, height: 11, rx: 2 }], ['path', { d: 'M5 15V5a2 2 0 0 1 2-2h8' }]],
795
- folder: [['path', { d: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z' }]],
796
- index: [['path', { d: 'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01' }]],
797
- tidy: [['path', { d: 'm4 20 11-11M14 4l1 2 2 1-2 1-1 2-1-2-2-1 2-1zM19 11l.7 1.3L21 13l-1.3.7L19 15l-.7-1.3L17 13l1.3-.7z' }]],
798
- archive: [['rect', { x: 3, y: 4, width: 18, height: 5, rx: 1 }], ['path', { d: 'M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4' }]],
799
- alert: [['path', { d: 'M12 4 2.5 20h19z' }], ['path', { d: 'M12 10v4M12 17h.01' }]],
800
- clock: [['circle', { cx: 12, cy: 12, r: 8.5 }], ['path', { d: 'M12 7.5V12l3 2' }]],
801
- check: [['path', { d: 'm5 12 5 5 9-10' }]],
802
- chevron: [['path', { d: 'm9 6 6 6-6 6' }]],
803
- book: [['path', { d: 'M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z' }], ['path', { d: 'M4 19V5' }]],
804
- issue: [['path', { d: 'M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z' }]],
805
- mail: [['rect', { x: 3, y: 5, width: 18, height: 14, rx: 2 }], ['path', { d: 'm3 7 9 6 9-6' }]],
806
- user: [['circle', { cx: 12, cy: 8.6, r: 3.6 }], ['path', { d: 'M5 19.5c1.2-3.3 3.9-5 7-5s5.8 1.7 7 5z' }]],
807
- feedback: [['path', { d: 'M4.5 6.5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11l-4 3v-3h-.5a2 2 0 0 1-2-2z' }],
808
- ['path', { d: 'm9 10.3 2 2 4-4' }]],
809
- project: [['path', { d: 'M12 4 3.5 8.5 12 13l8.5-4.5z' }], ['path', { d: 'm3.5 12.5 8.5 4.5 8.5-4.5M3.5 16.3 12 20.8l8.5-4.5' }]],
810
- reference: [['path', { d: 'M7 3.5h10a1 1 0 0 1 1 1v16l-6-3.8-6 3.8v-16a1 1 0 0 1 1-1z' }]],
811
- moment: [['path', { d: 'M10 3.5l1.6 4.4L16 9.5l-4.4 1.6L10 15.5l-1.6-4.4L4 9.5l4.4-1.6z' }],
812
- ['path', { d: 'M17.5 14v5.5M14.75 16.75h5.5' }]],
813
- upcoming: [['rect', { x: 4, y: 5.5, width: 16, height: 14.5, rx: 2.5 }], ['path', { d: 'M4 10h16M8.5 3.5v4M15.5 3.5v4' }],
814
- ['circle', { cx: 15.3, cy: 15, r: 1.3, fill: 'currentColor', stroke: 'none' }]],
815
- self: [['path', { d: 'M12 19.5s-7-4.3-7-9.6A3.9 3.9 0 0 1 12 7.6a3.9 3.9 0 0 1 7 2.3c0 5.3-7 9.6-7 9.6z' }]],
816
- other: [['path', { d: 'M13.5 3.5H7a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9z' }], ['path', { d: 'M13.5 3.5V9H19' }]],
817
- }
818
- const icon = (name, size = 16, weight = 1.8) => h('svg', {
819
- width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: weight,
820
- strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, focusable: 'false',
821
- }, ...ICONS[name].map(([tag, attributes], i) => h(tag, { key: i, ...attributes })))
822
-
823
- /** The project's mark, [[▮]] in mint on its dark tile, as in its icon. */
824
- function Logo() {
825
- return h('svg', { className: 'eng-logo', width: 44, height: 44, viewBox: '0 0 64 64', 'aria-hidden': true, focusable: 'false' },
826
- h('rect', { width: 64, height: 64, rx: 14, fill: '#0F1B2D' }),
827
- h('path', { d: 'M13 17.5H9v29h4M22 17.5h-4v29h4M42 17.5h4v29h-4M51 17.5h4v29h-4', fill: 'none', stroke: '#6EE7C8',
828
- strokeWidth: 4, strokeLinecap: 'round', strokeLinejoin: 'round' }),
829
- h('rect', { x: 27.5, y: 23, width: 9, height: 18, rx: 2.4, fill: '#6EE7C8' }))
830
- }
831
-
832
- /** When a listing was read, its day with its time, as this computer shows them. */
833
- const timeOf = (at) => new Date(at).toLocaleString([], { month: '2-digit', day: '2-digit', hour: '2-digit',
834
- minute: '2-digit' })
835
-
836
- /**
837
- * The banner atop the memory page, in the project's own colours on any theme: its name, the
838
- * listing in three numbers as read at `at` with a refresh beside the time, and the two
839
- * settings that matter most in a panel of their own. Numbers only once there is a listing
840
- * with something to count.
841
- */
842
- function Hero({ data, at, refresh, t }) {
843
- const counted = data !== undefined && (data.stores.length > 0 || data.unreadable > 0)
844
- const sum = (of) => data.stores.reduce((total, store) => total + of(store), 0)
845
- const notes = counted ? sum((store) => store.notes.length) : 0
846
- const stat = (n, label) => h('div', { className: 'eng-stat', key: label }, h('b', null, String(n)), h('span', null, label))
847
- return h('header', { className: 'eng-hero' },
848
- h('div', { className: 'eng-hero-main' },
849
- h('div', { className: 'eng-brand' }, h(Logo), h('h1', { className: 'eng-hero-title' }, t('panelTitle'))),
850
- counted ? h('div', { className: 'eng-stats' },
851
- stat(notes, t(notes === 1 ? 'statNote' : 'statNotes')),
852
- stat(data.stores.length, t(data.stores.length === 1 ? 'statStore' : 'statStores')),
853
- stat(sum((store) => store.archive.length), t('statArchive'))) : null,
854
- h('div', { className: 'eng-hero-foot' },
855
- data === undefined ? null : h('p', { className: 'eng-hero-read' },
856
- icon('clock', 13), t('statsReadAt', { time: timeOf(at) })),
857
- h('button', { type: 'button', className: 'eng-hero-btn', onClick: refresh }, icon('refresh', 14), t('refresh')))),
858
- h('div', { className: 'eng-hero-side' }, h(SettingsStrip, { t })))
859
- }
860
-
861
- /** What the numbers leave out — a listing cut short, files or stores it could not read — since
862
- * what was not listed is not counted as nothing. */
863
- function Caveats({ data, t }) {
864
- const partial = data.more === true || data.stores.some((store) => store.more)
865
- // a note or a folder it could not read: the store's check-up says so too
866
- const incomplete = data.stores.some((store) => store.health?.checked === false &&
867
- store.health.reason === 'unreadable')
868
- const lines = [
869
- partial ? t('statsPartial') : null,
870
- incomplete ? t('statsIncomplete') : null,
871
- data.unreadable > 0 ? t('statsUnreadable', { count: data.unreadable }) : null,
872
- ].filter((line) => line !== null)
873
- return lines.length === 0 ? null
874
- : h('p', { className: 'eng-caveat' }, icon('alert', 14), h('span', null, lines.join(' ')))
875
- }
876
-
877
- /**
878
- * One store: where it is, how full its index is (a bar to the nearer of its two caps), what
879
- * its check-up (index.js checkUp) found for the AI to tidy up — with the tidy-up instructions
880
- * to copy, or to select where there is no clipboard — and its notes, a row each: the type's
881
- * mark, the name, the type and size, and what stands out (a plan's day, a note grown past one
882
- * fact, one the index leaves out). While the page filters, the rows that match and no more.
883
- */
884
- function StoreSection({ store, cap, canOpen, open, match, kind, now, t }) {
885
- const [tidy, setTidy] = useState('idle')
886
- const alive = useRef(true)
887
- useEffect(() => () => { alive.current = false }, [])
888
- const title = store.kind === 'user' ? [t('storeUser'), ...store.titles].join(' · ')
889
- : store.kind === 'pinned' ? [t('storePinned'), ...store.titles].join(' · ')
890
- : store.titles.join(' · ')
891
- const { index } = store
892
- const sizes = index === null ? {} : { size: sizeOf(t, index.bytes), maxSize: sizeOf(t, cap.maxBytes) }
893
- // lines are counted only for an index read whole; past that, its bytes say over or not
894
- const usage = index === null ? t('noIndex')
895
- : index.lines !== undefined ? t('usage', { lines: index.lines, maxLines: cap.maxLines, ...sizes })
896
- : t(index.over ? 'usageOver' : 'usageSize', sizes)
897
- const fill = index === null ? undefined : fillOf(index, cap)
898
- const filtering = match !== undefined || kind !== undefined
899
- const keep = (file) => match === undefined || match(file)
900
- const notes = store.notes.filter((note) => (kind === undefined || note.type === kind) && keep(note.name))
901
- .sort(byTypeThenName)
902
- const archived = kind === undefined ? store.archive.filter(keep).sort(byName) : []
903
-
904
- const check = store.health ?? undefined
905
- const checked = check?.checked === true
906
- const unindexed = new Set(checked ? check.unindexed : [])
907
- const untyped = store.notes.filter((note) => note.type === 'other').length
908
- const large = store.notes.filter((note) => note.bytes > LARGE_NOTE).length
909
- // pointers to nothing past what the page is told of are still pointers to nothing
910
- const broken = checked && (check.broken.length > 0 || check.brokenMore)
911
- const findings = [
912
- index?.over ? h('p', { className: 'eng-attn-item', key: 'over' }, t('overHint')) : null,
913
- broken ? h('div', { className: 'eng-attn-item', key: 'broken' },
914
- check.broken.length === 0 ? t('healthBrokenUnlisted')
915
- : t(check.brokenMore ? 'healthBrokenMore' : 'healthBroken', { count: check.broken.length }),
916
- // what the index says, as it says it: there is no file to open
917
- check.broken.length > 0 ? h('ul', { className: 'eng-broken' },
918
- check.broken.map((target) => h('li', { key: target }, h('code', null, target)))) : null) : null,
919
- checked && check.unindexed.length > 0
920
- ? h('p', { className: 'eng-attn-item', key: 'unindexed' }, t('healthUnindexed', { count: check.unindexed.length })) : null,
921
- checked && untyped > 0 ? h('p', { className: 'eng-attn-item', key: 'untyped' }, t('healthUntyped', { count: untyped })) : null,
922
- large > 0 ? h('p', { className: 'eng-attn-item', key: 'large' }, t('attnLarge', { count: large })) : null,
923
- ].filter((finding) => finding !== null)
924
- // while filtering, the names that match and nothing else: the findings come back after
925
- const attention = !filtering && findings.length > 0
926
- // a check-up that did not run says why, except past the cap, which the findings say already
927
- const unchecked = check === undefined || check === null || check.checked ? undefined
928
- : { large: 'healthLarge', partial: 'healthPartial', unreadable: 'healthUnreadable' }[check.reason]
929
-
930
- const prompt = t('tidyPrompt', { dir: store.dir })
931
- const copyTidy = async () => {
932
- const done = await copyText(prompt)
933
- if (alive.current) setTidy(done ? 'copied' : 'failed')
934
- }
935
- // one per store: in the findings where there are any, else among the store's own actions
936
- const tidyButton = (className) => h('button', { type: 'button', className, onClick: copyTidy },
937
- icon('tidy', 14), t(tidy === 'copied' ? 'tidyCopied' : 'tidyCopy'))
938
-
939
- const planText = (plan) => {
940
- if (plan.status === 'undated') return t('badgeUndated')
941
- if (plan.status === 'today') return t('badgeToday')
942
- // the year where it is not this one, so last year's plan is not taken for this year's
943
- const year = Number(plan.date.slice(0, 4))
944
- const day = { m: Number(plan.date.slice(5, 7)), d: Number(plan.date.slice(8, 10)) }
945
- const date = year === new Date(now).getFullYear() ? t('monthDay', day) : t('yearMonthDay', { y: year, ...day })
946
- return plan.status === 'past' ? t('badgePast', { date })
947
- : plan.days === 1 ? t('badgeTomorrow', { date }) : t('badgeSoon', { date, days: plan.days })
948
- }
949
- /** A note's row, or an archived file's (no note given): to open where dsh can, else text. */
950
- const row = (file, note) => {
951
- const type = note === undefined ? 'archive' : note.type
952
- const plan = type === 'upcoming' ? planOf(file, now) : undefined
953
- const meta = note === undefined ? t('archived')
954
- : note.unread ? t('noteUnread')
955
- : note.bytes === undefined ? t(typeKey(type))
956
- : t('noteMeta', { type: t(typeKey(type)), size: sizeOf(t, note.bytes) })
957
- const badges = [
958
- plan === undefined ? null : h('span', { className: 'eng-badge', key: 'plan',
959
- 'data-tone': plan.status === 'past' ? 'warn' : plan.status === 'undated' ? 'quiet' : undefined }, planText(plan)),
960
- note?.bytes > LARGE_NOTE ? h('span', { className: 'eng-badge', 'data-tone': 'warn', key: 'large' }, t('badgeLarge')) : null,
961
- note !== undefined && unindexed.has(file) ? h('span', { className: 'eng-badge', key: 'unindexed' }, t('badgeUnindexed')) : null,
962
- ].filter((badge) => badge !== null)
963
- const parts = [
964
- h('span', { className: 'eng-mark', key: 'mark' }, icon(Object.hasOwn(ICONS, type) ? type : 'other', 18, 1.6)),
965
- h('span', { className: 'eng-row-text', key: 'text' },
966
- h('span', { className: 'eng-name' }, shownName(file, plan)),
967
- h('span', { className: 'eng-row-meta' }, meta)),
968
- badges.length > 0 ? h('span', { className: 'eng-badges', key: 'badges' }, badges) : null,
969
- canOpen ? h('span', { className: 'eng-row-go', key: 'go' }, icon('chevron', 14)) : null,
970
- ]
971
- const props = { className: 'eng-row', 'data-type': type, title: file }
972
- return h('li', { key: file }, canOpen
973
- ? h('button', { type: 'button', ...props, onClick: () => open(store, file, note === undefined) }, ...parts)
974
- : h('div', props, ...parts))
975
- }
976
- const archive = archived.length === 0 ? null
977
- : h('details', { className: 'eng-archive', open: match === undefined ? undefined : true },
978
- h('summary', null, icon('archive', 16), h('span', null, t('archive', { count: archived.length }))),
979
- h('ul', { className: 'eng-rows' }, archived.map((file) => row(file, undefined))))
980
-
981
- return h('section', { className: 'eng-store', 'aria-label': title },
982
- h('div', { className: 'eng-store-head' },
983
- h('h2', { className: 'eng-store-title' }, title),
984
- h('span', { className: 'eng-store-count' },
985
- t(store.notes.length === 1 ? 'storeCountOne' : 'storeCount', { count: store.notes.length })),
986
- // the nearer cap, whichever it is; over it, full and marked, not a bar that stops at the edge
987
- fill === undefined ? null : h('span', { className: 'eng-meter', 'data-over': index.over === true || fill > 1,
988
- 'aria-hidden': true },
989
- h('span', { className: 'eng-meter-fill', style: { width: `${Math.min(100, Math.floor(fill * 100))}%` } })),
990
- h('span', { className: 'eng-usage', 'data-over': index?.over === true, title: index?.over ? t('overHint') : undefined }, usage),
991
- h('div', { className: 'eng-store-actions' },
992
- attention ? null : tidyButton('eng-btn eng-btn-ghost'),
993
- // the folder is shown with its index selected: no index, no folder to show
994
- ...(canOpen && index !== null ? [
995
- h('button', { type: 'button', className: 'eng-btn eng-btn-ghost', key: 'index',
996
- onClick: () => open(store, index.name, false) }, icon('index', 14), t('openIndex')),
997
- h('button', { type: 'button', className: 'eng-btn eng-btn-ghost', key: 'folder',
998
- onClick: () => open(store, undefined, false) }, icon('folder', 14), t('openFolder'))] : []))),
999
- h('p', { className: 'eng-path' }, store.dir),
1000
- !filtering && checked && findings.length === 0
1001
- ? h('p', { className: 'eng-store-ok' }, icon('check', 13), t('healthOk')) : null,
1002
- attention ? h('div', { className: 'eng-attn', role: 'note' },
1003
- icon('alert', 16),
1004
- h('div', { className: 'eng-attn-body' },
1005
- h('h3', { className: 'eng-attn-title' }, t('attnTitle')),
1006
- ...findings,
1007
- h('p', { className: 'eng-attn-item', key: 'doctor' }, t('healthFix'))),
1008
- tidyButton('eng-btn')) : null,
1009
- tidy === 'failed' ? h('div', { className: 'eng-tidy', role: 'status' },
1010
- h('p', null, t('tidyFailed')),
1011
- h('textarea', { readOnly: true, value: prompt, 'aria-label': t('tidyCopy'),
1012
- onFocus: (event) => event.target.select() })) : null,
1013
- !filtering && unchecked !== undefined ? h('p', { className: 'eng-note' }, t(unchecked)) : null,
1014
- notes.length > 0 || archive !== null ? h('div', { className: 'eng-list' },
1015
- notes.length > 0 ? h('ul', { className: 'eng-rows' }, notes.map((note) => row(note.name, note))) : null,
1016
- archive) : null,
1017
- filtering && notes.length === 0 && archived.length === 0
1018
- ? h('p', { className: 'eng-filter-none' }, t('filterNone')) : null,
1019
- store.more ? h('p', { className: 'eng-note' }, t('more')) : null)
1020
- }
1021
-
1022
- /** A store with anything in it: an index with text, a note, an archived note. A folder or an
1023
- * empty index alone is not memory yet. */
1024
- const hasMemory = (store) => (store.index !== null && store.index.bytes > 0) ||
1025
- store.notes.length > 0 || store.archive.length > 0
1026
-
1027
- /** A store not read to its end: a listing cut short, or a file or folder it could not read. */
1028
- const readInPart = (store) => store.more === true ||
1029
- (store.health?.checked === false && store.health.reason === 'unreadable')
1030
-
1031
- /** How to use it, in a few lines: open while there is no memory yet, folded once there is. */
1032
- function HowTo({ open, t }) {
1033
- return h('details', { className: 'eng-howto', open },
1034
- h('summary', null, icon('book', 15), t('howTo')),
1035
- h('ul', null, HOW_TO.map((key) => h('li', { key }, t(key)))))
1036
- }
1037
-
1038
- /** The OS family for a bug report, and nothing that tells one machine from another. */
1039
- function osName() {
1040
- const platform = String(globalThis.navigator?.userAgentData?.platform ?? globalThis.navigator?.platform ?? '')
1041
- return /^win/i.test(platform) ? 'Windows' : /^mac/i.test(platform) ? 'macOS'
1042
- : /linux/i.test(platform) ? 'Linux' : 'unknown'
1043
- }
1044
-
1045
- /**
1046
- * Where to report a problem or send an idea: a new issue, its body started with the
1047
- * plugin's version and the OS (no path, no note), or the mailbox, whose address the
1048
- * button copies — the desktop app opens only web links, not `mailto:`.
1049
- */
1050
- function Feedback({ t }) {
1051
- const [copy, setCopy] = useState('copy')
1052
- const alive = useRef(true)
1053
- useEffect(() => () => { alive.current = false }, [])
1054
- const copyAddress = async () => {
1055
- const done = await copyText(EMAIL)
1056
- if (alive.current) setCopy(done ? 'copied' : 'copyFailed')
1057
- }
1058
- const href = `${ISSUES}?body=${encodeURIComponent(t('issueBody', { version: VERSION, os: osName() }))}`
1059
- return h('footer', { className: 'eng-feedback' },
1060
- h('p', null,
1061
- icon('issue', 14),
1062
- t('feedbackLead'),
1063
- h('a', { className: 'eng-link', href, target: '_blank', rel: 'noopener noreferrer' }, t('feedbackIssue')),
1064
- t('feedbackMail'),
1065
- h('span', { className: 'eng-email' }, EMAIL),
1066
- h('button', { type: 'button', className: 'eng-btn eng-btn-small', onClick: copyAddress },
1067
- t(copy === 'copied' ? 'copied' : 'copy'))),
1068
- copy === 'copyFailed' ? h('p', { className: 'eng-feedback-note', role: 'status' }, t('copyFailed')) : null,
1069
- h('p', { className: 'eng-feedback-note' }, t('feedbackNote', { version: VERSION })))
1070
- }
1071
-
1072
- /**
1073
- * The sidebar's Memory page: a banner with the listing's numbers and two settings, then the
1074
- * stores recall can use, their notes a row each, by type and by name as the user filters.
1075
- */
1076
- function MemoryPage({ t }) {
1077
- const { state, load } = useMemory()
1078
- const [status, setStatus] = useState(undefined)
1079
- const [query, setQuery] = useState('')
1080
- const [kind, setKind] = useState(undefined)
1081
- const alive = useRef(true)
1082
- useEffect(() => () => { alive.current = false }, [])
1083
-
1084
- const open = async (store, file, archive) => {
1085
- setStatus(undefined)
1086
- let reply
1087
- try {
1088
- const response = await request(MEMORY_API, {
1089
- method: 'POST',
1090
- headers: { 'content-type': 'application/json' },
1091
- body: JSON.stringify({ store: store.id, ...(file === undefined ? {} : { file }), ...(archive ? { archive: true } : {}) }),
1092
- })
1093
- reply = response.body ?? { ok: false, error: 'failed', message: `HTTP ${response.status}` }
1094
- } catch (error) {
1095
- reply = { ok: false, error: 'failed', message: String(error?.message ?? error) }
1096
- }
1097
- if (!alive.current) return
1098
- setStatus(reply.ok ? { tone: 'ok', text: t('opened', { name: file === undefined ? store.dir : nameOf(file) }) }
1099
- : Object.hasOwn(OPEN_FAILURES, reply.error) ? { tone: 'error', text: t(OPEN_FAILURES[reply.error]) }
1100
- : { tone: 'error', text: t('openFailed', { reason: reply.message ?? reply.error ?? '' }) })
1101
- }
1102
-
1103
- const data = state.phase === 'ready' ? state.data : undefined
1104
- const canOpen = data?.canOpen === true
1105
- // a type a refresh left with nothing is no longer a filter, nor one again when it returns
1106
- const present = data === undefined || kind === undefined ||
1107
- data.stores.some((store) => store.notes.some((note) => note.type === kind))
1108
- useEffect(() => { if (!present) setKind(undefined) }, [present])
1109
- // a name filter over what was listed: case- and width-insensitive, the .md left out
1110
- const needle = query.trim().normalize('NFKC').toLowerCase()
1111
- const match = needle === '' ? undefined
1112
- : (file) => nameOf(file).normalize('NFKC').toLowerCase().includes(needle)
1113
- let body
1114
- if (state.phase === 'loading') body = h('p', { className: 'eng-note' }, t('listing'))
1115
- else if (state.phase === 'error') body = h('div', { className: 'eng-banner', 'data-tone': 'error' }, t(state.reason))
1116
- else {
1117
- const notes = data.stores.flatMap((store) => store.notes)
1118
- const archived = data.stores.reduce((sum, store) => sum + store.archive.length, 0)
1119
- const counts = TYPES.map((type) => [type, notes.filter((note) => note.type === type).length])
1120
- .filter(([, count]) => count > 0)
1121
- const shown = present ? kind : undefined
1122
- const tab = (type, label, count) => h('button', { type: 'button', className: 'eng-tab', key: type ?? 'all',
1123
- 'data-type': type ?? 'all', 'aria-pressed': shown === type, onClick: () => setKind(type) },
1124
- label, h('span', { className: 'eng-tab-count' }, String(count)))
1125
- const matched = match === undefined ? 0 : data.stores.reduce((sum, store) => sum +
1126
- store.notes.filter((note) => (shown === undefined || note.type === shown) && match(note.name)).length +
1127
- (shown === undefined ? store.archive.filter(match).length : 0), 0)
1128
- body = [
1129
- data.pinned === 'relative' ? h('p', { className: 'eng-note', key: 'pinned' }, t('pinnedRelative')) : null,
1130
- data.stores.length === 0 && data.pinned === undefined && !(data.unreadable > 0) && data.more !== true
1131
- ? h('p', { className: 'eng-note', key: 'empty' }, t('empty')) : null,
1132
- notes.length + archived > 0 ? h('div', { className: 'eng-toolbar', key: 'toolbar' },
1133
- h('div', { className: 'eng-tabs', role: 'group', 'aria-label': t('typeLabel') },
1134
- tab(undefined, t('typeAll'), notes.length),
1135
- ...counts.map(([type, count]) => tab(type, t(typeKey(type)), count))),
1136
- h('label', { className: 'eng-search' },
1137
- icon('search', 15),
1138
- h('input', { type: 'search', className: 'eng-input', value: query, placeholder: t('filterPlaceholder'),
1139
- 'aria-label': t('filterLabel'), onChange: (event) => setQuery(event.target.value) }))) : null,
1140
- match === undefined ? null : h('p', { className: 'eng-filter-count', key: 'count', role: 'status',
1141
- 'aria-live': 'polite' }, t('filterCount', { count: matched })),
1142
- ...data.stores.map((store) => h(StoreSection, { key: store.id, store, cap: data.cap, canOpen, open, match,
1143
- kind: shown, now: state.at, t })),
1144
- data.more ? h('p', { className: 'eng-note', key: 'more' }, t('more')) : null,
1145
- ]
1146
- }
1147
- return h('div', { className: 'eng-memory' },
1148
- h(Hero, { data, at: state.at, refresh: () => { setStatus(undefined); load() }, t }),
1149
- data === undefined ? null : h(Caveats, { data, t }),
1150
- status ? h('div', { className: 'eng-banner', 'data-tone': status.tone, role: 'status' }, status.text) : null,
1151
- data !== undefined && !canOpen && data.stores.length > 0 ? h('p', { className: 'eng-note' }, t('openUnavailable')) : null,
1152
- body,
1153
- h(HowTo, { open: data !== undefined && data.pinned !== 'relative' && data.more !== true &&
1154
- !(data.unreadable > 0) && !data.stores.some((store) => hasMemory(store) || readInPart(store)), t }),
1155
- h(Feedback, { t }))
1156
- }
1157
-
1158
- /** The sidebar entry's icon: the logo, [[ ]] around a cursor, drawn in the row's own colour
1159
- * (so it follows dsh's light and dark themes) at the size it asks for. */
1160
- function MemoryIcon({ size }) {
1161
- return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
1162
- strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
1163
- h('path', { d: 'M5.1 3.5H2.5v17h2.6M9.2 3.5H6.6v17h2.6' }),
1164
- h('path', { d: 'M18.9 3.5h2.6v17h-2.6M14.8 3.5h2.6v17h-2.6' }),
1165
- h('rect', { x: 10.4, y: 7, width: 3.2, height: 10, rx: 1, fill: 'currentColor', stroke: 'none' }))
1166
- }
1167
-
1168
- return {
1169
- inject: ['slots', 'locale'],
1170
- apply(ctx) {
1171
- ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-engramory: dictionaries')
1172
- ctx.effect(() => {
1173
- const tag = document.createElement('style')
1174
- tag.dataset.plugin = 'dsh-engramory'
1175
- tag.dataset.pluginCss = 'dsh-engramory/settings.css'
1176
- tag.textContent = CSS
1177
- document.head.appendChild(tag)
1178
- return () => tag.remove()
1179
- }, 'dsh-engramory: styles')
1180
- ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1181
- name: 'plugins.bundle.config',
1182
- key: PACKAGE,
1183
- locale: NS,
1184
- }, SettingsPage))
1185
- const t = ctx.locale.bind(NS)
1186
- ctx.slots.inject('main', () => ctx.slots.register({
1187
- name: 'main',
1188
- key: PANEL,
1189
- locale: NS,
1190
- }, MemoryPage))
1191
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1192
- name: 'sidebar.panellist',
1193
- id: PANEL,
1194
- // after dsh's own entries (Plugins 0, Automations 10)
1195
- order: 20,
1196
- locale: NS,
1197
- label: () => t('panel'),
1198
- }, MemoryIcon))
1199
- },
1200
- }
1201
- },
1202
- })
1
+ /**
2
+ * dsh-engramory, browser half: the settings on the package's own page in the Plugins page,
3
+ * and the sidebar's Memory entry — a page listing the memory stores by name, with the two
4
+ * settings that matter most at its top. The settings go through the route index.js
5
+ * registers for them (the memory's language follows dsh's); the page lists the stores and
6
+ * opens a note in the desktop's own app through the memory route, so no note's text is
7
+ * ever read into the page.
8
+ *
9
+ * Plain script, no build step, like index.js: React comes from the page's module table,
10
+ * no Harness client package is loaded as a module (dsh's guidance — they change without
11
+ * notice), and the colours are the host's theme tokens, so light, dark and third-party themes
12
+ * follow — but for the memory page's banner, in the project's own navy and mint on any theme,
13
+ * that mint again in an index's fill bar and a clean check-up's tick, and the note types'
14
+ * marks, each a muted colour of its own leaned toward the theme's text.
15
+ * Visible text goes through the locale service.
16
+ */
17
+ window.__ModuleLoader__.load({
18
+ id: 'dsh-engramory',
19
+ factory(require) {
20
+ const React = require('react')
21
+ const h = React.createElement
22
+ const { useCallback, useEffect, useRef, useState } = React
23
+
24
+ const NS = 'engramory'
25
+ /** The Plugins page keys a package's own settings by its package name. */
26
+ const PACKAGE = 'dsh-engramory'
27
+ /** The sidebar entry and the main-column page it opens share this id. */
28
+ const PANEL = 'engramory'
29
+ /** Relative to the page, as dsh's own pages fetch, so a mounted deployment keeps its prefix. */
30
+ const SETTINGS_API = 'api/engramory/settings'
31
+ const MEMORY_API = 'api/engramory/memory'
32
+ /** This plugin's version, for the feedback footer; a test keeps it equal to package.json's. */
33
+ const VERSION = '1.4.0'
34
+ /** Where feedback goes: a new issue on the repository, or the project's mailbox. Opening
35
+ * the link is the browser's (the desktop app hands it to the system's); the footer submits
36
+ * nothing by itself. */
37
+ const ISSUES = 'https://github.com/tinqiao-oss/engramory/issues/new'
38
+ const EMAIL = 'engramory@agent.qq.com'
39
+ /** Where "Check for updates" asks for the latest version, in turn: npm's own registry, then
40
+ * npmmirror, its mirror in China, for when npm cannot be reached. Asked on that click only. */
41
+ const REGISTRIES = [['npm', 'https://registry.npmjs.org'], ['npmmirror', 'https://registry.npmmirror.com']]
42
+ /** Where to look when neither answers, and what a newer version changed. */
43
+ const NPM_PAGE = 'https://www.npmjs.com/package/dsh-engramory?activeTab=versions'
44
+ const RELEASE = 'https://github.com/tinqiao-oss/engramory/releases/tag/v'
45
+ /** A version as SemVer writes one: three numbers without leading zeros, then maybe a prerelease
46
+ * tag and build metadata, each in dot-separated identifiers (a numeric one without leading zeros). */
47
+ const SEMVER = /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
48
+ /** The how-to's lines, in order. */
49
+ const HOW_TO = ['howToSay', 'howToRecall', 'howToEdit', 'howToMove', 'howToSocial']
50
+ /** A note past this is almost always a timeline under one slug (SKILL.md: "A note has a size
51
+ * too"); the doctor warns at the same size (ENGRAMORY_NOTE_WARN_BYTES). */
52
+ const LARGE_NOTE = 12 * 1024
53
+ /** An `upcoming` note named with its date: `2026-10-31-interview`, `2026-10-31面试` (SKILL.md §2.2). */
54
+ const DATED = /^(\d{4})-(\d{2})-(\d{2})(?!\d)/
55
+ const DEFAULT_LINES = 200
56
+ const DEFAULT_BYTES = 25600
57
+ /** The order the memory page shows note types in (SKILL.md §2, §2.2). */
58
+ const TYPES = ['user', 'feedback', 'project', 'reference', 'moment', 'upcoming', 'self', 'other']
59
+
60
+ const zh = {
61
+ summary: '大肥鱼模式和记忆权限、索引上限。',
62
+ loading: '正在读取设置…',
63
+ loadFailed: '读不到设置。',
64
+ retry: '重试',
65
+ unavailable: '这个 dsh 不能在页面里保存这些设置(没有配置编辑服务)。请改配置文件 cordis.patch.yml,写法见插件说明。',
66
+ expression: '配置文件里有设置是用 !!js 表达式写的,这里显示不了它的实际值,所以只读。请直接改 cordis.patch.yml。',
67
+ companion: '大肥鱼模式',
68
+ companionHint: '多记三类:经历、约定、我自己,用角色口吻回忆。',
69
+ audience: '记忆权限',
70
+ audiencePrivate: '专属',
71
+ audienceSocial: '社交',
72
+ audiencePrivateHint: '只有你用这个 dsh:每个对话都能用记忆。',
73
+ audienceSocialHint: '别人也能跟你的 AI 聊(接了 QQ、微信等):只有你本人聊、没有别人插过话的对话能用记忆。',
74
+ cap: '索引上限',
75
+ capHint: '默认 200 行 / 25600 字节,超过后 AI 要先压缩才能再写。',
76
+ capLines: '行',
77
+ capBytes: '字节',
78
+ save: '保存',
79
+ saving: '保存中…',
80
+ discard: '放弃修改',
81
+ reloading: '已保存,插件正在用新设置重新加载…',
82
+ saved: '已保存。',
83
+ savedUnconfirmed: '已保存,但重新读到的设置和刚才填的不一样(或者插件还没加载好)。请刷新页面看看。',
84
+ stale: '设置在别处被改过,已重新读取。请再改一次。',
85
+ overridden: '更高一层的配置覆盖了这些值,这里保存不了。',
86
+ invalid: '有一项填得不对:',
87
+ failed: '保存失败:',
88
+ panel: '记忆',
89
+ panelTitle: 'Engramory 记忆',
90
+ refresh: '刷新',
91
+ stripNote: '说明和索引上限在「插件 → Engramory 记忆」。',
92
+ stripReadOnly: '这里改不了,见「插件 → Engramory 记忆」。',
93
+ listing: '正在读取记忆…',
94
+ listFailed: '读不到记忆库。',
95
+ listTimeout: '读取超时了,可能有工作区在连不上的网络盘上。稍后点刷新再试。',
96
+ empty: '还没有记忆。AI 第一次存记忆时会自动建好记忆库。',
97
+ pinnedRelative: '配置里固定的索引(indexPath)是相对路径,跟着每个会话的目录走,这里列不出来。改成绝对路径就能在这里看到。',
98
+ storeUser: '全局记忆',
99
+ storePinned: '固定的记忆库',
100
+ usage: '索引 {lines} / {maxLines} 行 · {size} / {maxSize}',
101
+ usageOver: '索引 {size} / {maxSize},超出上限',
102
+ usageSize: '索引 {size} / {maxSize}',
103
+ sizeBytes: '{n} B',
104
+ sizeKB: '{n} KB',
105
+ overHint: '超出上限了,AI 只读得到前面一部分,该压缩了。',
106
+ noIndex: '还没有索引',
107
+ openIndex: '打开索引',
108
+ openFolder: '打开文件夹',
109
+ opened: '已打开 {name}。',
110
+ revealed: '已在文件夹里显示 {name}。',
111
+ openUnavailable: '这台 dsh 不能在本机打开文件(比如远程访问时)。文件在上面写的位置。',
112
+ openMissing: '找不到这个文件了,可能刚被改名或删掉。点刷新看看。',
113
+ openBusy: '还在打开上一个,稍等一下再点。',
114
+ openFailed: '打不开:{reason}',
115
+ typeUser: '用户',
116
+ typeFeedback: '反馈',
117
+ typeProject: '项目',
118
+ typeReference: '参考',
119
+ typeMoment: '经历',
120
+ typeUpcoming: '约定',
121
+ typeSelf: '我自己',
122
+ typeOther: '其他',
123
+ archive: '归档 {count} 份',
124
+ more: '文件太多,这里只列出了一部分。',
125
+ healthOk: '体检:没发现问题。',
126
+ healthBroken: '索引里指向不存在的文件({count})',
127
+ healthBrokenMore: '索引里指向不存在的文件({count} 个以上)',
128
+ healthBrokenUnlisted: '索引里有指向不存在的文件,太多了,这里没列出。',
129
+ healthUnindexed: '不在索引里({count}):AI 回忆从索引开始,这些它通常找不到,除非别的笔记链到它们。',
130
+ healthUntyped: '没写类型或类型不认识({count}),列在「其他」里。',
131
+ healthFix: '完整检查可以用 engramory_doctor.py。',
132
+ healthLarge: '要核对的太多,没做体检。',
133
+ healthUnreadable: '有文件读不了,没做体检。',
134
+ healthPartial: '文件太多没列全,没做体检。',
135
+ howTo: '怎么用',
136
+ howToSay: '想让 AI 记住什么,直接跟它说,比如「记住:我习惯用 pnpm」「把这个决定记下来」。平时它也会尽量自己挑值得长期记住的记下来,比如你纠正过它的做法。',
137
+ howToRecall: '默认每次对话都会带上记忆的目录(索引),AI 用到细节时再打开那条笔记,不用你提醒。',
138
+ howToEdit: '这里列出读得到的记忆,打开笔记就能直接改;想让 AI 忘掉什么,跟它说「忘掉……」就行。',
139
+ howToMove: '记忆是存在运行 dsh 那台电脑上的普通 markdown 文件,位置写在每个库的标题下面。换电脑时把那个文件夹拷到新电脑的同一位置;在配置里指定过位置的,配置也一起带过去。',
140
+ howToSocial: '接了 QQ、微信等、别人也能跟你的 AI 聊的话,在上面打开「大肥鱼模式」,再把「记忆权限」改成「社交」:只有认得出是你本人的对话才拿得到记忆。这不是安全隔离,详见插件说明。',
141
+ feedbackLead: '遇到问题或有建议:',
142
+ feedbackIssue: '到 GitHub 提 issue',
143
+ feedbackMail: ',或发邮件到',
144
+ copy: '复制',
145
+ copied: '已复制',
146
+ copyFailed: '复制不了,请手动选中上面的地址。',
147
+ feedbackNote: '邮件会由 AI 助手协助整理,issue 是公开的,两处都别把记忆内容原样贴上去。',
148
+ versionLine: '插件版本 {version}',
149
+ checkUpdate: '检查更新',
150
+ checking: '正在检查…',
151
+ updateNewer: '有新版本 {latest}(你装的是 {current})',
152
+ updateNotes: '看这一版改了什么',
153
+ updateHow: '升级时要写上版本号(只写名字的话,pnpm 默认不装发布不满 24 小时的版本):',
154
+ updateDesktop: '桌面版:在「插件」页卸载「Engramory 记忆」,再搜索安装',
155
+ updateCli: '命令行:',
156
+ updateProfile: '<名字>',
157
+ updateAfter: '装完重启 dsh(桌面版从托盘退出再打开)。记忆和设置都会保留。',
158
+ updateCurrent: '已是最新版本:{source} 上最新的就是 {latest}。',
159
+ updateAhead: '你装的 {current} 比 {source} 上最新的 {latest} 还新。',
160
+ updateMirror: 'npm 没有给出版本号,这是镜像 npmmirror 的结果,它有时比 npm 晚几分钟同步。',
161
+ updateFailed: '查不到最新版本:npm 和 npmmirror 都没有给出版本号。可以到网页上看:',
162
+ updateNpm: 'npm 上的版本列表',
163
+ copySpecFailed: '复制不了,请手动选中上面的版本号。',
164
+ updateNote: '检查更新会向 npm(连不上再试 npmmirror)查最新版本号,请求里不带任何记忆内容;不点就不联网。',
165
+ issueBody: '(写下遇到的问题或建议)\n\n---\ndsh-engramory {version}\n打开这个页面的电脑:{os}\ndsh 版本:',
166
+ statNote: '条记忆',
167
+ statNotes: '条记忆',
168
+ statStore: '个记忆库',
169
+ statStores: '个记忆库',
170
+ statArchive: '份归档',
171
+ statsReadAt: '读取于 {time},约定的天数按这时算',
172
+ statsPartial: '列表太长,只列出了一部分,这些数字偏少。',
173
+ statsUnreadable: '有 {count} 处可能存放记忆库的位置没读到(读不了或查不了),没算在内。',
174
+ statsIncomplete: '有的库里有文件读不了,这些数字可能偏少。',
175
+ typeAll: '全部',
176
+ typeLabel: '按类型筛选',
177
+ storeCount: '{count} 条',
178
+ storeCountOne: '{count} 条',
179
+ noteMeta: '{type} · {size}',
180
+ noteUnread: '读不了',
181
+ archived: '已归档',
182
+ monthDay: '{m}月{d}日',
183
+ yearMonthDay: '{y}年{m}月{d}日',
184
+ badgePast: '{date} · 日期已过,待确认',
185
+ badgeToday: '就是今天',
186
+ badgeTomorrow: '{date} · 明天',
187
+ badgeSoon: '{date} · 还有 {days} 天',
188
+ badgeUndated: '未定日期',
189
+ badgeLarge: '偏大,建议拆分',
190
+ badgeUnindexed: '不在索引里',
191
+ attnTitle: '可以整理一下',
192
+ attnLarge: '超过 12 KB 的笔记 {count} 篇:一条笔记该只记一件事,可以让 AI 拆成几篇。',
193
+ filterLabel: '筛选笔记',
194
+ filterPlaceholder: '按名字筛选',
195
+ filterCount: '匹配 {count} 条(只在已列出的笔记里找)',
196
+ filterNone: '这个库里没有匹配的笔记。',
197
+ tidyCopy: '复制整理指令',
198
+ tidyCopied: '已复制,粘贴进对话发给 AI',
199
+ tidyFailed: '复制不了,请手动选中下面的指令:',
200
+ tidyPrompt: '请按 Engramory 的记忆规则整理这个记忆库:{dir}\n- 索引里指向不存在文件的链接:找得到对应笔记的就改对,确实没有了的只删这个链接;一行里没有别的有效链接了,才删掉整行。\n- 不在索引里的笔记:以后回忆用得上的补进索引,过时的移进 archive/ 或删掉;不要为了补齐全部加进去。\n- 没写类型的笔记补上 type。\n- 索引超出上限就先压缩:合并重复,细节挪回笔记,索引只留指针。\n- 超过约 12 KB 的笔记,按规则拆成几篇。\n- 日期已过的约定别删,问到结果再改写成经历。\n改完再看一遍索引有没有超出上限,然后告诉我改了什么。',
201
+ }
202
+ const en = {
203
+ summary: 'Companion mode and memory access, and the index cap.',
204
+ loading: 'Reading the settings…',
205
+ loadFailed: 'Could not read the settings.',
206
+ retry: 'Retry',
207
+ unavailable: 'This dsh cannot save these settings from a page (it has no config editor). Edit cordis.patch.yml instead; the plugin README shows how.',
208
+ expression: 'A setting in the config is written as a !!js expression, whose value this page cannot show, so it is read-only. Edit cordis.patch.yml directly.',
209
+ companion: 'Companion mode (大肥鱼模式)',
210
+ companionHint: 'Keeps three more kinds of note — moments, plans, the character itself — and recalls in character.',
211
+ audience: 'Memory access',
212
+ audiencePrivate: 'Private',
213
+ audienceSocial: 'Social',
214
+ audiencePrivateHint: 'Only you use this dsh: every conversation gets the memory.',
215
+ audienceSocialHint: 'Others can talk to your AI too (through QQ, WeChat…): only conversations you alone have written in get the memory.',
216
+ cap: 'Index cap',
217
+ capHint: 'Default 200 lines / 25600 bytes; past it the AI must compact before writing more.',
218
+ capLines: 'lines',
219
+ capBytes: 'bytes',
220
+ save: 'Save',
221
+ saving: 'Saving…',
222
+ discard: 'Discard changes',
223
+ reloading: 'Saved; the plugin is reloading with the new settings…',
224
+ saved: 'Saved.',
225
+ savedUnconfirmed: 'Saved, but the settings read back differ from what you entered (or the plugin has not finished loading). Reload the page to check.',
226
+ stale: 'The settings changed elsewhere and were read again. Make your change once more.',
227
+ overridden: 'A higher configuration layer overrides these values, so they cannot be saved here.',
228
+ invalid: 'One field is not acceptable: ',
229
+ failed: 'Saving failed: ',
230
+ panel: 'Memory',
231
+ panelTitle: 'Engramory memory',
232
+ refresh: 'Refresh',
233
+ stripNote: 'Explanations and the index cap: Plugins → Engramory memory.',
234
+ stripReadOnly: 'Cannot be changed here; see Plugins → Engramory memory.',
235
+ listing: 'Reading the memory…',
236
+ listFailed: 'Could not read the memory stores.',
237
+ listTimeout: 'Reading took too long — a workspace may be on a network drive that does not answer. Refresh to try again.',
238
+ empty: 'No memory yet. The store is created the first time the AI saves something.',
239
+ pinnedRelative: 'The pinned index (indexPath) is a relative path, which follows each conversation\'s directory, so it cannot be listed here. Pin an absolute path to see it here.',
240
+ storeUser: 'Global memory',
241
+ storePinned: 'Pinned store',
242
+ usage: 'Index {lines} / {maxLines} lines · {size} / {maxSize}',
243
+ usageOver: 'Index {size} / {maxSize}, over the cap',
244
+ usageSize: 'Index {size} / {maxSize}',
245
+ sizeBytes: '{n} B',
246
+ sizeKB: '{n} KB',
247
+ overHint: 'Over the cap: the AI reads only the first part. Time to compact it.',
248
+ noIndex: 'No index yet',
249
+ openIndex: 'Open the index',
250
+ openFolder: 'Open the folder',
251
+ opened: 'Opened {name}.',
252
+ revealed: 'Showed {name} in its folder.',
253
+ openUnavailable: 'This dsh cannot open files on its own computer (when reached remotely, say). The files are where the path above says.',
254
+ openMissing: 'That file is gone — renamed or deleted just now, perhaps. Refresh to see.',
255
+ openBusy: 'Still opening the previous one — click again in a moment.',
256
+ openFailed: 'Could not open it: {reason}',
257
+ typeUser: 'User',
258
+ typeFeedback: 'Feedback',
259
+ typeProject: 'Project',
260
+ typeReference: 'Reference',
261
+ typeMoment: 'Moments',
262
+ typeUpcoming: 'Coming up',
263
+ typeSelf: 'Myself',
264
+ typeOther: 'Other',
265
+ archive: 'Archive ({count})',
266
+ more: 'Too many files: only some are listed here.',
267
+ healthOk: 'Check-up: nothing to fix.',
268
+ healthBroken: 'The index points to files that are not there ({count})',
269
+ healthBrokenMore: 'The index points to files that are not there (over {count})',
270
+ healthBrokenUnlisted: 'The index points to files that are not there: too many to list here.',
271
+ healthUnindexed: 'Not in the index ({count}): recall starts from the index, so the AI will not find these unless another note links to them.',
272
+ healthUntyped: 'No type, or one it does not know ({count}), listed under Other.',
273
+ healthFix: 'For a full check, run engramory_doctor.py.',
274
+ healthLarge: 'Too much to check here, so no check-up.',
275
+ healthUnreadable: 'Some files could not be read, so no check-up.',
276
+ healthPartial: 'Too many files to list them all, so no check-up here.',
277
+ howTo: 'How to use it',
278
+ howToSay: 'To have the AI remember something, just tell it: "remember that I use pnpm", "note this decision down". It also tries to keep what is worth keeping on its own, such as a way of working you corrected.',
279
+ howToRecall: 'By default every conversation carries the memory\'s table of contents (the index), and the AI opens a note when it needs the details; you do not have to remind it.',
280
+ howToEdit: 'The memory this page can read is listed here; open a note to edit it. To have the AI forget something, tell it "forget …".',
281
+ howToMove: 'The memory is plain markdown files on the computer dsh runs on, in the folder shown under each store\'s title. On a new computer, copy that folder to the same place, and if your configuration names where the store is, bring that setting along.',
282
+ howToSocial: 'If others can talk to your AI too (through QQ, WeChat and the like), turn on Companion mode above and set Memory access to Social: only conversations it can tell are yours get the memory. This is not a security boundary; see the plugin\'s README.',
283
+ feedbackLead: 'Found a problem or have an idea? ',
284
+ feedbackIssue: 'Open an issue on GitHub',
285
+ feedbackMail: ', or email ',
286
+ copy: 'Copy',
287
+ copied: 'Copied',
288
+ copyFailed: 'Could not copy; select the address above by hand.',
289
+ feedbackNote: 'Emails are sorted with the help of an AI assistant, and issues are public: do not paste your memory notes into either.',
290
+ versionLine: 'Plugin version {version}',
291
+ checkUpdate: 'Check for updates',
292
+ checking: 'Checking…',
293
+ updateNewer: 'Version {latest} is out (you have {current})',
294
+ updateNotes: 'What changed',
295
+ updateHow: 'Name the version when you upgrade: by name alone, pnpm by default does not install a version published less than 24 hours ago.',
296
+ updateDesktop: 'Desktop app: on the Plugins page, uninstall Engramory memory, then search for and install',
297
+ updateCli: 'Command line: ',
298
+ updateProfile: '<name>',
299
+ updateAfter: 'Then restart dsh (in the desktop app, quit from the tray and open it again). Your memory and settings stay.',
300
+ updateCurrent: 'You have the latest version: the latest on {source} is {latest}.',
301
+ updateAhead: 'The {current} you have is newer than the latest on {source}, {latest}.',
302
+ updateMirror: 'npm gave no version, so this is from its mirror npmmirror, which can be a few minutes behind npm.',
303
+ updateFailed: 'Could not find the latest version: neither npm nor npmmirror gave one. The versions are listed on npm\'s site: ',
304
+ updateNpm: 'dsh-engramory on npm',
305
+ copySpecFailed: 'Could not copy; select the version above by hand.',
306
+ updateNote: 'Checking asks npm (or npmmirror, when npm cannot be reached) for the latest version number; nothing from your memory goes with it. Nothing is asked until you click.',
307
+ issueBody: '(What happened, or your idea)\n\n---\ndsh-engramory {version}\nComputer this page was opened on: {os}\ndsh version: ',
308
+ statNote: 'note',
309
+ statNotes: 'notes',
310
+ statStore: 'store',
311
+ statStores: 'stores',
312
+ statArchive: 'archived',
313
+ statsReadAt: 'Read at {time}; days to a plan count from then',
314
+ statsPartial: 'The listing was too long to finish, so these numbers fall short.',
315
+ statsUnreadable: '{count} places that may hold a memory store could not be read and are not counted.',
316
+ statsIncomplete: 'Some files in a store could not be read, so these numbers may fall short.',
317
+ typeAll: 'All',
318
+ typeLabel: 'Filter by type',
319
+ storeCount: '{count} notes',
320
+ storeCountOne: '{count} note',
321
+ noteMeta: '{type} · {size}',
322
+ noteUnread: 'Could not be read',
323
+ archived: 'Archived',
324
+ monthDay: '{m}/{d}',
325
+ yearMonthDay: '{y}/{m}/{d}',
326
+ badgePast: '{date} · passed, outcome to confirm',
327
+ badgeToday: 'Today',
328
+ badgeTomorrow: '{date} · tomorrow',
329
+ badgeSoon: '{date} · in {days} days',
330
+ badgeUndated: 'No date yet',
331
+ badgeLarge: 'Large: worth splitting',
332
+ badgeUnindexed: 'Not in the index',
333
+ attnTitle: 'Worth tidying up',
334
+ attnLarge: 'Notes past 12 KB: {count}. A note should hold one fact, and the AI can split these.',
335
+ filterLabel: 'Filter notes',
336
+ filterPlaceholder: 'Filter by name',
337
+ filterCount: '{count} matching (among the notes listed)',
338
+ filterNone: 'No matching notes in this store.',
339
+ tidyCopy: 'Copy tidy-up instructions',
340
+ tidyCopied: 'Copied; paste it into a conversation',
341
+ tidyFailed: 'Could not copy; select the instructions below by hand:',
342
+ tidyPrompt: 'Tidy up this memory store by the Engramory rules: {dir}\n- Links in the index to files that are not there: fix the ones whose note you can find; where there is none, remove that link alone, and the line only when it has no other live link left.\n- Notes the index does not name: add the ones recall will need, move the outdated ones into archive/ or delete them; do not add them all just to be complete.\n- Notes with no type: give them one.\n- An index over its cap: compact it first by merging duplicates and moving detail back into the notes, so the index holds pointers only.\n- Notes past about 12 KB: split them as the rules say.\n- Plans whose date has passed: do not delete them; rewrite them as what happened once you learn the outcome.\nThen check the index is within its cap, and tell me what you changed.',
343
+ }
344
+
345
+ const CSS = `
346
+ .eng-page{display:flex;flex-direction:column;gap:18px;font-size:13px;line-height:1.55;color:var(--dsw-alias-label-primary);max-width:760px;}
347
+ .eng-section{display:flex;flex-direction:column;gap:8px;}
348
+ .eng-title{font-size:14px;font-weight:600;margin:0;}
349
+ .eng-heading{display:flex;align-items:center;gap:10px;}
350
+ .eng-hint{margin:0;font-size:12px;color:var(--dsw-alias-label-secondary);}
351
+ .eng-note{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary);}
352
+ .eng-banner{padding:8px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);font-size:12px;}
353
+ .eng-banner[data-tone="error"]{color:var(--dsw-alias-state-error-primary);}
354
+ .eng-banner[data-tone="ok"]{color:var(--dsw-alias-state-success-primary);}
355
+ .eng-segment{display:inline-flex;gap:2px;padding:2px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-interactive-bg-hover);align-self:flex-start;}
356
+ .eng-segment button{border:0;background:transparent;color:var(--dsw-alias-label-secondary);border-radius:6px;padding:4px 12px;font:inherit;font-size:12px;cursor:pointer;}
357
+ .eng-segment button[aria-pressed="true"]{background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.12);}
358
+ .eng-segment button:disabled{cursor:default;}
359
+ .eng-switch{position:relative;width:32px;height:18px;border-radius:999px;border:0;padding:0;cursor:pointer;background:var(--dsw-alias-border-l2);flex:none;}
360
+ .eng-switch[aria-checked="true"]{background:var(--dsw-alias-brand-primary);}
361
+ .eng-switch:disabled{opacity:.5;cursor:default;}
362
+ .eng-switch::after{content:"";position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:var(--dsw-alias-switch-thumb,#fff);transition:transform .15s ease;}
363
+ .eng-switch[aria-checked="true"]::after{transform:translateX(14px);}
364
+ .eng-input{border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:inherit;padding:5px 9px;font:inherit;font-size:12px;outline:none;min-width:0;}
365
+ .eng-input:focus{border-color:var(--dsw-alias-brand-primary);}
366
+ .eng-input[aria-invalid="true"]{border-color:var(--dsw-alias-state-error-primary);}
367
+ .eng-cap{display:flex;gap:12px;align-items:center;flex-wrap:wrap;}
368
+ .eng-cap label{display:flex;align-items:center;gap:6px;color:var(--dsw-alias-label-secondary);font-size:12px;}
369
+ .eng-cap input{width:110px;}
370
+ .eng-btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);border-radius:8px;padding:5px 14px;font:inherit;font-size:12px;line-height:18px;cursor:pointer;white-space:nowrap;}
371
+ .eng-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);}
372
+ .eng-btn:disabled{opacity:.5;cursor:default;}
373
+ .eng-btn-primary{background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary));border-color:transparent;color:var(--dsw-alias-label-primary-foreground,#fff);}
374
+ .eng-btn-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-fill,var(--dsw-alias-brand-primary));opacity:.9;}
375
+ .eng-btn-ghost{border-color:transparent;background:transparent;color:var(--dsw-alias-label-secondary);padding:4px 8px;}
376
+ .eng-btn-small{padding:1px 8px;font-size:11.5px;}
377
+ .eng-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
378
+ .eng-memory{box-sizing:border-box;height:100%;overflow:auto;display:flex;flex-direction:column;align-items:center;gap:20px;padding:28px clamp(24px,4vw,48px) 48px;color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px;}
379
+ [data-platform=darwin] .eng-memory{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px));}
380
+ .eng-memory>*{box-sizing:border-box;width:100%;max-width:960px;flex:none;}
381
+ .eng-memory svg{display:block;flex:none;}
382
+ .eng-hero{display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:24px 40px;padding:30px 32px;border-radius:24px;color:#e8f3f0;background:radial-gradient(120% 140% at 100% 0%,#1f4a5a 0%,rgba(31,74,90,0) 55%),linear-gradient(135deg,#0f1b2d 0%,#14263f 100%);box-shadow:0 12px 32px rgba(15,27,45,.18);}
383
+ .eng-hero-main{display:flex;flex-direction:column;gap:24px;flex:1 1 340px;min-width:0;}
384
+ .eng-brand{display:flex;align-items:center;gap:14px;}
385
+ .eng-logo{border-radius:12px;box-shadow:0 0 0 1px rgba(110,231,200,.35);}
386
+ .eng-hero-title{margin:0;font-size:21px;font-weight:600;line-height:28px;letter-spacing:.01em;}
387
+ .eng-hero-version{margin-left:10px;font-family:var(--ds-font-family-code,ui-monospace,monospace);font-size:13px;font-weight:400;letter-spacing:0;color:rgba(232,243,240,.6);}
388
+ .eng-stats{display:flex;align-items:baseline;flex-wrap:wrap;gap:6px 0;}
389
+ .eng-stat{display:inline-flex;align-items:baseline;gap:6px;}
390
+ .eng-stat+.eng-stat{margin-left:18px;padding-left:18px;border-left:1px solid rgba(232,243,240,.18);}
391
+ .eng-stat b{font-size:40px;line-height:44px;font-weight:600;color:#6ee7c8;font-variant-numeric:tabular-nums;letter-spacing:-.02em;}
392
+ .eng-stat span{font-size:13px;color:rgba(232,243,240,.75);}
393
+ .eng-hero-foot{display:flex;align-items:center;flex-wrap:wrap;gap:8px 10px;}
394
+ .eng-hero-read{display:inline-flex;align-items:center;gap:6px;margin:0;padding:3px 10px;border-radius:999px;background:rgba(255,255,255,.06);font-size:12px;line-height:18px;color:rgba(232,243,240,.62);}
395
+ .eng-hero-side{display:flex;flex-direction:column;flex:0 1 300px;min-width:260px;}
396
+ .eng-hero .eng-strip{display:flex;flex-direction:column;gap:14px;padding:18px 20px;border-radius:18px;background:rgba(255,255,255,.06);box-shadow:inset 0 0 0 1px rgba(255,255,255,.08);}
397
+ .eng-hero .eng-strip-item{display:flex;align-items:center;justify-content:space-between;gap:20px;min-height:30px;font-size:13px;color:rgba(232,243,240,.8);}
398
+ .eng-hero .eng-strip-item:first-child{font-weight:600;color:#e8f3f0;}
399
+ .eng-hero .eng-strip-note{margin:0;font-size:11.5px;line-height:17px;color:rgba(232,243,240,.74);}
400
+ .eng-hero .eng-switch{width:46px;height:26px;background:rgba(255,255,255,.24);}
401
+ .eng-hero .eng-switch::after{top:3px;left:3px;width:20px;height:20px;}
402
+ .eng-hero .eng-switch[aria-checked="true"]::after{transform:translateX(20px);}
403
+ .eng-hero .eng-switch[aria-checked="true"]{background:#6ee7c8;}
404
+ .eng-hero .eng-switch[aria-checked="true"]::after{background:#0f1b2d;}
405
+ .eng-hero .eng-segment{border:0;border-radius:999px;background:rgba(0,0,0,.25);}
406
+ .eng-hero .eng-segment button{border-radius:999px;padding:3px 14px;font-size:12.5px;line-height:18px;color:rgba(232,243,240,.62);}
407
+ .eng-hero .eng-segment button[aria-pressed="true"]{background:#6ee7c8;color:#0f1b2d;box-shadow:none;}
408
+ .eng-hero .eng-btn,.eng-hero-btn{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border:1px solid rgba(232,243,240,.22);border-radius:999px;background:transparent;color:#e8f3f0;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap;}
409
+ .eng-hero .eng-btn:hover:not(:disabled),.eng-hero-btn:hover{background:rgba(255,255,255,.08);}
410
+ .eng-hero :focus-visible{outline:2px solid #6ee7c8;outline-offset:2px;}
411
+ .eng-caveat{display:flex;align-items:flex-start;gap:8px;margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
412
+ .eng-caveat svg{margin-top:2px;color:var(--dsw-alias-state-warn-label);}
413
+ .eng-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;margin-top:6px;}
414
+ .eng-tabs{display:flex;flex-wrap:wrap;gap:2px;flex:1 1 auto;min-width:0;}
415
+ .eng-tab{display:inline-flex;align-items:center;gap:5px;height:30px;padding:0 10px;border:0;border-radius:9px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;cursor:pointer;}
416
+ .eng-tab:hover{background:var(--dsw-alias-interactive-bg-hover);}
417
+ .eng-tab[aria-pressed="true"]{background:var(--dsw-alias-interactive-bg-active);color:var(--dsw-alias-label-primary);font-weight:500;}
418
+ .eng-tab-count{font-size:11.5px;font-weight:400;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;}
419
+ .eng-search{position:relative;display:flex;align-items:center;flex:0 1 240px;min-width:160px;color:var(--dsw-alias-label-caption);}
420
+ .eng-search svg{position:absolute;left:10px;pointer-events:none;}
421
+ .eng-search .eng-input{width:100%;height:34px;padding-left:32px;border-radius:10px;font-size:13px;}
422
+ .eng-filter-count,.eng-filter-none{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary);}
423
+ .eng-store{display:flex;flex-direction:column;gap:10px;margin-top:10px;}
424
+ .eng-store-head{display:flex;align-items:center;flex-wrap:wrap;gap:6px 10px;}
425
+ .eng-store-title{margin:0;font-size:15px;font-weight:600;line-height:22px;}
426
+ .eng-store-count{font-size:12px;color:var(--dsw-alias-label-tertiary);}
427
+ .eng-meter{display:inline-block;width:56px;height:4px;margin-left:4px;border-radius:999px;background:var(--dsw-alias-border-l2);overflow:hidden;}
428
+ .eng-meter-fill{display:block;height:100%;border-radius:999px;background:#2bb894;background:color-mix(in srgb,#2bb894 76%,var(--dsw-alias-label-primary));}
429
+ .eng-meter[data-over="true"] .eng-meter-fill{background:var(--dsw-alias-state-error-primary);}
430
+ .eng-usage{font-size:11.5px;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;}
431
+ .eng-usage[data-over="true"]{color:var(--dsw-alias-state-error-primary);}
432
+ .eng-store-actions{margin-left:auto;display:inline-flex;flex-wrap:wrap;gap:2px;}
433
+ .eng-path{margin:-8px 0 0;font-family:var(--ds-font-family-code,ui-monospace,monospace);font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;}
434
+ .eng-store-ok{display:flex;align-items:center;gap:6px;margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary);}
435
+ .eng-store-ok svg{color:#2bb894;color:color-mix(in srgb,#2bb894 76%,var(--dsw-alias-label-primary));}
436
+ .eng-attn{display:flex;align-items:flex-start;gap:10px;padding:10px 10px 10px 14px;border-radius:14px;background:var(--dsw-alias-state-warn-tertiary);background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 11%,transparent);}
437
+ .eng-attn>svg{margin-top:2px;color:var(--dsw-alias-state-warn-label);}
438
+ .eng-attn-body{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0;}
439
+ .eng-attn-title{margin:0;font-size:12.5px;font-weight:600;line-height:20px;color:var(--dsw-alias-state-warn-label);}
440
+ .eng-attn-item{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
441
+ .eng-broken{display:flex;flex-wrap:wrap;gap:4px;margin:4px 0 0;padding:0;list-style:none;}
442
+ .eng-broken code{padding:0 6px;border-radius:6px;background:var(--dsw-alias-interactive-bg-hover);font-family:var(--ds-font-family-code,ui-monospace,monospace);font-size:11px;line-height:18px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;}
443
+ .eng-attn>.eng-btn{flex:none;}
444
+ .eng-tidy{display:flex;flex-direction:column;gap:6px;}
445
+ .eng-tidy p{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
446
+ .eng-tidy textarea{box-sizing:border-box;width:100%;min-height:150px;resize:vertical;font:inherit;font-size:12px;line-height:18px;}
447
+ .eng-list{display:flex;flex-direction:column;padding:4px;border:.5px solid var(--dsw-alias-border-l3);border-radius:16px;}
448
+ .eng-rows{display:flex;flex-direction:column;margin:0;padding:0;list-style:none;}
449
+ .eng-row{box-sizing:border-box;display:flex;align-items:center;gap:12px;width:100%;min-height:52px;padding:6px 10px;border:0;border-radius:12px;background:transparent;color:inherit;font:inherit;text-align:left;}
450
+ button.eng-row{cursor:pointer;}
451
+ button.eng-row:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);}
452
+ .eng-row[data-type="user"]{--eng-type:#6f86c6;}
453
+ .eng-row[data-type="feedback"]{--eng-type:#b39a45;}
454
+ .eng-row[data-type="project"]{--eng-type:#4e9a78;}
455
+ .eng-row[data-type="reference"]{--eng-type:#8b78c4;}
456
+ .eng-row[data-type="moment"]{--eng-type:#c07193;}
457
+ .eng-row[data-type="upcoming"]{--eng-type:#c9735c;}
458
+ .eng-row[data-type="self"]{--eng-type:#3f9aa6;}
459
+ .eng-mark{display:grid;place-items:center;width:32px;height:32px;flex:none;border-radius:10px;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l4);color:var(--eng-type,var(--dsw-alias-label-tertiary));color:color-mix(in srgb,var(--eng-type,var(--dsw-alias-label-tertiary)) 80%,var(--dsw-alias-label-primary));}
460
+ .eng-row-text{display:flex;flex-direction:column;flex:1;min-width:0;}
461
+ .eng-name{font-size:13.5px;font-weight:500;line-height:19px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
462
+ .eng-row-meta{font-size:11.5px;line-height:16px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
463
+ .eng-badges{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:6px;max-width:55%;}
464
+ .eng-badge{padding:0 8px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary);font-size:11.5px;line-height:20px;white-space:nowrap;}
465
+ .eng-badge[data-tone="warn"]{background:var(--dsw-alias-state-warn-tertiary);background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 14%,transparent);color:var(--dsw-alias-state-warn-label);}
466
+ .eng-badge[data-tone="quiet"]{background:transparent;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3);color:var(--dsw-alias-label-tertiary);}
467
+ .eng-row-go{color:var(--dsw-alias-label-caption);}
468
+ .eng-archive{border-top:.5px dashed var(--dsw-alias-border-l2);margin-top:4px;padding-top:4px;}
469
+ .eng-list>.eng-archive:first-child{border-top:0;margin-top:0;padding-top:0;}
470
+ .eng-archive>summary{display:flex;align-items:center;gap:12px;min-height:44px;padding:4px 14px 4px 18px;border-radius:12px;cursor:pointer;font-size:12.5px;color:var(--dsw-alias-label-secondary);list-style:none;}
471
+ .eng-archive>summary::-webkit-details-marker{display:none;}
472
+ .eng-archive>summary::after,.eng-howto>summary::after{content:"";margin-left:auto;width:6px;height:6px;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:rotate(-45deg);opacity:.55;}
473
+ .eng-archive[open]>summary::after,.eng-howto[open]>summary::after{transform:rotate(45deg);}
474
+ .eng-archive>summary:hover{background:var(--dsw-alias-interactive-bg-hover);}
475
+ .eng-howto{box-sizing:border-box;padding:12px 14px;border:.5px solid var(--dsw-alias-border-l3);border-radius:14px;}
476
+ .eng-howto>summary{display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;font-weight:500;line-height:20px;list-style:none;}
477
+ .eng-howto>summary::-webkit-details-marker{display:none;}
478
+ .eng-howto ul{display:flex;flex-direction:column;gap:4px;margin:10px 0 2px;padding-left:18px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);}
479
+ .eng-feedback{display:flex;flex-direction:column;gap:2px;padding-top:14px;border-top:.5px solid var(--dsw-alias-border-l2);font-size:12px;line-height:22px;color:var(--dsw-alias-label-secondary);}
480
+ .eng-feedback p{display:flex;align-items:center;flex-wrap:wrap;margin:0;}
481
+ .eng-feedback p svg{margin-right:6px;color:var(--dsw-alias-label-tertiary);}
482
+ .eng-link{color:var(--dsw-alias-brand-primary);text-decoration:underline;text-underline-offset:2px;}
483
+ .eng-link:hover{opacity:.8;}
484
+ .eng-email{margin:0 8px 0 2px;font-family:var(--ds-font-family-code,ui-monospace,monospace);user-select:all;color:var(--dsw-alias-label-primary);}
485
+ .eng-feedback-note{color:var(--dsw-alias-label-tertiary);}
486
+ .eng-version,.eng-update{display:flex;flex-direction:column;gap:2px;}
487
+ .eng-update{margin:2px 0 6px;}
488
+ .eng-version>p>.eng-btn{margin-left:8px;}
489
+ .eng-update-new{margin-right:8px;font-weight:500;color:var(--dsw-alias-label-primary);}
490
+ .eng-update ul{margin:0;padding-left:18px;}
491
+ .eng-update li{margin:0;}
492
+ .eng-update li .eng-btn{margin-left:6px;}
493
+ .eng-code{margin:0 2px 0 6px;font-family:var(--ds-font-family-code,ui-monospace,monospace);user-select:all;color:var(--dsw-alias-label-primary);}
494
+ .eng-name:focus-visible,.eng-row:focus-visible,.eng-btn:focus-visible,.eng-tab:focus-visible,.eng-link:focus-visible,.eng-howto>summary:focus-visible,.eng-archive>summary:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary));outline-offset:1px;}
495
+ `
496
+
497
+ /** The settings the page edits, in the order the host computes its revision from. */
498
+ const settingsOf = (data) => ({
499
+ companion: data.companion === true,
500
+ audience: data.audience === 'social' ? 'social' : 'private',
501
+ maxLines: data.maxLines,
502
+ maxBytes: data.maxBytes,
503
+ })
504
+ const revisionOf = (settings) => JSON.stringify(settings)
505
+ const capOf = (text, max) => {
506
+ const value = Number(text)
507
+ return /^\s*\d+\s*$/.test(String(text)) && Number.isInteger(value) && value >= 1 && value <= max
508
+ ? value
509
+ : undefined
510
+ }
511
+
512
+ /** fetch with a deadline: a request the host never answers must not hold the page busy. */
513
+ async function request(url, init = {}) {
514
+ const deadline = new AbortController()
515
+ const timer = setTimeout(() => deadline.abort(), 15000)
516
+ try {
517
+ const response = await fetch(url, { cache: 'no-store', ...init, signal: deadline.signal,
518
+ headers: { accept: 'application/json', ...(init.headers ?? {}) } })
519
+ // the body is read under the same deadline: headers alone do not finish a request
520
+ const body = await response.json().catch(() => undefined)
521
+ return { ok: response.ok, status: response.status, body }
522
+ } finally {
523
+ clearTimeout(timer)
524
+ }
525
+ }
526
+
527
+ async function fetchSettings() {
528
+ const response = await request(SETTINGS_API)
529
+ if (!response.ok || response.body === undefined) throw new Error(`HTTP ${response.status}`)
530
+ return response.body
531
+ }
532
+
533
+ /**
534
+ * The settings as the host has them, and a save that waits for the reloaded plugin to
535
+ * read them back. `onAdopt` hears every settings read, a save's included.
536
+ */
537
+ function useSettings(t, onAdopt) {
538
+ const [state, setState] = useState({ phase: 'loading' })
539
+ const [busy, setBusy] = useState(false)
540
+ const [banner, setBanner] = useState(undefined)
541
+ const alive = useRef(true)
542
+ // a second click before the page re-renders as busy must not send a second save
543
+ const saving = useRef(false)
544
+ useEffect(() => () => { alive.current = false }, [])
545
+
546
+ const adopt = useCallback((data) => {
547
+ const settings = settingsOf(data)
548
+ setState({ phase: 'ready', data, settings })
549
+ onAdopt?.(settings)
550
+ }, [onAdopt])
551
+ const load = useCallback(async () => {
552
+ setState((s) => (s.phase === 'ready' ? s : { phase: 'loading' }))
553
+ try {
554
+ const data = await fetchSettings()
555
+ if (alive.current) adopt(data)
556
+ } catch {
557
+ if (alive.current) setState({ phase: 'error' })
558
+ }
559
+ }, [adopt])
560
+ useEffect(() => { load() }, [load])
561
+
562
+ const save = async (next) => {
563
+ if (saving.current) return
564
+ saving.current = true
565
+ setBusy(true)
566
+ setBanner(undefined)
567
+ try {
568
+ let result
569
+ try {
570
+ const response = await request(SETTINGS_API, {
571
+ method: 'POST',
572
+ headers: { 'content-type': 'application/json' },
573
+ body: JSON.stringify({ revision: state.data.revision, ...next }),
574
+ })
575
+ result = response.body ?? { ok: false, error: 'failed', message: `HTTP ${response.status}` }
576
+ } catch (error) {
577
+ result = { ok: false, error: 'failed', message: String(error?.message ?? error) }
578
+ }
579
+ if (!alive.current) return
580
+ if (result.ok) {
581
+ // The plugin reloads with the new config; its route comes back with it.
582
+ setBanner({ tone: 'ok', text: t('reloading') })
583
+ const wanted = revisionOf(next)
584
+ let fresh
585
+ for (let i = 0; i < 20 && alive.current; i++) {
586
+ await new Promise((resolve) => setTimeout(resolve, 400))
587
+ try {
588
+ fresh = await fetchSettings()
589
+ if (revisionOf(settingsOf(fresh)) === wanted) break
590
+ } catch { /* still reloading */ }
591
+ }
592
+ if (!alive.current) return
593
+ if (fresh !== undefined) adopt(fresh)
594
+ // The save landed either way; say so plainly when what came back differs.
595
+ setBanner(fresh !== undefined && revisionOf(settingsOf(fresh)) === wanted
596
+ ? { tone: 'ok', text: t('saved') }
597
+ : { tone: 'error', text: t('savedUnconfirmed') })
598
+ } else if (result.error === 'stale') {
599
+ await load()
600
+ if (alive.current) setBanner({ tone: 'error', text: t('stale') })
601
+ } else if (result.error === 'expression') {
602
+ // the profile changed under the page: read it again, which makes the page read-only
603
+ await load()
604
+ if (alive.current) setBanner({ tone: 'error', text: t('expression') })
605
+ } else if (result.error === 'overridden') {
606
+ setBanner({ tone: 'error', text: t('overridden') })
607
+ } else if (result.error === 'invalid') {
608
+ setBanner({ tone: 'error', text: t('invalid') + (result.field ?? '') })
609
+ } else if (result.error === 'unavailable') {
610
+ setBanner({ tone: 'error', text: t('unavailable') })
611
+ } else {
612
+ setBanner({ tone: 'error', text: t('failed') + (result.message ?? '') })
613
+ }
614
+ } finally {
615
+ saving.current = false
616
+ if (alive.current) setBusy(false)
617
+ }
618
+ }
619
+ return { state, busy, banner, setBanner, load, save }
620
+ }
621
+
622
+ /** A host-styled switch: role=switch with aria-checked, as the host's own. */
623
+ function Switch({ checked, disabled, label, onChange }) {
624
+ return h('button', {
625
+ type: 'button', role: 'switch', className: 'eng-switch', 'aria-checked': checked,
626
+ 'aria-label': label, disabled, onClick: () => onChange(!checked),
627
+ })
628
+ }
629
+
630
+ /** A host-styled two-way choice: buttons with aria-pressed in one group. */
631
+ function Segment({ label, value, options, disabled, onChange }) {
632
+ return h('div', { className: 'eng-segment', role: 'group', 'aria-label': label },
633
+ options.map(([key, text]) => h('button', {
634
+ type: 'button', key, 'aria-pressed': value === key, disabled, onClick: () => onChange(key),
635
+ }, text)))
636
+ }
637
+
638
+ function CompanionSection({ draft, t, disabled, update }) {
639
+ return h('section', { className: 'eng-section' },
640
+ h('div', { className: 'eng-heading' },
641
+ h('h3', { className: 'eng-title' }, t('companion')),
642
+ h(Switch, { checked: draft.companion, disabled, label: t('companion'),
643
+ onChange: (on) => update({ companion: on }) })),
644
+ h('p', { className: 'eng-hint' }, t('companionHint')))
645
+ }
646
+
647
+ function AudienceSection({ draft, t, disabled, update }) {
648
+ return h('section', { className: 'eng-section' },
649
+ h('h3', { className: 'eng-title' }, t('audience')),
650
+ h(Segment, { label: t('audience'), value: draft.audience, disabled,
651
+ options: [['private', t('audiencePrivate')], ['social', t('audienceSocial')]],
652
+ onChange: (audience) => update({ audience }) }),
653
+ h('p', { className: 'eng-hint' }, t(draft.audience === 'social' ? 'audienceSocialHint' : 'audiencePrivateHint')))
654
+ }
655
+
656
+ function CapSection({ caps, t, disabled, setCaps }) {
657
+ const field = (key, label, max) => h('label', null,
658
+ h('input', { className: 'eng-input', inputMode: 'numeric', value: caps[key], disabled,
659
+ 'aria-invalid': capOf(caps[key], max) === undefined,
660
+ onChange: (e) => setCaps({ ...caps, [key]: e.target.value }) }),
661
+ label)
662
+ return h('section', { className: 'eng-section' },
663
+ h('h3', { className: 'eng-title' }, t('cap')),
664
+ h('div', { className: 'eng-cap' },
665
+ field('maxLines', t('capLines'), Number.MAX_SAFE_INTEGER), field('maxBytes', t('capBytes'), Number.MAX_SAFE_INTEGER)),
666
+ h('p', { className: 'eng-hint' }, t('capHint')))
667
+ }
668
+
669
+ /** The whole form, with what each setting means: the package's page in the Plugins page. */
670
+ function SettingsForm({ t }) {
671
+ const [draft, setDraft] = useState(undefined)
672
+ const [caps, setCaps] = useState({ maxLines: String(DEFAULT_LINES), maxBytes: String(DEFAULT_BYTES) })
673
+ const onAdopt = useCallback((settings) => {
674
+ setDraft(settings)
675
+ setCaps({ maxLines: String(settings.maxLines), maxBytes: String(settings.maxBytes) })
676
+ }, [])
677
+ const { state, busy, banner, setBanner, load, save } = useSettings(t, onAdopt)
678
+
679
+ if (state.phase === 'loading' || draft === undefined && state.phase !== 'error') {
680
+ return h('p', { className: 'eng-note' }, t('loading'))
681
+ }
682
+ if (state.phase === 'error') {
683
+ return h('div', { className: 'eng-page' },
684
+ h('div', { className: 'eng-banner', 'data-tone': 'error' }, t('loadFailed')),
685
+ h('div', { className: 'eng-actions' }, h('button', { type: 'button', className: 'eng-btn', onClick: load }, t('retry'))))
686
+ }
687
+
688
+ const { data, settings } = state
689
+ const editable = data.editable === true
690
+ const disabled = !editable || busy
691
+ const maxLines = capOf(caps.maxLines, Number.MAX_SAFE_INTEGER)
692
+ const maxBytes = capOf(caps.maxBytes, Number.MAX_SAFE_INTEGER)
693
+ const next = { ...draft, maxLines: maxLines ?? draft.maxLines, maxBytes: maxBytes ?? draft.maxBytes }
694
+ const valid = maxLines !== undefined && maxBytes !== undefined
695
+ const dirty = revisionOf(next) !== revisionOf(settings)
696
+ const update = (patch) => { setDraft({ ...draft, ...patch }); setBanner(undefined) }
697
+ const discard = () => {
698
+ setDraft(settings)
699
+ setCaps({ maxLines: String(settings.maxLines), maxBytes: String(settings.maxBytes) })
700
+ setBanner(undefined)
701
+ }
702
+
703
+ return h('div', { className: 'eng-page' },
704
+ editable ? null : h('div', { className: 'eng-banner' },
705
+ t(data.readOnly === 'expression' ? 'expression' : 'unavailable')),
706
+ h(CompanionSection, { draft, t, disabled, update }),
707
+ // memory access is a choice inside companion mode: off, it changes nothing
708
+ draft.companion ? h(AudienceSection, { draft, t, disabled, update }) : null,
709
+ h(CapSection, { caps, t, disabled, setCaps }),
710
+ banner ? h('div', { className: 'eng-banner', 'data-tone': banner.tone, role: 'status' }, banner.text) : null,
711
+ editable ? h('div', { className: 'eng-actions' },
712
+ h('button', { type: 'button', className: 'eng-btn eng-btn-primary', disabled: busy || !dirty || !valid, onClick: () => save(next) },
713
+ busy ? t('saving') : t('save')),
714
+ h('button', { type: 'button', className: 'eng-btn', disabled: busy || !dirty, onClick: discard }, t('discard')))
715
+ : null)
716
+ }
717
+
718
+ function SettingsPage(props) {
719
+ if (props.view === 'summary') return props.t('summary')
720
+ return h(SettingsForm, props)
721
+ }
722
+
723
+ /**
724
+ * The two settings that matter most, atop the memory page, each saved as it is switched;
725
+ * what they mean, and the index cap, stay on the package's page.
726
+ */
727
+ function SettingsStrip({ t }) {
728
+ const { state, busy, banner, load, save } = useSettings(t)
729
+ if (state.phase === 'error') {
730
+ return h('section', { className: 'eng-strip' },
731
+ h('p', { className: 'eng-strip-note' }, t('loadFailed')),
732
+ h('button', { type: 'button', className: 'eng-btn', onClick: load }, t('retry')))
733
+ }
734
+ if (state.phase !== 'ready') return null
735
+ const { data, settings } = state
736
+ const disabled = data.editable !== true || busy
737
+ const change = (patch) => save({ ...settings, ...patch })
738
+ return h('section', { className: 'eng-strip' },
739
+ h('div', { className: 'eng-strip-item' },
740
+ h('span', null, t('companion')),
741
+ h(Switch, { checked: settings.companion, disabled, label: t('companion'),
742
+ onChange: (on) => change({ companion: on }) })),
743
+ // memory access is a choice inside companion mode: off, it changes nothing
744
+ settings.companion ? h('div', { className: 'eng-strip-item' },
745
+ h('span', null, t('audience')),
746
+ h(Segment, { label: t('audience'), value: settings.audience, disabled,
747
+ options: [['private', t('audiencePrivate')], ['social', t('audienceSocial')]],
748
+ onChange: (audience) => { if (audience !== settings.audience) change({ audience }) } })) : null,
749
+ h('p', { className: 'eng-strip-note', role: banner ? 'status' : undefined },
750
+ busy ? t('saving') : banner ? banner.text : t(data.editable === true ? 'stripNote' : 'stripReadOnly')))
751
+ }
752
+
753
+ /** The memory route's listing, read again on `load`; a reply that a later read overtook is dropped. */
754
+ function useMemory() {
755
+ const [state, setState] = useState({ phase: 'loading' })
756
+ const alive = useRef(true)
757
+ const generation = useRef(0)
758
+ useEffect(() => () => { alive.current = false }, [])
759
+ const load = useCallback(async () => {
760
+ const mine = ++generation.current
761
+ setState((s) => (s.phase === 'ready' ? s : { phase: 'loading' }))
762
+ let next
763
+ try {
764
+ const response = await request(MEMORY_API)
765
+ next = response.ok && Array.isArray(response.body?.stores)
766
+ ? { phase: 'ready', data: response.body, at: Date.now() }
767
+ : { phase: 'error', reason: response.status === 503 ? 'listTimeout' : 'listFailed' }
768
+ } catch {
769
+ next = { phase: 'error', reason: 'listFailed' }
770
+ }
771
+ if (alive.current && mine === generation.current) setState(next)
772
+ }, [])
773
+ useEffect(() => { load() }, [load])
774
+ return { state, load }
775
+ }
776
+
777
+ /** What the page says for each way the memory route declines to open a file. */
778
+ const OPEN_FAILURES = {
779
+ unavailable: 'openUnavailable', missing: 'openMissing', busy: 'openBusy', timeout: 'listTimeout',
780
+ }
781
+ const nameOf = (file) => file.replace(/\.md$/i, '')
782
+ /**
783
+ * A name or path from disk as the page shows it: a control character, a line or paragraph
784
+ * separator, a bidirectional mark, embedding, override or isolate, or a character with no
785
+ * width of its own (a zero-width space, a word joiner, a byte order mark) — any of which can
786
+ * make a name read as another, or hide part of it — shown as its code point (`[U+202E]`).
787
+ * The joiners some scripts and emoji are written with (U+200C, U+200D) are left as they are.
788
+ * What the page sends back to open a file is the name as it is.
789
+ */
790
+ const HIDDEN = [[0x0, 0x1f], [0x7f, 0x9f], [0x61c, 0x61c], [0x200b, 0x200b], [0x200e, 0x200f],
791
+ [0x2028, 0x202e], [0x2060, 0x2064], [0x2066, 0x2069], [0xfeff, 0xfeff]]
792
+ const legible = (text) => Array.from(String(text), (ch) => {
793
+ const code = ch.codePointAt(0)
794
+ return HIDDEN.some(([low, high]) => code >= low && code <= high)
795
+ ? `[U+${code.toString(16).toUpperCase().padStart(4, '0')}]`
796
+ : ch
797
+ }).join('')
798
+ const sizeOf = (t, bytes) => (bytes < 1024 ? t('sizeBytes', { n: bytes }) : t('sizeKB', { n: (bytes / 1024).toFixed(1) }))
799
+ const typeKey = (type) => `type${type[0].toUpperCase()}${type.slice(1)}`
800
+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
801
+ const byName = (a, b) => collator.compare(a, b)
802
+ /** Notes in the protocol's order of types, then by name. */
803
+ const byTypeThenName = (a, b) => TYPES.indexOf(a.type) - TYPES.indexOf(b.type) || byName(a.name, b.name)
804
+
805
+ /** Put `text` on the clipboard; false where there is none (a page over plain http) or it is refused. */
806
+ async function copyText(text) {
807
+ try {
808
+ await globalThis.navigator.clipboard.writeText(text)
809
+ return true
810
+ } catch {
811
+ return false
812
+ }
813
+ }
814
+
815
+ /** The date an `upcoming` note is named with, if it is a real day: `YYYY-MM-DD`, else undefined. */
816
+ function dateOf(file) {
817
+ const m = DATED.exec(nameOf(file))
818
+ if (m === null) return undefined
819
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]
820
+ const day = new Date(Date.UTC(y, mo - 1, d))
821
+ return day.getUTCFullYear() === y && day.getUTCMonth() === mo - 1 && day.getUTCDate() === d
822
+ ? `${m[1]}-${m[2]}-${m[3]}` : undefined
823
+ }
824
+ /** A `YYYY-MM-DD` day as a number of days, to subtract one from another. */
825
+ const dayNumber = (date) => Date.UTC(Number(date.slice(0, 4)), Number(date.slice(5, 7)) - 1,
826
+ Number(date.slice(8, 10))) / 86400000
827
+ /** Today on this computer's calendar, as `YYYY-MM-DD`. */
828
+ function todayOf(now) {
829
+ const d = new Date(now)
830
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
831
+ }
832
+
833
+ /**
834
+ * Where an `upcoming` note stands against today on this computer: a date passed only says
835
+ * the outcome is yet to be asked about (SKILL.md §2.2 keeps the note until it is known),
836
+ * so nothing here is called late or stale. No date, or no real one, is undated.
837
+ */
838
+ function planOf(file, now) {
839
+ const date = dateOf(file)
840
+ if (date === undefined) return { status: 'undated' }
841
+ const days = dayNumber(date) - dayNumber(todayOf(now))
842
+ return { status: days < 0 ? 'past' : days === 0 ? 'today' : 'ahead', days, date }
843
+ }
844
+
845
+ /** A note's name as listed: a plan's date is in its badge, so it is not said again before the name. */
846
+ function shownName(file, plan) {
847
+ const name = nameOf(file)
848
+ if (plan?.date === undefined) return name
849
+ const rest = name.slice(10).replace(/^[\s_-]+/, '')
850
+ return rest === '' ? name : rest
851
+ }
852
+
853
+ /** How full an index is, the nearer of its two caps; its lines only when they were counted. */
854
+ function fillOf(index, cap) {
855
+ const lines = index.lines === undefined ? 0 : index.lines / cap.maxLines
856
+ return Math.max(lines, index.bytes / cap.maxBytes)
857
+ }
858
+
859
+ /** Line icons on a 24-unit grid, in the current colour: [element, attributes] each. One per
860
+ * note type (TYPES), drawn alike, so the type's colour tells them apart before the shape does. */
861
+ const ICONS = {
862
+ refresh: [['path', { d: 'M20 11a8 8 0 1 0-2.3 5.7' }], ['path', { d: 'M20 4v7h-7' }]],
863
+ search: [['circle', { cx: 11, cy: 11, r: 7 }], ['path', { d: 'm20 20-3.5-3.5' }]],
864
+ copy: [['rect', { x: 9, y: 9, width: 11, height: 11, rx: 2 }], ['path', { d: 'M5 15V5a2 2 0 0 1 2-2h8' }]],
865
+ folder: [['path', { d: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z' }]],
866
+ index: [['path', { d: 'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01' }]],
867
+ tidy: [['path', { d: 'm4 20 11-11M14 4l1 2 2 1-2 1-1 2-1-2-2-1 2-1zM19 11l.7 1.3L21 13l-1.3.7L19 15l-.7-1.3L17 13l1.3-.7z' }]],
868
+ archive: [['rect', { x: 3, y: 4, width: 18, height: 5, rx: 1 }], ['path', { d: 'M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4' }]],
869
+ alert: [['path', { d: 'M12 4 2.5 20h19z' }], ['path', { d: 'M12 10v4M12 17h.01' }]],
870
+ clock: [['circle', { cx: 12, cy: 12, r: 8.5 }], ['path', { d: 'M12 7.5V12l3 2' }]],
871
+ check: [['path', { d: 'm5 12 5 5 9-10' }]],
872
+ chevron: [['path', { d: 'm9 6 6 6-6 6' }]],
873
+ book: [['path', { d: 'M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z' }], ['path', { d: 'M4 19V5' }]],
874
+ issue: [['path', { d: 'M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z' }]],
875
+ mail: [['rect', { x: 3, y: 5, width: 18, height: 14, rx: 2 }], ['path', { d: 'm3 7 9 6 9-6' }]],
876
+ package: [['path', { d: 'M12 3 4 7v10l8 4 8-4V7z' }], ['path', { d: 'm4 7 8 4 8-4M12 11v10' }]],
877
+ user: [['circle', { cx: 12, cy: 8.6, r: 3.6 }], ['path', { d: 'M5 19.5c1.2-3.3 3.9-5 7-5s5.8 1.7 7 5z' }]],
878
+ feedback: [['path', { d: 'M4.5 6.5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H11l-4 3v-3h-.5a2 2 0 0 1-2-2z' }],
879
+ ['path', { d: 'm9 10.3 2 2 4-4' }]],
880
+ project: [['path', { d: 'M12 4 3.5 8.5 12 13l8.5-4.5z' }], ['path', { d: 'm3.5 12.5 8.5 4.5 8.5-4.5M3.5 16.3 12 20.8l8.5-4.5' }]],
881
+ reference: [['path', { d: 'M7 3.5h10a1 1 0 0 1 1 1v16l-6-3.8-6 3.8v-16a1 1 0 0 1 1-1z' }]],
882
+ moment: [['path', { d: 'M10 3.5l1.6 4.4L16 9.5l-4.4 1.6L10 15.5l-1.6-4.4L4 9.5l4.4-1.6z' }],
883
+ ['path', { d: 'M17.5 14v5.5M14.75 16.75h5.5' }]],
884
+ upcoming: [['rect', { x: 4, y: 5.5, width: 16, height: 14.5, rx: 2.5 }], ['path', { d: 'M4 10h16M8.5 3.5v4M15.5 3.5v4' }],
885
+ ['circle', { cx: 15.3, cy: 15, r: 1.3, fill: 'currentColor', stroke: 'none' }]],
886
+ self: [['path', { d: 'M12 19.5s-7-4.3-7-9.6A3.9 3.9 0 0 1 12 7.6a3.9 3.9 0 0 1 7 2.3c0 5.3-7 9.6-7 9.6z' }]],
887
+ other: [['path', { d: 'M13.5 3.5H7a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9z' }], ['path', { d: 'M13.5 3.5V9H19' }]],
888
+ }
889
+ const icon = (name, size = 16, weight = 1.8) => h('svg', {
890
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: weight,
891
+ strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, focusable: 'false',
892
+ }, ...ICONS[name].map(([tag, attributes], i) => h(tag, { key: i, ...attributes })))
893
+
894
+ /** The project's mark, [[▮]] in mint on its dark tile, as in its icon. */
895
+ function Logo() {
896
+ return h('svg', { className: 'eng-logo', width: 44, height: 44, viewBox: '0 0 64 64', 'aria-hidden': true, focusable: 'false' },
897
+ h('rect', { width: 64, height: 64, rx: 14, fill: '#0F1B2D' }),
898
+ h('path', { d: 'M13 17.5H9v29h4M22 17.5h-4v29h4M42 17.5h4v29h-4M51 17.5h4v29h-4', fill: 'none', stroke: '#6EE7C8',
899
+ strokeWidth: 4, strokeLinecap: 'round', strokeLinejoin: 'round' }),
900
+ h('rect', { x: 27.5, y: 23, width: 9, height: 18, rx: 2.4, fill: '#6EE7C8' }))
901
+ }
902
+
903
+ /** When a listing was read, its day with its time, as this computer shows them. */
904
+ const timeOf = (at) => new Date(at).toLocaleString([], { month: '2-digit', day: '2-digit', hour: '2-digit',
905
+ minute: '2-digit' })
906
+
907
+ /**
908
+ * The banner atop the memory page, in the project's own colours on any theme: its name with
909
+ * the plugin's version, the listing in three numbers as read at `at` with a refresh beside the
910
+ * time, and the two settings that matter most in a panel of their own. Numbers only once there
911
+ * is a listing with something to count.
912
+ */
913
+ function Hero({ data, at, refresh, t }) {
914
+ const counted = data !== undefined && (data.stores.length > 0 || data.unreadable > 0)
915
+ const sum = (of) => data.stores.reduce((total, store) => total + of(store), 0)
916
+ const notes = counted ? sum((store) => store.notes.length) : 0
917
+ const stat = (n, label) => h('div', { className: 'eng-stat', key: label }, h('b', null, String(n)), h('span', null, label))
918
+ return h('header', { className: 'eng-hero' },
919
+ h('div', { className: 'eng-hero-main' },
920
+ h('div', { className: 'eng-brand' }, h(Logo), h('h1', { className: 'eng-hero-title' }, t('panelTitle'),
921
+ h('span', { className: 'eng-hero-version' }, `v${VERSION}`))),
922
+ counted ? h('div', { className: 'eng-stats' },
923
+ stat(notes, t(notes === 1 ? 'statNote' : 'statNotes')),
924
+ stat(data.stores.length, t(data.stores.length === 1 ? 'statStore' : 'statStores')),
925
+ stat(sum((store) => store.archive.length), t('statArchive'))) : null,
926
+ h('div', { className: 'eng-hero-foot' },
927
+ data === undefined ? null : h('p', { className: 'eng-hero-read' },
928
+ icon('clock', 13), t('statsReadAt', { time: timeOf(at) })),
929
+ h('button', { type: 'button', className: 'eng-hero-btn', onClick: refresh }, icon('refresh', 14), t('refresh')))),
930
+ h('div', { className: 'eng-hero-side' }, h(SettingsStrip, { t })))
931
+ }
932
+
933
+ /** What the numbers leave out — a listing cut short, files or stores it could not read — since
934
+ * what was not listed is not counted as nothing. */
935
+ function Caveats({ data, t }) {
936
+ const partial = data.more === true || data.stores.some((store) => store.more)
937
+ // a note or a folder it could not read: the store's check-up says so too
938
+ const incomplete = data.stores.some((store) => store.health?.checked === false &&
939
+ store.health.reason === 'unreadable')
940
+ const lines = [
941
+ partial ? t('statsPartial') : null,
942
+ incomplete ? t('statsIncomplete') : null,
943
+ data.unreadable > 0 ? t('statsUnreadable', { count: data.unreadable }) : null,
944
+ ].filter((line) => line !== null)
945
+ return lines.length === 0 ? null
946
+ : h('p', { className: 'eng-caveat' }, icon('alert', 14), h('span', null, lines.join(' ')))
947
+ }
948
+
949
+ /**
950
+ * One store: where it is, how full its index is (a bar to the nearer of its two caps), what
951
+ * its check-up (index.js checkUp) found for the AI to tidy up — with the tidy-up instructions
952
+ * to copy, or to select where there is no clipboard — and its notes, a row each: the type's
953
+ * mark, the name, the type and size, and what stands out (a plan's day, a note grown past one
954
+ * fact, one the index leaves out). While the page filters, the rows that match and no more.
955
+ */
956
+ function StoreSection({ store, cap, canOpen, open, match, kind, now, t }) {
957
+ const [tidy, setTidy] = useState('idle')
958
+ const alive = useRef(true)
959
+ useEffect(() => () => { alive.current = false }, [])
960
+ const title = legible(store.kind === 'user' ? [t('storeUser'), ...store.titles].join(' · ')
961
+ : store.kind === 'pinned' ? [t('storePinned'), ...store.titles].join(' · ')
962
+ : store.titles.join(' · '))
963
+ const { index } = store
964
+ const sizes = index === null ? {} : { size: sizeOf(t, index.bytes), maxSize: sizeOf(t, cap.maxBytes) }
965
+ // lines are counted only for an index read whole; past that, its bytes say over or not
966
+ const usage = index === null ? t('noIndex')
967
+ : index.lines !== undefined ? t('usage', { lines: index.lines, maxLines: cap.maxLines, ...sizes })
968
+ : t(index.over ? 'usageOver' : 'usageSize', sizes)
969
+ const fill = index === null ? undefined : fillOf(index, cap)
970
+ const filtering = match !== undefined || kind !== undefined
971
+ const keep = (file) => match === undefined || match(file)
972
+ const notes = store.notes.filter((note) => (kind === undefined || note.type === kind) && keep(note.name))
973
+ .sort(byTypeThenName)
974
+ const archived = kind === undefined ? store.archive.filter(keep).sort(byName) : []
975
+
976
+ const check = store.health ?? undefined
977
+ const checked = check?.checked === true
978
+ const unindexed = new Set(checked ? check.unindexed : [])
979
+ const untyped = store.notes.filter((note) => note.type === 'other').length
980
+ const large = store.notes.filter((note) => note.bytes > LARGE_NOTE).length
981
+ // pointers to nothing past what the page is told of are still pointers to nothing
982
+ const broken = checked && (check.broken.length > 0 || check.brokenMore)
983
+ const findings = [
984
+ index?.over ? h('p', { className: 'eng-attn-item', key: 'over' }, t('overHint')) : null,
985
+ broken ? h('div', { className: 'eng-attn-item', key: 'broken' },
986
+ check.broken.length === 0 ? t('healthBrokenUnlisted')
987
+ : t(check.brokenMore ? 'healthBrokenMore' : 'healthBroken', { count: check.broken.length }),
988
+ // what the index says, as it says it: there is no file to open
989
+ check.broken.length > 0 ? h('ul', { className: 'eng-broken' },
990
+ check.broken.map((target) => h('li', { key: target }, h('code', null, legible(target))))) : null) : null,
991
+ checked && check.unindexed.length > 0
992
+ ? h('p', { className: 'eng-attn-item', key: 'unindexed' }, t('healthUnindexed', { count: check.unindexed.length })) : null,
993
+ checked && untyped > 0 ? h('p', { className: 'eng-attn-item', key: 'untyped' }, t('healthUntyped', { count: untyped })) : null,
994
+ large > 0 ? h('p', { className: 'eng-attn-item', key: 'large' }, t('attnLarge', { count: large })) : null,
995
+ ].filter((finding) => finding !== null)
996
+ // while filtering, the names that match and nothing else: the findings come back after
997
+ const attention = !filtering && findings.length > 0
998
+ // a check-up that did not run says why, except past the cap, which the findings say already
999
+ const unchecked = check === undefined || check === null || check.checked ? undefined
1000
+ : { large: 'healthLarge', partial: 'healthPartial', unreadable: 'healthUnreadable' }[check.reason]
1001
+
1002
+ const prompt = t('tidyPrompt', { dir: store.dir })
1003
+ const copyTidy = async () => {
1004
+ const done = await copyText(prompt)
1005
+ if (alive.current) setTidy(done ? 'copied' : 'failed')
1006
+ }
1007
+ // one per store: in the findings where there are any, else among the store's own actions
1008
+ const tidyButton = (className) => h('button', { type: 'button', className, onClick: copyTidy },
1009
+ icon('tidy', 14), t(tidy === 'copied' ? 'tidyCopied' : 'tidyCopy'))
1010
+
1011
+ const planText = (plan) => {
1012
+ if (plan.status === 'undated') return t('badgeUndated')
1013
+ if (plan.status === 'today') return t('badgeToday')
1014
+ // the year where it is not this one, so last year's plan is not taken for this year's
1015
+ const year = Number(plan.date.slice(0, 4))
1016
+ const day = { m: Number(plan.date.slice(5, 7)), d: Number(plan.date.slice(8, 10)) }
1017
+ const date = year === new Date(now).getFullYear() ? t('monthDay', day) : t('yearMonthDay', { y: year, ...day })
1018
+ return plan.status === 'past' ? t('badgePast', { date })
1019
+ : plan.days === 1 ? t('badgeTomorrow', { date }) : t('badgeSoon', { date, days: plan.days })
1020
+ }
1021
+ /** A note's row, or an archived file's (no note given): to open where dsh can, else text. */
1022
+ const row = (file, note) => {
1023
+ const type = note === undefined ? 'archive' : note.type
1024
+ const plan = type === 'upcoming' ? planOf(file, now) : undefined
1025
+ const meta = note === undefined ? t('archived')
1026
+ : note.unread ? t('noteUnread')
1027
+ : note.bytes === undefined ? t(typeKey(type))
1028
+ : t('noteMeta', { type: t(typeKey(type)), size: sizeOf(t, note.bytes) })
1029
+ const badges = [
1030
+ plan === undefined ? null : h('span', { className: 'eng-badge', key: 'plan',
1031
+ 'data-tone': plan.status === 'past' ? 'warn' : plan.status === 'undated' ? 'quiet' : undefined }, planText(plan)),
1032
+ note?.bytes > LARGE_NOTE ? h('span', { className: 'eng-badge', 'data-tone': 'warn', key: 'large' }, t('badgeLarge')) : null,
1033
+ note !== undefined && unindexed.has(file) ? h('span', { className: 'eng-badge', key: 'unindexed' }, t('badgeUnindexed')) : null,
1034
+ ].filter((badge) => badge !== null)
1035
+ const parts = [
1036
+ h('span', { className: 'eng-mark', key: 'mark' }, icon(Object.hasOwn(ICONS, type) ? type : 'other', 18, 1.6)),
1037
+ h('span', { className: 'eng-row-text', key: 'text' },
1038
+ h('span', { className: 'eng-name' }, legible(shownName(file, plan))),
1039
+ h('span', { className: 'eng-row-meta' }, meta)),
1040
+ badges.length > 0 ? h('span', { className: 'eng-badges', key: 'badges' }, badges) : null,
1041
+ canOpen ? h('span', { className: 'eng-row-go', key: 'go' }, icon('chevron', 14)) : null,
1042
+ ]
1043
+ const props = { className: 'eng-row', 'data-type': type, title: legible(file) }
1044
+ return h('li', { key: file }, canOpen
1045
+ ? h('button', { type: 'button', ...props, onClick: () => open(store, file, note === undefined) }, ...parts)
1046
+ : h('div', props, ...parts))
1047
+ }
1048
+ const archive = archived.length === 0 ? null
1049
+ : h('details', { className: 'eng-archive', open: match === undefined ? undefined : true },
1050
+ h('summary', null, icon('archive', 16), h('span', null, t('archive', { count: archived.length }))),
1051
+ h('ul', { className: 'eng-rows' }, archived.map((file) => row(file, undefined))))
1052
+
1053
+ return h('section', { className: 'eng-store', 'aria-label': title },
1054
+ h('div', { className: 'eng-store-head' },
1055
+ h('h2', { className: 'eng-store-title' }, title),
1056
+ h('span', { className: 'eng-store-count' },
1057
+ t(store.notes.length === 1 ? 'storeCountOne' : 'storeCount', { count: store.notes.length })),
1058
+ // the nearer cap, whichever it is; over it, full and marked, not a bar that stops at the edge
1059
+ fill === undefined ? null : h('span', { className: 'eng-meter', 'data-over': index.over === true || fill > 1,
1060
+ 'aria-hidden': true },
1061
+ h('span', { className: 'eng-meter-fill', style: { width: `${Math.min(100, Math.floor(fill * 100))}%` } })),
1062
+ h('span', { className: 'eng-usage', 'data-over': index?.over === true, title: index?.over ? t('overHint') : undefined }, usage),
1063
+ h('div', { className: 'eng-store-actions' },
1064
+ attention ? null : tidyButton('eng-btn eng-btn-ghost'),
1065
+ // the folder is shown with its index selected: no index, no folder to show
1066
+ ...(canOpen && index !== null ? [
1067
+ h('button', { type: 'button', className: 'eng-btn eng-btn-ghost', key: 'index',
1068
+ onClick: () => open(store, index.name, false) }, icon('index', 14), t('openIndex')),
1069
+ h('button', { type: 'button', className: 'eng-btn eng-btn-ghost', key: 'folder',
1070
+ onClick: () => open(store, undefined, false) }, icon('folder', 14), t('openFolder'))] : []))),
1071
+ h('p', { className: 'eng-path' }, legible(store.dir)),
1072
+ !filtering && checked && findings.length === 0
1073
+ ? h('p', { className: 'eng-store-ok' }, icon('check', 13), t('healthOk')) : null,
1074
+ attention ? h('div', { className: 'eng-attn', role: 'note' },
1075
+ icon('alert', 16),
1076
+ h('div', { className: 'eng-attn-body' },
1077
+ h('h3', { className: 'eng-attn-title' }, t('attnTitle')),
1078
+ ...findings,
1079
+ h('p', { className: 'eng-attn-item', key: 'doctor' }, t('healthFix'))),
1080
+ tidyButton('eng-btn')) : null,
1081
+ tidy === 'failed' ? h('div', { className: 'eng-tidy', role: 'status' },
1082
+ h('p', null, t('tidyFailed')),
1083
+ h('textarea', { readOnly: true, value: prompt, 'aria-label': t('tidyCopy'),
1084
+ onFocus: (event) => event.target.select() })) : null,
1085
+ !filtering && unchecked !== undefined ? h('p', { className: 'eng-note' }, t(unchecked)) : null,
1086
+ notes.length > 0 || archive !== null ? h('div', { className: 'eng-list' },
1087
+ notes.length > 0 ? h('ul', { className: 'eng-rows' }, notes.map((note) => row(note.name, note))) : null,
1088
+ archive) : null,
1089
+ filtering && notes.length === 0 && archived.length === 0
1090
+ ? h('p', { className: 'eng-filter-none' }, t('filterNone')) : null,
1091
+ store.more ? h('p', { className: 'eng-note' }, t('more')) : null)
1092
+ }
1093
+
1094
+ /** A store with anything in it: an index with text, a note, an archived note. A folder or an
1095
+ * empty index alone is not memory yet. */
1096
+ const hasMemory = (store) => (store.index !== null && store.index.bytes > 0) ||
1097
+ store.notes.length > 0 || store.archive.length > 0
1098
+
1099
+ /** A store not read to its end: a listing cut short, or a file or folder it could not read. */
1100
+ const readInPart = (store) => store.more === true ||
1101
+ (store.health?.checked === false && store.health.reason === 'unreadable')
1102
+
1103
+ /** How to use it, in a few lines: open while there is no memory yet, folded once there is. */
1104
+ function HowTo({ open, t }) {
1105
+ return h('details', { className: 'eng-howto', open },
1106
+ h('summary', null, icon('book', 15), t('howTo')),
1107
+ h('ul', null, HOW_TO.map((key) => h('li', { key }, t(key)))))
1108
+ }
1109
+
1110
+ /** The OS family for a bug report, and nothing that tells one machine from another. */
1111
+ function osName() {
1112
+ const platform = String(globalThis.navigator?.userAgentData?.platform ?? globalThis.navigator?.platform ?? '')
1113
+ return /^win/i.test(platform) ? 'Windows' : /^mac/i.test(platform) ? 'macOS'
1114
+ : /linux/i.test(platform) ? 'Linux' : 'unknown'
1115
+ }
1116
+
1117
+ /** The latest version on npm and the registry that said so, asked of each in turn until one
1118
+ * answers with a version; undefined when none does. Each gets 8 seconds, body included, and no cookie or
1119
+ * referrer goes with the request: the package's name is all it asks about. */
1120
+ async function latestVersion() {
1121
+ for (const [source, registry] of REGISTRIES) {
1122
+ const deadline = new AbortController()
1123
+ const timer = setTimeout(() => deadline.abort(), 8000)
1124
+ try {
1125
+ const response = await fetch(`${registry}/${PACKAGE}/latest`, { cache: 'no-store', credentials: 'omit',
1126
+ referrerPolicy: 'no-referrer', signal: deadline.signal, headers: { accept: 'application/json' } })
1127
+ const version = response.ok ? (await response.json())?.version : undefined
1128
+ if (typeof version === 'string' && version.length <= 64 && SEMVER.test(version)) return { version, source }
1129
+ } catch {
1130
+ // unreachable, refused, too slow or not JSON: the next registry
1131
+ } finally {
1132
+ clearTimeout(timer)
1133
+ // a body left unread (an error's) or half read is let go, not left streaming
1134
+ deadline.abort()
1135
+ }
1136
+ }
1137
+ return undefined
1138
+ }
1139
+
1140
+ /** -1, 0 or 1 as version `a` is older than, the same as or newer than `b` (both SEMVER): by
1141
+ * the three numbers, then a prerelease before its release. Two prereleases of one release
1142
+ * count as the same; this package publishes none to npm's `latest`. */
1143
+ function compareVersions(a, b) {
1144
+ const x = SEMVER.exec(a)
1145
+ const y = SEMVER.exec(b)
1146
+ for (let i = 1; i <= 3; i++) {
1147
+ if (Number(x[i]) !== Number(y[i])) return Number(x[i]) < Number(y[i]) ? -1 : 1
1148
+ }
1149
+ return x[4] === y[4] || (x[4] !== undefined && y[4] !== undefined) ? 0 : x[4] === undefined ? 1 : -1
1150
+ }
1151
+
1152
+ /**
1153
+ * The installed version and, on a click and only then, how it stands against the latest on
1154
+ * npm. A newer one comes with the steps that install it, the version named: by name alone,
1155
+ * pnpm (the desktop's, and the CLI's from pnpm 11) takes only a version a day old. dsh has no
1156
+ * update for a plugin outside its own catalog, so the desktop's way is uninstall and install.
1157
+ */
1158
+ function UpdateCheck({ t }) {
1159
+ const [check, setCheck] = useState({ phase: 'idle' })
1160
+ const [copy, setCopy] = useState('copy')
1161
+ const alive = useRef(true)
1162
+ useEffect(() => () => { alive.current = false }, [])
1163
+ const run = async () => {
1164
+ setCheck({ phase: 'checking' })
1165
+ setCopy('copy')
1166
+ const found = await latestVersion()
1167
+ if (!alive.current) return
1168
+ setCheck(found === undefined ? { phase: 'failed' } : { phase: 'done', latest: found.version,
1169
+ source: found.source, order: compareVersions(found.version, VERSION) })
1170
+ }
1171
+ const spec = `${PACKAGE}@${check.latest}`
1172
+ const copySpec = async () => {
1173
+ const done = await copyText(spec)
1174
+ if (alive.current) setCopy(done ? 'copied' : 'copyFailed')
1175
+ }
1176
+ const external = (href, text) => h('a', { className: 'eng-link', href, target: '_blank', rel: 'noopener noreferrer' }, text)
1177
+ let result = null
1178
+ if (check.phase === 'failed') {
1179
+ result = h('p', { role: 'status' }, t('updateFailed'), external(NPM_PAGE, t('updateNpm')))
1180
+ } else if (check.phase === 'done' && check.order <= 0) {
1181
+ result = h('p', { role: 'status' },
1182
+ check.order === 0 ? t('updateCurrent', { latest: check.latest, source: check.source })
1183
+ : t('updateAhead', { latest: check.latest, current: VERSION, source: check.source }))
1184
+ } else if (check.phase === 'done') {
1185
+ result = h('div', { className: 'eng-update', role: 'status' },
1186
+ h('p', null,
1187
+ h('span', { className: 'eng-update-new' }, t('updateNewer', { latest: check.latest, current: VERSION })),
1188
+ external(`${RELEASE}${check.latest}`, t('updateNotes'))),
1189
+ h('p', null, t('updateHow')),
1190
+ h('ul', null,
1191
+ h('li', null, t('updateDesktop'), h('code', { className: 'eng-code' }, spec),
1192
+ h('button', { type: 'button', className: 'eng-btn eng-btn-small', onClick: copySpec },
1193
+ t(copy === 'copied' ? 'copied' : 'copy'))),
1194
+ h('li', null, t('updateCli'),
1195
+ h('code', { className: 'eng-code' }, `dsh plugin --profile ${t('updateProfile')} add ${spec}`))),
1196
+ copy === 'copyFailed' ? h('p', { className: 'eng-feedback-note' }, t('copySpecFailed')) : null,
1197
+ h('p', null, t('updateAfter')))
1198
+ }
1199
+ // a mirror's word, which may trail npm's, is said to be one
1200
+ const mirrored = check.phase === 'done' && check.source !== 'npm'
1201
+ ? h('p', { className: 'eng-feedback-note' }, t('updateMirror')) : null
1202
+ return h('div', { className: 'eng-version' },
1203
+ h('p', null,
1204
+ icon('package', 14),
1205
+ t('versionLine', { version: VERSION }),
1206
+ h('button', { type: 'button', className: 'eng-btn eng-btn-small', disabled: check.phase === 'checking',
1207
+ onClick: run }, t(check.phase === 'checking' ? 'checking' : 'checkUpdate'))),
1208
+ result,
1209
+ mirrored,
1210
+ h('p', { className: 'eng-feedback-note' }, t('updateNote')))
1211
+ }
1212
+
1213
+ /**
1214
+ * Where to report a problem or send an idea: a new issue, its body started with the
1215
+ * plugin's version and the OS (no path, no note), or the mailbox, whose address the
1216
+ * button copies — the desktop app opens only web links, not `mailto:`. Above them, the
1217
+ * version and the check for a newer one.
1218
+ */
1219
+ function Feedback({ t }) {
1220
+ const [copy, setCopy] = useState('copy')
1221
+ const alive = useRef(true)
1222
+ useEffect(() => () => { alive.current = false }, [])
1223
+ const copyAddress = async () => {
1224
+ const done = await copyText(EMAIL)
1225
+ if (alive.current) setCopy(done ? 'copied' : 'copyFailed')
1226
+ }
1227
+ const href = `${ISSUES}?body=${encodeURIComponent(t('issueBody', { version: VERSION, os: osName() }))}`
1228
+ return h('footer', { className: 'eng-feedback' },
1229
+ h(UpdateCheck, { t }),
1230
+ h('p', null,
1231
+ icon('issue', 14),
1232
+ t('feedbackLead'),
1233
+ h('a', { className: 'eng-link', href, target: '_blank', rel: 'noopener noreferrer' }, t('feedbackIssue')),
1234
+ t('feedbackMail'),
1235
+ h('span', { className: 'eng-email' }, EMAIL),
1236
+ h('button', { type: 'button', className: 'eng-btn eng-btn-small', onClick: copyAddress },
1237
+ t(copy === 'copied' ? 'copied' : 'copy'))),
1238
+ copy === 'copyFailed' ? h('p', { className: 'eng-feedback-note', role: 'status' }, t('copyFailed')) : null,
1239
+ h('p', { className: 'eng-feedback-note' }, t('feedbackNote')))
1240
+ }
1241
+
1242
+ /**
1243
+ * The sidebar's Memory page: a banner with the listing's numbers and two settings, then the
1244
+ * stores recall can use, their notes a row each, by type and by name as the user filters.
1245
+ */
1246
+ function MemoryPage({ t }) {
1247
+ const { state, load } = useMemory()
1248
+ const [status, setStatus] = useState(undefined)
1249
+ const [query, setQuery] = useState('')
1250
+ const [kind, setKind] = useState(undefined)
1251
+ const alive = useRef(true)
1252
+ useEffect(() => () => { alive.current = false }, [])
1253
+
1254
+ const open = async (store, file, archive) => {
1255
+ setStatus(undefined)
1256
+ let reply
1257
+ try {
1258
+ const response = await request(MEMORY_API, {
1259
+ method: 'POST',
1260
+ headers: { 'content-type': 'application/json' },
1261
+ body: JSON.stringify({ store: store.id, ...(file === undefined ? {} : { file }), ...(archive ? { archive: true } : {}) }),
1262
+ })
1263
+ reply = response.body ?? { ok: false, error: 'failed', message: `HTTP ${response.status}` }
1264
+ } catch (error) {
1265
+ reply = { ok: false, error: 'failed', message: String(error?.message ?? error) }
1266
+ }
1267
+ if (!alive.current) return
1268
+ // a file shown in its folder rather than opened (an index not named .md) is said to be
1269
+ setStatus(reply.ok ? { tone: 'ok', text: file === undefined ? t('opened', { name: legible(store.dir) })
1270
+ : t(reply.revealed === true ? 'revealed' : 'opened', { name: legible(nameOf(file)) }) }
1271
+ : Object.hasOwn(OPEN_FAILURES, reply.error) ? { tone: 'error', text: t(OPEN_FAILURES[reply.error]) }
1272
+ : { tone: 'error', text: t('openFailed', { reason: reply.message ?? reply.error ?? '' }) })
1273
+ }
1274
+
1275
+ const data = state.phase === 'ready' ? state.data : undefined
1276
+ const canOpen = data?.canOpen === true
1277
+ // a type a refresh left with nothing is no longer a filter, nor one again when it returns
1278
+ const present = data === undefined || kind === undefined ||
1279
+ data.stores.some((store) => store.notes.some((note) => note.type === kind))
1280
+ useEffect(() => { if (!present) setKind(undefined) }, [present])
1281
+ // a name filter over what was listed: case- and width-insensitive, the .md left out — by
1282
+ // the name as it is or as the page shows it (legible), so what is on the page can be typed
1283
+ const needle = query.trim().normalize('NFKC').toLowerCase()
1284
+ const match = needle === '' ? undefined
1285
+ : (file) => [nameOf(file), legible(nameOf(file))]
1286
+ .some((name) => name.normalize('NFKC').toLowerCase().includes(needle))
1287
+ let body
1288
+ if (state.phase === 'loading') body = h('p', { className: 'eng-note' }, t('listing'))
1289
+ else if (state.phase === 'error') body = h('div', { className: 'eng-banner', 'data-tone': 'error' }, t(state.reason))
1290
+ else {
1291
+ const notes = data.stores.flatMap((store) => store.notes)
1292
+ const archived = data.stores.reduce((sum, store) => sum + store.archive.length, 0)
1293
+ const counts = TYPES.map((type) => [type, notes.filter((note) => note.type === type).length])
1294
+ .filter(([, count]) => count > 0)
1295
+ const shown = present ? kind : undefined
1296
+ const tab = (type, label, count) => h('button', { type: 'button', className: 'eng-tab', key: type ?? 'all',
1297
+ 'data-type': type ?? 'all', 'aria-pressed': shown === type, onClick: () => setKind(type) },
1298
+ label, h('span', { className: 'eng-tab-count' }, String(count)))
1299
+ const matched = match === undefined ? 0 : data.stores.reduce((sum, store) => sum +
1300
+ store.notes.filter((note) => (shown === undefined || note.type === shown) && match(note.name)).length +
1301
+ (shown === undefined ? store.archive.filter(match).length : 0), 0)
1302
+ body = [
1303
+ data.pinned === 'relative' ? h('p', { className: 'eng-note', key: 'pinned' }, t('pinnedRelative')) : null,
1304
+ data.stores.length === 0 && data.pinned === undefined && !(data.unreadable > 0) && data.more !== true
1305
+ ? h('p', { className: 'eng-note', key: 'empty' }, t('empty')) : null,
1306
+ notes.length + archived > 0 ? h('div', { className: 'eng-toolbar', key: 'toolbar' },
1307
+ h('div', { className: 'eng-tabs', role: 'group', 'aria-label': t('typeLabel') },
1308
+ tab(undefined, t('typeAll'), notes.length),
1309
+ ...counts.map(([type, count]) => tab(type, t(typeKey(type)), count))),
1310
+ h('label', { className: 'eng-search' },
1311
+ icon('search', 15),
1312
+ h('input', { type: 'search', className: 'eng-input', value: query, placeholder: t('filterPlaceholder'),
1313
+ 'aria-label': t('filterLabel'), onChange: (event) => setQuery(event.target.value) }))) : null,
1314
+ match === undefined ? null : h('p', { className: 'eng-filter-count', key: 'count', role: 'status',
1315
+ 'aria-live': 'polite' }, t('filterCount', { count: matched })),
1316
+ ...data.stores.map((store) => h(StoreSection, { key: store.id, store, cap: data.cap, canOpen, open, match,
1317
+ kind: shown, now: state.at, t })),
1318
+ data.more ? h('p', { className: 'eng-note', key: 'more' }, t('more')) : null,
1319
+ ]
1320
+ }
1321
+ return h('div', { className: 'eng-memory' },
1322
+ h(Hero, { data, at: state.at, refresh: () => { setStatus(undefined); load() }, t }),
1323
+ data === undefined ? null : h(Caveats, { data, t }),
1324
+ status ? h('div', { className: 'eng-banner', 'data-tone': status.tone, role: 'status' }, status.text) : null,
1325
+ data !== undefined && !canOpen && data.stores.length > 0 ? h('p', { className: 'eng-note' }, t('openUnavailable')) : null,
1326
+ body,
1327
+ h(HowTo, { open: data !== undefined && data.pinned !== 'relative' && data.more !== true &&
1328
+ !(data.unreadable > 0) && !data.stores.some((store) => hasMemory(store) || readInPart(store)), t }),
1329
+ h(Feedback, { t }))
1330
+ }
1331
+
1332
+ /** The sidebar entry's icon: the logo, [[ ]] around a cursor, drawn in the row's own colour
1333
+ * (so it follows dsh's light and dark themes) at the size it asks for. */
1334
+ function MemoryIcon({ size }) {
1335
+ return h('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
1336
+ strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
1337
+ h('path', { d: 'M5.1 3.5H2.5v17h2.6M9.2 3.5H6.6v17h2.6' }),
1338
+ h('path', { d: 'M18.9 3.5h2.6v17h-2.6M14.8 3.5h2.6v17h-2.6' }),
1339
+ h('rect', { x: 10.4, y: 7, width: 3.2, height: 10, rx: 1, fill: 'currentColor', stroke: 'none' }))
1340
+ }
1341
+
1342
+ return {
1343
+ inject: ['slots', 'locale'],
1344
+ apply(ctx) {
1345
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-engramory: dictionaries')
1346
+ ctx.effect(() => {
1347
+ const tag = document.createElement('style')
1348
+ tag.dataset.plugin = 'dsh-engramory'
1349
+ tag.dataset.pluginCss = 'dsh-engramory/settings.css'
1350
+ tag.textContent = CSS
1351
+ document.head.appendChild(tag)
1352
+ return () => tag.remove()
1353
+ }, 'dsh-engramory: styles')
1354
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1355
+ name: 'plugins.bundle.config',
1356
+ key: PACKAGE,
1357
+ locale: NS,
1358
+ }, SettingsPage))
1359
+ const t = ctx.locale.bind(NS)
1360
+ ctx.slots.inject('main', () => ctx.slots.register({
1361
+ name: 'main',
1362
+ key: PANEL,
1363
+ locale: NS,
1364
+ }, MemoryPage))
1365
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1366
+ name: 'sidebar.panellist',
1367
+ id: PANEL,
1368
+ // after dsh's own entries (Plugins 0, Automations 10)
1369
+ order: 20,
1370
+ locale: NS,
1371
+ label: () => t('panel'),
1372
+ }, MemoryIcon))
1373
+ },
1374
+ }
1375
+ },
1376
+ })