dsh-instruction-memory 1.6.2 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -155,6 +155,8 @@ window.__ModuleLoader__.load({
155
155
  border:1px dashed var(--dsw-alias-border-l2,rgba(0,0,0,.18)); color:var(--dsw-alias-label-secondary,#8a9099); }
156
156
  .im-err { font-size:12px; color:var(--dsw-alias-state-error-primary,#d94838); }
157
157
  .im-ok { font-size:12px; color:var(--dsw-alias-state-success-primary,#18a058); }
158
+ .im-confirm { border:1px solid var(--dsw-alias-border-l2,#d9dde3); border-radius:8px; padding:8px 10px; margin:8px 0; background:var(--dsw-alias-bg-l2,#f5f6f8); }
159
+ .im-confirm-text { font-size:12px; line-height:1.5; margin-bottom:8px; }
158
160
  .im-warn { font-size:12px; color:var(--dsw-alias-state-warn-primary,#d97706); }
159
161
  .im-meta { font-size:11.5px; color:var(--dsw-alias-label-secondary,#8a9099); word-break:break-all; }
160
162
  .im-pre { margin:0; padding:12px 14px; border-radius:8px; font-size:11.5px; line-height:1.65;
@@ -273,7 +275,7 @@ window.__ModuleLoader__.load({
273
275
  'err.httpDetail': '宿主返回 HTTP {status}:{detail}',
274
276
  'err.timeout': '请求宿主超时(15 秒无响应)',
275
277
  'export.failed': '导出失败:宿主返回了无法识别的数据',
276
- 'import.confirm': '导入会把文件里的配置集、条目与用户形象并入当前记忆:现有内容不会被删除,但你当前的排列会被整体改写。确定继续?',
278
+ 'import.confirm': '导入会把文件里的配置集、条目与用户形象并入当前记忆:现有内容不会被删除,但你当前的排列会被整体改写。注意导入的条目会保留其「触发词」与「适用情形」——一旦命中,该条目会在下一次注入中变成「本轮强制」。确定继续?',
277
279
  'import.notJson': '导入文件不是有效的 JSON({detail})',
278
280
  'import.tooLarge': '文件约 {size} MB,远超本插件可导入的规模(约 {limit} MB 以内)。请确认选择的是「导出」生成的 JSON 文件。',
279
281
  'editor.new': '新增指令',
@@ -299,7 +301,8 @@ window.__ModuleLoader__.load({
299
301
  'editor.needTitleOrContent': '请至少填写标题或指令内容',
300
302
  'editor.conflictOverwrite': '这条记忆刚被其他窗口或进程修改过。继续保存会用你当前的编辑内容覆盖对方的修改,确定要继续吗?',
301
303
  'editor.confirmDiscard': '当前编辑内容尚未保存,确定放弃这些修改吗?',
302
- 'confirm.unavailable': '当前环境无法弹出确认对话框,操作已取消,未做任何改动。',
304
+ 'confirm.yes': '确认',
305
+ 'confirm.no': '取消',
303
306
  'body.expand': '展开全部',
304
307
  'body.collapse': '收起',
305
308
  'budget.label': '注入字数上限(字符)',
@@ -319,6 +322,7 @@ window.__ModuleLoader__.load({
319
322
  'tags.label': '标签(可选,仅用于在本页分组与筛选,不会注入提示词)',
320
323
  'tags.placeholder': '输入标签后回车,逗号分隔多个,例如:代码规范',
321
324
  'tags.hint': '每条最多 {max} 个标签,单个不超过 {len} 字符',
325
+ 'triggers.hint': '每条最多 {max} 个触发词,单个不超过 {len} 字符;用户消息里出现任一触发词时,该条目在下一次注入中临时提升为「本轮强制」',
322
326
  'tags.remove': '移除标签 {tag}',
323
327
  'tags.duplicate': '已有同名标签',
324
328
  'tags.full': '每条最多 {max} 个标签',
@@ -368,8 +372,10 @@ window.__ModuleLoader__.load({
368
372
  'profiles.omitted': '本轮未包含',
369
373
  'profiles.omittedTitle': '这张形象因注入字数上限未进入本轮提示',
370
374
  'export.saved': '已请求保存。若保存框被取消、或下载被浏览器/系统拦下,文件不会出现——请重试,或改用下面的「完整 JSON」',
371
- 'export.savedToApp': '已交给 DSH Go 保存:在系统分享面板里选「保存到文件」即可',
372
375
  'export.fallbackHint': '当前环境无法触发文件下载,完整 JSON 已放在下面:全选复制后自行保存',
376
+ 'export.androidHint': '已把完整 JSON 放在下方(含 {sets} 个配置集、{entries} 条指令、{profiles} 个形象):手机端无法触发文件下载,请全选复制后自行保存。',
377
+ 'export.bridgeHint': '已向 DSH Go 的岛通道发送 {chunks} 条消息(含 {sets} 个配置集、{entries} 条指令、{profiles} 个形象)。注意:当前 App 版本可能没有「保存为文件」的处理,面板无法确认文件是否落地——若系统分享面板没有出现或没有保存成功,请用下面的完整 JSON。',
378
+ 'export.desktopHint': '桌面端:已尝试用浏览器下载通道保存,但宿主的下载处理只接管自身标记的链接,插件无法确认文件是否落地。下面的「完整 JSON」是保底通道——若下载目录里没有文件,请全选复制后自行保存。',
373
379
  'export.fallbackClose': '关闭',
374
380
  'import.webviewHint': 'Android / WebView 上若文件选择器不弹出,请改用「源码模式」粘贴 JSON',
375
381
  'sse.down': '实时更新已断开(连续重试仍失败),数据可能是旧的:请点「重新载入」',
@@ -399,6 +405,7 @@ window.__ModuleLoader__.load({
399
405
  'entry.enabled': '启用',
400
406
  'entry.edit': '编辑',
401
407
  'entry.delete': '删除',
408
+ 'entry.deleteAria': '删除指令「{title}」',
402
409
  'entry.untitled': '未命名指令',
403
410
  'entry.confirmDelete': '确定删除「{title}」?删除后无法恢复。',
404
411
  'entry.when': '适用情形:{when}',
@@ -436,6 +443,7 @@ window.__ModuleLoader__.load({
436
443
  'diag.copied': '诊断信息已复制到剪贴板',
437
444
  'diag.copyManual': '自动复制不可用;请手动全选复制下方文本。',
438
445
  'diag.hostWarn': '安全提示:设置路由当前绑定在非回环地址({host}),同一网络内的设备可以无鉴权访问此页面,请勿在不可信网络暴露;如需对外发布,请阅读 README 的「经反向代理对外发布」。',
446
+ 'diag.writeRefused': '写操作已停用:当前 profile 没有宿主的 connection 会话鉴权门。没有该门时,插件无法区分「设置页发出的请求」与「本机任意进程伪造的请求」,因此保存、导入、删除等修改一律返回 503(读取不受影响)。请让宿主提供 connection 服务;单用户设备可用环境变量 DSH_INSTRUCTION_MEMORY_ALLOW_UNGUARDED_WRITES=1 显式恢复(重启后生效)。',
439
447
  'diag.hostWarnFence': '安全提示:设置路由当前绑定在非回环地址({host}),但宿主鉴权门已挂载——访问仍需登录 DSH 后的浏览器会话,未登录请求会被 401/403 拒绝;仍建议只在可信网络暴露。',
440
448
  'diag.hostWarnTrusted': '安全提示:设置路由绑定在非回环地址({host}),且宿主没有发布鉴权服务;当前唯一放行条件是你配置的 {count} 个可信主机名——那只放宽主机名校验,不提供任何身份认证。请仅在可信网络暴露,或改用隧道方案。',
441
449
  'diag.groupStorage': '存储',
@@ -465,6 +473,7 @@ window.__ModuleLoader__.load({
465
473
  'diag.issueSection': '注入错误',
466
474
  // ---- 反馈邮件 ----
467
475
  'feedback.section': '反馈',
476
+ 'feedback.mobileUnavailable': '手机上无法发送反馈:该功能需要宿主进程带 SMTP 配置启动,而 DSH Go 的 App 内进程不继承外部环境变量。请改用桌面版反馈,或到插件仓库提交 issue。',
468
477
  'feedback.show': '反馈',
469
478
  'feedback.hide': '收起反馈',
470
479
  'feedback.intro': '遇到问题或有功能建议?填写下面的表单,通过邮件发送给插件维护者。',
@@ -576,7 +585,7 @@ window.__ModuleLoader__.load({
576
585
  'err.httpDetail': 'Host returned HTTP {status}: {detail}',
577
586
  'err.timeout': 'Host request timed out (no response for 15 s)',
578
587
  'export.failed': 'Export failed: the host returned unrecognized data',
579
- 'import.confirm': 'Import merges the file’s sets, entries and personas into the current memory: nothing is deleted, but your current arrangement is rewritten. Continue?',
588
+ 'import.confirm': 'Import merges the file’s sets, entries and personas into the current memory: nothing is deleted, but your current arrangement is rewritten. Imported entries keep their trigger words and conditions — once one matches, that entry becomes 本轮强制 on the next injection. Continue?',
580
589
  'import.notJson': 'The import file is not valid JSON ({detail})',
581
590
  'import.tooLarge': 'This file is about {size} MB, far beyond what this plugin can import (keep it within about {limit} MB). Make sure you selected a JSON file produced by Export.',
582
591
  'editor.new': 'New instruction',
@@ -602,7 +611,8 @@ window.__ModuleLoader__.load({
602
611
  'editor.needTitleOrContent': 'Fill in at least a title or the instruction content',
603
612
  'editor.conflictOverwrite': 'Another window or process just changed this entry. Saving now replaces their edit with yours. Continue?',
604
613
  'editor.confirmDiscard': 'The draft has unsaved changes. Discard them?',
605
- 'confirm.unavailable': 'This shell cannot show a confirmation dialog, so the action was cancelled and nothing changed.',
614
+ 'confirm.yes': 'Confirm',
615
+ 'confirm.no': 'Cancel',
606
616
  'body.expand': 'Show all',
607
617
  'body.collapse': 'Show less',
608
618
  'budget.label': 'Injection size limit (characters)',
@@ -622,6 +632,7 @@ window.__ModuleLoader__.load({
622
632
  'tags.label': 'Tags (optional; used only for grouping/filtering on this page, never injected)',
623
633
  'tags.placeholder': 'Type a tag and press Enter; separate several with commas, e.g. code-style',
624
634
  'tags.hint': 'Up to {max} tags per entry, each at most {len} characters',
635
+ 'triggers.hint': 'Up to {max} trigger words per entry, each at most {len} characters; when a user message contains one, the entry is promoted to 本轮强制 for the next injection',
625
636
  'tags.remove': 'Remove tag {tag}',
626
637
  'tags.duplicate': 'This tag already exists',
627
638
  'tags.full': 'Up to {max} tags per entry',
@@ -671,8 +682,10 @@ window.__ModuleLoader__.load({
671
682
  'profiles.omitted': 'Not in this turn',
672
683
  'profiles.omittedTitle': 'This persona was dropped by the injection limit and did not reach this turn',
673
684
  'export.saved': 'Save requested. If you cancelled the dialog or the download was blocked, no file is written — retry, or use the full JSON below',
674
- 'export.savedToApp': 'Handed to DSH Go — pick “Save to Files” in the system share sheet',
675
685
  'export.fallbackHint': 'This environment cannot start a file download; the full JSON is below — select all and copy it',
686
+ 'export.androidHint': 'The full JSON is below ({sets} sets, {entries} entries, {profiles} personas). This surface cannot start a file download — select all and copy it.',
687
+ 'export.bridgeHint': 'Sent {chunks} message(s) to the DSH Go island channel ({sets} sets, {entries} entries, {profiles} personas). Note: this app build may have no "save as file" handler, so the panel cannot confirm a file landed — if no share sheet appeared or nothing was saved, use the full JSON below.',
688
+ 'export.desktopHint': 'Desktop: the browser download path was attempted, but the host only claims its own marked links, so the plugin cannot confirm a file landed. The full JSON below is the guaranteed route — if nothing appeared in your downloads, copy it from there.',
676
689
  'export.fallbackClose': 'Close',
677
690
  'import.webviewHint': 'On Android / WebView, if the file picker does not open, paste the JSON into “Source mode” instead',
678
691
  'sse.down': 'Live updates stopped (retries kept failing) and the data may be stale — click “Reload”',
@@ -702,6 +715,7 @@ window.__ModuleLoader__.load({
702
715
  'entry.enabled': 'Enabled',
703
716
  'entry.edit': 'Edit',
704
717
  'entry.delete': 'Delete',
718
+ 'entry.deleteAria': 'Delete instruction “{title}”',
705
719
  'entry.untitled': 'Untitled instruction',
706
720
  'entry.confirmDelete': 'Delete “{title}”? This cannot be undone.',
707
721
  'entry.when': 'Applies when: {when}',
@@ -739,6 +753,7 @@ window.__ModuleLoader__.load({
739
753
  'diag.copied': 'Diagnostics copied to the clipboard',
740
754
  'diag.copyManual': 'Automatic copy is unavailable; select and copy the text below manually.',
741
755
  'diag.hostWarn': 'Security notice: the settings route is bound to a non-loopback address ({host}); other devices on the same network can reach this page without authentication. Do not expose it on an untrusted network — for public deployments read “Publishing behind a reverse proxy” in the README.',
756
+ 'diag.writeRefused': 'Writes are disabled: this profile has no host `connection` authentication fence. Without it the plugin cannot tell "the settings page sent this" from "any local process forged this", so saves, imports and deletes all answer 503 (reads still work). Let the host provide the connection service, or — on a single-user device — set DSH_INSTRUCTION_MEMORY_ALLOW_UNGUARDED_WRITES=1 and restart.',
742
757
  'diag.hostWarnFence': 'Security notice: the settings route is bound to a non-loopback address ({host}), but the host authentication fence is attached — access still requires a signed-in DSH browser session, and unauthenticated requests are refused with 401/403. Keep it on a trusted network anyway.',
743
758
  'diag.hostWarnTrusted': 'Security notice: the settings route is bound to a non-loopback address ({host}) and the host publishes no authentication service; the only thing letting requests in is your {count} trusted hostname(s) — that relaxes a hostname check, it does not authenticate anyone. Keep it on a trusted network or use a tunnel.',
744
759
  'diag.groupStorage': 'Storage',
@@ -768,6 +783,7 @@ window.__ModuleLoader__.load({
768
783
  'diag.issueSection': 'Injection error',
769
784
  // ---- feedback mail ----
770
785
  'feedback.section': 'Feedback',
786
+ 'feedback.mobileUnavailable': 'Feedback cannot be sent from the phone: it needs SMTP configuration in the host process, and the DSH Go shell clears the environment. Use the desktop build, or open an issue in the plugin repository.',
771
787
  'feedback.show': 'Feedback',
772
788
  'feedback.hide': 'Hide feedback',
773
789
  'feedback.intro': 'Found a problem or have a suggestion? Send it to the plugin maintainer by email with the form below.',
@@ -995,6 +1011,16 @@ window.__ModuleLoader__.load({
995
1011
  // keep the editor usable against an older Host that predates them.
996
1012
  const MAX_TAGS = 8
997
1013
  const MAX_TAG_LEN = 24
1014
+ /**
1015
+ * v1.6.0's trigger list had its own ceilings in the host
1016
+ * (`MAX_TRIGGERS`/`MAX_TRIGGER_LENGTH`). They equal the tag ceilings today,
1017
+ * but that was a numerical coincidence, not a contract: the editor used to
1018
+ * slice at a hard-coded 8 and reuse the tag caps, so changing either host
1019
+ * limit would leave the panel silently disagreeing with the loader. These
1020
+ * two defaults only stand in for a host that predates the published limits.
1021
+ */
1022
+ const MAX_TRIGGERS = 8
1023
+ const MAX_TRIGGER_LEN = 24
998
1024
  const DEFAULT_MAX_TITLE = 120
999
1025
  const DEFAULT_MAX_CONTENT = 6000
1000
1026
  const DEFAULT_MAX_WHEN = 200
@@ -1019,9 +1045,22 @@ window.__ModuleLoader__.load({
1019
1045
  maxWhen: pick('maxWhen', DEFAULT_MAX_WHEN),
1020
1046
  maxTags: pick('maxTagsPerEntry', MAX_TAGS),
1021
1047
  maxTagLength: pick('maxTagLength', MAX_TAG_LEN),
1048
+ maxTriggers: pick('maxTriggers', MAX_TRIGGERS),
1049
+ maxTriggerLength: pick('maxTriggerLength', MAX_TRIGGER_LEN),
1022
1050
  }
1023
1051
  }
1024
1052
 
1053
+ /**
1054
+ * The same ceilings, selected for the box being rendered: tags and trigger
1055
+ * words share the parsing rules but not the limits.
1056
+ */
1057
+ function capsFor(limits, kind) {
1058
+ const caps = fieldLimitsOf(limits)
1059
+ return kind === 'triggers'
1060
+ ? { ...caps, maxTags: caps.maxTriggers, maxTagLength: caps.maxTriggerLength }
1061
+ : caps
1062
+ }
1063
+
1025
1064
  /**
1026
1065
  * Parse free text typed into the tag box into normalised tag candidates.
1027
1066
  * Tags are split on commas (ASCII/full-width), semicolons and newlines —
@@ -1030,9 +1069,9 @@ window.__ModuleLoader__.load({
1030
1069
  * the count cap. Both caps come from the snapshot when supplied. Pinned as
1031
1070
  * a pure export.
1032
1071
  */
1033
- function parseTagInput(text, limits) {
1072
+ function parseTagInput(text, limits, kind) {
1034
1073
  if (typeof text !== 'string') return []
1035
- const caps = fieldLimitsOf(limits)
1074
+ const caps = capsFor(limits, kind)
1036
1075
  const out = []
1037
1076
  const seen = new Set()
1038
1077
  for (const piece of text.split(/[,,;;\n\r]+/)) {
@@ -1091,7 +1130,7 @@ window.__ModuleLoader__.load({
1091
1130
  content: entry.content,
1092
1131
  mode: entry.mode,
1093
1132
  when: entry.when,
1094
- triggers: Array.isArray(entry.triggers) ? entry.triggers.slice(0, 8) : [],
1133
+ triggers: Array.isArray(entry.triggers) ? entry.triggers.slice(0, MAX_TRIGGERS) : [],
1095
1134
  priority: entry.priority,
1096
1135
  enabled: entry.enabled,
1097
1136
  tags: Array.isArray(entry.tags) ? entry.tags.slice() : [],
@@ -1153,6 +1192,169 @@ window.__ModuleLoader__.load({
1153
1192
  const CONFIRM_NO = 'no'
1154
1193
  const CONFIRM_UNAVAILABLE = 'unavailable'
1155
1194
 
1195
+ /**
1196
+ * DSH Go island chunking, in BYTES (1.6.4).
1197
+ *
1198
+ * The bridge's ceiling is `IslandMessageLimits.maxBytes` = 16 KB, counted by
1199
+ * the shell as `raw.length` — UTF-16 units of the DECODED JSON string
1200
+ * (`island_messages.dart`). Two earlier budgets were wrong for that:
1201
+ * 6000 JS code units (a 6000-character CJK chunk serialised to 18098 bytes)
1202
+ * and then 12 KiB of raw UTF-8 (1.6.4), which ignored JSON escaping: `"` and
1203
+ * `\` cost two units each and a control character costs six, so a quote- or
1204
+ * backslash-heavy chunk (code, JSON, Windows paths) measured 24678 and a
1205
+ * control-character payload 73830 — both well past 16384. `splitForBridge`
1206
+ * below charges the ESCAPED cost per code point instead.
1207
+ */
1208
+ const ISLAND_CHUNK_BYTES = 12 * 1024
1209
+ /** The shell's ceiling, in UTF-16 units of the serialised frame. */
1210
+ const ISLAND_FRAME_LIMIT = 16 * 1024
1211
+
1212
+ /** UTF-8 length of one code point (no Buffer/TextEncoder dependency). */
1213
+ function utf8SizeOf(ch) {
1214
+ const code = typeof ch.codePointAt === 'function' ? ch.codePointAt(0) : 0
1215
+ if (code <= 0x7f) return 1
1216
+ if (code <= 0x7ff) return 2
1217
+ if (code <= 0xffff) return 3
1218
+ return 4
1219
+ }
1220
+
1221
+ /**
1222
+ * UTF-16 units one code point costs INSIDE a JSON string: `"` and `\` become
1223
+ * two-unit escapes, a C0 control becomes a six-unit `\u00XX`, a surrogate
1224
+ * pair is two units, everything else one. Exactly what `JSON.stringify`
1225
+ * does, without building the string per character.
1226
+ */
1227
+ function islandJsonCost(ch) {
1228
+ const code = typeof ch.codePointAt === 'function' ? ch.codePointAt(0) : 0
1229
+ if (code === 0x22 || code === 0x5c) return 2
1230
+ if (code < 0x20) return 6
1231
+ if (code > 0xffff) return 2
1232
+ return 1
1233
+ }
1234
+
1235
+ /**
1236
+ * Split `text` so that every FRAME — the JSON envelope plus the chunk, as
1237
+ * `JSON.stringify` would produce it — stays inside the shell's 16 KiB
1238
+ * ceiling, never cutting a surrogate pair. `id`/`name` are passed so the
1239
+ * envelope's own cost is charged against the budget; the fixed slack covers
1240
+ * `last` flipping and the chunking of the id (which is ASCII by design).
1241
+ */
1242
+ function splitForBridge(text, name, id) {
1243
+ if (typeof text !== 'string' || text === '') return []
1244
+ const envelope = JSON.stringify({
1245
+ t: 'save', id: typeof id === 'string' ? id : 'im-xxxxxxxx', name: typeof name === 'string' ? name : '', data: '', last: false,
1246
+ }).length
1247
+ const budget = Math.max(256, ISLAND_FRAME_LIMIT - envelope - 64)
1248
+ const out = []
1249
+ let current = ''
1250
+ let units = 0
1251
+ for (const ch of text) {
1252
+ const cost = islandJsonCost(ch)
1253
+ if (units + cost > budget && current !== '') {
1254
+ out.push(current)
1255
+ current = ''
1256
+ units = 0
1257
+ }
1258
+ current += ch
1259
+ units += cost
1260
+ }
1261
+ if (current !== '') out.push(current)
1262
+ return out
1263
+ }
1264
+
1265
+ /**
1266
+ * Split `text` so that every piece fits `maxBytes` of UTF-8, never cutting
1267
+ * a surrogate pair in half (iteration is by code point, so an emoji or a
1268
+ * CJK ext-B character can never be torn). An empty string yields no pieces.
1269
+ */
1270
+ function splitByBytes(text, maxBytes) {
1271
+ if (typeof text !== 'string' || text === '') return []
1272
+ const limit = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 256
1273
+ ? Math.floor(maxBytes)
1274
+ : ISLAND_CHUNK_BYTES
1275
+ const out = []
1276
+ let current = ''
1277
+ let bytes = 0
1278
+ for (const ch of text) {
1279
+ const size = utf8SizeOf(ch)
1280
+ if (bytes + size > limit && current !== '') {
1281
+ out.push(current)
1282
+ current = ''
1283
+ bytes = 0
1284
+ }
1285
+ current += ch
1286
+ bytes += size
1287
+ }
1288
+ if (current !== '') out.push(current)
1289
+ return out
1290
+ }
1291
+
1292
+ /**
1293
+ * UA half of the Android/WebView detection, at module scope so the dialog
1294
+ * probe below can use it. `isAndroidWebView()` (inside the panel) keeps the
1295
+ * same predicate; 1.6.4 also treats the presence of the island bridge as a
1296
+ * positive signal, because a custom UA would otherwise look like a desktop
1297
+ * browser and take the blob-download branch that can never work there.
1298
+ */
1299
+ function looksLikeAndroidWebView() {
1300
+ try {
1301
+ const ua = typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string'
1302
+ ? navigator.userAgent
1303
+ : ''
1304
+ return /;\s*wv\)/i.test(ua) || (/Android/i.test(ua) && !/Chrome\/\d+/i.test(ua))
1305
+ } catch {
1306
+ return false
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * S3 (1.6.5): the island bridge counts only when it can actually take a
1312
+ * message. `window.DshGoIsland = {}` — set by any script, or by another
1313
+ * plugin sharing this settings page — used to flip the whole mobile branch
1314
+ * (no blob export, feedback form replaced by a note, confirmations pushed
1315
+ * onto the arm-leak route), while `sendToAppBridge` itself required
1316
+ * `postMessage`. Both judgments agree now.
1317
+ */
1318
+ function hasIslandBridge(target) {
1319
+ try {
1320
+ const current = target === undefined
1321
+ ? (typeof window !== 'undefined' ? window : undefined)
1322
+ : target
1323
+ return current !== undefined && current !== null
1324
+ && current.DshGoIsland !== undefined && current.DshGoIsland !== null
1325
+ && typeof current.DshGoIsland.postMessage === 'function'
1326
+ } catch {
1327
+ return false
1328
+ }
1329
+ }
1330
+
1331
+ /**
1332
+ * Can `window.confirm` be believed on this surface?
1333
+ *
1334
+ * DSH Go's WebView sets a NavigationDelegate and `DshGoIsland`, and NO
1335
+ * `WebChromeClient.onJsConfirm` (`island_handle.dart`). A confirm() there
1336
+ * does not throw and does not show anything: it returns `false`
1337
+ * immediately. `askConfirm` used to read that as "the user pressed
1338
+ * Cancel", so eight destructive actions — entry delete, bulk delete,
1339
+ * persona delete, set delete, history restore/delete, whole-store restore
1340
+ * and import — became silent no-ops on the phone. Since 1.6.5 the callers
1341
+ * park the question in the panel instead of relying on a dialog at all, so
1342
+ * there is no "unavailable" dead end left to explain.
1343
+ *
1344
+ * Electron already had a sibling problem with `prompt()` (exists, throws);
1345
+ * the WebView shape is the same class, one layer quieter.
1346
+ */
1347
+ function confirmDialogsAreTrustworthy() {
1348
+ try {
1349
+ if (typeof window === 'undefined') return false
1350
+ if (looksLikeAndroidWebView()) return false
1351
+ if (hasIslandBridge()) return false
1352
+ return typeof window.confirm === 'function'
1353
+ } catch {
1354
+ return false
1355
+ }
1356
+ }
1357
+
1156
1358
  /**
1157
1359
  * The single gate every confirmation goes through.
1158
1360
  *
@@ -1184,6 +1386,15 @@ window.__ModuleLoader__.load({
1184
1386
  if (typeof window === 'undefined' || typeof window.confirm !== 'function') {
1185
1387
  return fallback ? CONFIRM_YES : CONFIRM_UNAVAILABLE
1186
1388
  }
1389
+ // A dialog that CANNOT be shown is not a "no" (1.6.4). On DSH Go the
1390
+ // function exists and answers `false` without ever rendering anything;
1391
+ // treating that as a cancel made every destructive action a silent
1392
+ // no-op. The callers now route CONFIRM_UNAVAILABLE to an in-panel
1393
+ // confirmation, so the action still happens — after the user actually
1394
+ // sees what it is.
1395
+ if (!confirmDialogsAreTrustworthy()) {
1396
+ return fallback ? CONFIRM_YES : CONFIRM_UNAVAILABLE
1397
+ }
1187
1398
  try {
1188
1399
  return window.confirm(message) === true ? CONFIRM_YES : CONFIRM_NO
1189
1400
  } catch {
@@ -1822,6 +2033,7 @@ window.__ModuleLoader__.load({
1822
2033
  inputId: 'im-entry-triggers',
1823
2034
  tags: Array.isArray(draft.triggers) ? draft.triggers : [],
1824
2035
  limits: props.limits,
2036
+ kind: 'triggers',
1825
2037
  disabled: props.busy,
1826
2038
  onChange: (next) => set({ triggers: next }),
1827
2039
  })))
@@ -1853,7 +2065,8 @@ window.__ModuleLoader__.load({
1853
2065
  function TagInput(props) {
1854
2066
  const [text, setText] = React.useState('')
1855
2067
  const tags = Array.isArray(props.tags) ? props.tags : []
1856
- const caps = fieldLimitsOf(props.limits)
2068
+ const kind = props.kind === 'triggers' ? 'triggers' : 'tags'
2069
+ const caps = capsFor(props.limits, kind)
1857
2070
  const merge = (pieces) => {
1858
2071
  const merged = []
1859
2072
  for (const tag of [...tags, ...pieces]) {
@@ -1862,7 +2075,7 @@ window.__ModuleLoader__.load({
1862
2075
  props.onChange(merged.slice(0, caps.maxTags))
1863
2076
  }
1864
2077
  const commit = () => {
1865
- const parsed = parseTagInput(text, props.limits)
2078
+ const parsed = parseTagInput(text, props.limits, kind)
1866
2079
  if (parsed.length > 0) merge(parsed)
1867
2080
  setText('')
1868
2081
  }
@@ -1897,7 +2110,7 @@ window.__ModuleLoader__.load({
1897
2110
  // v is the input's full new value (it already contains what was
1898
2111
  // typed before the separator) — do NOT prepend `text`, that
1899
2112
  // duplicated it ("b" + "b," -> "bb").
1900
- const parsed = parseTagInput(v, props.limits)
2113
+ const parsed = parseTagInput(v, props.limits, kind)
1901
2114
  if (parsed.length > 0) merge(parsed)
1902
2115
  setText('')
1903
2116
  } else {
@@ -1914,7 +2127,10 @@ window.__ModuleLoader__.load({
1914
2127
  },
1915
2128
  onBlur: commit,
1916
2129
  }),
1917
- h('div', { className: 'im-meta' }, t('tags.hint', { max: caps.maxTags, len: caps.maxTagLength })))
2130
+ h('div', { className: 'im-meta' },
2131
+ kind === 'triggers'
2132
+ ? t('triggers.hint', { max: caps.maxTags, len: caps.maxTagLength })
2133
+ : t('tags.hint', { max: caps.maxTags, len: caps.maxTagLength })))
1918
2134
  }
1919
2135
 
1920
2136
  /**
@@ -2063,6 +2279,79 @@ window.__ModuleLoader__.load({
2063
2279
  const [diagFallback, setDiagFallback] = React.useState(null)
2064
2280
  /** Export JSON rendered in-panel when the runtime has no download path. */
2065
2281
  const [exportFallback, setExportFallback] = React.useState(null)
2282
+ /**
2283
+ * S4 (1.6.5): the rendered export holds the WHOLE store — every set and
2284
+ * every persona — and it used to stay on screen until the user closed it.
2285
+ * That put the full memory into the task-switcher thumbnail and any screen
2286
+ * share, and on Android ≤ 9 into a clipboard any app could read. It now
2287
+ * clears itself after a few minutes and on unmount; copying still works
2288
+ * immediately.
2289
+ */
2290
+ const EXPORT_FALLBACK_TTL_MS = 180000
2291
+ const exportFallbackTimerRef = React.useRef(null)
2292
+ const stageExportFallback = (text) => {
2293
+ setExportFallback(text)
2294
+ if (exportFallbackTimerRef.current !== null) clearTimeout(exportFallbackTimerRef.current)
2295
+ exportFallbackTimerRef.current = setTimeout(() => {
2296
+ exportFallbackTimerRef.current = null
2297
+ setExportFallback(null)
2298
+ }, EXPORT_FALLBACK_TTL_MS)
2299
+ }
2300
+ const clearExportFallback = () => {
2301
+ if (exportFallbackTimerRef.current !== null) {
2302
+ clearTimeout(exportFallbackTimerRef.current)
2303
+ exportFallbackTimerRef.current = null
2304
+ }
2305
+ setExportFallback(null)
2306
+ }
2307
+ React.useEffect(() => () => {
2308
+ if (exportFallbackTimerRef.current !== null) {
2309
+ clearTimeout(exportFallbackTimerRef.current)
2310
+ exportFallbackTimerRef.current = null
2311
+ }
2312
+ }, [])
2313
+ /**
2314
+ * A confirmation waiting for an in-panel answer (1.6.4).
2315
+ *
2316
+ * DSH Go's WebView cannot show `window.confirm` and answers `false`
2317
+ * instead, so every destructive action used to fall into "the user said
2318
+ * no" and do nothing at all — no delete, no import, no restore, and not
2319
+ * even the "this runtime has no dialog" hint. When the dialog is
2320
+ * untrustworthy the question is parked here and rendered as a row with
2321
+ * 【确认】/【取消】; the action keeps working, one tap later.
2322
+ */
2323
+ const [pendingConfirm, setPendingConfirm] = React.useState(null)
2324
+ /** R2 (1.6.5): one activation of the confirm button runs the action once. */
2325
+ const confirmFiringRef = React.useRef(false)
2326
+ /**
2327
+ * The single confirmation entry point (1.6.5 contract).
2328
+ *
2329
+ * It ALWAYS answers "the caller should stop": with a working dialog it runs
2330
+ * `action` itself; without one it parks the question and runs `action` when
2331
+ * the user confirms in the panel; on "no" it does nothing. There is no
2332
+ * path where the caller has to run the action as well, and no replay of a
2333
+ * handler — the 1.6.4 design ("return false means you continue, and the
2334
+ * closure is only used to replay the handler") is what made entry delete a
2335
+ * silent no-op on desktop and, later, what made a leftover approval leak
2336
+ * into the next action with the same wording.
2337
+ *
2338
+ * So every call site reads `if (confirmThen(message, action)) return` and
2339
+ * the action body exists in exactly one place.
2340
+ */
2341
+ const confirmThen = (message, action) => {
2342
+ const ask = askConfirm(message)
2343
+ if (ask === CONFIRM_YES) {
2344
+ void action()
2345
+ return true
2346
+ }
2347
+ if (ask === CONFIRM_UNAVAILABLE) {
2348
+ // A fresh question re-arms the one-shot firing guard (R2).
2349
+ confirmFiringRef.current = false
2350
+ setPendingConfirm({ message, action })
2351
+ return true
2352
+ }
2353
+ return true
2354
+ }
2066
2355
  /** True once the event stream has failed long enough to stop pretending. */
2067
2356
  const [liveDown, setLiveDown] = React.useState(false)
2068
2357
  // Feedback form: closed by default so the settings card stays compact.
@@ -2288,19 +2577,18 @@ window.__ModuleLoader__.load({
2288
2577
  setBatchTagText('')
2289
2578
  }
2290
2579
 
2291
- async function doBatch(op, value) {
2292
- const ids = liveSelected()
2580
+ async function doBatch(op, value, fixedIds) {
2581
+ // S2 (1.6.5): the in-panel confirmation replays this handler, so the
2582
+ // selection could change between the question and the answer ("delete
2583
+ // 3 entries" then deleting N). The parked action carries its own ids.
2584
+ const ids = Array.isArray(fixedIds) ? fixedIds : liveSelected()
2293
2585
  if (ids.length === 0) {
2294
2586
  setError(t('batch.noneSelected'))
2295
2587
  return
2296
2588
  }
2297
- if (op === 'delete') {
2298
- const ask = askConfirm(t('batch.confirmDelete', { count: ids.length }))
2299
- if (ask !== CONFIRM_YES) {
2300
- if (ask === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2301
- return
2302
- }
2303
- }
2589
+ // The delete confirmation lives at the CALLER (the batch toolbar), not
2590
+ // here: 1.6.5's contract runs the action from inside confirmThen, so a
2591
+ // confirm inside this function would ask again on the replay.
2304
2592
  const result = await send('batch', { op, ids, value, baseRev: revOf() })
2305
2593
  if (result !== null && result.ok === true && op === 'delete') {
2306
2594
  // Drop deleted ids from the selection; other ops keep it so several
@@ -2374,13 +2662,12 @@ window.__ModuleLoader__.load({
2374
2662
  setError('')
2375
2663
  }
2376
2664
 
2377
- function removeProfile(profile) {
2665
+ function removeProfile(profile, confirmed) {
2378
2666
  if (busy) return
2379
- const ask = askConfirm(t('profiles.confirmDelete', {
2380
- name: profile.name !== '' ? profile.name : t('profiles.untitled'),
2381
- }))
2382
- if (ask !== CONFIRM_YES) {
2383
- if (ask === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2667
+ if (confirmed !== true) {
2668
+ confirmThen(t('profiles.confirmDelete', {
2669
+ name: profile.name !== '' ? profile.name : t('profiles.untitled'),
2670
+ }), () => removeProfile(profile, true))
2384
2671
  return
2385
2672
  }
2386
2673
  void send('delete-profile', { id: profile.id, baseRev: revOf() })
@@ -2441,15 +2728,15 @@ window.__ModuleLoader__.load({
2441
2728
  })
2442
2729
  }
2443
2730
 
2444
- function removeSet(set) {
2731
+ function removeSet(set, confirmed) {
2445
2732
  if (busy) return
2446
2733
  if (set.active === true) {
2447
2734
  setError(t('sets.deleteActive'))
2448
2735
  return
2449
2736
  }
2450
- const askDeleteSet = askConfirm(t('sets.deleteConfirm', { name: set.name, entries: set.entries, profiles: set.profiles }))
2451
- if (askDeleteSet !== CONFIRM_YES) {
2452
- if (askDeleteSet === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2737
+ if (confirmed !== true) {
2738
+ confirmThen(t('sets.deleteConfirm', { name: set.name, entries: set.entries, profiles: set.profiles }),
2739
+ () => removeSet(set, true))
2453
2740
  return
2454
2741
  }
2455
2742
  void send('delete-set', { id: set.id, baseRev: revOf() })
@@ -2482,7 +2769,7 @@ window.__ModuleLoader__.load({
2482
2769
  if (next) void loadHistory()
2483
2770
  }
2484
2771
 
2485
- function rollbackTo(item) {
2772
+ function rollbackTo(item, confirmed) {
2486
2773
  if (busy) return
2487
2774
  // Restoring makes the Host read a whole file; a snapshot far larger
2488
2775
  // than any real store is refused BEFORE the user confirms an operation
@@ -2493,10 +2780,10 @@ window.__ModuleLoader__.load({
2493
2780
  setError(sizeVerdict.message)
2494
2781
  return
2495
2782
  }
2496
- const when = new Date(item.epoch).toLocaleString()
2497
- const ask = askConfirm(t('history.restoreConfirm', { time: when, rev: item.rev, name: item.name }))
2498
- if (ask !== CONFIRM_YES) {
2499
- if (ask === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2783
+ if (confirmed !== true) {
2784
+ const when = new Date(item.epoch).toLocaleString()
2785
+ confirmThen(t('history.restoreConfirm', { time: when, rev: item.rev, name: item.name }),
2786
+ () => rollbackTo(item, true))
2500
2787
  return
2501
2788
  }
2502
2789
  void send('history-restore', { name: item.name, baseRev: revOf() }).then((result) => {
@@ -2504,11 +2791,10 @@ window.__ModuleLoader__.load({
2504
2791
  })
2505
2792
  }
2506
2793
 
2507
- function removeSnapshot(item) {
2794
+ function removeSnapshot(item, confirmed) {
2508
2795
  if (busy) return
2509
- const askDeleteHistory = askConfirm(t('history.deleteConfirm'))
2510
- if (askDeleteHistory !== CONFIRM_YES) {
2511
- if (askDeleteHistory === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2796
+ if (confirmed !== true) {
2797
+ confirmThen(t('history.deleteConfirm'), () => removeSnapshot(item, true))
2512
2798
  return
2513
2799
  }
2514
2800
  void send('history-delete', { name: item.name }).then((result) => {
@@ -2680,7 +2966,7 @@ window.__ModuleLoader__.load({
2680
2966
 
2681
2967
  function adoptLegacy() {
2682
2968
  if (busy) return
2683
- void send('adopt-legacy', { baseRev: revOf() })
2969
+ void send('adopt-legacy', { baseRev: revOf(), confirm: true })
2684
2970
  }
2685
2971
 
2686
2972
  function dismissLegacy() {
@@ -2690,11 +2976,12 @@ window.__ModuleLoader__.load({
2690
2976
 
2691
2977
  // ---- F14 whole-store restore (the "replace" door import does not open) ----
2692
2978
 
2693
- async function handleRestoreFile(file) {
2979
+ async function handleRestoreFile(file, confirmed) {
2694
2980
  try {
2695
- const askRestore = askConfirm(t('restore.confirm'))
2696
- if (askRestore !== CONFIRM_YES) {
2697
- if (askRestore === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2981
+ // 1.6.5 contract: confirmThen runs the action itself, so the replay
2982
+ // carries `confirmed` to skip this block instead of re-asking.
2983
+ if (confirmed !== true) {
2984
+ confirmThen(t('restore.confirm'), () => handleRestoreFile(file, true))
2698
2985
  return
2699
2986
  }
2700
2987
  const text = typeof file.text === 'function'
@@ -2712,7 +2999,7 @@ window.__ModuleLoader__.load({
2712
2999
  setError(t('import.notJson', { detail: String(err && err.message ? err.message : err) }))
2713
3000
  return
2714
3001
  }
2715
- await send('restore-data', { payload, baseRev: revOf() })
3002
+ await send('restore-data', { payload, baseRev: revOf(), confirm: true })
2716
3003
  } catch (err) {
2717
3004
  setError(String(err && err.message ? err.message : err))
2718
3005
  }
@@ -2778,49 +3065,67 @@ window.__ModuleLoader__.load({
2778
3065
  */
2779
3066
  function isAndroidWebView() {
2780
3067
  try {
2781
- const ua = typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string'
2782
- ? navigator.userAgent
2783
- : ''
2784
- // `; wv)` is the canonical WebView marker; DSH Go's webview island may
2785
- // also report a stock Chromium UA, so fall back to "Android without a
2786
- // full browser brand".
2787
- return /;\s*wv\)/i.test(ua)
2788
- || (/Android/i.test(ua) && !/Chrome\/\d+/i.test(ua))
3068
+ // A6 (1.6.4): the bridge is a PROTOCOL-level signal, the UA is a
3069
+ // guess. The old predicate said "may report a stock Chromium UA" and
3070
+ // then relied on `Android && !Chrome/` — which a stock Chromium UA
3071
+ // fails. If the island bridge is present we are inside DSH Go,
3072
+ // whatever the UA claims; the UA check stays as the secondary hint
3073
+ // for the first paint, before the channel is injected.
3074
+ if (hasIslandBridge()) return true
3075
+ return looksLikeAndroidWebView()
2789
3076
  } catch {
2790
3077
  return false
2791
3078
  }
2792
3079
  }
2793
3080
 
2794
3081
  /**
2795
- * Hand `text` to the DSH Go island bridge, in chunks that fit its 16 KB
2796
- * message cap (`IslandMessageLimits.maxBytes`). The app reassembles them
2797
- * and opens the system share sheet — the only export path a WebView has,
2798
- * since it never hands a `blob:` to a download listener.
3082
+ * The Electron desktop shell.
2799
3083
  *
2800
- * Returns false when the page is not inside DSH Go (or the bridge is
2801
- * missing), which leaves the browser path untouched.
3084
+ * `dsh-app://` is the protocol the renderer is loaded from, so this is a
3085
+ * direct observation rather than a user-agent guess — until 1.6.3 the
3086
+ * panel had NO desktop branch at all: every export fell through to the
3087
+ * generic `blob:` download, while the host's `will-download` handler only
3088
+ * recognises `#dsh-download=` URLs and leaves the rest to Chromium's
3089
+ * default policy, which the page cannot observe. That is why the desktop
3090
+ * export now also offers the in-panel copy instead of claiming a file.
3091
+ */
3092
+ function isDesktopShell() {
3093
+ try {
3094
+ return typeof location !== 'undefined' && typeof location.protocol === 'string'
3095
+ && location.protocol === 'dsh-app:'
3096
+ } catch {
3097
+ return false
3098
+ }
3099
+ }
3100
+
3101
+ /**
3102
+ * Hand `text` to the DSH Go island bridge in UTF-8-byte-bounded chunks.
3103
+ *
3104
+ * `sent` means only "postMessage did not throw". The stock DSH Go build
3105
+ * has no `save` branch in `parseIslandMessage` (`island_messages.dart`:
3106
+ * an unknown `t` returns null and is dropped), so 1.6.4 no longer treats
3107
+ * this as "a file exists": the caller keeps the in-panel JSON on screen
3108
+ * and the notice says "requested", not "saved".
2802
3109
  */
2803
3110
  async function sendToAppBridge(text, name) {
2804
3111
  try {
2805
3112
  const bridge = typeof window !== 'undefined' ? window.DshGoIsland : undefined
2806
- if (bridge === undefined || bridge === null || typeof bridge.postMessage !== 'function') return false
3113
+ if (bridge === undefined || bridge === null || typeof bridge.postMessage !== 'function') {
3114
+ return { sent: false, chunks: 0 }
3115
+ }
2807
3116
  const id = 'im-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
2808
- const CHUNK = 6000
2809
- let i = 0
2810
- while (i < text.length) {
2811
- let end = Math.min(text.length, i + CHUNK)
2812
- // Never split a surrogate pair across two messages: each one is its
2813
- // own JSON document and a lone surrogate would not survive it.
2814
- const code = text.charCodeAt(end - 1)
2815
- if (end < text.length && code >= 0xd800 && code <= 0xdbff) end += 1
3117
+ // R3 (1.6.5): budget the ESCAPED frame, not the raw bytes — the shell
3118
+ // counts UTF-16 units of the decoded JSON, and `"`/`\`/control chars
3119
+ // inflate well past any raw-byte budget.
3120
+ const chunks = splitForBridge(text, name, id)
3121
+ for (let i = 0; i < chunks.length; i += 1) {
2816
3122
  bridge.postMessage(JSON.stringify({
2817
- t: 'save', id, name, data: text.slice(i, end), last: end >= text.length,
3123
+ t: 'save', id, name, data: chunks[i], last: i === chunks.length - 1,
2818
3124
  }))
2819
- i = end
2820
3125
  }
2821
- return true
3126
+ return { sent: true, chunks: chunks.length }
2822
3127
  } catch {
2823
- return false
3128
+ return { sent: false, chunks: 0 }
2824
3129
  }
2825
3130
  }
2826
3131
 
@@ -2833,10 +3138,23 @@ window.__ModuleLoader__.load({
2833
3138
  }
2834
3139
  const text = JSON.stringify(result.export, null, 2) + '\n'
2835
3140
  const fileName = 'dsh-instruction-memory-' + new Date().toISOString().slice(0, 10) + '.json'
2836
- // Inside DSH Go the app can actually write the file; prefer that over
2837
- // both the download link and the in-panel copy.
2838
- if (await sendToAppBridge(text, fileName)) {
2839
- setNotice(t('export.savedToApp'))
3141
+ // A5 (1.6.4): an export carries EVERY set and every persona, while the
3142
+ // panel itself deliberately shows only the active set. Say what left
3143
+ // the machine instead of implying "your current view".
3144
+ const exported = result.export.data !== null && typeof result.export.data === 'object'
3145
+ ? result.export.data
3146
+ : {}
3147
+ const counts = {
3148
+ sets: Array.isArray(exported.sets) ? exported.sets.length : 1,
3149
+ entries: Array.isArray(exported.entries) ? exported.entries.length : 0,
3150
+ profiles: Array.isArray(exported.profiles) ? exported.profiles.length : 0,
3151
+ }
3152
+ // Inside DSH Go the app CAN write the file — but only if the shell
3153
+ // implements the `save` message, which the stock build does not.
3154
+ const bridge = await sendToAppBridge(text, fileName)
3155
+ if (bridge.sent) {
3156
+ stageExportFallback(text)
3157
+ setNotice(t('export.bridgeHint', { chunks: bridge.chunks, sets: counts.sets, entries: counts.entries, profiles: counts.profiles }))
2840
3158
  return
2841
3159
  }
2842
3160
  /**
@@ -2848,8 +3166,8 @@ window.__ModuleLoader__.load({
2848
3166
  * route unconditionally.
2849
3167
  */
2850
3168
  if (isAndroidWebView() || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') {
2851
- setExportFallback(text)
2852
- setNotice(t('export.fallbackHint'))
3169
+ stageExportFallback(text)
3170
+ setNotice(t('export.androidHint', { sets: counts.sets, entries: counts.entries, profiles: counts.profiles }))
2853
3171
  return
2854
3172
  }
2855
3173
  const blob = new Blob([text], { type: 'application/json' })
@@ -2861,13 +3179,21 @@ window.__ModuleLoader__.load({
2861
3179
  link.click()
2862
3180
  if (link.parentNode !== null) link.parentNode.removeChild(link)
2863
3181
  setTimeout(() => { URL.revokeObjectURL(url) }, 1000)
2864
- setNotice(t('export.saved'))
3182
+ if (isDesktopShell()) {
3183
+ // The desktop host cannot confirm this landed: its download handler
3184
+ // only claims `#dsh-download=` URLs, and a blob click is Chromium's
3185
+ // business. Offer the guaranteed route and say what was attempted.
3186
+ stageExportFallback(text)
3187
+ setNotice(t('export.desktopHint'))
3188
+ } else {
3189
+ setNotice(t('export.saved'))
3190
+ }
2865
3191
  } catch (err) {
2866
3192
  setError(String(err && err.message ? err.message : err))
2867
3193
  }
2868
3194
  }
2869
3195
 
2870
- async function handleImportFile(file) {
3196
+ async function handleImportFile(file, confirmed) {
2871
3197
  try {
2872
3198
  const verdict = importSizeVerdict(
2873
3199
  file && typeof file.size === 'number' ? file.size : NaN,
@@ -2892,17 +3218,14 @@ window.__ModuleLoader__.load({
2892
3218
  setError(t('import.notJson', { detail: String(err && err.message ? err.message : err) }))
2893
3219
  return
2894
3220
  }
2895
- // 1.6.1: the whole-store restore above asks first; import did not, so
2896
- // a file someone handed the user could become the instructions
2897
- // injected into every later turn with no confirmation at all. Same
2898
- // ask, same fallback semantics: with no dialog available, refuse
2899
- // rather than merge silently.
2900
- const askImport = askConfirm(t('import.confirm'))
2901
- if (askImport !== CONFIRM_YES) {
2902
- if (askImport === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
3221
+ // 1.6.1: import asks before merging; 1.6.5's contract runs the action
3222
+ // from inside confirmThen, so the replay carries `confirmed` and skips
3223
+ // this block rather than re-asking.
3224
+ if (confirmed !== true) {
3225
+ confirmThen(t('import.confirm'), () => handleImportFile(file, true))
2903
3226
  return
2904
3227
  }
2905
- await send('import-data', { payload, baseRev: revOf() })
3228
+ await send('import-data', { payload, baseRev: revOf(), confirm: true })
2906
3229
  } catch (err) {
2907
3230
  setError(String(err && err.message ? err.message : err))
2908
3231
  }
@@ -3055,7 +3378,13 @@ window.__ModuleLoader__.load({
3055
3378
  // with this draft — a silent overwrite. Ask first, and only
3056
3379
  // then retry against the rev we just learned.
3057
3380
  if (result.conflict === true && !allowOverwrite) {
3058
- if (askConfirm(t('editor.conflictOverwrite'), 'allow') === CONFIRM_YES) commit(revOf(), true)
3381
+ // S6 (1.6.5): the 'allow' fallback meant "no dialog → treat
3382
+ // as yes", so on a WebView a CRLF-less confirm refusal turned
3383
+ // into a silent overwrite of the other window's edit. This is
3384
+ // the only allow-fallback that can destroy someone else's
3385
+ // work, so it asks properly like every durable action.
3386
+ const overwrite = () => commit(revOf(), true)
3387
+ confirmThen(t('editor.conflictOverwrite'), overwrite)
3059
3388
  }
3060
3389
  })
3061
3390
  }
@@ -3092,7 +3421,7 @@ window.__ModuleLoader__.load({
3092
3421
  // known problem" — an absent field must not manufacture a warning.
3093
3422
  const security = view.security !== null && typeof view.security === 'object'
3094
3423
  ? view.security
3095
- : { hostGuarded: true, boundHost: '' }
3424
+ : { hostGuarded: true, boundHost: '', writeGate: 'fence' }
3096
3425
  // List order is display-only and never changes what the Host injects
3097
3426
  // (the injection order is decided host-side). Sorting, filtering and the
3098
3427
  // keyword scan all happen once, inside the memoised deriveListState.
@@ -3248,7 +3577,14 @@ window.__ModuleLoader__.load({
3248
3577
  disabled: busy,
3249
3578
  onClick: toggleFeedback,
3250
3579
  }, feedbackOpen ? t('feedback.hide') : t('feedback.show'))),
3251
- feedbackOpen
3580
+ // A10 (1.6.4): the feedback path needs SMTP credentials from the
3581
+ // environment (`DSH_INSTRUCTION_MEMORY_FEEDBACK_SMTP_HOST` and the
3582
+ // secret), and the DSH Go shell clears the environment. The button
3583
+ // would fail every time, so on the phone it explains itself instead.
3584
+ feedbackOpen && isAndroidWebView()
3585
+ ? h('div', { className: 'im-meta', key: 'feedback-mobile' }, t('feedback.mobileUnavailable'))
3586
+ : null,
3587
+ feedbackOpen && !isAndroidWebView()
3252
3588
  ? h('div', { className: 'im-feedback-form' },
3253
3589
  h('div', { className: 'im-meta' }, t('feedback.intro')),
3254
3590
  h('div', { className: 'im-grid2' },
@@ -3334,6 +3670,11 @@ window.__ModuleLoader__.load({
3334
3670
  ? t('diag.hostWarnTrusted', { host: security.boundHost !== '' ? security.boundHost : '?', count: security.trustedHostCount })
3335
3671
  : t('diag.hostWarn', { host: security.boundHost !== '' ? security.boundHost : '?' }))
3336
3672
  : null,
3673
+ // 1.6.3: a fence-less profile refuses every mutating method by default,
3674
+ // so a save button would fail only AFTER the user typed. Say it before.
3675
+ security.writeGate === 'refused'
3676
+ ? h('div', { className: 'im-hostwarn', key: 'writewarn' }, t('diag.writeRefused'))
3677
+ : null,
3337
3678
  h('div', { className: 'im-row' },
3338
3679
  h('div', null,
3339
3680
  h('h3', { className: 'im-h' }, t('panel.title')),
@@ -3599,7 +3940,15 @@ window.__ModuleLoader__.load({
3599
3940
  h('button', {
3600
3941
  className: 'im-btn im-btn-danger',
3601
3942
  disabled: busy,
3602
- onClick: () => doBatch('delete', undefined),
3943
+ onClick: () => {
3944
+ const ids = liveSelected()
3945
+ if (ids.length === 0) {
3946
+ setError(t('batch.noneSelected'))
3947
+ return
3948
+ }
3949
+ confirmThen(t('batch.confirmDelete', { count: ids.length }),
3950
+ () => { void doBatch('delete', undefined, ids) })
3951
+ },
3603
3952
  }, t('batch.delete')),
3604
3953
  h('button', { className: 'im-btn', disabled: busy, onClick: exitBatch }, t('batch.exit')))
3605
3954
  : null,
@@ -3788,7 +4137,7 @@ window.__ModuleLoader__.load({
3788
4137
  onFocus: (ev) => { if (typeof ev.target.select === 'function') ev.target.select() },
3789
4138
  }),
3790
4139
  h('div', { className: 'im-row-wrap' },
3791
- h('button', { className: 'im-btn', onClick: () => setExportFallback(null) }, t('export.fallbackClose'))))
4140
+ h('button', { className: 'im-btn', onClick: () => clearExportFallback() }, t('export.fallbackClose'))))
3792
4141
  : null,
3793
4142
  isAndroidWebView()
3794
4143
  ? h('div', { className: 'im-meta' }, t('import.webviewHint'))
@@ -3932,6 +4281,38 @@ window.__ModuleLoader__.load({
3932
4281
  : null),
3933
4282
  liveDown ? h('div', { className: 'im-meta', role: 'status' }, t('sse.down')) : null,
3934
4283
  error !== '' ? h('div', { className: 'im-err', role: 'alert' }, error) : null,
4284
+ // 1.6.4: the in-panel confirmation. Rendered where the banners are, so a
4285
+ // parked destructive action is impossible to miss and the list it
4286
+ // refers to sits right below it.
4287
+ pendingConfirm !== null
4288
+ ? h('div', { className: 'im-confirm', role: 'group', key: 'pending-confirm' },
4289
+ h('div', { className: 'im-confirm-text' }, pendingConfirm.message),
4290
+ h('div', { className: 'im-row' },
4291
+ h('button', {
4292
+ className: 'im-btn im-btn-primary',
4293
+ // R2 (1.6.5): one activation, one action. A double tap (or a
4294
+ // touch jitter) used to run the replayed handler twice; the
4295
+ // delete survived on the host's idempotency, but import/restore
4296
+ // were never verified. `busy` also blocks it here, so an action
4297
+ // that is already in flight cannot be re-fired from the bar.
4298
+ disabled: busy === true || confirmFiringRef.current === true,
4299
+ onClick: () => {
4300
+ const pending = pendingConfirm
4301
+ if (pending === null || confirmFiringRef.current === true) return
4302
+ // Stays true until the NEXT question is parked: a second
4303
+ // activation in the same tick (double tap, touch jitter) must
4304
+ // not run the action twice. The delete survived on the host's
4305
+ // idempotency; import/restore never had that guarantee.
4306
+ confirmFiringRef.current = true
4307
+ setPendingConfirm(null)
4308
+ void pending.action()
4309
+ },
4310
+ }, t('confirm.yes')),
4311
+ h('button', {
4312
+ className: 'im-btn',
4313
+ onClick: () => setPendingConfirm(null),
4314
+ }, t('confirm.no'))))
4315
+ : null,
3935
4316
  error === '' && notice !== '' ? h('div', { className: 'im-ok', role: 'status', 'aria-live': 'polite' }, notice) : null,
3936
4317
  error === '' && notice === '' && storage.error ? h('div', { className: 'im-err', role: 'alert' }, storage.error) : null,
3937
4318
  undo !== null ? h('div', { className: 'im-undo', key: 'undo' },
@@ -4098,32 +4479,51 @@ window.__ModuleLoader__.load({
4098
4479
  : h('button', {
4099
4480
  className: 'im-btn',
4100
4481
  disabled: busy,
4101
- onClick: () => { setDraft(cloneEntry(entry)); setProfileDraft(null); setError('') },
4482
+ onClick: () => {
4483
+ // A6 (1.6.5): the editor is an early return, so a confirmation
4484
+ // parked in the list view would be invisible while the draft
4485
+ // is open — the action would hang until the editor closed.
4486
+ setPendingConfirm(null)
4487
+ setDraft(cloneEntry(entry))
4488
+ setProfileDraft(null)
4489
+ setError('')
4490
+ },
4102
4491
  }, t('entry.edit')),
4103
4492
  batchMode
4104
4493
  ? null
4105
4494
  : h('button', {
4106
4495
  className: 'im-btn im-btn-danger',
4107
4496
  disabled: busy,
4497
+ // A bare "删除" is ambiguous for a screen reader (and for any
4498
+ // test) when the page also has set delete, snapshot delete and
4499
+ // batch delete. Name the target.
4500
+ 'aria-label': t('entry.deleteAria', {
4501
+ title: entry.title !== '' ? entry.title : t('entry.untitled'),
4502
+ }),
4503
+ title: t('entry.deleteAria', {
4504
+ title: entry.title !== '' ? entry.title : t('entry.untitled'),
4505
+ }),
4108
4506
  onClick: () => {
4109
- // Durable-data delete: if this shell has no working dialog,
4110
- // the delete is refused and the reason is shown — silently
4111
- // dropping an instruction because a button was clickable
4112
- // and the shell lacked confirm() is the worse failure.
4113
- const askEntry = askConfirm(t('entry.confirmDelete', {
4114
- title: entry.title !== '' ? entry.title : t('entry.untitled'),
4115
- }))
4116
- if (askEntry !== CONFIRM_YES) {
4117
- if (askEntry === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
4118
- return
4507
+ // R1 (1.6.5): the action lives AFTER the guard, never only
4508
+ // inside the replay closure. `confirmThen` returns false on
4509
+ // "a real dialog said yes" and does NOT run `run` itself, so
4510
+ // the 1.6.4 shape (action only in the closure, nothing after
4511
+ // the `if`) made this button a silent no-op on desktop and in
4512
+ // the browser. The lint gate now rejects that shape.
4513
+ const removeEntry = () => {
4514
+ // Keep the full entry for the undo bar; the POST response
4515
+ // (not this closure) is what confirms the deletion happened.
4516
+ setUndo(null)
4517
+ send('delete-entry', { id: entry.id, baseRev: revOf() }).then((result) => {
4518
+ if (result === null || result.ok !== true) return
4519
+ setUndo({ entry, expires: Date.now() + UNDO_TTL_MS })
4520
+ })
4119
4521
  }
4120
- // Keep the full entry for the undo bar; the POST response
4121
- // (not this closure) is what confirms the deletion happened.
4122
- setUndo(null)
4123
- send('delete-entry', { id: entry.id, baseRev: revOf() }).then((result) => {
4124
- if (result === null || result.ok !== true) return
4125
- setUndo({ entry, expires: Date.now() + UNDO_TTL_MS })
4126
- })
4522
+ // 1.6.5 contract: confirmThen runs this action itself (or parks
4523
+ // it), so there is exactly one execution site.
4524
+ confirmThen(t('entry.confirmDelete', {
4525
+ title: entry.title !== '' ? entry.title : t('entry.untitled'),
4526
+ }), removeEntry)
4127
4527
  },
4128
4528
  }, t('entry.delete'))),
4129
4529
  h(EntryBody, { text: entry.content, key: 'body' }),
@@ -4423,6 +4823,16 @@ window.__ModuleLoader__.load({
4423
4823
  exports.__sameSnapshot = sameSnapshot
4424
4824
  exports.__confirmDiscard = confirmDiscard
4425
4825
  exports.__askConfirm = askConfirm
4826
+ // 1.6.4 mobile-shape hooks: the byte splitter and the "can a dialog be
4827
+ // believed here?" probe are the two pieces that decide whether a phone can
4828
+ // export and delete at all, so they are pinned in Node rather than left to
4829
+ // a device nobody has on the build machine.
4830
+ exports.__splitByBytes = splitByBytes
4831
+ exports.__splitForBridge = splitForBridge
4832
+ exports.__confirmDialogsAreTrustworthy = confirmDialogsAreTrustworthy
4833
+ exports.__islandChunkBytes = ISLAND_CHUNK_BYTES
4834
+ exports.__islandFrameLimit = ISLAND_FRAME_LIMIT
4835
+ exports.__hasIslandBridge = hasIslandBridge
4426
4836
  exports.__importSizeVerdict = importSizeVerdict
4427
4837
  exports.__nextBudgetText = nextBudgetText
4428
4838
  exports.__budgetMeter = budgetMeter