dsh-instruction-memory 1.6.3 → 1.6.6

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;
@@ -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': '注入字数上限(字符)',
@@ -369,8 +372,9 @@ window.__ModuleLoader__.load({
369
372
  'profiles.omitted': '本轮未包含',
370
373
  'profiles.omittedTitle': '这张形象因注入字数上限未进入本轮提示',
371
374
  'export.saved': '已请求保存。若保存框被取消、或下载被浏览器/系统拦下,文件不会出现——请重试,或改用下面的「完整 JSON」',
372
- 'export.savedToApp': '已交给 DSH Go 保存:在系统分享面板里选「保存到文件」即可',
373
375
  'export.fallbackHint': '当前环境无法触发文件下载,完整 JSON 已放在下面:全选复制后自行保存',
376
+ 'export.androidHint': '已把完整 JSON 放在下方(含 {sets} 个配置集、{entries} 条指令、{profiles} 个形象):手机端无法触发文件下载,请全选复制后自行保存。',
377
+ 'export.bridgeHint': '已向 DSH Go 的岛通道发送 {chunks} 条消息(含 {sets} 个配置集、{entries} 条指令、{profiles} 个形象)。注意:当前 App 版本可能没有「保存为文件」的处理,面板无法确认文件是否落地——若系统分享面板没有出现或没有保存成功,请用下面的完整 JSON。',
374
378
  'export.desktopHint': '桌面端:已尝试用浏览器下载通道保存,但宿主的下载处理只接管自身标记的链接,插件无法确认文件是否落地。下面的「完整 JSON」是保底通道——若下载目录里没有文件,请全选复制后自行保存。',
375
379
  'export.fallbackClose': '关闭',
376
380
  'import.webviewHint': 'Android / WebView 上若文件选择器不弹出,请改用「源码模式」粘贴 JSON',
@@ -401,6 +405,7 @@ window.__ModuleLoader__.load({
401
405
  'entry.enabled': '启用',
402
406
  'entry.edit': '编辑',
403
407
  'entry.delete': '删除',
408
+ 'entry.deleteAria': '删除指令「{title}」',
404
409
  'entry.untitled': '未命名指令',
405
410
  'entry.confirmDelete': '确定删除「{title}」?删除后无法恢复。',
406
411
  'entry.when': '适用情形:{when}',
@@ -468,6 +473,7 @@ window.__ModuleLoader__.load({
468
473
  'diag.issueSection': '注入错误',
469
474
  // ---- 反馈邮件 ----
470
475
  'feedback.section': '反馈',
476
+ 'feedback.mobileUnavailable': '手机上无法发送反馈:该功能需要宿主进程带 SMTP 配置启动,而 DSH Go 的 App 内进程不继承外部环境变量。请改用桌面版反馈,或到插件仓库提交 issue。',
471
477
  'feedback.show': '反馈',
472
478
  'feedback.hide': '收起反馈',
473
479
  'feedback.intro': '遇到问题或有功能建议?填写下面的表单,通过邮件发送给插件维护者。',
@@ -605,7 +611,8 @@ window.__ModuleLoader__.load({
605
611
  'editor.needTitleOrContent': 'Fill in at least a title or the instruction content',
606
612
  'editor.conflictOverwrite': 'Another window or process just changed this entry. Saving now replaces their edit with yours. Continue?',
607
613
  'editor.confirmDiscard': 'The draft has unsaved changes. Discard them?',
608
- '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',
609
616
  'body.expand': 'Show all',
610
617
  'body.collapse': 'Show less',
611
618
  'budget.label': 'Injection size limit (characters)',
@@ -675,8 +682,9 @@ window.__ModuleLoader__.load({
675
682
  'profiles.omitted': 'Not in this turn',
676
683
  'profiles.omittedTitle': 'This persona was dropped by the injection limit and did not reach this turn',
677
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',
678
- 'export.savedToApp': 'Handed to DSH Go — pick “Save to Files” in the system share sheet',
679
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.',
680
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.',
681
689
  'export.fallbackClose': 'Close',
682
690
  'import.webviewHint': 'On Android / WebView, if the file picker does not open, paste the JSON into “Source mode” instead',
@@ -707,6 +715,7 @@ window.__ModuleLoader__.load({
707
715
  'entry.enabled': 'Enabled',
708
716
  'entry.edit': 'Edit',
709
717
  'entry.delete': 'Delete',
718
+ 'entry.deleteAria': 'Delete instruction “{title}”',
710
719
  'entry.untitled': 'Untitled instruction',
711
720
  'entry.confirmDelete': 'Delete “{title}”? This cannot be undone.',
712
721
  'entry.when': 'Applies when: {when}',
@@ -774,6 +783,7 @@ window.__ModuleLoader__.load({
774
783
  'diag.issueSection': 'Injection error',
775
784
  // ---- feedback mail ----
776
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.',
777
787
  'feedback.show': 'Feedback',
778
788
  'feedback.hide': 'Hide feedback',
779
789
  'feedback.intro': 'Found a problem or have a suggestion? Send it to the plugin maintainer by email with the form below.',
@@ -1182,6 +1192,169 @@ window.__ModuleLoader__.load({
1182
1192
  const CONFIRM_NO = 'no'
1183
1193
  const CONFIRM_UNAVAILABLE = 'unavailable'
1184
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
+
1185
1358
  /**
1186
1359
  * The single gate every confirmation goes through.
1187
1360
  *
@@ -1213,6 +1386,15 @@ window.__ModuleLoader__.load({
1213
1386
  if (typeof window === 'undefined' || typeof window.confirm !== 'function') {
1214
1387
  return fallback ? CONFIRM_YES : CONFIRM_UNAVAILABLE
1215
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
+ }
1216
1398
  try {
1217
1399
  return window.confirm(message) === true ? CONFIRM_YES : CONFIRM_NO
1218
1400
  } catch {
@@ -2097,6 +2279,79 @@ window.__ModuleLoader__.load({
2097
2279
  const [diagFallback, setDiagFallback] = React.useState(null)
2098
2280
  /** Export JSON rendered in-panel when the runtime has no download path. */
2099
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
+ }
2100
2355
  /** True once the event stream has failed long enough to stop pretending. */
2101
2356
  const [liveDown, setLiveDown] = React.useState(false)
2102
2357
  // Feedback form: closed by default so the settings card stays compact.
@@ -2322,19 +2577,18 @@ window.__ModuleLoader__.load({
2322
2577
  setBatchTagText('')
2323
2578
  }
2324
2579
 
2325
- async function doBatch(op, value) {
2326
- 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()
2327
2585
  if (ids.length === 0) {
2328
2586
  setError(t('batch.noneSelected'))
2329
2587
  return
2330
2588
  }
2331
- if (op === 'delete') {
2332
- const ask = askConfirm(t('batch.confirmDelete', { count: ids.length }))
2333
- if (ask !== CONFIRM_YES) {
2334
- if (ask === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2335
- return
2336
- }
2337
- }
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.
2338
2592
  const result = await send('batch', { op, ids, value, baseRev: revOf() })
2339
2593
  if (result !== null && result.ok === true && op === 'delete') {
2340
2594
  // Drop deleted ids from the selection; other ops keep it so several
@@ -2408,13 +2662,12 @@ window.__ModuleLoader__.load({
2408
2662
  setError('')
2409
2663
  }
2410
2664
 
2411
- function removeProfile(profile) {
2665
+ function removeProfile(profile, confirmed) {
2412
2666
  if (busy) return
2413
- const ask = askConfirm(t('profiles.confirmDelete', {
2414
- name: profile.name !== '' ? profile.name : t('profiles.untitled'),
2415
- }))
2416
- if (ask !== CONFIRM_YES) {
2417
- 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))
2418
2671
  return
2419
2672
  }
2420
2673
  void send('delete-profile', { id: profile.id, baseRev: revOf() })
@@ -2475,15 +2728,15 @@ window.__ModuleLoader__.load({
2475
2728
  })
2476
2729
  }
2477
2730
 
2478
- function removeSet(set) {
2731
+ function removeSet(set, confirmed) {
2479
2732
  if (busy) return
2480
2733
  if (set.active === true) {
2481
2734
  setError(t('sets.deleteActive'))
2482
2735
  return
2483
2736
  }
2484
- const askDeleteSet = askConfirm(t('sets.deleteConfirm', { name: set.name, entries: set.entries, profiles: set.profiles }))
2485
- if (askDeleteSet !== CONFIRM_YES) {
2486
- 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))
2487
2740
  return
2488
2741
  }
2489
2742
  void send('delete-set', { id: set.id, baseRev: revOf() })
@@ -2516,7 +2769,7 @@ window.__ModuleLoader__.load({
2516
2769
  if (next) void loadHistory()
2517
2770
  }
2518
2771
 
2519
- function rollbackTo(item) {
2772
+ function rollbackTo(item, confirmed) {
2520
2773
  if (busy) return
2521
2774
  // Restoring makes the Host read a whole file; a snapshot far larger
2522
2775
  // than any real store is refused BEFORE the user confirms an operation
@@ -2527,10 +2780,10 @@ window.__ModuleLoader__.load({
2527
2780
  setError(sizeVerdict.message)
2528
2781
  return
2529
2782
  }
2530
- const when = new Date(item.epoch).toLocaleString()
2531
- const ask = askConfirm(t('history.restoreConfirm', { time: when, rev: item.rev, name: item.name }))
2532
- if (ask !== CONFIRM_YES) {
2533
- 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))
2534
2787
  return
2535
2788
  }
2536
2789
  void send('history-restore', { name: item.name, baseRev: revOf() }).then((result) => {
@@ -2538,11 +2791,10 @@ window.__ModuleLoader__.load({
2538
2791
  })
2539
2792
  }
2540
2793
 
2541
- function removeSnapshot(item) {
2794
+ function removeSnapshot(item, confirmed) {
2542
2795
  if (busy) return
2543
- const askDeleteHistory = askConfirm(t('history.deleteConfirm'))
2544
- if (askDeleteHistory !== CONFIRM_YES) {
2545
- if (askDeleteHistory === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
2796
+ if (confirmed !== true) {
2797
+ confirmThen(t('history.deleteConfirm'), () => removeSnapshot(item, true))
2546
2798
  return
2547
2799
  }
2548
2800
  void send('history-delete', { name: item.name }).then((result) => {
@@ -2724,11 +2976,12 @@ window.__ModuleLoader__.load({
2724
2976
 
2725
2977
  // ---- F14 whole-store restore (the "replace" door import does not open) ----
2726
2978
 
2727
- async function handleRestoreFile(file) {
2979
+ async function handleRestoreFile(file, confirmed) {
2728
2980
  try {
2729
- const askRestore = askConfirm(t('restore.confirm'))
2730
- if (askRestore !== CONFIRM_YES) {
2731
- 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))
2732
2985
  return
2733
2986
  }
2734
2987
  const text = typeof file.text === 'function'
@@ -2812,14 +3065,14 @@ window.__ModuleLoader__.load({
2812
3065
  */
2813
3066
  function isAndroidWebView() {
2814
3067
  try {
2815
- const ua = typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string'
2816
- ? navigator.userAgent
2817
- : ''
2818
- // `; wv)` is the canonical WebView marker; DSH Go's webview island may
2819
- // also report a stock Chromium UA, so fall back to "Android without a
2820
- // full browser brand".
2821
- return /;\s*wv\)/i.test(ua)
2822
- || (/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()
2823
3076
  } catch {
2824
3077
  return false
2825
3078
  }
@@ -2846,35 +3099,33 @@ window.__ModuleLoader__.load({
2846
3099
  }
2847
3100
 
2848
3101
  /**
2849
- * Hand `text` to the DSH Go island bridge, in chunks that fit its 16 KB
2850
- * message cap (`IslandMessageLimits.maxBytes`). The app reassembles them
2851
- * and opens the system share sheet — the only export path a WebView has,
2852
- * since it never hands a `blob:` to a download listener.
3102
+ * Hand `text` to the DSH Go island bridge in UTF-8-byte-bounded chunks.
2853
3103
  *
2854
- * Returns false when the page is not inside DSH Go (or the bridge is
2855
- * missing), which leaves the browser path untouched.
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".
2856
3109
  */
2857
3110
  async function sendToAppBridge(text, name) {
2858
3111
  try {
2859
3112
  const bridge = typeof window !== 'undefined' ? window.DshGoIsland : undefined
2860
- 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
+ }
2861
3116
  const id = 'im-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
2862
- const CHUNK = 6000
2863
- let i = 0
2864
- while (i < text.length) {
2865
- let end = Math.min(text.length, i + CHUNK)
2866
- // Never split a surrogate pair across two messages: each one is its
2867
- // own JSON document and a lone surrogate would not survive it.
2868
- const code = text.charCodeAt(end - 1)
2869
- 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) {
2870
3122
  bridge.postMessage(JSON.stringify({
2871
- 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,
2872
3124
  }))
2873
- i = end
2874
3125
  }
2875
- return true
3126
+ return { sent: true, chunks: chunks.length }
2876
3127
  } catch {
2877
- return false
3128
+ return { sent: false, chunks: 0 }
2878
3129
  }
2879
3130
  }
2880
3131
 
@@ -2887,10 +3138,23 @@ window.__ModuleLoader__.load({
2887
3138
  }
2888
3139
  const text = JSON.stringify(result.export, null, 2) + '\n'
2889
3140
  const fileName = 'dsh-instruction-memory-' + new Date().toISOString().slice(0, 10) + '.json'
2890
- // Inside DSH Go the app can actually write the file; prefer that over
2891
- // both the download link and the in-panel copy.
2892
- if (await sendToAppBridge(text, fileName)) {
2893
- 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 }))
2894
3158
  return
2895
3159
  }
2896
3160
  /**
@@ -2902,8 +3166,8 @@ window.__ModuleLoader__.load({
2902
3166
  * route unconditionally.
2903
3167
  */
2904
3168
  if (isAndroidWebView() || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') {
2905
- setExportFallback(text)
2906
- setNotice(t('export.fallbackHint'))
3169
+ stageExportFallback(text)
3170
+ setNotice(t('export.androidHint', { sets: counts.sets, entries: counts.entries, profiles: counts.profiles }))
2907
3171
  return
2908
3172
  }
2909
3173
  const blob = new Blob([text], { type: 'application/json' })
@@ -2919,7 +3183,7 @@ window.__ModuleLoader__.load({
2919
3183
  // The desktop host cannot confirm this landed: its download handler
2920
3184
  // only claims `#dsh-download=` URLs, and a blob click is Chromium's
2921
3185
  // business. Offer the guaranteed route and say what was attempted.
2922
- setExportFallback(text)
3186
+ stageExportFallback(text)
2923
3187
  setNotice(t('export.desktopHint'))
2924
3188
  } else {
2925
3189
  setNotice(t('export.saved'))
@@ -2929,7 +3193,7 @@ window.__ModuleLoader__.load({
2929
3193
  }
2930
3194
  }
2931
3195
 
2932
- async function handleImportFile(file) {
3196
+ async function handleImportFile(file, confirmed) {
2933
3197
  try {
2934
3198
  const verdict = importSizeVerdict(
2935
3199
  file && typeof file.size === 'number' ? file.size : NaN,
@@ -2954,14 +3218,11 @@ window.__ModuleLoader__.load({
2954
3218
  setError(t('import.notJson', { detail: String(err && err.message ? err.message : err) }))
2955
3219
  return
2956
3220
  }
2957
- // 1.6.1: the whole-store restore above asks first; import did not, so
2958
- // a file someone handed the user could become the instructions
2959
- // injected into every later turn with no confirmation at all. Same
2960
- // ask, same fallback semantics: with no dialog available, refuse
2961
- // rather than merge silently.
2962
- const askImport = askConfirm(t('import.confirm'))
2963
- if (askImport !== CONFIRM_YES) {
2964
- 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))
2965
3226
  return
2966
3227
  }
2967
3228
  await send('import-data', { payload, baseRev: revOf(), confirm: true })
@@ -3117,7 +3378,13 @@ window.__ModuleLoader__.load({
3117
3378
  // with this draft — a silent overwrite. Ask first, and only
3118
3379
  // then retry against the rev we just learned.
3119
3380
  if (result.conflict === true && !allowOverwrite) {
3120
- 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)
3121
3388
  }
3122
3389
  })
3123
3390
  }
@@ -3310,7 +3577,14 @@ window.__ModuleLoader__.load({
3310
3577
  disabled: busy,
3311
3578
  onClick: toggleFeedback,
3312
3579
  }, feedbackOpen ? t('feedback.hide') : t('feedback.show'))),
3313
- 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()
3314
3588
  ? h('div', { className: 'im-feedback-form' },
3315
3589
  h('div', { className: 'im-meta' }, t('feedback.intro')),
3316
3590
  h('div', { className: 'im-grid2' },
@@ -3666,7 +3940,15 @@ window.__ModuleLoader__.load({
3666
3940
  h('button', {
3667
3941
  className: 'im-btn im-btn-danger',
3668
3942
  disabled: busy,
3669
- 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
+ },
3670
3952
  }, t('batch.delete')),
3671
3953
  h('button', { className: 'im-btn', disabled: busy, onClick: exitBatch }, t('batch.exit')))
3672
3954
  : null,
@@ -3855,7 +4137,7 @@ window.__ModuleLoader__.load({
3855
4137
  onFocus: (ev) => { if (typeof ev.target.select === 'function') ev.target.select() },
3856
4138
  }),
3857
4139
  h('div', { className: 'im-row-wrap' },
3858
- h('button', { className: 'im-btn', onClick: () => setExportFallback(null) }, t('export.fallbackClose'))))
4140
+ h('button', { className: 'im-btn', onClick: () => clearExportFallback() }, t('export.fallbackClose'))))
3859
4141
  : null,
3860
4142
  isAndroidWebView()
3861
4143
  ? h('div', { className: 'im-meta' }, t('import.webviewHint'))
@@ -3999,6 +4281,38 @@ window.__ModuleLoader__.load({
3999
4281
  : null),
4000
4282
  liveDown ? h('div', { className: 'im-meta', role: 'status' }, t('sse.down')) : null,
4001
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,
4002
4316
  error === '' && notice !== '' ? h('div', { className: 'im-ok', role: 'status', 'aria-live': 'polite' }, notice) : null,
4003
4317
  error === '' && notice === '' && storage.error ? h('div', { className: 'im-err', role: 'alert' }, storage.error) : null,
4004
4318
  undo !== null ? h('div', { className: 'im-undo', key: 'undo' },
@@ -4165,32 +4479,51 @@ window.__ModuleLoader__.load({
4165
4479
  : h('button', {
4166
4480
  className: 'im-btn',
4167
4481
  disabled: busy,
4168
- 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
+ },
4169
4491
  }, t('entry.edit')),
4170
4492
  batchMode
4171
4493
  ? null
4172
4494
  : h('button', {
4173
4495
  className: 'im-btn im-btn-danger',
4174
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
+ }),
4175
4506
  onClick: () => {
4176
- // Durable-data delete: if this shell has no working dialog,
4177
- // the delete is refused and the reason is shown — silently
4178
- // dropping an instruction because a button was clickable
4179
- // and the shell lacked confirm() is the worse failure.
4180
- const askEntry = askConfirm(t('entry.confirmDelete', {
4181
- title: entry.title !== '' ? entry.title : t('entry.untitled'),
4182
- }))
4183
- if (askEntry !== CONFIRM_YES) {
4184
- if (askEntry === CONFIRM_UNAVAILABLE) setError(t('confirm.unavailable'))
4185
- 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
+ })
4186
4521
  }
4187
- // Keep the full entry for the undo bar; the POST response
4188
- // (not this closure) is what confirms the deletion happened.
4189
- setUndo(null)
4190
- send('delete-entry', { id: entry.id, baseRev: revOf() }).then((result) => {
4191
- if (result === null || result.ok !== true) return
4192
- setUndo({ entry, expires: Date.now() + UNDO_TTL_MS })
4193
- })
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)
4194
4527
  },
4195
4528
  }, t('entry.delete'))),
4196
4529
  h(EntryBody, { text: entry.content, key: 'body' }),
@@ -4490,6 +4823,16 @@ window.__ModuleLoader__.load({
4490
4823
  exports.__sameSnapshot = sameSnapshot
4491
4824
  exports.__confirmDiscard = confirmDiscard
4492
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
4493
4836
  exports.__importSizeVerdict = importSizeVerdict
4494
4837
  exports.__nextBudgetText = nextBudgetText
4495
4838
  exports.__budgetMeter = budgetMeter