@jidekaixin2dian/dsh-file-actions 0.1.22 → 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
@@ -1388,7 +1388,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1388
1388
 
1389
1389
  return {
1390
1390
  activeSession,
1391
- /** Resolve one path to a real file or directory, or null when it is neither. */
1391
+ /** Resolve a file/directory identity, or a named probe error. */
1392
1392
  async probe(sessionId, path, signal) {
1393
1393
  if (!files) return { error: 'unavailable' }
1394
1394
  // A cancelled lookup still has queued paths; each would otherwise spend a stat
@@ -1411,7 +1411,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1411
1411
  } catch { /* not a directory either */ }
1412
1412
  return { error: failure }
1413
1413
  },
1414
- /** Immediate children of one directory, or null when it is not a directory. */
1414
+ /** Directory entries with truncation status; null means the listing failed. */
1415
1415
  async list(sessionId, path, signal) {
1416
1416
  if (!files) return null
1417
1417
  if (signal?.aborted) return null
@@ -1535,6 +1535,15 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1535
1535
  }
1536
1536
  }
1537
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} */
1538
1547
  function candidateFromEvent(event, doc) {
1539
1548
  const target = event.target
1540
1549
  if (!target || !target.closest) return null
@@ -1959,6 +1968,99 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1959
1968
  }
1960
1969
  }
1961
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
+
1962
2064
  class FileMenu {
1963
2065
  constructor(options) {
1964
2066
  this.model = options.model
@@ -1976,7 +2078,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
1976
2078
  this.body = null
1977
2079
  this.thumbUrl = null
1978
2080
  this.thumbPath = null
1979
- this.lightbox = null
2081
+ this.lightboxView = null
2082
+ this.referenceView = null
1980
2083
  this.submenu = null
1981
2084
  this.submenuFor = null
1982
2085
  this.subOffset = null
@@ -2146,88 +2249,34 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2146
2249
  async openReference(target, context) {
2147
2250
  this.closeReference()
2148
2251
  this.closeSubmenu()
2149
- const overlay = makeNode('div', { class: 'dfa-reference-overlay' })
2150
- const panel = makeNode('section', { class: 'dfa-reference', role: 'dialog', 'aria-modal': 'true', 'aria-label': this.t.referencePreview })
2151
- const floor = menuFloor()
2152
- if (floor) overlay.style.setProperty('--dfa-floor', floor.replace(/, 0\.94\)$/, ', 1)'))
2153
- overlay.style.color = getComputedStyle(this.root).color
2154
- const info = makeNode('div', { class: 'dfa-reference-info' }, [
2155
- makeNode('div', { class: 'dfa-reference-title', text: this.t.referencePreview }),
2156
- makeNode('div', { class: 'dfa-reference-path', text: `${target.displayPath || target.absolutePath} · ${formatLocation(target, this.t)}` }),
2157
- ])
2158
- const close = makeNode('button', { type: 'button', text: this.t.closePreview })
2159
- const body = makeNode('div', { class: 'dfa-reference-body', tabindex: '0', 'aria-label': this.t.referencePreview })
2160
- body.appendChild(makeNode('div', { class: 'dfa-reference-status', text: this.t.referenceLoading, role: 'status' }))
2161
- const hint = makeNode('div', { class: 'dfa-reference-hint' })
2162
- const copy = makeNode('button', { type: 'button', text: this.t.copySource, disabled: true })
2163
- const open = makeNode('button', { type: 'button', text: this.t.open })
2164
- panel.appendChild(makeNode('div', { class: 'dfa-reference-head' }, [info, close]))
2165
- panel.appendChild(body)
2166
- panel.appendChild(makeNode('div', { class: 'dfa-reference-footer' }, [hint, makeNode('div', { class: 'dfa-reference-actions' }, [open, copy])]))
2167
- overlay.appendChild(panel)
2168
- this.referencePreview = overlay
2169
- const current = () => !this.closed && this.referencePreview === overlay && (!context.isCurrent || context.isCurrent())
2170
- const readContext = { ...context, isCurrent: current, confirmMessage: this.t.confirmOutsidePreview }
2171
- close.addEventListener('click', () => this.closeReference())
2172
- overlay.addEventListener('click', event => { if (event.target === overlay) this.closeReference() })
2173
- open.addEventListener('click', () => { if (current()) void dispatch({ action: 'open' }, target, readContext) })
2174
- copy.addEventListener('click', async () => {
2175
- if (!current() || copy.disabled) return
2176
- copy.disabled = true
2177
- // Re-read with the original version: never copy a file newer than the preview.
2178
- await dispatch({ action: 'copySource' }, target, { ...readContext, outsideConfirmed: true })
2179
- 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()),
2180
2255
  })
2181
- document.body.appendChild(overlay)
2182
- close.focus({ preventScroll: true })
2183
- const result = await readTextTarget(target, readContext)
2184
- if (!current()) return
2185
- if (!result) { this.closeReference(); return }
2186
- const preview = result && !result.error ? referenceContext(result.text, target, context.contextLines) : null
2187
- body.replaceChildren()
2188
- if (!preview) {
2189
- body.appendChild(makeNode('div', { class: 'dfa-reference-status', role: 'status', text: result?.error || this.t.invalidLines }))
2190
- return
2191
- }
2192
- // A later copy must match the read even if the original carrier had no version.
2193
- if (result.version !== undefined) target = { ...target, version: result.version }
2194
- for (const row of preview.rows) body.appendChild(makeNode('div', { class: 'dfa-reference-row', 'data-selected': row.selected }, [
2195
- makeNode('span', { class: 'dfa-reference-number', text: row.line, 'aria-hidden': 'true' }),
2196
- makeNode('span', { class: 'dfa-reference-code', text: row.text || ' ' }),
2197
- ]))
2198
- hint.textContent = this.t.referenceWindow.replace('{from}', preview.from).replace('{to}', preview.to).replace('{total}', preview.total)
2199
- + (preview.clipped ? ` · ${this.t.previewClipped}` : '')
2200
- copy.disabled = false
2201
- body.querySelector('[data-selected="true"]')?.scrollIntoView({ block: 'center' })
2256
+ this.referenceView = view
2257
+ view.mount()
2258
+ await view.load()
2202
2259
  }
2203
2260
 
2204
2261
  closeReference() {
2205
- if (!this.referencePreview) return
2206
- this.referencePreview.remove()
2207
- this.referencePreview = null
2262
+ if (!this.referenceView) return
2263
+ this.referenceView.dispose()
2264
+ this.referenceView = null
2208
2265
  try { this.root?.focus({ preventScroll: true }) } catch { /* menu unmounted */ }
2209
2266
  }
2210
2267
 
2211
- /** Show the same preview at full size; the menu stays open behind it. */
2212
2268
  openPreview() {
2213
- if (!this.thumbUrl || this.lightbox) return
2214
- const overlay = makeNode('div', { class: 'dfa-lightbox', role: 'dialog', 'aria-modal': 'true',
2215
- 'aria-label': this.model.title, tabindex: '-1' })
2216
- overlay.appendChild(makeNode('img', { src: this.thumbUrl, alt: this.model.title }))
2217
- overlay.appendChild(makeNode('div', { class: 'dfa-lightbox-hint',
2218
- text: this.model.kind === 'video' ? this.t.previewVideoHint : this.t.previewHint }))
2219
- overlay.addEventListener('click', () => this.closeLightbox())
2220
- document.body.appendChild(overlay)
2221
- requestAnimationFrame(() => overlay.setAttribute('data-show', 'true'))
2222
- this.lightbox = overlay
2223
- 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()
2224
2273
  }
2225
2274
 
2226
2275
  closeLightbox() {
2227
- if (!this.lightbox) return
2228
- this.lightbox.remove()
2229
- this.lightbox = null
2230
- 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 */ }
2231
2280
  }
2232
2281
 
2233
2282
  /** Drop a preview once its bytes have arrived, tagged with the file it belongs to. */
@@ -2598,32 +2647,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2598
2647
  handleKeyDown(event) {
2599
2648
  if (!this.root) return
2600
2649
  if (event.isComposing || event.keyCode === 229) return
2601
- if (this.referencePreview) {
2602
- if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.closeReference() }
2603
- if (event.key === 'Tab') {
2604
- const controls = [...this.referencePreview.querySelectorAll('button:not(:disabled), [tabindex="0"]')]
2605
- const at = controls.indexOf(document.activeElement)
2606
- event.preventDefault()
2607
- controls[(at + (event.shiftKey ? -1 : 1) + controls.length) % controls.length]?.focus()
2608
- }
2609
- return
2610
- }
2611
- // The lightbox is modal: Escape dismisses it. Every other key is left alone so
2612
- // the video transport (space, arrows) keeps working.
2613
- if (this.lightbox) {
2614
- if (event.key === 'Escape') {
2615
- event.preventDefault()
2616
- event.stopPropagation()
2617
- this.closeLightbox()
2618
- } else if (event.key === 'Tab') {
2619
- // The image is not a control; keep focus on the dialog instead of tabbing
2620
- // into the browser chrome, whose blur would otherwise close the whole menu.
2621
- event.preventDefault()
2622
- event.stopPropagation()
2623
- this.lightbox.focus({ preventScroll: true })
2624
- }
2625
- return
2626
- }
2650
+ if (this.referenceView) { this.referenceView.handleKeyDown(event); return }
2651
+ if (this.lightboxView) { this.lightboxView.handleKeyDown(event); return }
2627
2652
  const typing = this.searchInput && event.target === this.searchInput
2628
2653
  if (typing && !['ArrowDown', 'ArrowUp', 'Enter', 'Escape', 'Tab'].includes(event.key)) return
2629
2654
  // While the submenu is open it owns the arrows, Enter and Escape, so a
@@ -2720,7 +2745,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2720
2745
  // menu when it opens. Only a real window blur may close it.
2721
2746
  if (event.type === 'blur' && event.target !== window) return
2722
2747
  const target = event.target
2723
- 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
2724
2749
  if (target instanceof Node && (this.root.contains(target) || (this.submenu && this.submenu.contains(target)))) return
2725
2750
  this.close()
2726
2751
  }
@@ -2818,33 +2843,34 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2818
2843
  const READ_CHUNK_BYTES = 2 * 1024 * 1024
2819
2844
  const READ_TOTAL_MAX_BYTES = 64 * 1024 * 1024
2820
2845
 
2846
+ /** @returns {Promise<{kind:'ok',bytes:Uint8Array}|{kind:'failed'|'changed'|'too-large'}>} */
2821
2847
  async function readAllBytes(bridge, sessionId, path) {
2822
2848
  const chunks = []
2823
2849
  let total = 0
2824
2850
  let identity
2825
2851
  for (let guard = 0; guard < 64; guard += 1) {
2826
2852
  const result = await bridge.readBytes(sessionId, path, { range: { offset: total, length: READ_CHUNK_BYTES } })
2827
- if (!result || !(result.data instanceof Uint8Array)) return null
2853
+ if (!result || !(result.data instanceof Uint8Array)) return { kind: 'failed' }
2828
2854
  if (typeof result.version !== 'string' || !result.version || typeof result.absolutePath !== 'string'
2829
- || result.offset !== total || typeof result.eof !== 'boolean') return null
2855
+ || result.offset !== total || typeof result.eof !== 'boolean') return { kind: 'failed' }
2830
2856
  if (!identity) identity = { version: result.version, path: result.absolutePath, bytes: result.bytes }
2831
2857
  else if (result.version !== identity.version || result.absolutePath !== identity.path
2832
- || result.bytes !== identity.bytes) return { changed: true }
2833
- if (result.data.byteLength === 0 && result.eof === false) return null
2834
- 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' }
2835
2861
  chunks.push(result.data)
2836
2862
  total += result.data.byteLength
2837
- 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' }
2838
2864
  if (result.eof !== false) {
2839
- if (chunks.length === 1) return result.data
2865
+ if (chunks.length === 1) return { kind: 'ok', bytes: result.data }
2840
2866
  const merged = new Uint8Array(total)
2841
2867
  let at = 0
2842
2868
  for (const chunk of chunks) { merged.set(chunk, at); at += chunk.byteLength }
2843
- return merged
2869
+ return { kind: 'ok', bytes: merged }
2844
2870
  }
2845
- if (total >= READ_TOTAL_MAX_BYTES) return { tooLarge: true }
2871
+ if (total >= READ_TOTAL_MAX_BYTES) return { kind: 'too-large' }
2846
2872
  }
2847
- return null
2873
+ return { kind: 'failed' }
2848
2874
  }
2849
2875
 
2850
2876
  function downloadBytes(bytes, name, mime) {
@@ -2932,7 +2958,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2932
2958
  const MAX_COPY_BYTES = 2 * 1024 * 1024
2933
2959
 
2934
2960
  async function readTextTarget(target, context) {
2935
- const { bridge, t, sessionId } = context
2961
+ const { bridge, t } = context
2962
+ const sessionId = target.sessionId ?? context.sessionId
2936
2963
  const current = () => !context.isCurrent || context.isCurrent()
2937
2964
  if (!current()) return null
2938
2965
  if (typeof target.bytes === 'number' && target.bytes > MAX_COPY_BYTES) return { error: t.tooLarge }
@@ -2970,7 +2997,8 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
2970
2997
  }
2971
2998
 
2972
2999
  async function dispatch(item, target, context) {
2973
- const { bridge, t, sessionId } = context
3000
+ const { bridge, t } = context
3001
+ const sessionId = target.sessionId ?? context.sessionId
2974
3002
  const path = target.absolutePath
2975
3003
  const copyingText = item.action === 'copyContents' || item.action === 'copyLines' || item.action === 'copySource'
2976
3004
  if (item.action === 'openLink' || item.action === 'copyLink' || item.action === 'copyLinkText') {
@@ -3045,21 +3073,21 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3045
3073
  }
3046
3074
  win.opener = null
3047
3075
  const bytes = await readAllBytes(bridge, sessionId, path)
3048
- if (!bytes || bytes.tooLarge || bytes.changed) {
3076
+ if (bytes.kind !== 'ok') {
3049
3077
  try { win.close() } catch { /* already gone */ }
3050
- 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 })
3051
3079
  return
3052
3080
  }
3053
- 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 })
3054
3082
  return
3055
3083
  }
3056
3084
  if (item.action === 'saveAs') {
3057
3085
  const bytes = await readAllBytes(bridge, sessionId, path)
3058
- if (!bytes || bytes.tooLarge || bytes.changed) {
3059
- 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 })
3060
3088
  return
3061
3089
  }
3062
- downloadBytes(bytes, basename(path), mimeOf(path))
3090
+ downloadBytes(bytes.bytes, basename(path), mimeOf(path))
3063
3091
  return
3064
3092
  }
3065
3093
  if (copyingText) {
@@ -3098,26 +3126,288 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3098
3126
  }
3099
3127
  }
3100
3128
 
3129
+ function createApplicationCache(bridge, storage, notifySettings) {
3130
+ let disposed = false
3131
+ // Associations are per file type, so one query per extension serves the page.
3132
+ // Ten minutes keeps a newly installed editor visible without re-asking the
3133
+ // OS on every right-click.
3134
+ const APPS_TTL_MS = 10 * 60 * 1000
3135
+ const APPS_EMPTY_TTL_MS = 15000
3136
+ // The Host walk costs ~1.2 s and an association list rarely changes, so the answer
3137
+ // is also stored across reloads: the first right-click of a session is instant.
3138
+ const APPS_STORE_KEY = 'dsh-file-actions.apps.v1'
3139
+ const APPS_STORE_TTL_MS = 24 * 60 * 60 * 1000
3140
+ const APPS_STORE_MAX_CHARS = 512 * 1024
3141
+ const APPS_STORE_RECORD_MAX_CHARS = 48 * 1024
3142
+ const appsCache = new Map()
3143
+ const appsPending = new Map()
3144
+ let appsEpoch = 0
3145
+ let storeTimer = 0
3146
+
3147
+ function readAppsStore() {
3148
+ try {
3149
+ const raw = storage.getItem(APPS_STORE_KEY)
3150
+ const parsed = raw ? JSON.parse(raw) : null
3151
+ return parsed && typeof parsed === 'object' && parsed.entries && typeof parsed.entries === 'object'
3152
+ ? parsed.entries : {}
3153
+ } catch { return {} }
3154
+ }
3155
+
3156
+ function writeAppsStore() {
3157
+ storeTimer = 0
3158
+ try {
3159
+ const entries = {}
3160
+ let chars = 0
3161
+ // Newest first: with a bounded budget, the extension asked about last is the
3162
+ // one most likely to be opened again next.
3163
+ for (const [key, value] of [...appsCache.entries()].sort((a, b) => b[1].at - a[1].at)) {
3164
+ // Empty answers are too volatile to persist; they expire in 15 s anyway.
3165
+ if (!value.result.apps.length) continue
3166
+ const shape = (withIcons) => ({ at: value.at, apps: value.result.apps.map((app) => ({
3167
+ id: app.id, name: app.name, default: app.default === true, icon: withIcons ? (app.icon || null) : null })) })
3168
+ let record = shape(true)
3169
+ let size = JSON.stringify(record).length
3170
+ // A heavy icon set is not worth more than the association itself.
3171
+ if (size > APPS_STORE_RECORD_MAX_CHARS) { record = shape(false); size = JSON.stringify(record).length }
3172
+ if (chars + size > APPS_STORE_MAX_CHARS) continue
3173
+ entries[key] = record
3174
+ chars += size
3175
+ }
3176
+ storage.setItem(APPS_STORE_KEY, JSON.stringify({ version: 1, entries }))
3177
+ } catch { /* storage blocked or full: the in-memory cache still works */ }
3178
+ }
3179
+
3180
+ function scheduleStoreWrite() {
3181
+ if (disposed || storeTimer) return
3182
+ storeTimer = setTimeout(writeAppsStore, 400)
3183
+ }
3184
+
3185
+ for (const [key, record] of Object.entries(readAppsStore())) {
3186
+ if (!record || typeof record.at !== 'number' || !Array.isArray(record.apps)) continue
3187
+ if (Date.now() - record.at > APPS_STORE_TTL_MS) continue
3188
+ // Storage is editable by the page, so only well-formed rows get in: a nameless
3189
+ // entry would render as an empty row in the submenu.
3190
+ const apps = record.apps.filter((app) => app && typeof app.id === 'string' && app.id !== ''
3191
+ && typeof app.name === 'string' && app.name !== '')
3192
+ if (!apps.length) continue
3193
+ appsCache.set(key, { result: { state: 'ready', apps }, at: record.at, ttl: APPS_STORE_TTL_MS, needsValidation: true })
3194
+ }
3195
+ /**
3196
+ * One association query per extension, shared by the hover prefetch and the
3197
+ * menu. Walking the OS registry is the slow part on Windows, so a second menu
3198
+ * for the same extension — or a menu opened while the hover query is still
3199
+ * running — must join the existing request instead of starting another one.
3200
+ */
3201
+ function applicationsFor(path, refresh = false) {
3202
+ if (disposed) return Promise.resolve({ state: 'failed', apps: [] })
3203
+ const key = extname(path).toLowerCase()
3204
+ const cached = appsCache.get(key)
3205
+ if (!refresh && cached && Date.now() - cached.at < cached.ttl) return Promise.resolve(cached.result)
3206
+ const pending = appsPending.get(key)
3207
+ if (pending) return pending
3208
+ const epoch = appsEpoch
3209
+ const request = bridge.applications(path).then((result) => {
3210
+ if (disposed || epoch !== appsEpoch) return result
3211
+ // A successful empty answer is cached briefly: the OS may still be
3212
+ // registering a handler, but it is not worth a walk on every click.
3213
+ if (result.state === 'ready') {
3214
+ if (appsCache.size >= 64) appsCache.delete(appsCache.keys().next().value)
3215
+ appsCache.set(key, { result, at: Date.now(), ttl: result.apps.length ? APPS_TTL_MS : APPS_EMPTY_TTL_MS })
3216
+ scheduleStoreWrite()
3217
+ notifySettings()
3218
+ } else if (refresh) {
3219
+ appsCache.delete(key)
3220
+ scheduleStoreWrite()
3221
+ }
3222
+ return result
3223
+ }).finally(() => { if (appsPending.get(key) === request) appsPending.delete(key) })
3224
+ appsPending.set(key, request)
3225
+ return request
3226
+ }
3227
+
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
+ },
3255
+ }
3256
+ }
3257
+
3258
+ function createPreviewCache(bridge, isCurrentMenu) {
3259
+ let disposed = false
3260
+ // A thumbnail is worth one bounded read; bigger files just keep the tile.
3261
+ const THUMB_MAX_BYTES = 8 * 1024 * 1024
3262
+ // Bound the cache by bytes, not entries: one poster or 4.9 MB still can hold
3263
+ // megabytes, and twelve of those would pin ~100 MB of object URLs for the page.
3264
+ const THUMB_CACHE_MAX_BYTES = 16 * 1024 * 1024
3265
+ const thumbCache = new Map()
3266
+
3267
+ /**
3268
+ * Decode one frame of a video into a poster image. The bytes are already in
3269
+ * memory, so this costs a decoder spin, not another Host read; a file Chromium
3270
+ * cannot decode (or a codec it lacks) simply yields no poster.
3271
+ */
3272
+ function videoPoster(bytes, mime) {
3273
+ return new Promise((resolve) => {
3274
+ let settled = false
3275
+ let url = ''
3276
+ const finish = (value) => {
3277
+ if (settled) return
3278
+ settled = true
3279
+ if (url) URL.revokeObjectURL(url)
3280
+ resolve(value)
3281
+ }
3282
+ try {
3283
+ url = URL.createObjectURL(new Blob([bytes], { type: mime }))
3284
+ const video = document.createElement('video')
3285
+ video.muted = true
3286
+ video.playsInline = true
3287
+ video.preload = 'auto'
3288
+ video.onloadeddata = () => {
3289
+ // Ten percent in, capped: the first frames of a clip are often black or
3290
+ // a fade, and a poster of a black frame is worse than none.
3291
+ const span = Number(video.duration) || 1
3292
+ try { video.currentTime = Math.min(3, Math.max(0.2, span * 0.1)) } catch { finish(null) }
3293
+ }
3294
+ video.onseeked = () => {
3295
+ try {
3296
+ const width = video.videoWidth || 480
3297
+ const height = video.videoHeight || 270
3298
+ const scale = Math.min(1, 480 / Math.max(width, height))
3299
+ const canvas = document.createElement('canvas')
3300
+ canvas.width = Math.max(1, Math.round(width * scale))
3301
+ canvas.height = Math.max(1, Math.round(height * scale))
3302
+ canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
3303
+ finish(canvas.toDataURL('image/jpeg', 0.72))
3304
+ } catch {
3305
+ finish(null)
3306
+ }
3307
+ }
3308
+ video.onerror = () => finish(null)
3309
+ // A poster is a nicety: never keep the menu waiting on a stubborn file.
3310
+ setTimeout(() => finish(null), 4000)
3311
+ video.src = url
3312
+ } catch {
3313
+ finish(null)
3314
+ }
3315
+ })
3316
+ }
3317
+
3318
+ async function loadThumb(handle, sessionId, absolutePath, bytes, version) {
3319
+ if (disposed) return
3320
+ try {
3321
+ if (typeof bytes === 'number' && bytes > THUMB_MAX_BYTES) { handle.setThumbnail(null, absolutePath); return }
3322
+ const key = JSON.stringify([sessionId, absolutePath, version])
3323
+ const cached = version && thumbCache.get(key)
3324
+ if (cached) {
3325
+ if (isCurrentMenu(handle) && !handle.closed) handle.setThumbnail(cached.url, absolutePath)
3326
+ return
3327
+ }
3328
+ const result = await bridge.readBytes(sessionId, absolutePath)
3329
+ if (disposed || !isCurrentMenu(handle) || handle.closed) return
3330
+ if (!result || !(result.data instanceof Uint8Array) || result.eof === false || result.data.byteLength > THUMB_MAX_BYTES) {
3331
+ handle.setThumbnail(null, absolutePath)
3332
+ return
3333
+ }
3334
+ const mime = mimeOf(absolutePath)
3335
+ const url = classify(absolutePath, false).kind === 'video'
3336
+ ? await videoPoster(result.data, mime)
3337
+ : URL.createObjectURL(new Blob([result.data], { type: mime }))
3338
+ if (!url) { handle.setThumbnail(null, absolutePath); return }
3339
+ if (disposed) { URL.revokeObjectURL(url); return }
3340
+ const previous = thumbCache.get(key)
3341
+ if (previous) URL.revokeObjectURL(previous.url)
3342
+ thumbCache.set(key, { url, at: Date.now(), size: url.startsWith('blob:') ? result.data.byteLength : url.length * 2 })
3343
+ let total = 0
3344
+ for (const entry of thumbCache.values()) total += entry.size
3345
+ for (const [oldKey, entry] of thumbCache) {
3346
+ if (total <= THUMB_CACHE_MAX_BYTES && thumbCache.size <= 12) break
3347
+ if (oldKey === key) break
3348
+ URL.revokeObjectURL(entry.url)
3349
+ thumbCache.delete(oldKey)
3350
+ total -= entry.size
3351
+ }
3352
+ if (isCurrentMenu(handle) && !handle.closed) handle.setThumbnail(url, absolutePath)
3353
+ } catch (error) {
3354
+ if (isCurrentMenu(handle) && !handle.closed) handle.setThumbnail(null, absolutePath)
3355
+ console.warn('[dsh-file-actions] thumbnail failed:', error)
3356
+ }
3357
+ }
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
+
3101
3399
  function start(ctx) {
3102
3400
  if (typeof document === 'undefined' || typeof window === 'undefined') return
3103
3401
  ensureCss()
3104
3402
  const bridge = createBridge(ctx)
3105
3403
  const t = messages(detectLanguage(ctx))
3106
3404
 
3107
- let menu = null
3405
+ const menuSession = createMenuSession(bridge)
3108
3406
  let followFrame = 0
3109
- let generation = 0
3110
- let disposed = false
3111
- let lookupController = null
3112
3407
 
3113
3408
  function closeMenu() {
3114
- generation++
3115
- if (lookupController) { lookupController.abort(); lookupController = null }
3116
3409
  if (followFrame) { cancelAnimationFrame(followFrame); followFrame = 0 }
3117
- if (menu) {
3118
- menu.close()
3119
- menu = null
3120
- }
3410
+ menuSession.close()
3121
3411
  }
3122
3412
 
3123
3413
  // Guessed text must be verified before cancelling the browser's menu. Warm
@@ -3135,15 +3425,12 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3135
3425
  return cached && Date.now() - cached.at < 5000 ? cached.value : null
3136
3426
  }
3137
3427
 
3138
- // A relative reference in prose often names a file that only exists one directory
3139
- // down — `docs/HANDOFF.md` while the session root is its parent. Try the root's
3140
- // immediate subdirectories once: a single hit is unambiguous, several are a guess.
3141
3428
  const RESCUE_TTL_MS = 60 * 1000
3142
3429
  const rescueCache = new Map()
3143
3430
  const RESCUE_CACHE_MAX = 200
3144
- function rememberRescue(key, path) {
3431
+ function rememberRescue(key, result) {
3145
3432
  if (rescueCache.size >= RESCUE_CACHE_MAX && !rescueCache.has(key)) rescueCache.delete(rescueCache.keys().next().value)
3146
- rescueCache.set(key, { path, at: Date.now() })
3433
+ rescueCache.set(key, { result, at: Date.now() })
3147
3434
  }
3148
3435
  // Prose often abbreviates a path that lives several directories down — `docs/x.md`
3149
3436
  // while the session root is three levels above it. Walk the tree breadth-first with a
@@ -3156,7 +3443,6 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3156
3443
  const RESCUE_PARALLEL = 6
3157
3444
  // A walk that ran out of budget saw only part of the tree: it can prove neither a
3158
3445
  // hit nor a miss, so it must not be reported as "not found" or cached as one.
3159
- const RESCUE_INCOMPLETE = Symbol('rescue-incomplete')
3160
3446
  // Build output never holds the file a message refers to, and walking it costs the
3161
3447
  // whole budget on its own.
3162
3448
  const RESCUE_SKIP = new Set(['node_modules', 'dist', 'build', 'out', 'bin', 'obj', 'target', 'vendor', 'coverage'])
@@ -3175,21 +3461,21 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3175
3461
  // level at a time in small parallel batches, and stop at the first matching level:
3176
3462
  // shallower wins, and two hits at that level mean the name is ambiguous, not usable.
3177
3463
  async function resolveBelowRoot(session, relativePath, isActive = () => true, signal) {
3178
- if (!session || typeof session.cwd !== 'string' || !session.cwd || !relativePath || isAbsolutePath(relativePath)) return null
3464
+ if (!session || typeof session.cwd !== 'string' || !session.cwd || !relativePath || isAbsolutePath(relativePath)) return { kind: 'missing' }
3179
3465
  // A bare file name matches half the tree; only a path with a directory part is
3180
3466
  // specific enough to be worth the walk.
3181
- if (!relativePath.includes('/') && !relativePath.includes('\\')) return null
3467
+ if (!relativePath.includes('/') && !relativePath.includes('\\')) return { kind: 'missing' }
3182
3468
  const cacheKey = JSON.stringify([session.id, session.cwd, relativePath])
3183
3469
  const cached = rescueCache.get(cacheKey)
3184
- const ttl = cached && cached.path ? RESCUE_TTL_MS : RESCUE_MISS_TTL_MS
3185
- if (cached && Date.now() - cached.at < ttl) return cached.path
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
3186
3472
  const deadline = Date.now() + RESCUE_BUDGET_MS
3187
3473
  let level = [session.cwd]
3188
3474
  let probes = 0
3189
3475
  let found = null
3190
3476
  let complete = true
3191
3477
  for (let depth = 0; depth < RESCUE_MAX_DEPTH && level.length && !found; depth += 1) {
3192
- if (!isActive()) return null
3478
+ if (!isActive()) return { kind: 'cancelled' }
3193
3479
  if (Date.now() >= deadline || probes >= RESCUE_MAX_PROBES) { complete = false; break }
3194
3480
  const listings = new Array(level.length)
3195
3481
  let levelComplete = true
@@ -3202,10 +3488,10 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3202
3488
  if (!listing || listing.truncated) levelComplete = false
3203
3489
  listings[index] = listing
3204
3490
  })
3205
- if (!isActive()) return null
3491
+ if (!isActive()) return { kind: 'cancelled' }
3206
3492
  // A partial level cannot prove either uniqueness or absence. Leave the cache
3207
3493
  // untouched so a transient listing error does not become a five-minute miss.
3208
- if (!levelComplete) return RESCUE_INCOMPLETE
3494
+ if (!levelComplete) return { kind: 'incomplete' }
3209
3495
  const children = []
3210
3496
  listings.forEach((listing, index) => {
3211
3497
  for (const entry of listing.entries) {
@@ -3223,21 +3509,22 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3223
3509
  if (!probe || (probe.error && probe.error !== 'notFound')) levelComplete = false
3224
3510
  if (probe && !probe.error) hits.push(probe.absolutePath)
3225
3511
  })
3226
- if (!isActive()) return null
3227
- if (!levelComplete) return RESCUE_INCOMPLETE
3228
- if (hits.length > 1) { rememberRescue(cacheKey, null); return null }
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 }
3229
3515
  if (hits.length === 1) found = hits[0]
3230
3516
  level = children
3231
3517
  }
3232
- if (!complete) return RESCUE_INCOMPLETE
3233
- rememberRescue(cacheKey, found)
3234
- return found
3518
+ if (!complete) return { kind: 'incomplete' }
3519
+ const result = found ? { kind: 'found', path: found } : { kind: 'missing' }
3520
+ rememberRescue(cacheKey, result)
3521
+ return result
3235
3522
  }
3236
3523
  function warmCandidate(candidate) {
3237
3524
  if (!candidate || candidate.link) return
3238
3525
  const { session, path, key } = locate(candidate)
3239
3526
  if (!session || !path) return
3240
- const guess = ['text', 'title'].includes(candidate.source) && candidate.explicit !== true
3527
+ const guess = requiresVerification(candidate)
3241
3528
  if (!guess) {
3242
3529
  // An explicit carrier already names a real path, so the association query —
3243
3530
  // the slowest part of the menu — can start on hover instead of on click.
@@ -3246,7 +3533,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3246
3533
  }
3247
3534
  if (cachedProbe(candidate) || probePending.has(key) || probePending.size >= 4) return
3248
3535
  const pending = bridge.probe(session.id, path).then((value) => {
3249
- if (disposed) return
3536
+ if (menuSession.disposed) return
3250
3537
  if (probeCache.size >= 64) probeCache.delete(probeCache.keys().next().value)
3251
3538
  probeCache.set(key, { value, at: Date.now() })
3252
3539
  // The path is confirmed, so warm the association query as well.
@@ -3261,14 +3548,17 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3261
3548
  const notifySettings = () => { for (const render of settingsViews) render() }
3262
3549
  const config = clientPreferences(preferenceStorage)
3263
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
3264
3554
 
3265
3555
  async function openAt(candidate, x, y, keyboard) {
3266
- if (disposed) return
3556
+ if (menuSession.disposed) return
3267
3557
  closeMenu()
3268
3558
  // Glass is a per-open decision: the wallpaper plugin can switch its gate at any
3269
3559
  // time, and the menu is rebuilt on every right-click anyway.
3270
3560
  try { document.documentElement.dataset.dfaGlass = config.get().glass === 'off' ? 'off' : 'on' } catch { /* no document */ }
3271
- const attempt = ++generation
3561
+ const operation = menuSession.begin()
3272
3562
  let handle
3273
3563
  try {
3274
3564
  if (candidate.link) {
@@ -3276,26 +3566,24 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3276
3566
  const target = { link: candidate.link, text }
3277
3567
  handle = new FileMenu({ model: buildLinkMenuModel({ url: candidate.link, text, t, menuMode: config.get().menuMode }),
3278
3568
  x, y, keyboard, anchor: candidate.element, t,
3279
- onClose: () => { if (menu === handle) menu = null },
3569
+ onClose: () => { menuSession.releaseMenu(handle) },
3280
3570
  onPick: (item) => { void dispatch(item, target, { bridge, t }) },
3281
3571
  })
3282
- menu = handle
3572
+ menuSession.setMenu(handle)
3283
3573
  handle.open()
3284
3574
  return
3285
3575
  }
3286
- const controller = new AbortController()
3287
- lookupController = controller
3288
3576
  const { session, located, path, key } = locate(candidate)
3289
3577
  const modelInput = { absolutePath: path, displayPath: located.path, apps: [], appsState: 'loading',
3290
3578
  location: located, reference: candidate.reference || candidate.path, t, menuMode: config.get().menuMode }
3579
+ /** @type {VerifiedFileTarget|undefined} */
3291
3580
  let target
3292
- const activeSessionId = bridge.activeSession()?.id
3293
- const isCurrent = () => !disposed && attempt === generation && bridge.activeSession()?.id === activeSessionId
3581
+ const isCurrent = operation.isCurrent
3294
3582
  handle = new FileMenu({ model: buildStatusModel(path, t.checking, t),
3295
3583
  x, y, keyboard, anchor: candidate.element, t,
3296
3584
  onClose: () => {
3297
- if (lookupController === controller) { controller.abort(); lookupController = null }
3298
- if (menu === handle) menu = null
3585
+ operation.cancelLookup()
3586
+ menuSession.releaseMenu(handle)
3299
3587
  },
3300
3588
  onPick: (item) => {
3301
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 }
@@ -3309,40 +3597,38 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3309
3597
  if (target) void dispatch(item, target, { bridge, t, sessionId: session.id, isCurrent,
3310
3598
  onFileChanged: () => probeCache.delete(locate(candidate).key),
3311
3599
  validateApplication: async (file, id) => {
3312
- const cached = appsCache.get(extname(file).toLowerCase())
3313
- const result = await applicationsFor(file, cached?.needsValidation === true)
3600
+ const result = await applicationsFor(file, applications.needsValidation(file))
3314
3601
  return result.state === 'ready' && result.apps.some((app) => app.id === id)
3315
3602
  },
3316
3603
  onOpenFailed: (file) => {
3317
- appsCache.delete(extname(file).toLowerCase())
3318
- scheduleStoreWrite()
3604
+ applications.invalidatePath(file)
3319
3605
  void applicationsFor(file, true)
3320
3606
  },
3321
3607
  })
3322
3608
  },
3323
3609
  })
3324
- menu = handle
3610
+ menuSession.setMenu(handle)
3325
3611
  handle.open()
3326
3612
  if (!session) {
3327
3613
  handle.setModel(buildStatusModel(path, t.noSession, t, true))
3328
3614
  return
3329
3615
  }
3330
- let probe = cachedProbe(candidate) || await (probePending.get(key) || bridge.probe(session.id, path, controller.signal))
3616
+ let probe = cachedProbe(candidate) || await (probePending.get(key) || bridge.probe(session.id, path, operation.signal))
3331
3617
  if (probe && probe.error === 'notFound') {
3332
3618
  // Prose often abbreviates a nested path; the walk is bounded, so tell the user
3333
3619
  // what the extra beat is for before spending it.
3334
3620
  handle.setModel(buildStatusModel(path, t.locating, t))
3335
- const rescued = await resolveBelowRoot(session, located.path, () => isCurrent() && !handle.closed, controller.signal)
3621
+ const rescued = await resolveBelowRoot(session, located.path, () => isCurrent() && !handle.closed, operation.signal)
3336
3622
  if (!isCurrent() || handle.closed) return
3337
3623
  // Never claim the file is absent when the walk stopped early; the retry row
3338
3624
  // re-runs the same lookup once the tree is reachable again.
3339
- if (rescued === RESCUE_INCOMPLETE) {
3625
+ if (rescued.kind === 'incomplete') {
3340
3626
  handle.setModel(buildStatusModel(path, t.lookupIncomplete, t, true))
3341
3627
  return
3342
3628
  }
3343
- if (rescued) probe = await bridge.probe(session.id, rescued, controller.signal)
3629
+ if (rescued.kind === 'found') probe = await bridge.probe(session.id, rescued.path, operation.signal)
3344
3630
  }
3345
- if (disposed || attempt !== generation || handle.closed) return
3631
+ if (menuSession.disposed || !operation.isPending() || handle.closed) return
3346
3632
  if (!probe || probe.error) {
3347
3633
  handle.setModel(buildStatusModel(path, t[probe?.error] || t.probeFailed, t, true))
3348
3634
  return
@@ -3351,227 +3637,33 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3351
3637
  Object.assign(modelInput, { absolutePath: probe.absolutePath, displayPath, isDir: probe.isDir,
3352
3638
  bytes: probe.bytes, outsideWorkspace: !isInside(session.cwd, probe.absolutePath),
3353
3639
  cwd: session.cwd, preferredId: preferences.get(probe.absolutePath) })
3354
- target = { absolutePath: probe.absolutePath, displayPath,
3640
+ target = { sessionId: session.id, absolutePath: probe.absolutePath, displayPath,
3355
3641
  isDir: probe.isDir, version: probe.version, line: located.line, endLine: located.endLine, column: located.column, bytes: probe.bytes,
3356
3642
  reference: candidate.reference || candidate.path, outsideWorkspace: !isInside(session.cwd, probe.absolutePath) }
3357
3643
  handle.setModel(buildMenuModel(modelInput))
3358
3644
  if (!probe.isDir) void enrich(handle, modelInput)
3359
3645
  const previewKind = classify(probe.absolutePath, false).kind
3360
3646
  if (!probe.isDir && (previewKind === 'image' || previewKind === 'video' || extname(probe.absolutePath) === 'svg')) {
3361
- void loadThumb(handle, session.id, probe.absolutePath, probe.bytes, probe.version)
3647
+ void previews.load(handle, session.id, probe.absolutePath, probe.bytes, probe.version)
3362
3648
  }
3363
3649
  } catch (error) {
3364
- if (!disposed && attempt === generation && handle && !handle.closed) {
3650
+ if (!menuSession.disposed && operation.isPending() && handle && !handle.closed) {
3365
3651
  handle.setModel(buildStatusModel(candidate.path, t.probeFailed, t, true))
3366
3652
  }
3367
3653
  console.warn('[dsh-file-actions] context menu failed:', error)
3368
3654
  }
3369
3655
  }
3370
3656
 
3371
- // Associations are per file type, so one query per extension serves the page.
3372
- // Ten minutes keeps a newly installed editor visible without re-asking the
3373
- // OS on every right-click.
3374
- const APPS_TTL_MS = 10 * 60 * 1000
3375
- const APPS_EMPTY_TTL_MS = 15000
3376
- // The Host walk costs ~1.2 s and an association list rarely changes, so the answer
3377
- // is also stored across reloads: the first right-click of a session is instant.
3378
- const APPS_STORE_KEY = 'dsh-file-actions.apps.v1'
3379
- const APPS_STORE_TTL_MS = 24 * 60 * 60 * 1000
3380
- const APPS_STORE_MAX_CHARS = 512 * 1024
3381
- const APPS_STORE_RECORD_MAX_CHARS = 48 * 1024
3382
- const appsCache = new Map()
3383
- const appsPending = new Map()
3384
- let appsEpoch = 0
3385
- let storeTimer = 0
3386
-
3387
- function readAppsStore() {
3388
- try {
3389
- const raw = window.localStorage.getItem(APPS_STORE_KEY)
3390
- const parsed = raw ? JSON.parse(raw) : null
3391
- return parsed && typeof parsed === 'object' && parsed.entries && typeof parsed.entries === 'object'
3392
- ? parsed.entries : {}
3393
- } catch { return {} }
3394
- }
3395
-
3396
- function writeAppsStore() {
3397
- storeTimer = 0
3398
- try {
3399
- const entries = {}
3400
- let chars = 0
3401
- // Newest first: with a bounded budget, the extension asked about last is the
3402
- // one most likely to be opened again next.
3403
- for (const [key, value] of [...appsCache.entries()].sort((a, b) => b[1].at - a[1].at)) {
3404
- // Empty answers are too volatile to persist; they expire in 15 s anyway.
3405
- if (!value.result.apps.length) continue
3406
- const shape = (withIcons) => ({ at: value.at, apps: value.result.apps.map((app) => ({
3407
- id: app.id, name: app.name, default: app.default === true, icon: withIcons ? (app.icon || null) : null })) })
3408
- let record = shape(true)
3409
- let size = JSON.stringify(record).length
3410
- // A heavy icon set is not worth more than the association itself.
3411
- if (size > APPS_STORE_RECORD_MAX_CHARS) { record = shape(false); size = JSON.stringify(record).length }
3412
- if (chars + size > APPS_STORE_MAX_CHARS) continue
3413
- entries[key] = record
3414
- chars += size
3415
- }
3416
- window.localStorage.setItem(APPS_STORE_KEY, JSON.stringify({ version: 1, entries }))
3417
- } catch { /* storage blocked or full: the in-memory cache still works */ }
3418
- }
3419
-
3420
- function scheduleStoreWrite() {
3421
- if (storeTimer) return
3422
- storeTimer = setTimeout(writeAppsStore, 400)
3423
- }
3424
-
3425
- for (const [key, record] of Object.entries(readAppsStore())) {
3426
- if (!record || typeof record.at !== 'number' || !Array.isArray(record.apps)) continue
3427
- if (Date.now() - record.at > APPS_STORE_TTL_MS) continue
3428
- // Storage is editable by the page, so only well-formed rows get in: a nameless
3429
- // entry would render as an empty row in the submenu.
3430
- const apps = record.apps.filter((app) => app && typeof app.id === 'string' && app.id !== ''
3431
- && typeof app.name === 'string' && app.name !== '')
3432
- if (!apps.length) continue
3433
- appsCache.set(key, { result: { state: 'ready', apps }, at: record.at, ttl: APPS_STORE_TTL_MS, needsValidation: true })
3434
- }
3435
- /**
3436
- * One association query per extension, shared by the hover prefetch and the
3437
- * menu. Walking the OS registry is the slow part on Windows, so a second menu
3438
- * for the same extension — or a menu opened while the hover query is still
3439
- * running — must join the existing request instead of starting another one.
3440
- */
3441
- function applicationsFor(path, refresh = false) {
3442
- const key = extname(path).toLowerCase()
3443
- const cached = appsCache.get(key)
3444
- if (!refresh && cached && Date.now() - cached.at < cached.ttl) return Promise.resolve(cached.result)
3445
- const pending = appsPending.get(key)
3446
- if (pending) return pending
3447
- const epoch = appsEpoch
3448
- const request = bridge.applications(path).then((result) => {
3449
- if (disposed || epoch !== appsEpoch) return result
3450
- // A successful empty answer is cached briefly: the OS may still be
3451
- // registering a handler, but it is not worth a walk on every click.
3452
- if (result.state === 'ready') {
3453
- if (appsCache.size >= 64) appsCache.delete(appsCache.keys().next().value)
3454
- appsCache.set(key, { result, at: Date.now(), ttl: result.apps.length ? APPS_TTL_MS : APPS_EMPTY_TTL_MS })
3455
- scheduleStoreWrite()
3456
- notifySettings()
3457
- } else if (refresh) {
3458
- appsCache.delete(key)
3459
- scheduleStoreWrite()
3460
- }
3461
- return result
3462
- }).finally(() => { if (appsPending.get(key) === request) appsPending.delete(key) })
3463
- appsPending.set(key, request)
3464
- return request
3465
- }
3466
-
3467
3657
  async function enrich(handle, input) {
3468
- const needsValidation = appsCache.get(extname(input.absolutePath).toLowerCase())?.needsValidation === true
3658
+ const needsValidation = applications.needsValidation(input.absolutePath)
3469
3659
  const paint = (result) => {
3470
- if (disposed || menu !== handle || handle.closed) return
3660
+ if (menuSession.disposed || menuSession.menu !== handle || handle.closed) return
3471
3661
  if (input.appsState === result.state && JSON.stringify(input.apps) === JSON.stringify(result.apps)) return
3472
3662
  Object.assign(input, { apps: result.apps, appsState: result.state })
3473
3663
  handle.setModel(buildMenuModel(input))
3474
3664
  }
3475
3665
  paint(await applicationsFor(input.absolutePath))
3476
- if (needsValidation && !disposed) paint(await applicationsFor(input.absolutePath, true))
3477
- }
3478
-
3479
- // A thumbnail is worth one bounded read; bigger files just keep the tile.
3480
- const THUMB_MAX_BYTES = 8 * 1024 * 1024
3481
- // Bound the cache by bytes, not entries: one poster or 4.9 MB still can hold
3482
- // megabytes, and twelve of those would pin ~100 MB of object URLs for the page.
3483
- const THUMB_CACHE_MAX_BYTES = 16 * 1024 * 1024
3484
- const thumbCache = new Map()
3485
-
3486
- /**
3487
- * Decode one frame of a video into a poster image. The bytes are already in
3488
- * memory, so this costs a decoder spin, not another Host read; a file Chromium
3489
- * cannot decode (or a codec it lacks) simply yields no poster.
3490
- */
3491
- function videoPoster(bytes, mime) {
3492
- return new Promise((resolve) => {
3493
- let settled = false
3494
- let url = ''
3495
- const finish = (value) => {
3496
- if (settled) return
3497
- settled = true
3498
- if (url) URL.revokeObjectURL(url)
3499
- resolve(value)
3500
- }
3501
- try {
3502
- url = URL.createObjectURL(new Blob([bytes], { type: mime }))
3503
- const video = document.createElement('video')
3504
- video.muted = true
3505
- video.playsInline = true
3506
- video.preload = 'auto'
3507
- video.onloadeddata = () => {
3508
- // Ten percent in, capped: the first frames of a clip are often black or
3509
- // a fade, and a poster of a black frame is worse than none.
3510
- const span = Number(video.duration) || 1
3511
- try { video.currentTime = Math.min(3, Math.max(0.2, span * 0.1)) } catch { finish(null) }
3512
- }
3513
- video.onseeked = () => {
3514
- try {
3515
- const width = video.videoWidth || 480
3516
- const height = video.videoHeight || 270
3517
- const scale = Math.min(1, 480 / Math.max(width, height))
3518
- const canvas = document.createElement('canvas')
3519
- canvas.width = Math.max(1, Math.round(width * scale))
3520
- canvas.height = Math.max(1, Math.round(height * scale))
3521
- canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
3522
- finish(canvas.toDataURL('image/jpeg', 0.72))
3523
- } catch {
3524
- finish(null)
3525
- }
3526
- }
3527
- video.onerror = () => finish(null)
3528
- // A poster is a nicety: never keep the menu waiting on a stubborn file.
3529
- setTimeout(() => finish(null), 4000)
3530
- video.src = url
3531
- } catch {
3532
- finish(null)
3533
- }
3534
- })
3535
- }
3536
-
3537
- async function loadThumb(handle, sessionId, absolutePath, bytes, version) {
3538
- try {
3539
- if (typeof bytes === 'number' && bytes > THUMB_MAX_BYTES) { handle.setThumbnail(null, absolutePath); return }
3540
- const key = JSON.stringify([sessionId, absolutePath, version])
3541
- const cached = version && thumbCache.get(key)
3542
- if (cached) {
3543
- if (menu === handle && !handle.closed) handle.setThumbnail(cached.url, absolutePath)
3544
- return
3545
- }
3546
- const result = await bridge.readBytes(sessionId, absolutePath)
3547
- if (disposed || menu !== handle || handle.closed) return
3548
- if (!result || !(result.data instanceof Uint8Array) || result.eof === false || result.data.byteLength > THUMB_MAX_BYTES) {
3549
- handle.setThumbnail(null, absolutePath)
3550
- return
3551
- }
3552
- const mime = mimeOf(absolutePath)
3553
- const url = classify(absolutePath, false).kind === 'video'
3554
- ? await videoPoster(result.data, mime)
3555
- : URL.createObjectURL(new Blob([result.data], { type: mime }))
3556
- if (!url) { handle.setThumbnail(null, absolutePath); return }
3557
- if (disposed) { URL.revokeObjectURL(url); return }
3558
- const previous = thumbCache.get(key)
3559
- if (previous) URL.revokeObjectURL(previous.url)
3560
- thumbCache.set(key, { url, at: Date.now(), size: url.startsWith('blob:') ? result.data.byteLength : url.length * 2 })
3561
- let total = 0
3562
- for (const entry of thumbCache.values()) total += entry.size
3563
- for (const [oldKey, entry] of thumbCache) {
3564
- if (total <= THUMB_CACHE_MAX_BYTES && thumbCache.size <= 12) break
3565
- if (oldKey === key) break
3566
- URL.revokeObjectURL(entry.url)
3567
- thumbCache.delete(oldKey)
3568
- total -= entry.size
3569
- }
3570
- if (menu === handle && !handle.closed) handle.setThumbnail(url, absolutePath)
3571
- } catch (error) {
3572
- if (menu === handle && !handle.closed) handle.setThumbnail(null, absolutePath)
3573
- console.warn('[dsh-file-actions] thumbnail failed:', error)
3574
- }
3666
+ if (needsValidation && !menuSession.disposed) paint(await applicationsFor(input.absolutePath, true))
3575
3667
  }
3576
3668
 
3577
3669
  /** Take the click and open our menu, unless the pointer sits on our own menu. */
@@ -3586,7 +3678,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3586
3678
  closeMenu()
3587
3679
  const candidate = candidateFromEvent(event, document)
3588
3680
  if (!candidate) return
3589
- if (['text', 'title'].includes(candidate.source) && candidate.explicit !== true) {
3681
+ if (requiresVerification(candidate)) {
3590
3682
  const probe = cachedProbe(candidate)
3591
3683
  if (!probe || probe.error) { warmCandidate(candidate); return }
3592
3684
  }
@@ -3631,7 +3723,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3631
3723
  clientY: rect.top + rect.height / 2,
3632
3724
  }, document)
3633
3725
  if (!candidate) return
3634
- if (['text', 'title'].includes(candidate.source) && candidate.explicit !== true) {
3726
+ if (requiresVerification(candidate)) {
3635
3727
  const probe = cachedProbe(candidate)
3636
3728
  if (!probe || probe.error) { warmCandidate(candidate); return }
3637
3729
  }
@@ -3657,14 +3749,14 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3657
3749
  // the page moving; closing on it would make those lists unusable.
3658
3750
  const target = event && event.target
3659
3751
  if (target && target.closest && target.closest(`[${MENU_ATTR}], .dfa-reference-overlay`)) return
3660
- if (!menu) return
3752
+ if (!menuSession.menu) return
3661
3753
  if (event && event.type === 'scroll') {
3662
3754
  // One read per frame: a scroll burst fires many events, and each follow()
3663
3755
  // reads a layout box. Coalescing keeps the glide smooth instead of jittery.
3664
3756
  if (followFrame) return
3665
3757
  followFrame = requestAnimationFrame(() => {
3666
3758
  followFrame = 0
3667
- if (menu) menu.followAnchor()
3759
+ menuSession.menu?.followAnchor()
3668
3760
  })
3669
3761
  return
3670
3762
  }
@@ -3696,22 +3788,18 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3696
3788
  subscribe(render) { settingsViews.add(render); return () => settingsViews.delete(render) },
3697
3789
  update(patch) { const ok = config.set(patch); if (ok) { closeMenu(); notifySettings() } return ok },
3698
3790
  reset() { const ok = config.reset(); if (ok) { closeMenu(); notifySettings() } return ok },
3699
- applicationName(id) {
3700
- for (const { result } of appsCache.values()) { const app = result.apps.find(app => app.id === id); if (app) return app.name }
3701
- return basename(id) || id
3702
- },
3703
- cacheCount: () => appsCache.size,
3791
+ applicationName: applications.nameOf,
3792
+ cacheCount: applications.size,
3704
3793
  clearCache() {
3705
- try { preferenceStorage.removeItem(APPS_STORE_KEY) } catch { return false }
3706
- if (storeTimer) { clearTimeout(storeTimer); storeTimer = 0 }
3707
- appsEpoch++; appsCache.clear(); appsPending.clear(); closeMenu(); notifySettings()
3794
+ if (!applications.clear(true)) return false
3795
+ closeMenu(); notifySettings()
3708
3796
  return true
3709
3797
  },
3710
3798
  }
3711
3799
  const disposeSettings = registerSettings(ctx, settingsController)
3712
3800
  const onStorage = event => {
3713
3801
  if (event.key === CLIENT_SETTINGS_KEY || event.key === 'dsh-file-actions.preferred-apps.v1' || event.key === null) { closeMenu(); notifySettings() }
3714
- 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() }
3715
3803
  }
3716
3804
  window.addEventListener('storage', onStorage)
3717
3805
  let installed = true
@@ -3721,7 +3809,7 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3721
3809
  if (!installed) return
3722
3810
  installed = false
3723
3811
  liveInstalls = Math.max(0, liveInstalls - 1)
3724
- disposed = true
3812
+ menuSession.dispose()
3725
3813
  disposeSettings()
3726
3814
  settingsViews.clear()
3727
3815
  window.removeEventListener('storage', onStorage)
@@ -3742,11 +3830,9 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3742
3830
  window.removeEventListener('resize', onViewportChange)
3743
3831
  document.removeEventListener('scroll', onViewportChange, true)
3744
3832
  closeMenu()
3745
- if (storeTimer) { clearTimeout(storeTimer); storeTimer = 0 }
3746
3833
  if (silentHintTimer) { clearTimeout(silentHintTimer); silentHintTimer = 0 }
3747
- for (const value of thumbCache.values()) URL.revokeObjectURL(value.url)
3748
- thumbCache.clear()
3749
- appsCache.clear()
3834
+ previews.dispose()
3835
+ applications.dispose()
3750
3836
  if (activeCleanup === cleanup) activeCleanup = null
3751
3837
  }
3752
3838
  activeCleanup = cleanup
@@ -3823,6 +3909,9 @@ background-color:var(--dfa-floor,Canvas);background-image:none;
3823
3909
  linkFromHref,
3824
3910
  candidateFromEvent,
3825
3911
  createBridge,
3912
+ createMenuSession,
3913
+ createApplicationCache,
3914
+ createPreviewCache,
3826
3915
  fillBrowserWindow,
3827
3916
  tokenAtPoint,
3828
3917
  unwrap,