dsh-remote-vs 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Download one remote file or directory to the local machine.
3
+ *
4
+ * The Host streams the bytes over `REMOTE_API.download` (file) or
5
+ * `REMOTE_API.downloadDir` (one remote `tar -czf -` archive). When the browser
6
+ * offers the File System Access API the user picks the destination in a native
7
+ * "save as" dialog and the response body is written chunk by chunk into that
8
+ * file — streamed, never assembled into a Blob — which is also what feeds the
9
+ * progress meter. Without the API (Firefox, some Electron shells) the download
10
+ * falls back to an anchor click, i.e. the browser's configured download folder,
11
+ * with no progress to report.
12
+ *
13
+ * The runner (`downloads.ts`) preflights with `files` op=stat, so a vanished or
14
+ * unreadable path shows the Host's real error instead of an empty saved file.
15
+ */
16
+
17
+ import { REMOTE_API, selectionDownloadName } from '../protocol.ts'
18
+
19
+ /** What one download attempt ended as. */
20
+ export type DownloadOutcome = 'saved' | 'downloaded'
21
+
22
+ /** One progress sample: `total` is absent for a streamed archive (chunked). */
23
+ export interface DownloadProgress {
24
+ loaded: number
25
+ total?: number
26
+ }
27
+
28
+ /** Hooks the runner uses for the progress panel and its cancel button. */
29
+ export interface SaveOptions {
30
+ onProgress?: (progress: DownloadProgress) => void
31
+ signal?: AbortSignal
32
+ }
33
+
34
+ /** The writable file the save picker hands back (FileSystemWritableFileStream). */
35
+ interface SaveFileWritable {
36
+ write: (chunk: Uint8Array) => Promise<void>
37
+ close: () => Promise<void>
38
+ abort: () => Promise<void>
39
+ }
40
+
41
+ /** Minimal shape of the File System Access save picker (Chromium/Edge). */
42
+ interface SaveFileHandle {
43
+ createWritable: () => Promise<SaveFileWritable>
44
+ remove?: () => Promise<void>
45
+ }
46
+
47
+ interface SaveFilePickerApi {
48
+ showSaveFilePicker?: (options: { suggestedName?: string }) => Promise<SaveFileHandle>
49
+ }
50
+
51
+ /** File name a remote POSIX path should be saved as. */
52
+ export function downloadFileName(path: string): string {
53
+ const trimmed = path.replace(/[\\/]+$/, '')
54
+ const at = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
55
+ return at < 0 ? trimmed : trimmed.slice(at + 1)
56
+ }
57
+
58
+ /**
59
+ * Same-origin URL of the streaming download route for one remote file.
60
+ *
61
+ * Deliberately RELATIVE, including on Desktop: the page origin there is
62
+ * `dsh-app://app` and the Electron shell proxies app-origin HTTP to its Host,
63
+ * so the click stays same-origin (the `download` attribute applies) and passes
64
+ * the route's loopback/same-origin fence. Naming the published loopback origin
65
+ * instead would make it a cross-site GET, which that fence rejects.
66
+ */
67
+ export function downloadUrl(alias: string, path: string): string {
68
+ return `${REMOTE_API.download}?${new URLSearchParams({ alias, path }).toString()}`
69
+ }
70
+
71
+ /** Same-origin URL of the streaming directory-archive route. */
72
+ export function downloadDirUrl(alias: string, path: string): string {
73
+ return `${REMOTE_API.downloadDir}?${new URLSearchParams({ alias, path }).toString()}`
74
+ }
75
+
76
+ /** Same-origin URL of the multi-selection archive route (one `path` per entry). */
77
+ export function downloadManyUrl(alias: string, paths: readonly string[]): string {
78
+ const query = new URLSearchParams({ alias })
79
+ for (const path of paths) query.append('path', path)
80
+ return `${REMOTE_API.downloadMany}?${query.toString()}`
81
+ }
82
+
83
+ /**
84
+ * Hand one download to the browser (fallback when no save picker exists).
85
+ *
86
+ * The element is attached to the document on purpose: a detached anchor is
87
+ * ignored by some Chromium versions, and Desktop's shell hooks the download at
88
+ * the document level.
89
+ */
90
+ export function triggerDownload(href: string, fileName: string): void {
91
+ const anchor = document.createElement('a')
92
+ anchor.href = href
93
+ anchor.download = fileName
94
+ anchor.rel = 'noopener'
95
+ anchor.style.display = 'none'
96
+ document.body.append(anchor)
97
+ try {
98
+ anchor.click()
99
+ } finally {
100
+ anchor.remove()
101
+ }
102
+ }
103
+
104
+ /** An error shaped like the one `AbortSignal` consumers expect. */
105
+ function abortError(): Error {
106
+ const error = new Error('download cancelled')
107
+ error.name = 'AbortError'
108
+ return error
109
+ }
110
+
111
+ /** Delete the just-created target after a failed transfer (best effort). */
112
+ async function discard(handle: SaveFileHandle): Promise<void> {
113
+ try {
114
+ await handle.remove?.()
115
+ } catch {
116
+ // The browser may keep the handle locked for a moment; an empty file is a
117
+ // better outcome than masking the real error.
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Save one streamed URL to a destination the user picks.
123
+ *
124
+ * The picker runs while the click's transient activation is still valid, so it
125
+ * must come before the network work. A picker that refuses the call (expired
126
+ * activation, policy) falls back to the browser download flow instead of
127
+ * failing the download outright.
128
+ *
129
+ * @returns `'saved'` for the picked destination, `'downloaded'` for the
130
+ * browser-default fallback.
131
+ */
132
+ export async function saveRemoteUrl(href: string, fileName: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
133
+ const picker = (globalThis as unknown as SaveFilePickerApi).showSaveFilePicker
134
+ if (typeof picker !== 'function') {
135
+ if (options.signal?.aborted === true) throw abortError()
136
+ triggerDownload(href, fileName)
137
+ return 'downloaded'
138
+ }
139
+ let handle: SaveFileHandle
140
+ try {
141
+ handle = await picker.call(globalThis, { suggestedName: fileName })
142
+ } catch (error) {
143
+ if (error instanceof Error && error.name === 'AbortError') throw error
144
+ if (error instanceof Error && (error.name === 'SecurityError' || error.name === 'NotAllowedError')) {
145
+ if (options.signal?.aborted === true) throw abortError()
146
+ triggerDownload(href, fileName)
147
+ return 'downloaded'
148
+ }
149
+ throw error
150
+ }
151
+ const signal = options.signal
152
+ let response: Response
153
+ try {
154
+ response = await fetch(href, signal === undefined ? undefined : { signal })
155
+ } catch (error) {
156
+ await discard(handle)
157
+ throw error
158
+ }
159
+ if (!response.ok || response.body === null) {
160
+ const detail = await response.text().catch(() => '')
161
+ await discard(handle)
162
+ throw new Error(detail.trim() === '' ? `HTTP ${response.status}` : detail.trim())
163
+ }
164
+ const lengthHeader = response.headers.get('content-length')
165
+ const parsedTotal = lengthHeader === null ? Number.NaN : Number(lengthHeader)
166
+ const total = Number.isFinite(parsedTotal) && parsedTotal >= 0 ? parsedTotal : undefined
167
+ const writable = await handle.createWritable()
168
+ const reader = response.body.getReader()
169
+ let loaded = 0
170
+ try {
171
+ options.onProgress?.({ loaded, ...(total === undefined ? {} : { total }) })
172
+ for (;;) {
173
+ if (signal?.aborted === true) throw abortError()
174
+ const { done, value } = await reader.read()
175
+ if (done) break
176
+ loaded += value.byteLength
177
+ await writable.write(value)
178
+ options.onProgress?.({ loaded, ...(total === undefined ? {} : { total }) })
179
+ }
180
+ await writable.close()
181
+ } catch (error) {
182
+ try {
183
+ await reader.cancel()
184
+ } catch {
185
+ // Stream already gone.
186
+ }
187
+ try {
188
+ await writable.abort()
189
+ } catch {
190
+ // Already closed.
191
+ }
192
+ await discard(handle)
193
+ throw error
194
+ }
195
+ return 'saved'
196
+ }
197
+
198
+ /** Save one remote file (fresh name from its POSIX basename). */
199
+ export function saveRemoteFile(alias: string, path: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
200
+ return saveRemoteUrl(downloadUrl(alias, path), downloadFileName(path), options)
201
+ }
202
+
203
+ /** Save one remote directory as a single `.tar.gz`. */
204
+ export function saveRemoteDir(alias: string, path: string, options: SaveOptions = {}): Promise<DownloadOutcome> {
205
+ const name = downloadFileName(path) || 'root'
206
+ return saveRemoteUrl(downloadDirUrl(alias, path), `${name}.tar.gz`, options)
207
+ }
208
+
209
+ /** Save several selected entries as one `.tar.gz` archive. */
210
+ export function saveRemoteMany(alias: string, paths: readonly string[], options: SaveOptions = {}): Promise<DownloadOutcome> {
211
+ return saveRemoteUrl(downloadManyUrl(alias, paths), selectionDownloadName(paths.length), options)
212
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Download runner and its tiny observable store.
3
+ *
4
+ * The explorer/search menus start one download each; this module owns the
5
+ * stat preflight, the file-vs-directory choice, the cancel handle and the
6
+ * progress/status snapshot the dock renders. Kept outside React on purpose:
7
+ * the dock is portaled to `<body>` and may unmount with its sidebar tab, while
8
+ * a download already streaming must keep running to completion.
9
+ */
10
+
11
+ import { api } from './api.ts'
12
+ import { saveRemoteDir, saveRemoteFile, saveRemoteMany, type DownloadOutcome } from './download.ts'
13
+
14
+ /** One download's lifecycle state. */
15
+ export type DownloadStatus = 'running' | 'done' | 'failed' | 'cancelled'
16
+
17
+ /** One task as the dock renders it. */
18
+ export interface DownloadTask {
19
+ id: string
20
+ /** Basename of the remote path (or `selection-N` for a multi-selection). */
21
+ name: string
22
+ /** Resolved from the stat preflight; `hint.directory` until then. */
23
+ directory: boolean
24
+ /** Entries in a multi-selection archive; absent for a single path. */
25
+ selection?: number
26
+ status: DownloadStatus
27
+ loaded: number
28
+ /** Absent for a streamed archive (chunked, size unknown). */
29
+ total?: number
30
+ /** Failure text, or the note shown for the browser-default fallback. */
31
+ error?: string
32
+ /** `browserDefault` means no save dialog existed and the file went to Downloads. */
33
+ via?: 'picker' | 'browserDefault'
34
+ startedAt: number
35
+ finishedAt?: number
36
+ }
37
+
38
+ /** Human byte size for the progress line. */
39
+ export function formatByteCount(bytes: number): string {
40
+ if (!Number.isFinite(bytes) || bytes < 0) return '0 B'
41
+ if (bytes < 1024) return `${Math.round(bytes)} B`
42
+ const units = ['KiB', 'MiB', 'GiB', 'TiB']
43
+ let value = bytes / 1024
44
+ let unit = 0
45
+ while (value >= 1024 && unit < units.length - 1) {
46
+ value /= 1024
47
+ unit += 1
48
+ }
49
+ return `${value >= 100 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`
50
+ }
51
+
52
+ let tasks: readonly DownloadTask[] = []
53
+ const listeners = new Set<() => void>()
54
+ const controllers = new Map<string, AbortController>()
55
+ let sequence = 0
56
+
57
+ const notify = (): void => {
58
+ for (const listener of [...listeners]) listener()
59
+ }
60
+
61
+ const patch = (id: string, next: Partial<DownloadTask>): void => {
62
+ tasks = tasks.map(task => (task.id === id ? { ...task, ...next } : task))
63
+ notify()
64
+ }
65
+
66
+ /** Store surface: `useSyncExternalStore(subscribe, getSnapshot, getSnapshot)`. */
67
+ export const downloadsStore = {
68
+ subscribe(listener: () => void): () => void {
69
+ listeners.add(listener)
70
+ return () => {
71
+ listeners.delete(listener)
72
+ }
73
+ },
74
+ getSnapshot(): readonly DownloadTask[] {
75
+ return tasks
76
+ },
77
+ }
78
+
79
+ /** Progress sink handed to every starter. */
80
+ interface RunnerOptions {
81
+ signal: AbortSignal
82
+ onProgress: (progress: { loaded: number; total?: number }) => void
83
+ }
84
+
85
+ /**
86
+ * Run one task body: progress patches, terminal status, cancel mapping.
87
+ *
88
+ * The task row is published by the caller before any await, so the dock shows
89
+ * the row immediately and only the numbers move afterwards.
90
+ */
91
+ const launch = (id: string, controller: AbortController, run: (options: RunnerOptions) => Promise<DownloadOutcome>): void => {
92
+ void (async () => {
93
+ try {
94
+ const outcome = await run({
95
+ signal: controller.signal,
96
+ onProgress: (progress) => {
97
+ if (controller.signal.aborted) return
98
+ patch(id, {
99
+ loaded: progress.loaded,
100
+ ...(progress.total === undefined ? {} : { total: progress.total }),
101
+ })
102
+ },
103
+ })
104
+ patch(id, {
105
+ status: 'done',
106
+ finishedAt: Date.now(),
107
+ via: outcome === 'downloaded' ? 'browserDefault' : 'picker',
108
+ })
109
+ } catch (error) {
110
+ const aborted = controller.signal.aborted || (error instanceof Error && error.name === 'AbortError')
111
+ patch(id, {
112
+ status: aborted ? 'cancelled' : 'failed',
113
+ finishedAt: Date.now(),
114
+ ...(aborted ? {} : { error: error instanceof Error ? error.message : String(error) }),
115
+ })
116
+ } finally {
117
+ controllers.delete(id)
118
+ }
119
+ })()
120
+ }
121
+
122
+ /** Publish one running task and return its id plus cancel handle. */
123
+ const newTask = (task: Pick<DownloadTask, 'name' | 'directory'> & Partial<Pick<DownloadTask, 'selection'>>): { id: string; controller: AbortController } => {
124
+ const id = `download-${++sequence}`
125
+ const controller = new AbortController()
126
+ controllers.set(id, controller)
127
+ tasks = [...tasks, { ...task, id, status: 'running', loaded: 0, startedAt: Date.now() }]
128
+ notify()
129
+ return { id, controller }
130
+ }
131
+
132
+ /**
133
+ * Start one download (file or directory) and return its task id.
134
+ *
135
+ * The stat preflight runs here — not in the menus — so a deleted/unreadable
136
+ * remote path becomes a failed task with the Host's real message, and the
137
+ * file-vs-directory decision comes from the Host rather than a possibly stale
138
+ * tree row.
139
+ */
140
+ export function startDownload(alias: string, path: string, hint: { name: string; directory: boolean }): string {
141
+ const { id, controller } = newTask({ name: hint.name, directory: hint.directory })
142
+ launch(id, controller, async (options) => {
143
+ const entry = await api.fileOp.stat(alias, path)
144
+ // Seed the size from the stat, not from the HTTP response alone: the route
145
+ // sends `content-length`, but a shell or proxy in front of the page may
146
+ // strip it (DSH Desktop's forwarder deletes it), and then a plain file
147
+ // download would fall back to the archive wording ("packaging…").
148
+ patch(id, entry.isDir ? { directory: true } : { directory: false, total: entry.size })
149
+ return entry.isDir ? await saveRemoteDir(alias, path, options) : await saveRemoteFile(alias, path, options)
150
+ })
151
+ return id
152
+ }
153
+
154
+ /**
155
+ * Start one multi-selection download.
156
+ *
157
+ * The Host archives every selected entry into a single `.tar.gz`, so the user
158
+ * picks one destination instead of answering N save dialogs; mixed files and
159
+ * directories are fine (tar recurses). Entry validation happens Host-side
160
+ * before the archive starts, so no client preflight round trip is needed.
161
+ */
162
+ export function startSelectionDownload(alias: string, paths: readonly string[]): string {
163
+ const { id, controller } = newTask({ name: `selection-${paths.length}`, directory: true, selection: paths.length })
164
+ launch(id, controller, options => saveRemoteMany(alias, paths, options))
165
+ return id
166
+ }
167
+
168
+ /** Cancel one running download (the panel's stop button). */
169
+ export function cancelDownload(id: string): void {
170
+ controllers.get(id)?.abort()
171
+ }
172
+
173
+ /** Drop one task from the dock (finished tasks only in practice). */
174
+ export function dismissDownload(id: string): void {
175
+ controllers.get(id)?.abort()
176
+ controllers.delete(id)
177
+ tasks = tasks.filter(task => task.id !== id)
178
+ notify()
179
+ }
@@ -27,6 +27,12 @@ export const DYNAMIC_KEYS = [
27
27
  'history.details',
28
28
  'history.content',
29
29
  'history.diff',
30
+ // Reached through the `STATUS_KEY` lookup in `DownloadDock.tsx` (running is
31
+ // the only status the detail line never prints as a literal `t()` call), and
32
+ // through the archive-vs-file ternary for the unknown-size note.
33
+ 'downloads.running',
34
+ 'downloads.indeterminate',
35
+ 'downloads.sizeUnknown',
30
36
  ] as const
31
37
 
32
38
  const zh: Record<string, string> = {
@@ -191,6 +197,17 @@ const zh: Record<string, string> = {
191
197
  'files.cutClipboard': '已剪切到剪贴板',
192
198
  'files.copyRel': '复制相对路径',
193
199
  'files.copyAbs': '复制绝对路径',
200
+ 'files.download': '下载到本地',
201
+ 'downloads.running': '下载中',
202
+ 'downloads.done': '下载完成',
203
+ 'downloads.failed': '下载失败',
204
+ 'downloads.cancelled': '已取消',
205
+ 'downloads.cancel': '取消下载',
206
+ 'downloads.close': '关闭',
207
+ 'downloads.browserDefault': '已保存到浏览器默认下载目录',
208
+ 'downloads.indeterminate': '正在打包…',
209
+ 'downloads.sizeUnknown': '大小未知',
210
+ 'downloads.tooMany': '选择项过多(最多 100 项),请改为下载所在目录',
194
211
  'files.copied': '已复制',
195
212
  'files.moved': '已移动',
196
213
  'files.pasteFailed': '操作失败',
@@ -608,6 +625,17 @@ const en: Record<string, string> = {
608
625
  'files.cutClipboard': 'Cut to clipboard',
609
626
  'files.copyRel': 'Copy relative path',
610
627
  'files.copyAbs': 'Copy absolute path',
628
+ 'files.download': 'Download to Local',
629
+ 'downloads.running': 'Downloading',
630
+ 'downloads.done': 'Downloaded',
631
+ 'downloads.failed': 'Download failed',
632
+ 'downloads.cancelled': 'Cancelled',
633
+ 'downloads.cancel': 'Cancel download',
634
+ 'downloads.close': 'Dismiss',
635
+ 'downloads.browserDefault': 'Saved to the browser download folder',
636
+ 'downloads.indeterminate': 'Packaging…',
637
+ 'downloads.sizeUnknown': 'size unknown',
638
+ 'downloads.tooMany': 'Too many entries (max 100); download the containing folder instead',
611
639
  'files.copied': 'Copied',
612
640
  'files.moved': 'Moved',
613
641
  'files.pasteFailed': 'operation failed',
@@ -0,0 +1,84 @@
1
+ /**
2
+ * In-flight directory-listing requests, shared by the explorer's hover prefetch
3
+ * and the reads that follow it.
4
+ *
5
+ * Two rules the tree depends on:
6
+ * - JOIN only a request that started at the SAME revision. A listing read after
7
+ * a write must never be answered by a request issued before it, or pre-write
8
+ * rows paint as if they were final (a hover prefetch starts, a write lands,
9
+ * the click follows and joins the request that predates the write).
10
+ * - PAINT in request order. If a newer request supersedes an older one for the
11
+ * same directory, the older answer may still arrive; it must not overwrite the
12
+ * one the caller asked for.
13
+ *
14
+ * The cache itself stays in the component: this module only owns "which listing
15
+ * requests are on the wire and which answer may be stored".
16
+ */
17
+ import type { RemoteFileEntry } from '../protocol.ts'
18
+
19
+ /** One in-flight listing request and the revision it was issued at. */
20
+ interface ListingRequest {
21
+ promise: Promise<RemoteFileEntry[]>
22
+ revision: number
23
+ }
24
+
25
+ export class ListingRequests {
26
+ private readonly inFlight = new Map<string, ListingRequest>()
27
+ /** Newest request per key: only its answer may be stored. */
28
+ private readonly newest = new Map<string, number>()
29
+ private sequence = 0
30
+
31
+ /**
32
+ * @param keyOf - cache key for one directory (host alias + absolute path).
33
+ * @param load - performs the listing.
34
+ * @param store - applies a listing whose request is still the newest for its
35
+ * key; the component writes it into the listing cache.
36
+ */
37
+ constructor(
38
+ private readonly keyOf: (dir: string) => string,
39
+ private readonly load: (dir: string) => Promise<RemoteFileEntry[]>,
40
+ private readonly store: (key: string, entries: RemoteFileEntry[]) => void,
41
+ ) {}
42
+
43
+ /**
44
+ * List one directory, or join the request a hover prefetch already started.
45
+ *
46
+ * @param dir - absolute remote directory.
47
+ * @param revision - the explorer revision this read is meant to reflect. A
48
+ * request issued at another revision is never joined.
49
+ * @param fresh - start a new request even when one is in flight (a
50
+ * revalidation after a write, where joining the older read would be wrong).
51
+ */
52
+ request(dir: string, revision: number, fresh = false): Promise<RemoteFileEntry[]> {
53
+ const key = this.keyOf(dir)
54
+ const running = this.inFlight.get(key)
55
+ if (!fresh && running !== undefined && running.revision === revision) return running.promise
56
+ const sequence = (this.sequence += 1)
57
+ const promise = this.load(dir)
58
+ const entry: ListingRequest = { promise, revision }
59
+ this.inFlight.set(key, entry)
60
+ this.newest.set(key, sequence)
61
+ const settle = (): void => {
62
+ if (this.inFlight.get(key) === entry) this.inFlight.delete(key)
63
+ }
64
+ promise.then(
65
+ (entries) => {
66
+ if (this.newest.get(key) === sequence) {
67
+ this.newest.delete(key)
68
+ this.store(key, entries)
69
+ }
70
+ settle()
71
+ },
72
+ () => {
73
+ if (this.newest.get(key) === sequence) this.newest.delete(key)
74
+ settle()
75
+ },
76
+ )
77
+ return promise
78
+ }
79
+
80
+ /** Whether a listing for `dir` is on the wire. */
81
+ busy(dir: string): boolean {
82
+ return this.inFlight.has(this.keyOf(dir))
83
+ }
84
+ }
@@ -675,6 +675,14 @@ export interface MenuEntry {
675
675
  separated?: boolean
676
676
  }
677
677
 
678
+ /**
679
+ * Grace period after a menu appears during which a LEFT mousedown cannot close
680
+ * it: the opening gesture itself may still deliver one (platform-dependent, and
681
+ * a trackpad two-finger tap more often), and a panel re-render around the click
682
+ * can shift where that event lands.
683
+ */
684
+ const MENU_OPEN_GRACE_MS = 250
685
+
678
686
  /** Portal-rendered context menu, clamped to the viewport before paint. */
679
687
  export function ContextMenu(props: {
680
688
  x: number
@@ -684,6 +692,8 @@ export function ContextMenu(props: {
684
692
  }): ReactNode {
685
693
  const boxRef = useRef<HTMLDivElement>(null)
686
694
  const [pos, setPos] = useState({ left: props.x, top: props.y })
695
+ /** When this menu appeared (monotonic): see MENU_OPEN_GRACE_MS. */
696
+ const openedAt = useRef(typeof performance === 'undefined' ? 0 : performance.now())
687
697
 
688
698
  useLayoutEffect(() => {
689
699
  const box = boxRef.current
@@ -709,22 +719,39 @@ export function ContextMenu(props: {
709
719
 
710
720
  useEffect(() => {
711
721
  const onDown = (e: MouseEvent): void => {
722
+ // The right-click that opened this menu can deliver one more mousedown
723
+ // (platform-dependent; a trackpad two-finger tap does it more often), and
724
+ // the closing job belongs to LEFT presses anyway: a fresh right-click
725
+ // opens a NEW menu, which replaces this one without needing a close.
726
+ if (e.button === 2) return
727
+ if (performance.now() - openedAt.current < MENU_OPEN_GRACE_MS) return
712
728
  if (boxRef.current?.contains(e.target as Node) === true) return
713
729
  onCloseRef.current()
714
730
  }
715
731
  const onKey = (e: KeyboardEvent): void => {
716
732
  if (e.key === 'Escape') onCloseRef.current()
717
733
  }
718
- const onScroll = (): void => onCloseRef.current()
734
+ const onResize = (): void => onCloseRef.current()
735
+ const onScroll = (e: Event): void => {
736
+ // Only the PAGE scrolling moves the world under the menu. Element
737
+ // scrollers (the file tree, the chat log, the SCM list) fire scroll events
738
+ // while background work lands — a git status refresh was enough to close
739
+ // the menu the moment it opened, which read as "the menu flashes and never
740
+ // opens". The menu is portaled at fixed viewport coordinates, so those
741
+ // scrolls do not invalidate it.
742
+ const target = e.target
743
+ if (target instanceof Node && target !== document && target !== document.documentElement && target !== document.body) return
744
+ onCloseRef.current()
745
+ }
719
746
  window.addEventListener('mousedown', onDown, true)
720
747
  window.addEventListener('keydown', onKey)
721
748
  window.addEventListener('scroll', onScroll, true)
722
- window.addEventListener('resize', onScroll)
749
+ window.addEventListener('resize', onResize)
723
750
  return () => {
724
751
  window.removeEventListener('mousedown', onDown, true)
725
752
  window.removeEventListener('keydown', onKey)
726
753
  window.removeEventListener('scroll', onScroll, true)
727
- window.removeEventListener('resize', onScroll)
754
+ window.removeEventListener('resize', onResize)
728
755
  }
729
756
  }, [])
730
757