@jidekaixin2dian/dsh-file-actions 0.1.21 → 0.1.23

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
@@ -104,6 +104,7 @@ const factory = (require) => {
104
104
  noSession: '没有可用的会话',
105
105
  notFound: '找不到该文件',
106
106
  locating: '正在查找同名文件…',
107
+ lookupIncomplete: '未能查完:目录过多或读取失败',
107
108
  outsideWorkspace: '工作区外',
108
109
  defaultApp: '默认',
109
110
  appsUnit: '个应用',
@@ -243,6 +244,7 @@ const factory = (require) => {
243
244
  noSession: 'No active session',
244
245
  notFound: 'File not found',
245
246
  locating: 'Looking for the file…',
247
+ lookupIncomplete: 'Search did not finish: too many folders or a failed read',
246
248
  outsideWorkspace: 'Outside workspace',
247
249
  defaultApp: 'Default',
248
250
  appsUnit: 'apps',
@@ -337,12 +339,12 @@ const factory = (require) => {
337
339
  const PDF_EXT = new Set(['pdf'])
338
340
  const MD_EXT = new Set(['md', 'markdown', 'mdx'])
339
341
  const OFFICE_EXT = new Set(['doc', 'docx', 'docm', 'dotx', 'odt', 'rtf', 'pages', 'wps'])
340
- const SHEET_EXT = new Set(['xls', 'xlsx', 'xlsm', 'xlsb', 'ods', 'numbers', 'et'])
341
- const SLIDES_EXT = new Set(['ppt', 'pptx', 'pps', 'ppsx', 'odp', 'key', 'dps'])
342
- const SVG_EXT = new Set(['svg'])
343
- const NOTEBOOK_EXT = new Set(['ipynb'])
344
- const DATABASE_EXT = new Set(['db', 'sqlite', 'sqlite3', 'mdb', 'accdb', 'parquet', 'avro', 'orc', 'feather', 'dbf'])
345
- const EBOOK_EXT = new Set(['epub', 'mobi', 'azw', 'azw3', 'fb2', 'djvu'])
342
+ const SHEET_EXT = new Set(['xls', 'xlsx', 'xlsm', 'xlsb', 'ods', 'numbers', 'et'])
343
+ const SLIDES_EXT = new Set(['ppt', 'pptx', 'pps', 'ppsx', 'odp', 'key', 'dps'])
344
+ const SVG_EXT = new Set(['svg'])
345
+ const NOTEBOOK_EXT = new Set(['ipynb'])
346
+ const DATABASE_EXT = new Set(['db', 'sqlite', 'sqlite3', 'mdb', 'accdb', 'parquet', 'avro', 'orc', 'feather', 'dbf'])
347
+ const EBOOK_EXT = new Set(['epub', 'mobi', 'azw', 'azw3', 'fb2', 'djvu'])
346
348
  const ARCHIVE_EXT = new Set(['zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar', 'zst', 'lz4', 'cab', 'arj', 'lha', 'lzh'])
347
349
  const VIDEO_EXT = new Set(['mp4', 'm4v', 'mov', 'webm', 'ogv', 'mkv', 'avi', 'wmv', 'flv', 'mpg', 'mpeg', '3gp', 'mts', 'm2ts', 'vob', 'rmvb', 'f4v', 'asf'])
348
350
  const AUDIO_EXT = new Set(['mp3', 'wav', 'flac', 'm4a', 'aac', 'ogg', 'oga', 'opus', 'wma', 'aiff', 'mid', 'midi', 'ape', 'mka', 'amr', 'aif', 'ac3', 'dts', 'm4b'])
@@ -350,7 +352,7 @@ const EBOOK_EXT = new Set(['epub', 'mobi', 'azw', 'azw3', 'fb2', 'djvu'])
350
352
  const DATA_EXT = new Set(['json', 'jsonc', 'json5', 'jsonl', 'ndjson', 'har', 'yaml', 'yml', 'toml', 'ini',
351
353
  'cfg', 'conf', 'properties', 'plist', 'lock', 'csv', 'tsv', 'xml', 'xsd', 'xsl', 'xslt', 'sql', 'reg', 'inf', 'psd1', 'ps1xml'])
352
354
  const SCRIPT_EXT = new Set(['ps1', 'psm1', 'bat', 'cmd', 'sh', 'bash', 'zsh', 'fish', 'vbs', 'vbe', 'wsf', 'wsh', 'jse', 'ksh', 'csh', 'awk', 'sed', 'tcl'])
353
- const CODE_EXT = new Set(['js', 'mjs', 'cjs', 'jsx', 'ts', 'mts', 'cts', 'tsx', 'vue', 'svelte', 'astro', 'css',
355
+ const CODE_EXT = new Set(['js', 'mjs', 'cjs', 'jsx', 'ts', 'mts', 'cts', 'tsx', 'vue', 'svelte', 'astro', 'css',
354
356
  'scss', 'sass', 'less', 'styl', 'hbs', 'ejs', 'pug', 'twig', 'liquid', 'njk', 'py', 'pyi', 'rb', 'php', 'go',
355
357
  'rs', 'java', 'kt', 'kts', 'scala', 'groovy', 'clj', 'cljs', 'ex', 'exs', 'erl', 'hrl', 'hs', 'elm', 'lua',
356
358
  'pl', 'r', 'jl', 'dart', 'swift', 'm', 'mm', 'fs', 'fsx', 'cs', 'vb', 'pas', 'f90', 'for', 'asm', 's', 'v',
@@ -367,17 +369,20 @@ const CODE_EXT = new Set(['js', 'mjs', 'cjs', 'jsx', 'ts', 'mts', 'cts', 'tsx',
367
369
  'deb', 'rpm', 'appimage', 'wasm', 'scr', 'sys', 'cpl', 'msc'])
368
370
  // Chromium can play these in a blob tab; the rest only get external actions.
369
371
  const BROWSER_IMAGE = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'avif'])
370
- const BROWSER_VIDEO = new Set(['mp4', 'm4v', 'mov', 'webm', 'ogv'])
372
+ const BROWSER_VIDEO = new Set(['mp4', 'm4v', 'mov', 'webm', 'ogv'])
371
373
  const BROWSER_AUDIO = new Set(['mp3', 'wav', 'flac', 'm4a', 'ogg', 'oga', 'opus'])
372
374
 
373
- const KNOWN_EXT = new Set([...TEXT_EXT, ...IMAGE_EXT, ...PDF_EXT, ...OFFICE_EXT, ...ARCHIVE_EXT, ...VIDEO_EXT, ...AUDIO_EXT,
374
- // binaries and assets whose names still deserve a menu
375
- 'wasm', 'map', 'lockb', 'db', 'sqlite', 'sqlite3', 'parquet', 'arrow', 'avro', 'orc',
376
- 'woff', 'woff2', 'ttf', 'otf', 'ttc', 'eot', 'fon', 'icns', 'cur',
377
- 'psd', 'ai', 'eps', 'indd', 'fig', 'sketch', 'xd', 'blend', 'fbx', 'obj', 'glb', 'gltf', 'stl',
378
- 'step', 'stp', 'iges', 'igs', '3ds', 'max', 'c4d', 'ma', 'mb', 'abc', 'usd', 'usdz',
379
- 'iso', 'dmg', 'img', 'vhd', 'vhdx', 'vmdk', 'exe', 'msi', 'dll', 'so', 'dylib', 'bin', 'dat', 'pak',
380
- 'class', 'jar', 'war', 'apk', 'ipa', 'deb', 'rpm', 'appimage', 'raw', 'cr2', 'nef', 'arw', 'dng'])
375
+ // Detection and classification must share one extension inventory. Keeping a second
376
+ // hand-written list here made newly classified types disappear from bare chat text.
377
+ const KNOWN_EXT = new Set([
378
+ ...TEXT_EXT, ...IMAGE_EXT, ...HTML_EXT, ...PDF_EXT, ...MD_EXT,
379
+ ...OFFICE_EXT, ...SHEET_EXT, ...SLIDES_EXT, ...SVG_EXT, ...NOTEBOOK_EXT,
380
+ ...DATABASE_EXT, ...EBOOK_EXT, ...ARCHIVE_EXT, ...VIDEO_EXT, ...AUDIO_EXT,
381
+ ...SUBTITLE_EXT, ...DATA_EXT, ...SCRIPT_EXT, ...CODE_EXT, ...FONT_EXT,
382
+ ...DESIGN_EXT, ...MODEL_EXT, ...DISK_EXT, ...EXEC_EXT,
383
+ // Unclassified binaries and camera assets still deserve file actions.
384
+ 'map', 'lockb', 'arrow', 'bin', 'dat', 'pak', 'raw', 'cr2', 'nef', 'arw', 'dng',
385
+ ])
381
386
 
382
387
  const MIME = {
383
388
  html: 'text/html;charset=utf-8', htm: 'text/html;charset=utf-8', xhtml: 'application/xhtml+xml',
@@ -476,7 +481,9 @@ const BROWSER_VIDEO = new Set(['mp4', 'm4v', 'mov', 'webm', 'ogv'])
476
481
  /** Whether one path sits inside a root directory (case-insensitive on Windows). */
477
482
  function isInside(root, path) {
478
483
  const windows = /^(?:[A-Za-z]:|\\\\|\/\/)/.test(String(root || ''))
479
- const normalize = (value) => windows ? normalizeSlashes(value).toLowerCase() : normalizeSlashes(value)
484
+ // A backslash is a legal POSIX filename character, not a separator. Treating it
485
+ // as one can relabel a sibling such as `/tmp/repo\secret.txt` as workspace content.
486
+ const normalize = (value) => windows ? normalizeSlashes(value).toLowerCase() : String(value || '')
480
487
  const a = normalize(root || '').replace(/\/+$/, '')
481
488
  const b = normalize(path || '')
482
489
  if (a === '' && root === '/') return b.startsWith('/')
@@ -486,8 +493,10 @@ const BROWSER_VIDEO = new Set(['mp4', 'm4v', 'mov', 'webm', 'ogv'])
486
493
 
487
494
  /** The path relative to a root, or '' when it is not inside it. */
488
495
  function relativeTo(root, path) {
489
- const a = normalizeSlashes(root || '').replace(/\/+$/, '')
490
- const b = normalizeSlashes(path || '')
496
+ const windows = /^(?:[A-Za-z]:|\\\\|\/\/)/.test(String(root || ''))
497
+ const normalize = (value) => windows ? normalizeSlashes(value) : String(value || '')
498
+ const a = normalize(root).replace(/\/+$/, '')
499
+ const b = normalize(path)
491
500
  if (a === '' && root === '/') return b.startsWith('/') ? b.slice(1) : ''
492
501
  if (a === '' || b === '') return ''
493
502
  if (!isInside(root, path)) return ''
@@ -1272,21 +1281,31 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1272
1281
  /* ─────────────────────────────── toast ─────────────────────────────── */
1273
1282
 
1274
1283
  let toastTimer = null
1284
+ let toastFrame = 0
1285
+ // An action in flight when the plugin unloads still resolves afterwards. Without a
1286
+ // live-install guard it painted a brand-new toast onto a page that no longer has
1287
+ // this plugin, and nothing was left to remove it.
1288
+ let liveInstalls = 0
1275
1289
  function toast(text, options) {
1276
- if (typeof document === 'undefined' || !text) return
1290
+ if (liveInstalls === 0 || typeof document === 'undefined' || !text) return
1277
1291
  let node = document.querySelector('.dfa-toast')
1278
1292
  if (!node) {
1279
1293
  node = document.createElement('div')
1280
1294
  node.className = 'dfa-toast'
1281
- const floor = menuFloor()
1282
- if (floor) node.style.setProperty('--dfa-floor', floor)
1283
1295
  document.body.appendChild(node)
1284
1296
  }
1297
+ // The toast outlives menus and theme switches, so its contrast floor cannot be
1298
+ // captured only when the node happens to be created.
1299
+ const floor = menuFloor()
1300
+ if (floor) node.style.setProperty('--dfa-floor', floor)
1301
+ else node.style.removeProperty('--dfa-floor')
1285
1302
  node.textContent = text
1286
1303
  node.dataset.error = options && options.error ? 'true' : 'false'
1287
1304
  // Force a frame so a repeated message re-runs the fade-in.
1288
1305
  node.dataset.show = 'false'
1289
- requestAnimationFrame(() => {
1306
+ if (toastFrame) cancelAnimationFrame(toastFrame)
1307
+ toastFrame = requestAnimationFrame(() => {
1308
+ toastFrame = 0
1290
1309
  node.dataset.show = 'true'
1291
1310
  })
1292
1311
  if (toastTimer) clearTimeout(toastTimer)
@@ -1311,13 +1330,27 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1311
1330
  return 'probeFailed'
1312
1331
  }
1313
1332
 
1314
- async function boundedCall(call, milliseconds = 8000) {
1333
+ async function boundedCall(call, milliseconds = 8000, parentSignal) {
1334
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
1335
+ const signal = controller?.signal || parentSignal
1315
1336
  let timer
1337
+ let onAbort
1338
+ if (parentSignal?.aborted) throw new Error('Remote request aborted')
1316
1339
  try {
1317
- return await Promise.race([Promise.resolve().then(call), new Promise((_, reject) => {
1318
- timer = setTimeout(() => reject(new Error('Remote request timed out')), milliseconds)
1340
+ return await Promise.race([Promise.resolve().then(() => call(signal)), new Promise((_, reject) => {
1341
+ timer = setTimeout(() => {
1342
+ controller?.abort()
1343
+ reject(new Error('Remote request timed out'))
1344
+ }, milliseconds)
1345
+ if (parentSignal) {
1346
+ onAbort = () => { controller?.abort(); reject(new Error('Remote request aborted')) }
1347
+ parentSignal.addEventListener('abort', onAbort, { once: true })
1348
+ }
1319
1349
  })])
1320
- } finally { clearTimeout(timer) }
1350
+ } finally {
1351
+ clearTimeout(timer)
1352
+ if (parentSignal && onAbort) parentSignal.removeEventListener('abort', onAbort)
1353
+ }
1321
1354
  }
1322
1355
 
1323
1356
  function createBridge(ctx) {
@@ -1355,12 +1388,15 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1355
1388
 
1356
1389
  return {
1357
1390
  activeSession,
1358
- /** Resolve one path to a real file or directory, or null when it is neither. */
1359
- async probe(sessionId, path) {
1391
+ /** Resolve a file/directory identity, or a named probe error. */
1392
+ async probe(sessionId, path, signal) {
1360
1393
  if (!files) return { error: 'unavailable' }
1394
+ // A cancelled lookup still has queued paths; each would otherwise spend a stat
1395
+ // and a list on a request the caller has already given up on.
1396
+ if (signal?.aborted) return { error: 'aborted' }
1361
1397
  let failure = 'probeFailed'
1362
1398
  try {
1363
- const result = await boundedCall(() => files.stat(sessionId, path))
1399
+ const result = await boundedCall((requestSignal) => files.stat(sessionId, path, requestSignal), 8000, signal)
1364
1400
  const stat = unwrap(result)
1365
1401
  if (!result?.ok) failure = probeError(result?.error)
1366
1402
  if (stat && typeof stat.absolutePath === 'string') {
@@ -1368,19 +1404,21 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1368
1404
  }
1369
1405
  } catch (error) { failure = probeError(error) }
1370
1406
  try {
1371
- const listing = unwrap(await boundedCall(() => files.list(sessionId, path)))
1407
+ const listing = unwrap(await boundedCall((requestSignal) => files.list(sessionId, path, requestSignal), 8000, signal))
1372
1408
  if (listing && Array.isArray(listing.entries)) {
1373
1409
  return { isDir: true, absolutePath: path, bytes: undefined }
1374
1410
  }
1375
1411
  } catch { /* not a directory either */ }
1376
1412
  return { error: failure }
1377
1413
  },
1378
- /** Immediate children of one directory, or null when it is not a directory. */
1379
- async list(sessionId, path) {
1414
+ /** Directory entries with truncation status; null means the listing failed. */
1415
+ async list(sessionId, path, signal) {
1380
1416
  if (!files) return null
1417
+ if (signal?.aborted) return null
1381
1418
  try {
1382
- const listing = unwrap(await boundedCall(() => files.list(sessionId, path)))
1383
- return listing && Array.isArray(listing.entries) ? listing.entries : null
1419
+ const listing = unwrap(await boundedCall((requestSignal) => files.list(sessionId, path, requestSignal), 8000, signal))
1420
+ return listing && Array.isArray(listing.entries)
1421
+ ? { entries: listing.entries, truncated: listing.truncated === true } : null
1384
1422
  } catch {
1385
1423
  return null
1386
1424
  }
@@ -1474,7 +1512,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1474
1512
  * is tested as a path — never strip a leading dot, slash or drive letter.
1475
1513
  */
1476
1514
  function stripDecorations(value) {
1477
- return String(value || '').replace(/^[^\p{L}\p{N}._\\/-]+/u, '').trim()
1515
+ return String(value || '').replace(/^[^\p{L}\p{N}._~\\/-]+/u, '').trim()
1478
1516
  }
1479
1517
 
1480
1518
  /**
@@ -1497,6 +1535,15 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1497
1535
  }
1498
1536
  }
1499
1537
 
1538
+ /**
1539
+ * @typedef {{path?:string,link?:string,sessionId?:string,source:string,explicit?:boolean,reference?:string,element:Element}} ReferenceCandidate
1540
+ * @typedef {{sessionId:string,absolutePath:string,displayPath:string,isDir:boolean,version?:string,bytes?:number,line?:number,endLine?:number,column?:number,reference:string,outsideWorkspace:boolean}} VerifiedFileTarget
1541
+ */
1542
+ function requiresVerification(candidate) {
1543
+ return ['text', 'title'].includes(candidate.source) && candidate.explicit !== true
1544
+ }
1545
+
1546
+ /** @returns {ReferenceCandidate|null} */
1500
1547
  function candidateFromEvent(event, doc) {
1501
1548
  const target = event.target
1502
1549
  if (!target || !target.closest) return null
@@ -1921,6 +1968,99 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1921
1968
  }
1922
1969
  }
1923
1970
 
1971
+ function createReferencePreview(target, { t, root, context, onClose, isCurrent }) {
1972
+ const overlay = makeNode('div', { class: 'dfa-reference-overlay' })
1973
+ const panel = makeNode('section', { class: 'dfa-reference', role: 'dialog', 'aria-modal': 'true', 'aria-label': t.referencePreview })
1974
+ const floor = menuFloor()
1975
+ if (floor) overlay.style.setProperty('--dfa-floor', floor.replace(/, 0\.94\)$/, ', 1)'))
1976
+ overlay.style.color = getComputedStyle(root).color
1977
+ const info = makeNode('div', { class: 'dfa-reference-info' }, [
1978
+ makeNode('div', { class: 'dfa-reference-title', text: t.referencePreview }),
1979
+ makeNode('div', { class: 'dfa-reference-path', text: `${target.displayPath || target.absolutePath} · ${formatLocation(target, t)}` }),
1980
+ ])
1981
+ const close = makeNode('button', { type: 'button', text: t.closePreview })
1982
+ const body = makeNode('div', { class: 'dfa-reference-body', tabindex: '0', 'aria-label': t.referencePreview })
1983
+ body.appendChild(makeNode('div', { class: 'dfa-reference-status', text: t.referenceLoading, role: 'status' }))
1984
+ const hint = makeNode('div', { class: 'dfa-reference-hint' })
1985
+ const copy = makeNode('button', { type: 'button', text: t.copySource, disabled: true })
1986
+ const open = makeNode('button', { type: 'button', text: t.open })
1987
+ panel.appendChild(makeNode('div', { class: 'dfa-reference-head' }, [info, close]))
1988
+ panel.appendChild(body)
1989
+ panel.appendChild(makeNode('div', { class: 'dfa-reference-footer' }, [hint, makeNode('div', { class: 'dfa-reference-actions' }, [open, copy])]))
1990
+ overlay.appendChild(panel)
1991
+ const current = isCurrent
1992
+ const readContext = { ...context, isCurrent: current, confirmMessage: t.confirmOutsidePreview }
1993
+ close.addEventListener('click', () => onClose())
1994
+ overlay.addEventListener('click', event => { if (event.target === overlay) onClose() })
1995
+ open.addEventListener('click', () => { if (current()) void dispatch({ action: 'open' }, target, readContext) })
1996
+ copy.addEventListener('click', async () => {
1997
+ if (!current() || copy.disabled) return
1998
+ copy.disabled = true
1999
+ // Re-read with the original version: never copy a file newer than the preview.
2000
+ await dispatch({ action: 'copySource' }, target, { ...readContext, outsideConfirmed: true })
2001
+ if (current()) copy.disabled = false
2002
+ })
2003
+ return {
2004
+ element: overlay,
2005
+ mount() { document.body.appendChild(overlay); close.focus({ preventScroll: true }) },
2006
+ dispose() { overlay.remove() },
2007
+ handleKeyDown(event) {
2008
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose() }
2009
+ if (event.key === 'Tab') {
2010
+ const controls = [...overlay.querySelectorAll('button:not(:disabled), [tabindex="0"]')]
2011
+ const at = controls.indexOf(document.activeElement)
2012
+ event.preventDefault()
2013
+ controls[(at + (event.shiftKey ? -1 : 1) + controls.length) % controls.length]?.focus()
2014
+ }
2015
+ },
2016
+ async load() {
2017
+ const result = await readTextTarget(target, readContext)
2018
+ if (!current()) return
2019
+ if (!result) { onClose(); return }
2020
+ const preview = result && !result.error ? referenceContext(result.text, target, context.contextLines) : null
2021
+ body.replaceChildren()
2022
+ if (!preview) {
2023
+ body.appendChild(makeNode('div', { class: 'dfa-reference-status', role: 'status', text: result?.error || t.invalidLines }))
2024
+ return
2025
+ }
2026
+ // A later copy must match the read even if the original carrier had no version.
2027
+ if (result.version !== undefined) target = { ...target, version: result.version }
2028
+ for (const row of preview.rows) body.appendChild(makeNode('div', { class: 'dfa-reference-row', 'data-selected': row.selected }, [
2029
+ makeNode('span', { class: 'dfa-reference-number', text: row.line, 'aria-hidden': 'true' }),
2030
+ makeNode('span', { class: 'dfa-reference-code', text: row.text || ' ' }),
2031
+ ]))
2032
+ hint.textContent = t.referenceWindow.replace('{from}', preview.from).replace('{to}', preview.to).replace('{total}', preview.total)
2033
+ + (preview.clipped ? ` · ${t.previewClipped}` : '')
2034
+ copy.disabled = false
2035
+ body.querySelector('[data-selected="true"]')?.scrollIntoView({ block: 'center' })
2036
+ },
2037
+ }
2038
+ }
2039
+
2040
+ function createLightbox({ url, title, kind, t, onClose }) {
2041
+ const overlay = makeNode('div', { class: 'dfa-lightbox', role: 'dialog', 'aria-modal': 'true', 'aria-label': title, tabindex: '-1' })
2042
+ overlay.appendChild(makeNode('img', { src: url, alt: title }))
2043
+ overlay.appendChild(makeNode('div', { class: 'dfa-lightbox-hint', text: kind === 'video' ? t.previewVideoHint : t.previewHint }))
2044
+ overlay.addEventListener('click', onClose)
2045
+ let frame = 0
2046
+ return {
2047
+ element: overlay,
2048
+ mount() {
2049
+ document.body.appendChild(overlay)
2050
+ frame = requestAnimationFrame(() => { frame = 0; overlay.setAttribute('data-show', 'true') })
2051
+ try { overlay.focus({ preventScroll: true }) } catch { /* older engine */ }
2052
+ },
2053
+ dispose() { if (frame) cancelAnimationFrame(frame); overlay.remove() },
2054
+ handleKeyDown(event) {
2055
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose() }
2056
+ else if (event.key === 'Tab') {
2057
+ event.preventDefault(); event.stopPropagation()
2058
+ overlay.focus({ preventScroll: true })
2059
+ }
2060
+ },
2061
+ }
2062
+ }
2063
+
1924
2064
  class FileMenu {
1925
2065
  constructor(options) {
1926
2066
  this.model = options.model
@@ -1938,7 +2078,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1938
2078
  this.body = null
1939
2079
  this.thumbUrl = null
1940
2080
  this.thumbPath = null
1941
- this.lightbox = null
2081
+ this.lightboxView = null
2082
+ this.referenceView = null
1942
2083
  this.submenu = null
1943
2084
  this.submenuFor = null
1944
2085
  this.subOffset = null
@@ -2108,88 +2249,34 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2108
2249
  async openReference(target, context) {
2109
2250
  this.closeReference()
2110
2251
  this.closeSubmenu()
2111
- const overlay = makeNode('div', { class: 'dfa-reference-overlay' })
2112
- const panel = makeNode('section', { class: 'dfa-reference', role: 'dialog', 'aria-modal': 'true', 'aria-label': this.t.referencePreview })
2113
- const floor = menuFloor()
2114
- if (floor) overlay.style.setProperty('--dfa-floor', floor.replace(/, 0\.94\)$/, ', 1)'))
2115
- overlay.style.color = getComputedStyle(this.root).color
2116
- const info = makeNode('div', { class: 'dfa-reference-info' }, [
2117
- makeNode('div', { class: 'dfa-reference-title', text: this.t.referencePreview }),
2118
- makeNode('div', { class: 'dfa-reference-path', text: `${target.displayPath || target.absolutePath} · ${formatLocation(target, this.t)}` }),
2119
- ])
2120
- const close = makeNode('button', { type: 'button', text: this.t.closePreview })
2121
- const body = makeNode('div', { class: 'dfa-reference-body', tabindex: '0', 'aria-label': this.t.referencePreview })
2122
- body.appendChild(makeNode('div', { class: 'dfa-reference-status', text: this.t.referenceLoading, role: 'status' }))
2123
- const hint = makeNode('div', { class: 'dfa-reference-hint' })
2124
- const copy = makeNode('button', { type: 'button', text: this.t.copySource, disabled: true })
2125
- const open = makeNode('button', { type: 'button', text: this.t.open })
2126
- panel.appendChild(makeNode('div', { class: 'dfa-reference-head' }, [info, close]))
2127
- panel.appendChild(body)
2128
- panel.appendChild(makeNode('div', { class: 'dfa-reference-footer' }, [hint, makeNode('div', { class: 'dfa-reference-actions' }, [open, copy])]))
2129
- overlay.appendChild(panel)
2130
- this.referencePreview = overlay
2131
- const current = () => !this.closed && this.referencePreview === overlay && (!context.isCurrent || context.isCurrent())
2132
- const readContext = { ...context, isCurrent: current, confirmMessage: this.t.confirmOutsidePreview }
2133
- close.addEventListener('click', () => this.closeReference())
2134
- overlay.addEventListener('click', event => { if (event.target === overlay) this.closeReference() })
2135
- open.addEventListener('click', () => { if (current()) void dispatch({ action: 'open' }, target, readContext) })
2136
- copy.addEventListener('click', async () => {
2137
- if (!current() || copy.disabled) return
2138
- copy.disabled = true
2139
- // Re-read with the original version: never copy a file newer than the preview.
2140
- await dispatch({ action: 'copySource' }, target, { ...readContext, outsideConfirmed: true })
2141
- if (current()) copy.disabled = false
2252
+ const view = createReferencePreview(target, {
2253
+ t: this.t, root: this.root, context, onClose: () => this.closeReference(),
2254
+ isCurrent: () => !this.closed && this.referenceView === view && (!context.isCurrent || context.isCurrent()),
2142
2255
  })
2143
- document.body.appendChild(overlay)
2144
- close.focus({ preventScroll: true })
2145
- const result = await readTextTarget(target, readContext)
2146
- if (!current()) return
2147
- if (!result) { this.closeReference(); return }
2148
- const preview = result && !result.error ? referenceContext(result.text, target, context.contextLines) : null
2149
- body.replaceChildren()
2150
- if (!preview) {
2151
- body.appendChild(makeNode('div', { class: 'dfa-reference-status', role: 'status', text: result?.error || this.t.invalidLines }))
2152
- return
2153
- }
2154
- // A later copy must match the read even if the original carrier had no version.
2155
- if (result.version !== undefined) target = { ...target, version: result.version }
2156
- for (const row of preview.rows) body.appendChild(makeNode('div', { class: 'dfa-reference-row', 'data-selected': row.selected }, [
2157
- makeNode('span', { class: 'dfa-reference-number', text: row.line, 'aria-hidden': 'true' }),
2158
- makeNode('span', { class: 'dfa-reference-code', text: row.text || ' ' }),
2159
- ]))
2160
- hint.textContent = this.t.referenceWindow.replace('{from}', preview.from).replace('{to}', preview.to).replace('{total}', preview.total)
2161
- + (preview.clipped ? ` · ${this.t.previewClipped}` : '')
2162
- copy.disabled = false
2163
- body.querySelector('[data-selected="true"]')?.scrollIntoView({ block: 'center' })
2256
+ this.referenceView = view
2257
+ view.mount()
2258
+ await view.load()
2164
2259
  }
2165
2260
 
2166
2261
  closeReference() {
2167
- if (!this.referencePreview) return
2168
- this.referencePreview.remove()
2169
- this.referencePreview = null
2262
+ if (!this.referenceView) return
2263
+ this.referenceView.dispose()
2264
+ this.referenceView = null
2170
2265
  try { this.root?.focus({ preventScroll: true }) } catch { /* menu unmounted */ }
2171
2266
  }
2172
2267
 
2173
- /** Show the same preview at full size; the menu stays open behind it. */
2174
2268
  openPreview() {
2175
- if (!this.thumbUrl || this.lightbox) return
2176
- const overlay = makeNode('div', { class: 'dfa-lightbox', role: 'dialog', 'aria-modal': 'true',
2177
- 'aria-label': this.model.title, tabindex: '-1' })
2178
- overlay.appendChild(makeNode('img', { src: this.thumbUrl, alt: this.model.title }))
2179
- overlay.appendChild(makeNode('div', { class: 'dfa-lightbox-hint',
2180
- text: this.model.kind === 'video' ? this.t.previewVideoHint : this.t.previewHint }))
2181
- overlay.addEventListener('click', () => this.closeLightbox())
2182
- document.body.appendChild(overlay)
2183
- requestAnimationFrame(() => overlay.setAttribute('data-show', 'true'))
2184
- this.lightbox = overlay
2185
- try { overlay.focus({ preventScroll: true }) } catch { /* older engine */ }
2269
+ if (!this.thumbUrl || this.lightboxView) return
2270
+ const view = createLightbox({ url: this.thumbUrl, title: this.model.title, kind: this.model.kind, t: this.t, onClose: () => this.closeLightbox() })
2271
+ this.lightboxView = view
2272
+ view.mount()
2186
2273
  }
2187
2274
 
2188
2275
  closeLightbox() {
2189
- if (!this.lightbox) return
2190
- this.lightbox.remove()
2191
- this.lightbox = null
2192
- try { this.root?.focus({ preventScroll: true }) } catch { /* the menu may be gone */ }
2276
+ if (!this.lightboxView) return
2277
+ this.lightboxView.dispose()
2278
+ this.lightboxView = null
2279
+ try { this.root?.focus({ preventScroll: true }) } catch { /* menu unmounted */ }
2193
2280
  }
2194
2281
 
2195
2282
  /** Drop a preview once its bytes have arrived, tagged with the file it belongs to. */
@@ -2537,6 +2624,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2537
2624
  move(delta) {
2538
2625
  if (this.items.length === 0) return
2539
2626
  let next = this.index
2627
+ if (next < 0) next = delta > 0 ? -1 : 0
2540
2628
  for (let step = 0; step < this.items.length; step += 1) {
2541
2629
  next = (next + delta + this.items.length) % this.items.length
2542
2630
  if (!this.items[next].disabled) break
@@ -2559,26 +2647,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2559
2647
  handleKeyDown(event) {
2560
2648
  if (!this.root) return
2561
2649
  if (event.isComposing || event.keyCode === 229) return
2562
- if (this.referencePreview) {
2563
- if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.closeReference() }
2564
- if (event.key === 'Tab') {
2565
- const controls = [...this.referencePreview.querySelectorAll('button:not(:disabled), [tabindex="0"]')]
2566
- const at = controls.indexOf(document.activeElement)
2567
- event.preventDefault()
2568
- controls[(at + (event.shiftKey ? -1 : 1) + controls.length) % controls.length]?.focus()
2569
- }
2570
- return
2571
- }
2572
- // The lightbox is modal: Escape dismisses it. Every other key is left alone so
2573
- // the video transport (space, arrows) keeps working.
2574
- if (this.lightbox) {
2575
- if (event.key === 'Escape') {
2576
- event.preventDefault()
2577
- event.stopPropagation()
2578
- this.closeLightbox()
2579
- }
2580
- return
2581
- }
2650
+ if (this.referenceView) { this.referenceView.handleKeyDown(event); return }
2651
+ if (this.lightboxView) { this.lightboxView.handleKeyDown(event); return }
2582
2652
  const typing = this.searchInput && event.target === this.searchInput
2583
2653
  if (typing && !['ArrowDown', 'ArrowUp', 'Enter', 'Escape', 'Tab'].includes(event.key)) return
2584
2654
  // While the submenu is open it owns the arrows, Enter and Escape, so a
@@ -2675,7 +2745,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2675
2745
  // menu when it opens. Only a real window blur may close it.
2676
2746
  if (event.type === 'blur' && event.target !== window) return
2677
2747
  const target = event.target
2678
- if (target instanceof Node && (this.lightbox?.contains(target) || this.referencePreview?.contains(target))) return
2748
+ if (target instanceof Node && (this.lightboxView?.element.contains(target) || this.referenceView?.element.contains(target))) return
2679
2749
  if (target instanceof Node && (this.root.contains(target) || (this.submenu && this.submenu.contains(target)))) return
2680
2750
  this.close()
2681
2751
  }
@@ -2773,33 +2843,34 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2773
2843
  const READ_CHUNK_BYTES = 2 * 1024 * 1024
2774
2844
  const READ_TOTAL_MAX_BYTES = 64 * 1024 * 1024
2775
2845
 
2846
+ /** @returns {Promise<{kind:'ok',bytes:Uint8Array}|{kind:'failed'|'changed'|'too-large'}>} */
2776
2847
  async function readAllBytes(bridge, sessionId, path) {
2777
2848
  const chunks = []
2778
2849
  let total = 0
2779
2850
  let identity
2780
2851
  for (let guard = 0; guard < 64; guard += 1) {
2781
2852
  const result = await bridge.readBytes(sessionId, path, { range: { offset: total, length: READ_CHUNK_BYTES } })
2782
- if (!result || !(result.data instanceof Uint8Array)) return null
2853
+ if (!result || !(result.data instanceof Uint8Array)) return { kind: 'failed' }
2783
2854
  if (typeof result.version !== 'string' || !result.version || typeof result.absolutePath !== 'string'
2784
- || result.offset !== total || typeof result.eof !== 'boolean') return null
2855
+ || result.offset !== total || typeof result.eof !== 'boolean') return { kind: 'failed' }
2785
2856
  if (!identity) identity = { version: result.version, path: result.absolutePath, bytes: result.bytes }
2786
2857
  else if (result.version !== identity.version || result.absolutePath !== identity.path
2787
- || result.bytes !== identity.bytes) return { changed: true }
2788
- if (result.data.byteLength === 0 && result.eof === false) return null
2789
- if (total + result.data.byteLength > READ_TOTAL_MAX_BYTES || result.bytes > READ_TOTAL_MAX_BYTES) return { tooLarge: true }
2858
+ || result.bytes !== identity.bytes) return { kind: 'changed' }
2859
+ if (result.data.byteLength === 0 && result.eof === false) return { kind: 'failed' }
2860
+ if (total + result.data.byteLength > READ_TOTAL_MAX_BYTES || result.bytes > READ_TOTAL_MAX_BYTES) return { kind: 'too-large' }
2790
2861
  chunks.push(result.data)
2791
2862
  total += result.data.byteLength
2792
- if (result.eof && typeof result.bytes === 'number' && total !== result.bytes) return { changed: true }
2863
+ if (result.eof && typeof result.bytes === 'number' && total !== result.bytes) return { kind: 'changed' }
2793
2864
  if (result.eof !== false) {
2794
- if (chunks.length === 1) return result.data
2865
+ if (chunks.length === 1) return { kind: 'ok', bytes: result.data }
2795
2866
  const merged = new Uint8Array(total)
2796
2867
  let at = 0
2797
2868
  for (const chunk of chunks) { merged.set(chunk, at); at += chunk.byteLength }
2798
- return merged
2869
+ return { kind: 'ok', bytes: merged }
2799
2870
  }
2800
- if (total >= READ_TOTAL_MAX_BYTES) return { tooLarge: true }
2871
+ if (total >= READ_TOTAL_MAX_BYTES) return { kind: 'too-large' }
2801
2872
  }
2802
- return null
2873
+ return { kind: 'failed' }
2803
2874
  }
2804
2875
 
2805
2876
  function downloadBytes(bytes, name, mime) {
@@ -2887,7 +2958,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2887
2958
  const MAX_COPY_BYTES = 2 * 1024 * 1024
2888
2959
 
2889
2960
  async function readTextTarget(target, context) {
2890
- const { bridge, t, sessionId } = context
2961
+ const { bridge, t } = context
2962
+ const sessionId = target.sessionId ?? context.sessionId
2891
2963
  const current = () => !context.isCurrent || context.isCurrent()
2892
2964
  if (!current()) return null
2893
2965
  if (typeof target.bytes === 'number' && target.bytes > MAX_COPY_BYTES) return { error: t.tooLarge }
@@ -2925,7 +2997,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2925
2997
  }
2926
2998
 
2927
2999
  async function dispatch(item, target, context) {
2928
- const { bridge, t, sessionId } = context
3000
+ const { bridge, t } = context
3001
+ const sessionId = target.sessionId ?? context.sessionId
2929
3002
  const path = target.absolutePath
2930
3003
  const copyingText = item.action === 'copyContents' || item.action === 'copyLines' || item.action === 'copySource'
2931
3004
  if (item.action === 'openLink' || item.action === 'copyLink' || item.action === 'copyLinkText') {
@@ -2954,7 +3027,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2954
3027
  } else if (item.appId && hadFocus) {
2955
3028
  clearTimeout(silentHintTimer)
2956
3029
  silentHintTimer = setTimeout(() => {
2957
- if (!disposed && shouldHintSilentOpen(hadFocus, document.hasFocus())) toast(t.openNoEffect)
3030
+ if ((!context.isCurrent || context.isCurrent()) && shouldHintSilentOpen(hadFocus, document.hasFocus())) toast(t.openNoEffect)
2958
3031
  }, 1800)
2959
3032
  }
2960
3033
  return
@@ -3000,21 +3073,21 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3000
3073
  }
3001
3074
  win.opener = null
3002
3075
  const bytes = await readAllBytes(bridge, sessionId, path)
3003
- if (!bytes || bytes.tooLarge || bytes.changed) {
3076
+ if (bytes.kind !== 'ok') {
3004
3077
  try { win.close() } catch { /* already gone */ }
3005
- toast(bytes?.changed ? t.fileChanged : bytes?.tooLarge ? t.tooLarge : t.readFailed, { error: true })
3078
+ toast(bytes.kind === 'changed' ? t.fileChanged : bytes.kind === 'too-large' ? t.tooLarge : t.readFailed, { error: true })
3006
3079
  return
3007
3080
  }
3008
- if (!fillBrowserWindow(win, bytes, mimeOf(path), t)) toast(t.popupBlocked, { error: true })
3081
+ if (!fillBrowserWindow(win, bytes.bytes, mimeOf(path), t)) toast(t.popupBlocked, { error: true })
3009
3082
  return
3010
3083
  }
3011
3084
  if (item.action === 'saveAs') {
3012
3085
  const bytes = await readAllBytes(bridge, sessionId, path)
3013
- if (!bytes || bytes.tooLarge || bytes.changed) {
3014
- toast(bytes?.changed ? t.fileChanged : bytes?.tooLarge ? t.tooLarge : t.readFailed, { error: true })
3086
+ if (bytes.kind !== 'ok') {
3087
+ toast(bytes.kind === 'changed' ? t.fileChanged : bytes.kind === 'too-large' ? t.tooLarge : t.readFailed, { error: true })
3015
3088
  return
3016
3089
  }
3017
- downloadBytes(bytes, basename(path), mimeOf(path))
3090
+ downloadBytes(bytes.bytes, basename(path), mimeOf(path))
3018
3091
  return
3019
3092
  }
3020
3093
  if (copyingText) {
@@ -3053,239 +3126,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3053
3126
  }
3054
3127
  }
3055
3128
 
3056
- function start(ctx) {
3057
- if (typeof document === 'undefined' || typeof window === 'undefined') return
3058
- ensureCss()
3059
- const bridge = createBridge(ctx)
3060
- const t = messages(detectLanguage(ctx))
3061
-
3062
- let menu = null
3063
- let followFrame = 0
3064
- let generation = 0
3129
+ function createApplicationCache(bridge, storage, notifySettings) {
3065
3130
  let disposed = false
3066
-
3067
- function closeMenu() {
3068
- generation++
3069
- if (followFrame) { cancelAnimationFrame(followFrame); followFrame = 0 }
3070
- if (menu) {
3071
- menu.close()
3072
- menu = null
3073
- }
3074
- }
3075
-
3076
- // Guessed text must be verified before cancelling the browser's menu. Warm
3077
- // it on hover/focus; a cold right-click keeps the native menu for that click.
3078
- const probeCache = new Map()
3079
- const probePending = new Map()
3080
- function locate(candidate) {
3081
- const session = bridge.activeSession(candidate.sessionId)
3082
- const located = stripLocationSuffix(candidate.path)
3083
- const path = isAbsolutePath(located.path) ? located.path : joinPath(session?.cwd, located.path)
3084
- return { session, located, path, key: JSON.stringify([session?.id, path]) }
3085
- }
3086
- function cachedProbe(candidate) {
3087
- const cached = probeCache.get(locate(candidate).key)
3088
- return cached && Date.now() - cached.at < 5000 ? cached.value : null
3089
- }
3090
-
3091
- // A relative reference in prose often names a file that only exists one directory
3092
- // down — `docs/HANDOFF.md` while the session root is its parent. Try the root's
3093
- // immediate subdirectories once: a single hit is unambiguous, several are a guess.
3094
- const RESCUE_TTL_MS = 60 * 1000
3095
- const rescueCache = new Map()
3096
- const RESCUE_CACHE_MAX = 200
3097
- function rememberRescue(key, path) {
3098
- if (rescueCache.size >= RESCUE_CACHE_MAX && !rescueCache.has(key)) rescueCache.delete(rescueCache.keys().next().value)
3099
- rescueCache.set(key, { path, at: Date.now() })
3100
- }
3101
- // Prose often abbreviates a path that lives several directories down — `docs/x.md`
3102
- // while the session root is three levels above it. Walk the tree breadth-first with a
3103
- // hard call/time budget and accept a result only when exactly one descendant matches;
3104
- // a second hit means the name is ambiguous, which is the caller's problem, not ours.
3105
- const RESCUE_MAX_DEPTH = 3
3106
- const RESCUE_MAX_PROBES = 48
3107
- const RESCUE_BUDGET_MS = 900
3108
- const RESCUE_MISS_TTL_MS = 5 * 60 * 1000
3109
- const RESCUE_PARALLEL = 6
3110
- // Build output never holds the file a message refers to, and walking it costs the
3111
- // whole budget on its own.
3112
- const RESCUE_SKIP = new Set(['node_modules', 'dist', 'build', 'out', 'bin', 'obj', 'target', 'vendor', 'coverage'])
3113
-
3114
- async function eachLimited(items, worker, limit = RESCUE_PARALLEL) {
3115
- let cursor = 0
3116
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
3117
- while (cursor < items.length) {
3118
- const index = cursor++
3119
- await worker(items[index])
3120
- }
3121
- }))
3122
- }
3123
-
3124
- // Prose often abbreviates where a file lives on disk. Walk the tree breadth-first, one
3125
- // level at a time in small parallel batches, and stop at the first matching level:
3126
- // shallower wins, and two hits at that level mean the name is ambiguous, not usable.
3127
- async function resolveBelowRoot(session, relativePath) {
3128
- if (!session || !relativePath || isAbsolutePath(relativePath)) return null
3129
- // A bare file name matches half the tree; only a path with a directory part is
3130
- // specific enough to be worth the walk.
3131
- if (!relativePath.includes('/') && !relativePath.includes('\\')) return null
3132
- const cacheKey = JSON.stringify([session.id, relativePath])
3133
- const cached = rescueCache.get(cacheKey)
3134
- const ttl = cached && cached.path ? RESCUE_TTL_MS : RESCUE_MISS_TTL_MS
3135
- if (cached && Date.now() - cached.at < ttl) return cached.path
3136
- const deadline = Date.now() + RESCUE_BUDGET_MS
3137
- let level = [session.cwd]
3138
- let probes = 0
3139
- let found = null
3140
- for (let depth = 0; depth < RESCUE_MAX_DEPTH && level.length && !found; depth += 1) {
3141
- if (Date.now() > deadline) break
3142
- const listings = await Promise.all(level.map((dir) => bridge.list(session.id, dir)))
3143
- const children = []
3144
- listings.forEach((entries, index) => {
3145
- if (!entries) return
3146
- for (const entry of entries) {
3147
- if (!entry || (entry.type !== 'directory' && entry.type !== 'symlink')) continue
3148
- const name = String(entry.name || '')
3149
- if (!name || name.startsWith('.') || RESCUE_SKIP.has(name.toLowerCase())) continue
3150
- children.push(joinPath(level[index], name))
3151
- }
3152
- })
3153
- const hits = []
3154
- await eachLimited(children, async (dir) => {
3155
- if (found || probes >= RESCUE_MAX_PROBES || Date.now() > deadline) return
3156
- probes += 1
3157
- const probe = await bridge.probe(session.id, joinPath(dir, relativePath))
3158
- if (probe && !probe.error) hits.push(probe.absolutePath)
3159
- })
3160
- if (hits.length > 1) { rememberRescue(cacheKey, null); return null }
3161
- if (hits.length === 1) found = hits[0]
3162
- level = children
3163
- }
3164
- rememberRescue(cacheKey, found)
3165
- return found
3166
- }
3167
- function warmCandidate(candidate) {
3168
- if (!candidate || candidate.link) return
3169
- const { session, path, key } = locate(candidate)
3170
- if (!session || !path) return
3171
- const guess = ['text', 'title'].includes(candidate.source) && candidate.explicit !== true
3172
- if (!guess) {
3173
- // An explicit carrier already names a real path, so the association query —
3174
- // the slowest part of the menu — can start on hover instead of on click.
3175
- void applicationsFor(path)
3176
- return
3177
- }
3178
- if (cachedProbe(candidate) || probePending.has(key) || probePending.size >= 4) return
3179
- const pending = bridge.probe(session.id, path).then((value) => {
3180
- if (disposed) return
3181
- if (probeCache.size >= 64) probeCache.delete(probeCache.keys().next().value)
3182
- probeCache.set(key, { value, at: Date.now() })
3183
- // The path is confirmed, so warm the association query as well.
3184
- if (value && !value.isDir && !value.error) void applicationsFor(path)
3185
- }).finally(() => probePending.delete(key))
3186
- probePending.set(key, pending)
3187
- }
3188
- let preferenceStorage
3189
- try { preferenceStorage = window.localStorage } catch { /* private storage may be disabled */ }
3190
- const settingsViews = new Set()
3191
- const notifySettings = () => { for (const render of settingsViews) render() }
3192
- const config = clientPreferences(preferenceStorage)
3193
- const preferences = applicationPreferences(preferenceStorage, notifySettings)
3194
-
3195
- async function openAt(candidate, x, y, keyboard) {
3196
- if (disposed) return
3197
- closeMenu()
3198
- // Glass is a per-open decision: the wallpaper plugin can switch its gate at any
3199
- // time, and the menu is rebuilt on every right-click anyway.
3200
- try { document.documentElement.dataset.dfaGlass = config.get().glass === 'off' ? 'off' : 'on' } catch { /* no document */ }
3201
- const attempt = ++generation
3202
- let handle
3203
- try {
3204
- if (candidate.link) {
3205
- const text = String(candidate.element?.textContent || '').trim().slice(0, 512)
3206
- const target = { link: candidate.link, text }
3207
- handle = new FileMenu({ model: buildLinkMenuModel({ url: candidate.link, text, t, menuMode: config.get().menuMode }),
3208
- x, y, keyboard, anchor: candidate.element, t,
3209
- onClose: () => { if (menu === handle) menu = null },
3210
- onPick: (item) => { void dispatch(item, target, { bridge, t }) },
3211
- })
3212
- menu = handle
3213
- handle.open()
3214
- return
3215
- }
3216
- const { session, located, path } = locate(candidate)
3217
- const modelInput = { absolutePath: path, displayPath: located.path, apps: [], appsState: 'loading',
3218
- location: located, reference: candidate.reference || candidate.path, t, menuMode: config.get().menuMode }
3219
- let target
3220
- const activeSessionId = bridge.activeSession()?.id
3221
- const isCurrent = () => !disposed && attempt === generation && bridge.activeSession()?.id === activeSessionId
3222
- handle = new FileMenu({ model: buildStatusModel(path, t.checking, t),
3223
- x, y, keyboard, anchor: candidate.element, t,
3224
- onClose: () => { if (menu === handle) menu = null },
3225
- onPick: (item) => {
3226
- if (item.action === 'referencePreview' && target) { void handle.openReference(target, { bridge, t, sessionId: session.id, isCurrent, contextLines: config.get().contextLines, onFileChanged: () => probeCache.delete(locate(candidate).key) }); return }
3227
- if (item.action === 'retry') { void openAt(candidate, x, y, keyboard); return }
3228
- if (item.action === 'preferApp') {
3229
- const appId = preferences.get(path) === item.appId ? '' : item.appId
3230
- const saved = preferences.set(path, appId)
3231
- toast(saved ? (appId ? t.preferenceSaved : t.preferenceCleared) : t.preferenceFailed, { error: !saved })
3232
- return
3233
- }
3234
- if (target) void dispatch(item, target, { bridge, t, sessionId: session.id,
3235
- onFileChanged: () => probeCache.delete(locate(candidate).key),
3236
- validateApplication: async (file, id) => {
3237
- const cached = appsCache.get(extname(file).toLowerCase())
3238
- const result = await applicationsFor(file, cached?.needsValidation === true)
3239
- return result.state === 'ready' && result.apps.some((app) => app.id === id)
3240
- },
3241
- onOpenFailed: (file) => {
3242
- appsCache.delete(extname(file).toLowerCase())
3243
- scheduleStoreWrite()
3244
- void applicationsFor(file, true)
3245
- },
3246
- })
3247
- },
3248
- })
3249
- menu = handle
3250
- handle.open()
3251
- if (!session) {
3252
- handle.setModel(buildStatusModel(path, t.noSession, t, true))
3253
- return
3254
- }
3255
- let probe = cachedProbe(candidate) || await bridge.probe(session.id, path)
3256
- if (probe && probe.error === 'notFound') {
3257
- // Prose often abbreviates a nested path; the walk is bounded, so tell the user
3258
- // what the extra beat is for before spending it.
3259
- handle.setModel(buildStatusModel(path, t.locating, t))
3260
- const rescued = await resolveBelowRoot(session, located.path)
3261
- if (rescued) probe = await bridge.probe(session.id, rescued)
3262
- }
3263
- if (disposed || attempt !== generation || handle.closed) return
3264
- if (!probe || probe.error) {
3265
- handle.setModel(buildStatusModel(path, t[probe?.error] || t.probeFailed, t, true))
3266
- return
3267
- }
3268
- const displayPath = relativeTo(session.cwd, probe.absolutePath) || probe.absolutePath
3269
- Object.assign(modelInput, { absolutePath: probe.absolutePath, displayPath, isDir: probe.isDir,
3270
- bytes: probe.bytes, outsideWorkspace: !isInside(session.cwd, probe.absolutePath),
3271
- cwd: session.cwd, preferredId: preferences.get(probe.absolutePath) })
3272
- target = { absolutePath: probe.absolutePath, displayPath,
3273
- isDir: probe.isDir, version: probe.version, line: located.line, endLine: located.endLine, column: located.column, bytes: probe.bytes,
3274
- reference: candidate.reference || candidate.path, outsideWorkspace: !isInside(session.cwd, probe.absolutePath) }
3275
- handle.setModel(buildMenuModel(modelInput))
3276
- if (!probe.isDir) void enrich(handle, modelInput)
3277
- const previewKind = classify(probe.absolutePath, false).kind
3278
- if (!probe.isDir && (previewKind === 'image' || previewKind === 'video' || extname(probe.absolutePath) === 'svg')) {
3279
- void loadThumb(handle, session.id, probe.absolutePath, probe.bytes, probe.version)
3280
- }
3281
- } catch (error) {
3282
- if (!disposed && attempt === generation && handle && !handle.closed) {
3283
- handle.setModel(buildStatusModel(candidate.path, t.probeFailed, t, true))
3284
- }
3285
- console.warn('[dsh-file-actions] context menu failed:', error)
3286
- }
3287
- }
3288
-
3289
3131
  // Associations are per file type, so one query per extension serves the page.
3290
3132
  // Ten minutes keeps a newly installed editor visible without re-asking the
3291
3133
  // OS on every right-click.
@@ -3304,7 +3146,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3304
3146
 
3305
3147
  function readAppsStore() {
3306
3148
  try {
3307
- const raw = window.localStorage.getItem(APPS_STORE_KEY)
3149
+ const raw = storage.getItem(APPS_STORE_KEY)
3308
3150
  const parsed = raw ? JSON.parse(raw) : null
3309
3151
  return parsed && typeof parsed === 'object' && parsed.entries && typeof parsed.entries === 'object'
3310
3152
  ? parsed.entries : {}
@@ -3331,12 +3173,12 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3331
3173
  entries[key] = record
3332
3174
  chars += size
3333
3175
  }
3334
- window.localStorage.setItem(APPS_STORE_KEY, JSON.stringify({ version: 1, entries }))
3176
+ storage.setItem(APPS_STORE_KEY, JSON.stringify({ version: 1, entries }))
3335
3177
  } catch { /* storage blocked or full: the in-memory cache still works */ }
3336
3178
  }
3337
3179
 
3338
3180
  function scheduleStoreWrite() {
3339
- if (storeTimer) return
3181
+ if (disposed || storeTimer) return
3340
3182
  storeTimer = setTimeout(writeAppsStore, 400)
3341
3183
  }
3342
3184
 
@@ -3357,6 +3199,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3357
3199
  * running — must join the existing request instead of starting another one.
3358
3200
  */
3359
3201
  function applicationsFor(path, refresh = false) {
3202
+ if (disposed) return Promise.resolve({ state: 'failed', apps: [] })
3360
3203
  const key = extname(path).toLowerCase()
3361
3204
  const cached = appsCache.get(key)
3362
3205
  if (!refresh && cached && Date.now() - cached.at < cached.ttl) return Promise.resolve(cached.result)
@@ -3382,18 +3225,38 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3382
3225
  return request
3383
3226
  }
3384
3227
 
3385
- async function enrich(handle, input) {
3386
- const needsValidation = appsCache.get(extname(input.absolutePath).toLowerCase())?.needsValidation === true
3387
- const paint = (result) => {
3388
- if (disposed || menu !== handle || handle.closed) return
3389
- if (input.appsState === result.state && JSON.stringify(input.apps) === JSON.stringify(result.apps)) return
3390
- Object.assign(input, { apps: result.apps, appsState: result.state })
3391
- handle.setModel(buildMenuModel(input))
3392
- }
3393
- paint(await applicationsFor(input.absolutePath))
3394
- if (needsValidation && !disposed) paint(await applicationsFor(input.absolutePath, true))
3228
+ return {
3229
+ forPath: applicationsFor,
3230
+ needsValidation: path => appsCache.get(extname(path).toLowerCase())?.needsValidation === true,
3231
+ size: () => appsCache.size,
3232
+ nameOf(id) {
3233
+ for (const { result } of appsCache.values()) {
3234
+ const app = result.apps.find(app => app.id === id)
3235
+ if (app) return app.name
3236
+ }
3237
+ return basename(id) || id
3238
+ },
3239
+ invalidatePath(path) {
3240
+ if (disposed) return
3241
+ appsCache.delete(extname(path).toLowerCase()); scheduleStoreWrite()
3242
+ },
3243
+ clear(removeStored = false) {
3244
+ if (removeStored) { try { storage.removeItem(APPS_STORE_KEY) } catch { return false } }
3245
+ if (storeTimer) { clearTimeout(storeTimer); storeTimer = 0 }
3246
+ appsEpoch++; appsCache.clear(); appsPending.clear()
3247
+ return true
3248
+ },
3249
+ storageKey: APPS_STORE_KEY,
3250
+ dispose() {
3251
+ disposed = true
3252
+ if (storeTimer) clearTimeout(storeTimer)
3253
+ appsCache.clear(); appsPending.clear()
3254
+ },
3395
3255
  }
3256
+ }
3396
3257
 
3258
+ function createPreviewCache(bridge, isCurrentMenu) {
3259
+ let disposed = false
3397
3260
  // A thumbnail is worth one bounded read; bigger files just keep the tile.
3398
3261
  const THUMB_MAX_BYTES = 8 * 1024 * 1024
3399
3262
  // Bound the cache by bytes, not entries: one poster or 4.9 MB still can hold
@@ -3453,16 +3316,17 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3453
3316
  }
3454
3317
 
3455
3318
  async function loadThumb(handle, sessionId, absolutePath, bytes, version) {
3319
+ if (disposed) return
3456
3320
  try {
3457
3321
  if (typeof bytes === 'number' && bytes > THUMB_MAX_BYTES) { handle.setThumbnail(null, absolutePath); return }
3458
3322
  const key = JSON.stringify([sessionId, absolutePath, version])
3459
3323
  const cached = version && thumbCache.get(key)
3460
3324
  if (cached) {
3461
- if (menu === handle && !handle.closed) handle.setThumbnail(cached.url, absolutePath)
3325
+ if (isCurrentMenu(handle) && !handle.closed) handle.setThumbnail(cached.url, absolutePath)
3462
3326
  return
3463
3327
  }
3464
3328
  const result = await bridge.readBytes(sessionId, absolutePath)
3465
- if (disposed || menu !== handle || handle.closed) return
3329
+ if (disposed || !isCurrentMenu(handle) || handle.closed) return
3466
3330
  if (!result || !(result.data instanceof Uint8Array) || result.eof === false || result.data.byteLength > THUMB_MAX_BYTES) {
3467
3331
  handle.setThumbnail(null, absolutePath)
3468
3332
  return
@@ -3485,13 +3349,323 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3485
3349
  thumbCache.delete(oldKey)
3486
3350
  total -= entry.size
3487
3351
  }
3488
- if (menu === handle && !handle.closed) handle.setThumbnail(url, absolutePath)
3352
+ if (isCurrentMenu(handle) && !handle.closed) handle.setThumbnail(url, absolutePath)
3489
3353
  } catch (error) {
3490
- if (menu === handle && !handle.closed) handle.setThumbnail(null, absolutePath)
3354
+ if (isCurrentMenu(handle) && !handle.closed) handle.setThumbnail(null, absolutePath)
3491
3355
  console.warn('[dsh-file-actions] thumbnail failed:', error)
3492
3356
  }
3493
3357
  }
3494
3358
 
3359
+ return {
3360
+ load: loadThumb,
3361
+ dispose() {
3362
+ disposed = true
3363
+ for (const value of thumbCache.values()) URL.revokeObjectURL(value.url)
3364
+ thumbCache.clear()
3365
+ },
3366
+ }
3367
+ }
3368
+
3369
+ function createMenuSession(bridge) {
3370
+ let menu = null, generation = 0, disposed = false, lookup = null
3371
+ function close() {
3372
+ generation++
3373
+ if (lookup) { lookup.abort(); lookup = null }
3374
+ if (menu) { menu.close(); menu = null }
3375
+ }
3376
+ return {
3377
+ get menu() { return menu },
3378
+ get disposed() { return disposed },
3379
+ setMenu(value) { menu = value },
3380
+ releaseMenu(value) { if (menu === value) menu = null },
3381
+ close,
3382
+ begin() {
3383
+ close()
3384
+ const attempt = generation
3385
+ const sessionId = bridge.activeSession()?.id
3386
+ const controller = new AbortController()
3387
+ lookup = controller
3388
+ return {
3389
+ signal: controller.signal,
3390
+ isPending: () => !disposed && attempt === generation,
3391
+ isCurrent: () => !disposed && attempt === generation && bridge.activeSession()?.id === sessionId,
3392
+ cancelLookup() { if (lookup === controller) { controller.abort(); lookup = null } },
3393
+ }
3394
+ },
3395
+ dispose() { disposed = true; close() },
3396
+ }
3397
+ }
3398
+
3399
+ function start(ctx) {
3400
+ if (typeof document === 'undefined' || typeof window === 'undefined') return
3401
+ ensureCss()
3402
+ const bridge = createBridge(ctx)
3403
+ const t = messages(detectLanguage(ctx))
3404
+
3405
+ const menuSession = createMenuSession(bridge)
3406
+ let followFrame = 0
3407
+
3408
+ function closeMenu() {
3409
+ if (followFrame) { cancelAnimationFrame(followFrame); followFrame = 0 }
3410
+ menuSession.close()
3411
+ }
3412
+
3413
+ // Guessed text must be verified before cancelling the browser's menu. Warm
3414
+ // it on hover/focus; a cold right-click keeps the native menu for that click.
3415
+ const probeCache = new Map()
3416
+ const probePending = new Map()
3417
+ function locate(candidate) {
3418
+ const session = bridge.activeSession(candidate.sessionId)
3419
+ const located = stripLocationSuffix(candidate.path)
3420
+ const path = isAbsolutePath(located.path) ? located.path : joinPath(session?.cwd, located.path)
3421
+ return { session, located, path, key: JSON.stringify([session?.id, path]) }
3422
+ }
3423
+ function cachedProbe(candidate) {
3424
+ const cached = probeCache.get(locate(candidate).key)
3425
+ return cached && Date.now() - cached.at < 5000 ? cached.value : null
3426
+ }
3427
+
3428
+ const RESCUE_TTL_MS = 60 * 1000
3429
+ const rescueCache = new Map()
3430
+ const RESCUE_CACHE_MAX = 200
3431
+ function rememberRescue(key, result) {
3432
+ if (rescueCache.size >= RESCUE_CACHE_MAX && !rescueCache.has(key)) rescueCache.delete(rescueCache.keys().next().value)
3433
+ rescueCache.set(key, { result, at: Date.now() })
3434
+ }
3435
+ // Prose often abbreviates a path that lives several directories down — `docs/x.md`
3436
+ // while the session root is three levels above it. Walk the tree breadth-first with a
3437
+ // hard call/time budget and accept a result only when exactly one descendant matches;
3438
+ // a second hit means the name is ambiguous, which is the caller's problem, not ours.
3439
+ const RESCUE_MAX_DEPTH = 3
3440
+ const RESCUE_MAX_PROBES = 48
3441
+ const RESCUE_BUDGET_MS = 900
3442
+ const RESCUE_MISS_TTL_MS = 5 * 60 * 1000
3443
+ const RESCUE_PARALLEL = 6
3444
+ // A walk that ran out of budget saw only part of the tree: it can prove neither a
3445
+ // hit nor a miss, so it must not be reported as "not found" or cached as one.
3446
+ // Build output never holds the file a message refers to, and walking it costs the
3447
+ // whole budget on its own.
3448
+ const RESCUE_SKIP = new Set(['node_modules', 'dist', 'build', 'out', 'bin', 'obj', 'target', 'vendor', 'coverage'])
3449
+
3450
+ async function eachLimited(items, worker, limit = RESCUE_PARALLEL) {
3451
+ let cursor = 0
3452
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
3453
+ while (cursor < items.length) {
3454
+ const index = cursor++
3455
+ await worker(items[index], index)
3456
+ }
3457
+ }))
3458
+ }
3459
+
3460
+ // Prose often abbreviates where a file lives on disk. Walk the tree breadth-first, one
3461
+ // level at a time in small parallel batches, and stop at the first matching level:
3462
+ // shallower wins, and two hits at that level mean the name is ambiguous, not usable.
3463
+ async function resolveBelowRoot(session, relativePath, isActive = () => true, signal) {
3464
+ if (!session || typeof session.cwd !== 'string' || !session.cwd || !relativePath || isAbsolutePath(relativePath)) return { kind: 'missing' }
3465
+ // A bare file name matches half the tree; only a path with a directory part is
3466
+ // specific enough to be worth the walk.
3467
+ if (!relativePath.includes('/') && !relativePath.includes('\\')) return { kind: 'missing' }
3468
+ const cacheKey = JSON.stringify([session.id, session.cwd, relativePath])
3469
+ const cached = rescueCache.get(cacheKey)
3470
+ const ttl = cached?.result.kind === 'found' ? RESCUE_TTL_MS : RESCUE_MISS_TTL_MS
3471
+ if (cached && Date.now() - cached.at < ttl) return cached.result
3472
+ const deadline = Date.now() + RESCUE_BUDGET_MS
3473
+ let level = [session.cwd]
3474
+ let probes = 0
3475
+ let found = null
3476
+ let complete = true
3477
+ for (let depth = 0; depth < RESCUE_MAX_DEPTH && level.length && !found; depth += 1) {
3478
+ if (!isActive()) return { kind: 'cancelled' }
3479
+ if (Date.now() >= deadline || probes >= RESCUE_MAX_PROBES) { complete = false; break }
3480
+ const listings = new Array(level.length)
3481
+ let levelComplete = true
3482
+ // Directory expansion shares the same call budget as file probes. Promise.all
3483
+ // over an unbounded previous level turned a nominal 48-probe cap into a full scan.
3484
+ await eachLimited(level, async (dir, index) => {
3485
+ if (!isActive() || probes >= RESCUE_MAX_PROBES || Date.now() >= deadline) { levelComplete = false; return }
3486
+ probes += 1
3487
+ const listing = await bridge.list(session.id, dir, signal)
3488
+ if (!listing || listing.truncated) levelComplete = false
3489
+ listings[index] = listing
3490
+ })
3491
+ if (!isActive()) return { kind: 'cancelled' }
3492
+ // A partial level cannot prove either uniqueness or absence. Leave the cache
3493
+ // untouched so a transient listing error does not become a five-minute miss.
3494
+ if (!levelComplete) return { kind: 'incomplete' }
3495
+ const children = []
3496
+ listings.forEach((listing, index) => {
3497
+ for (const entry of listing.entries) {
3498
+ if (!entry || (entry.type !== 'directory' && entry.type !== 'symlink')) continue
3499
+ const name = String(entry.name || '')
3500
+ if (!name || name.startsWith('.') || RESCUE_SKIP.has(name.toLowerCase())) continue
3501
+ children.push(joinPath(level[index], name))
3502
+ }
3503
+ })
3504
+ const hits = []
3505
+ await eachLimited(children, async (dir) => {
3506
+ if (!isActive() || probes >= RESCUE_MAX_PROBES || Date.now() >= deadline) { levelComplete = false; return }
3507
+ probes += 1
3508
+ const probe = await bridge.probe(session.id, joinPath(dir, relativePath), signal)
3509
+ if (!probe || (probe.error && probe.error !== 'notFound')) levelComplete = false
3510
+ if (probe && !probe.error) hits.push(probe.absolutePath)
3511
+ })
3512
+ if (!isActive()) return { kind: 'cancelled' }
3513
+ if (!levelComplete) return { kind: 'incomplete' }
3514
+ if (hits.length > 1) { const result = { kind: 'ambiguous' }; rememberRescue(cacheKey, result); return result }
3515
+ if (hits.length === 1) found = hits[0]
3516
+ level = children
3517
+ }
3518
+ if (!complete) return { kind: 'incomplete' }
3519
+ const result = found ? { kind: 'found', path: found } : { kind: 'missing' }
3520
+ rememberRescue(cacheKey, result)
3521
+ return result
3522
+ }
3523
+ function warmCandidate(candidate) {
3524
+ if (!candidate || candidate.link) return
3525
+ const { session, path, key } = locate(candidate)
3526
+ if (!session || !path) return
3527
+ const guess = requiresVerification(candidate)
3528
+ if (!guess) {
3529
+ // An explicit carrier already names a real path, so the association query —
3530
+ // the slowest part of the menu — can start on hover instead of on click.
3531
+ void applicationsFor(path)
3532
+ return
3533
+ }
3534
+ if (cachedProbe(candidate) || probePending.has(key) || probePending.size >= 4) return
3535
+ const pending = bridge.probe(session.id, path).then((value) => {
3536
+ if (menuSession.disposed) return
3537
+ if (probeCache.size >= 64) probeCache.delete(probeCache.keys().next().value)
3538
+ probeCache.set(key, { value, at: Date.now() })
3539
+ // The path is confirmed, so warm the association query as well.
3540
+ if (value && !value.isDir && !value.error) void applicationsFor(path)
3541
+ return value
3542
+ }).finally(() => probePending.delete(key))
3543
+ probePending.set(key, pending)
3544
+ }
3545
+ let preferenceStorage
3546
+ try { preferenceStorage = window.localStorage } catch { /* private storage may be disabled */ }
3547
+ const settingsViews = new Set()
3548
+ const notifySettings = () => { for (const render of settingsViews) render() }
3549
+ const config = clientPreferences(preferenceStorage)
3550
+ const preferences = applicationPreferences(preferenceStorage, notifySettings)
3551
+ const applications = createApplicationCache(bridge, preferenceStorage, notifySettings)
3552
+ const previews = createPreviewCache(bridge, handle => menuSession.menu === handle)
3553
+ const applicationsFor = applications.forPath
3554
+
3555
+ async function openAt(candidate, x, y, keyboard) {
3556
+ if (menuSession.disposed) return
3557
+ closeMenu()
3558
+ // Glass is a per-open decision: the wallpaper plugin can switch its gate at any
3559
+ // time, and the menu is rebuilt on every right-click anyway.
3560
+ try { document.documentElement.dataset.dfaGlass = config.get().glass === 'off' ? 'off' : 'on' } catch { /* no document */ }
3561
+ const operation = menuSession.begin()
3562
+ let handle
3563
+ try {
3564
+ if (candidate.link) {
3565
+ const text = String(candidate.element?.textContent || '').trim().slice(0, 512)
3566
+ const target = { link: candidate.link, text }
3567
+ handle = new FileMenu({ model: buildLinkMenuModel({ url: candidate.link, text, t, menuMode: config.get().menuMode }),
3568
+ x, y, keyboard, anchor: candidate.element, t,
3569
+ onClose: () => { menuSession.releaseMenu(handle) },
3570
+ onPick: (item) => { void dispatch(item, target, { bridge, t }) },
3571
+ })
3572
+ menuSession.setMenu(handle)
3573
+ handle.open()
3574
+ return
3575
+ }
3576
+ const { session, located, path, key } = locate(candidate)
3577
+ const modelInput = { absolutePath: path, displayPath: located.path, apps: [], appsState: 'loading',
3578
+ location: located, reference: candidate.reference || candidate.path, t, menuMode: config.get().menuMode }
3579
+ /** @type {VerifiedFileTarget|undefined} */
3580
+ let target
3581
+ const isCurrent = operation.isCurrent
3582
+ handle = new FileMenu({ model: buildStatusModel(path, t.checking, t),
3583
+ x, y, keyboard, anchor: candidate.element, t,
3584
+ onClose: () => {
3585
+ operation.cancelLookup()
3586
+ menuSession.releaseMenu(handle)
3587
+ },
3588
+ onPick: (item) => {
3589
+ if (item.action === 'referencePreview' && target) { void handle.openReference(target, { bridge, t, sessionId: session.id, isCurrent, contextLines: config.get().contextLines, onFileChanged: () => probeCache.delete(locate(candidate).key) }); return }
3590
+ if (item.action === 'retry') { void openAt(candidate, x, y, keyboard); return }
3591
+ if (item.action === 'preferApp') {
3592
+ const appId = preferences.get(path) === item.appId ? '' : item.appId
3593
+ const saved = preferences.set(path, appId)
3594
+ toast(saved ? (appId ? t.preferenceSaved : t.preferenceCleared) : t.preferenceFailed, { error: !saved })
3595
+ return
3596
+ }
3597
+ if (target) void dispatch(item, target, { bridge, t, sessionId: session.id, isCurrent,
3598
+ onFileChanged: () => probeCache.delete(locate(candidate).key),
3599
+ validateApplication: async (file, id) => {
3600
+ const result = await applicationsFor(file, applications.needsValidation(file))
3601
+ return result.state === 'ready' && result.apps.some((app) => app.id === id)
3602
+ },
3603
+ onOpenFailed: (file) => {
3604
+ applications.invalidatePath(file)
3605
+ void applicationsFor(file, true)
3606
+ },
3607
+ })
3608
+ },
3609
+ })
3610
+ menuSession.setMenu(handle)
3611
+ handle.open()
3612
+ if (!session) {
3613
+ handle.setModel(buildStatusModel(path, t.noSession, t, true))
3614
+ return
3615
+ }
3616
+ let probe = cachedProbe(candidate) || await (probePending.get(key) || bridge.probe(session.id, path, operation.signal))
3617
+ if (probe && probe.error === 'notFound') {
3618
+ // Prose often abbreviates a nested path; the walk is bounded, so tell the user
3619
+ // what the extra beat is for before spending it.
3620
+ handle.setModel(buildStatusModel(path, t.locating, t))
3621
+ const rescued = await resolveBelowRoot(session, located.path, () => isCurrent() && !handle.closed, operation.signal)
3622
+ if (!isCurrent() || handle.closed) return
3623
+ // Never claim the file is absent when the walk stopped early; the retry row
3624
+ // re-runs the same lookup once the tree is reachable again.
3625
+ if (rescued.kind === 'incomplete') {
3626
+ handle.setModel(buildStatusModel(path, t.lookupIncomplete, t, true))
3627
+ return
3628
+ }
3629
+ if (rescued.kind === 'found') probe = await bridge.probe(session.id, rescued.path, operation.signal)
3630
+ }
3631
+ if (menuSession.disposed || !operation.isPending() || handle.closed) return
3632
+ if (!probe || probe.error) {
3633
+ handle.setModel(buildStatusModel(path, t[probe?.error] || t.probeFailed, t, true))
3634
+ return
3635
+ }
3636
+ const displayPath = relativeTo(session.cwd, probe.absolutePath) || probe.absolutePath
3637
+ Object.assign(modelInput, { absolutePath: probe.absolutePath, displayPath, isDir: probe.isDir,
3638
+ bytes: probe.bytes, outsideWorkspace: !isInside(session.cwd, probe.absolutePath),
3639
+ cwd: session.cwd, preferredId: preferences.get(probe.absolutePath) })
3640
+ target = { sessionId: session.id, absolutePath: probe.absolutePath, displayPath,
3641
+ isDir: probe.isDir, version: probe.version, line: located.line, endLine: located.endLine, column: located.column, bytes: probe.bytes,
3642
+ reference: candidate.reference || candidate.path, outsideWorkspace: !isInside(session.cwd, probe.absolutePath) }
3643
+ handle.setModel(buildMenuModel(modelInput))
3644
+ if (!probe.isDir) void enrich(handle, modelInput)
3645
+ const previewKind = classify(probe.absolutePath, false).kind
3646
+ if (!probe.isDir && (previewKind === 'image' || previewKind === 'video' || extname(probe.absolutePath) === 'svg')) {
3647
+ void previews.load(handle, session.id, probe.absolutePath, probe.bytes, probe.version)
3648
+ }
3649
+ } catch (error) {
3650
+ if (!menuSession.disposed && operation.isPending() && handle && !handle.closed) {
3651
+ handle.setModel(buildStatusModel(candidate.path, t.probeFailed, t, true))
3652
+ }
3653
+ console.warn('[dsh-file-actions] context menu failed:', error)
3654
+ }
3655
+ }
3656
+
3657
+ async function enrich(handle, input) {
3658
+ const needsValidation = applications.needsValidation(input.absolutePath)
3659
+ const paint = (result) => {
3660
+ if (menuSession.disposed || menuSession.menu !== handle || handle.closed) return
3661
+ if (input.appsState === result.state && JSON.stringify(input.apps) === JSON.stringify(result.apps)) return
3662
+ Object.assign(input, { apps: result.apps, appsState: result.state })
3663
+ handle.setModel(buildMenuModel(input))
3664
+ }
3665
+ paint(await applicationsFor(input.absolutePath))
3666
+ if (needsValidation && !menuSession.disposed) paint(await applicationsFor(input.absolutePath, true))
3667
+ }
3668
+
3495
3669
  /** Take the click and open our menu, unless the pointer sits on our own menu. */
3496
3670
  function openFromEvent(event) {
3497
3671
  const target = event.target
@@ -3504,7 +3678,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3504
3678
  closeMenu()
3505
3679
  const candidate = candidateFromEvent(event, document)
3506
3680
  if (!candidate) return
3507
- if (['text', 'title'].includes(candidate.source) && candidate.explicit !== true) {
3681
+ if (requiresVerification(candidate)) {
3508
3682
  const probe = cachedProbe(candidate)
3509
3683
  if (!probe || probe.error) { warmCandidate(candidate); return }
3510
3684
  }
@@ -3549,7 +3723,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3549
3723
  clientY: rect.top + rect.height / 2,
3550
3724
  }, document)
3551
3725
  if (!candidate) return
3552
- if (['text', 'title'].includes(candidate.source) && candidate.explicit !== true) {
3726
+ if (requiresVerification(candidate)) {
3553
3727
  const probe = cachedProbe(candidate)
3554
3728
  if (!probe || probe.error) { warmCandidate(candidate); return }
3555
3729
  }
@@ -3575,14 +3749,14 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3575
3749
  // the page moving; closing on it would make those lists unusable.
3576
3750
  const target = event && event.target
3577
3751
  if (target && target.closest && target.closest(`[${MENU_ATTR}], .dfa-reference-overlay`)) return
3578
- if (!menu) return
3752
+ if (!menuSession.menu) return
3579
3753
  if (event && event.type === 'scroll') {
3580
3754
  // One read per frame: a scroll burst fires many events, and each follow()
3581
3755
  // reads a layout box. Coalescing keeps the glide smooth instead of jittery.
3582
3756
  if (followFrame) return
3583
3757
  followFrame = requestAnimationFrame(() => {
3584
3758
  followFrame = 0
3585
- if (menu) menu.followAnchor()
3759
+ menuSession.menu?.followAnchor()
3586
3760
  })
3587
3761
  return
3588
3762
  }
@@ -3591,6 +3765,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3591
3765
 
3592
3766
  const install = () => {
3593
3767
  if (activeCleanup) activeCleanup()
3768
+ liveInstalls += 1
3594
3769
  document.addEventListener('contextmenu', onContextMenu, true)
3595
3770
  window.addEventListener('contextmenu', onContextMenuFallback)
3596
3771
  document.addEventListener('pointerover', onWarm, true)
@@ -3613,31 +3788,37 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3613
3788
  subscribe(render) { settingsViews.add(render); return () => settingsViews.delete(render) },
3614
3789
  update(patch) { const ok = config.set(patch); if (ok) { closeMenu(); notifySettings() } return ok },
3615
3790
  reset() { const ok = config.reset(); if (ok) { closeMenu(); notifySettings() } return ok },
3616
- applicationName(id) {
3617
- for (const { result } of appsCache.values()) { const app = result.apps.find(app => app.id === id); if (app) return app.name }
3618
- return basename(id) || id
3619
- },
3620
- cacheCount: () => appsCache.size,
3791
+ applicationName: applications.nameOf,
3792
+ cacheCount: applications.size,
3621
3793
  clearCache() {
3622
- try { preferenceStorage.removeItem(APPS_STORE_KEY) } catch { return false }
3623
- if (storeTimer) { clearTimeout(storeTimer); storeTimer = 0 }
3624
- appsEpoch++; appsCache.clear(); appsPending.clear(); closeMenu(); notifySettings()
3794
+ if (!applications.clear(true)) return false
3795
+ closeMenu(); notifySettings()
3625
3796
  return true
3626
3797
  },
3627
3798
  }
3628
3799
  const disposeSettings = registerSettings(ctx, settingsController)
3629
3800
  const onStorage = event => {
3630
3801
  if (event.key === CLIENT_SETTINGS_KEY || event.key === 'dsh-file-actions.preferred-apps.v1' || event.key === null) { closeMenu(); notifySettings() }
3631
- if (event.key === APPS_STORE_KEY || event.key === null) { appsEpoch++; appsCache.clear(); appsPending.clear(); notifySettings() }
3802
+ if (event.key === applications.storageKey || event.key === null) { applications.clear(); notifySettings() }
3632
3803
  }
3633
3804
  window.addEventListener('storage', onStorage)
3805
+ let installed = true
3634
3806
  const cleanup = () => {
3635
- disposed = true
3807
+ // The effect may be disposed more than once (a re-install disposes the old
3808
+ // one first); the teardown itself must stay single-shot.
3809
+ if (!installed) return
3810
+ installed = false
3811
+ liveInstalls = Math.max(0, liveInstalls - 1)
3812
+ menuSession.dispose()
3636
3813
  disposeSettings()
3637
3814
  settingsViews.clear()
3638
3815
  window.removeEventListener('storage', onStorage)
3639
3816
  if (typeof unsubscribe === 'function') unsubscribe()
3640
3817
  document.documentElement.removeAttribute('data-dfa-ready')
3818
+ document.documentElement.removeAttribute('data-dfa-glass')
3819
+ if (toastTimer) { clearTimeout(toastTimer); toastTimer = null }
3820
+ if (toastFrame) { cancelAnimationFrame(toastFrame); toastFrame = 0 }
3821
+ document.querySelector('.dfa-toast')?.remove()
3641
3822
  document.removeEventListener('contextmenu', onContextMenu, true)
3642
3823
  window.removeEventListener('contextmenu', onContextMenuFallback)
3643
3824
  document.removeEventListener('pointerover', onWarm, true)
@@ -3649,10 +3830,9 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3649
3830
  window.removeEventListener('resize', onViewportChange)
3650
3831
  document.removeEventListener('scroll', onViewportChange, true)
3651
3832
  closeMenu()
3652
- if (storeTimer) { clearTimeout(storeTimer); storeTimer = 0 }
3653
- for (const value of thumbCache.values()) URL.revokeObjectURL(value.url)
3654
- thumbCache.clear()
3655
- appsCache.clear()
3833
+ if (silentHintTimer) { clearTimeout(silentHintTimer); silentHintTimer = 0 }
3834
+ previews.dispose()
3835
+ applications.dispose()
3656
3836
  if (activeCleanup === cleanup) activeCleanup = null
3657
3837
  }
3658
3838
  activeCleanup = cleanup
@@ -3711,7 +3891,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3711
3891
  mimeOf,
3712
3892
  pickEditor,
3713
3893
  orderApplications,
3714
- shouldHintSilentOpen,
3894
+ shouldHintSilentOpen,
3715
3895
  applicationPreferences,
3716
3896
  clientPreferences,
3717
3897
  visibleMenuSections,
@@ -3729,6 +3909,9 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3729
3909
  linkFromHref,
3730
3910
  candidateFromEvent,
3731
3911
  createBridge,
3912
+ createMenuSession,
3913
+ createApplicationCache,
3914
+ createPreviewCache,
3732
3915
  fillBrowserWindow,
3733
3916
  tokenAtPoint,
3734
3917
  unwrap,