dsh-remote-vs 0.25.0 → 0.27.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.
Files changed (109) hide show
  1. package/README.en.md +12 -15
  2. package/README.md +11 -12
  3. package/THIRD-PARTY-NOTICES.md +193 -0
  4. package/lib/client.js +7313 -79961
  5. package/lib/index.js +1529 -964
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +22 -0
  8. package/lib/types/client/OutlinePanel.d.ts +22 -0
  9. package/lib/types/client/ProcessesSection.d.ts +19 -0
  10. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  11. package/lib/types/client/api.d.ts +42 -3
  12. package/lib/types/client/blame-model.d.ts +77 -0
  13. package/lib/types/client/changes/review-state.d.ts +19 -0
  14. package/lib/types/client/connection.d.ts +16 -0
  15. package/lib/types/client/i18n.d.ts +1 -1
  16. package/lib/types/client/outline-model.d.ts +59 -0
  17. package/lib/types/client/request-gate.d.ts +110 -0
  18. package/lib/types/client/scm/DiffView.d.ts +45 -7
  19. package/lib/types/client/scm/actions.d.ts +43 -4
  20. package/lib/types/client/store.d.ts +71 -0
  21. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  22. package/lib/types/client/vsc/blame.d.ts +19 -0
  23. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  24. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  25. package/lib/types/client/vsc/kit.d.ts +11 -2
  26. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  27. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  28. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  29. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  30. package/lib/types/client/vsc/terminal-theme.d.ts +28 -2
  31. package/lib/types/forward.d.ts +12 -0
  32. package/lib/types/fs-ops.d.ts +42 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/http.d.ts +2 -0
  35. package/lib/types/keygen.d.ts +9 -0
  36. package/lib/types/monitor.d.ts +8 -0
  37. package/lib/types/notices.d.ts +16 -1
  38. package/lib/types/p2/helper-rpc.d.ts +45 -0
  39. package/lib/types/processes.d.ts +43 -0
  40. package/lib/types/protocol.d.ts +34 -0
  41. package/lib/types/routes.d.ts +2 -0
  42. package/lib/types/store.d.ts +7 -0
  43. package/lib/types/terminal.d.ts +8 -0
  44. package/lib/types/view-settings.d.ts +5 -0
  45. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  46. package/package.json +3 -1
  47. package/src/client/CodeEditor.tsx +194 -9
  48. package/src/client/DirectoryFlow.tsx +16 -0
  49. package/src/client/DoctorPanel.tsx +70 -7
  50. package/src/client/EditorPane.tsx +574 -42
  51. package/src/client/HostsView.tsx +12 -3
  52. package/src/client/MonitorView.tsx +16 -5
  53. package/src/client/OutlinePanel.tsx +287 -0
  54. package/src/client/ProcessesSection.tsx +292 -0
  55. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  56. package/src/client/RemoteExplorer.tsx +929 -40
  57. package/src/client/RemoteRoot.tsx +147 -22
  58. package/src/client/SearchView.tsx +8 -0
  59. package/src/client/TerminalSnippets.tsx +83 -8
  60. package/src/client/api.ts +114 -13
  61. package/src/client/blame-model.ts +242 -0
  62. package/src/client/changes/ChangesDock.tsx +188 -6
  63. package/src/client/changes/changes.css +10 -3
  64. package/src/client/changes/review-state.ts +34 -0
  65. package/src/client/connection.ts +29 -0
  66. package/src/client/downloads.ts +49 -4
  67. package/src/client/i18n.ts +276 -8
  68. package/src/client/index.tsx +4 -0
  69. package/src/client/outline-model.ts +775 -0
  70. package/src/client/request-gate.ts +221 -0
  71. package/src/client/scm/CommitPane.tsx +20 -2
  72. package/src/client/scm/DiffView.tsx +343 -117
  73. package/src/client/scm/HistoryPanel.tsx +61 -3
  74. package/src/client/scm/RepoPicker.tsx +1 -1
  75. package/src/client/scm/ScmPanel.tsx +391 -87
  76. package/src/client/scm/actions.ts +150 -14
  77. package/src/client/store.tsx +426 -14
  78. package/src/client/ui.tsx +4 -0
  79. package/src/client/vsc/FindWidget.tsx +24 -9
  80. package/src/client/vsc/blame.ts +147 -0
  81. package/src/client/vsc/breadcrumb.tsx +91 -3
  82. package/src/client/vsc/change-marks.ts +93 -44
  83. package/src/client/vsc/editor-keymap.ts +59 -1
  84. package/src/client/vsc/file-icons.tsx +17 -3
  85. package/src/client/vsc/kit.tsx +29 -20
  86. package/src/client/vsc/preview-document.tsx +323 -0
  87. package/src/client/vsc/preview-model.ts +216 -0
  88. package/src/client/vsc/preview-services.ts +118 -0
  89. package/src/client/vsc/save-shortcut.ts +47 -1
  90. package/src/client/vsc/terminal-theme.ts +44 -18
  91. package/src/client/vsc/vsc.css +6509 -5458
  92. package/src/forward.ts +47 -9
  93. package/src/fs-ops.ts +124 -4
  94. package/src/git-ops.ts +54 -3
  95. package/src/http.ts +35 -4
  96. package/src/keygen.ts +55 -4
  97. package/src/monitor.ts +13 -0
  98. package/src/notices.ts +23 -1
  99. package/src/p2/helper-rpc.ts +113 -7
  100. package/src/p2/worlds.ts +14 -1
  101. package/src/processes.ts +177 -0
  102. package/src/protocol.ts +37 -0
  103. package/src/routes.ts +330 -43
  104. package/src/sftp.ts +51 -14
  105. package/src/store.ts +10 -0
  106. package/src/terminal.ts +73 -26
  107. package/src/view-settings.ts +50 -10
  108. package/lib/types/client/Dialog.d.ts +0 -14
  109. package/src/client/Dialog.tsx +0 -76
@@ -10,16 +10,24 @@
10
10
  * previous explorer, and `insertRemoteReference` still writes into the
11
11
  * on-screen session's composer draft.
12
12
  */
13
- import { memo, useCallback, useEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react'
14
- import { copyIntoCommand, joinAbs, moveToCommand } from '../fs-ops.ts'
13
+ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react'
14
+ import {
15
+ assertRemovablePath,
16
+ batchRemoveScript,
17
+ copyIntoCommand,
18
+ joinAbs,
19
+ moveToCommand,
20
+ parseDeleteMarker,
21
+ splitBatchRemovePaths,
22
+ } from '../fs-ops.ts'
15
23
  import { MAX_SELECTION_DOWNLOAD, type RemoteFileEntry } from '../protocol.ts'
16
- import { api, uploadFile } from './api.ts'
24
+ import { api, noteRemoteWrite, uploadFile } from './api.ts'
17
25
  import { startDownload, startSelectionDownload } from './downloads.ts'
18
- import { useConnectionStatus, isConnectionFailure } from './connection.ts'
26
+ import { useConnectionStatus, isConnectionFailure, pruneConnections } from './connection.ts'
19
27
  import { createDragExpander, type DragExpander } from './drag-expand.ts'
20
28
  import { insertRemoteReference, sameLocalDir } from './composer.ts'
21
29
  import { ListingRequests } from './listing-requests.ts'
22
- import { repoRelative, useExplorer } from './store.tsx'
30
+ import { refreshGit, repoRelative, useExplorer } from './store.tsx'
23
31
  import { planUpload, withDroppedDirs, type DroppedFile } from './upload-plan.ts'
24
32
  import { collectDroppedFiles, type EntryLike } from './upload-source.ts'
25
33
  import { useRemoteChatTarget } from './use-remote-chat-target.ts'
@@ -66,6 +74,16 @@ interface CreateState {
66
74
  */
67
75
  const PROBE_DEADLINE_MS = 8_000
68
76
 
77
+ /**
78
+ * Deadline for one streamed delete batch.
79
+ *
80
+ * The batch replaces the per-entry SFTP route precisely because a tree removal
81
+ * is slow (every child is walked server-side) and that route caps each request
82
+ * at 60 s. The batch therefore gets its own minutes-scale deadline; the markers
83
+ * still report per-path progress and the script always exits 0.
84
+ */
85
+ const DELETE_BATCH_TIMEOUT_MS = 300_000
86
+
69
87
  /** Resolve `promise` or `undefined` after `ms` (never rejects). */
70
88
  function withDeadline<T>(promise: Promise<T>, ms: number, label: string): Promise<T | undefined> {
71
89
  return new Promise<T | undefined>((resolve) => {
@@ -87,6 +105,11 @@ function withDeadline<T>(promise: Promise<T>, ms: number, label: string): Promis
87
105
  })
88
106
  }
89
107
 
108
+ /** Whether a rejection is the stream abort (the user pressed ✕), not a failure. */
109
+ function isAbortError(error: unknown): boolean {
110
+ return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError'
111
+ }
112
+
90
113
  function dirKey(alias: string, dir: string): string {
91
114
  return `${alias}:${dir}`
92
115
  }
@@ -299,9 +322,73 @@ function formatUploadLabel(
299
322
  return `${t('files.uploading')} ${counter} · ${percent}% · ${shortSize(upload.loaded)}/${shortSize(upload.size)} · ${upload.name}`
300
323
  }
301
324
 
325
+ /**
326
+ * The delete bar text: how many of the selection are settled, and which path is
327
+ * on the wire right now.
328
+ *
329
+ * A `rm -rf` batch can run for minutes; without the counter and the path the
330
+ * pane is indistinguishable from a hung one, which is the same 2026-10-20
331
+ * complaint the upload bar was built for.
332
+ */
333
+ function formatDeleteLabel(
334
+ t: (key: string) => string,
335
+ progress: { done: number; total: number; name: string },
336
+ ): string {
337
+ return t('files.deleting')
338
+ .replace('{done}', String(progress.done))
339
+ .replace('{total}', String(progress.total))
340
+ .replace('{name}', progress.name)
341
+ }
342
+
343
+ /**
344
+ * Feed one streamed stdout chunk through a line buffer and hand out every
345
+ * COMPLETE marker line.
346
+ *
347
+ * The stream splits wherever the transport felt like it: a marker can arrive as
348
+ * `RV_DEL_`, then `OK 3\n` in the next chunk. Only complete lines are parsed,
349
+ * and the unfinished tail is returned so the next chunk can continue it; the
350
+ * caller flushes it with a final `'\n'` when the command ends.
351
+ *
352
+ * Exported because it is the one place where a cross-chunk parse bug would
353
+ * silently mis-count deletions; the local probe drives it directly.
354
+ */
355
+ export function drainDeleteMarkers(
356
+ buffer: string,
357
+ text: string,
358
+ onMarker: (marker: { kind: 'item' | 'ok' | 'fail'; index: number }) => void,
359
+ ): string {
360
+ let pending = buffer + text
361
+ for (;;) {
362
+ const newline = pending.indexOf('\n')
363
+ if (newline < 0) break
364
+ const line = pending.slice(0, newline)
365
+ pending = pending.slice(newline + 1)
366
+ const marker = parseDeleteMarker(line)
367
+ if (marker !== undefined) onMarker(marker)
368
+ }
369
+ return pending
370
+ }
371
+
302
372
  /** How many directory listings stay cached; each one is a whole directory. */
303
373
  const LISTING_CACHE_KEEP = 50
304
374
 
375
+ /**
376
+ * How many EXPANDED directories whose rows are currently NOT drawn may keep
377
+ * their listing cached.
378
+ *
379
+ * `trimListings` exempts every open directory, because an evicted open
380
+ * directory has no rows to draw from and nothing would ever ask for it again.
381
+ * That exemption was unbounded: collapsing an ancestor leaves its descendants
382
+ * in `expanded` (so re-opening it restores their expansion), and a long
383
+ * browsing session in a deep tree therefore kept every directory it ever
384
+ * opened — each one up to the host's 20000-entry listing cap. The bound below
385
+ * keeps the RECENT remembered expansions and forgets the oldest ones, which
386
+ * costs one click (the folder comes back collapsed and re-lists) instead of
387
+ * holding unbounded memory. Directories whose rows are ON SCREEN are never
388
+ * touched.
389
+ */
390
+ const HIDDEN_EXPANDED_KEEP = 20
391
+
305
392
  /**
306
393
  * Hover intent before a directory's listing is prefetched: long enough that
307
394
  * sweeping the pointer across the tree does not fire a request per row, short
@@ -309,6 +396,127 @@ const LISTING_CACHE_KEEP = 50
309
396
  */
310
397
  const PREFETCH_HOVER_MS = 150
311
398
 
399
+ /**
400
+ * Height of one painted tree row, in px.
401
+ *
402
+ * Fixed rather than measured: the window below turns the scroll offset into a
403
+ * row index with arithmetic (`offset / height`) and the two spacers stand in
404
+ * for every row outside the slice, so one row that renders taller than this
405
+ * makes the whole slice drift from the scrollbar. The stylesheet box alone is
406
+ * not stable: `.rvs-node` is 18 px line box + 4 + 4 px padding = 26 px, and 30 px
407
+ * while the hover actions (a 22 px button) are on screen, while the inline
408
+ * create row with its input is already 28 px. `TREE_ROW_BOX` therefore pins
409
+ * every row root to this height inline instead of touching the shared CSS.
410
+ */
411
+ const TREE_ROW_HEIGHT = 28
412
+
413
+ /** Rows painted above and below the viewport, so a wheel step is already ready. */
414
+ const TREE_OVERSCAN = 8
415
+
416
+ /**
417
+ * Rows painted when the scroller has no measurable viewport (jsdom, or a panel
418
+ * parked behind `display:none`): there is no offset to slice against, and a
419
+ * tree that renders NOTHING is indistinguishable from an empty one — the gates
420
+ * that query tree rows would fail on a page that merely has not been laid out.
421
+ * A visible browser always reports a positive `clientHeight` and never takes
422
+ * this branch.
423
+ */
424
+ const TREE_WINDOW_FALLBACK = 40
425
+
426
+ /** Trees at most this many rows are painted whole by the no-viewport fallback. */
427
+ const TREE_WINDOW_FALLBACK_ALL = 100
428
+
429
+ /**
430
+ * Inline box for every row root (entry, create and loading/offline rows).
431
+ *
432
+ * The 2 px vertical padding replaces the stylesheet's 4 px so the 22 px hover
433
+ * button still fits inside the pinned height; horizontal padding stays in CSS
434
+ * and `paddingLeft` is added per row (indentation).
435
+ */
436
+ const TREE_ROW_BOX = {
437
+ height: TREE_ROW_HEIGHT,
438
+ boxSizing: 'border-box',
439
+ paddingTop: 2,
440
+ paddingBottom: 2,
441
+ } as const
442
+
443
+ /**
444
+ * The ONE collator every directory listing sorts with.
445
+ *
446
+ * A directory is sorted whole on each listings change, so a 20 000-entry folder
447
+ * costs ~261 000 pairwise comparisons (measured on a shuffled fixture: 20 000 ×
448
+ * log2(20 000) ≈ 280 000 is the bound), and `String.prototype.localeCompare`
449
+ * resolves a collator on every single call. Reusing one `Intl.Collator` turns
450
+ * that into a plain method call.
451
+ *
452
+ * The options are `localeCompare()`'s defaults — `undefined` locale is the same
453
+ * browser default, `sensitivity: 'variant'` is the default (case and accent
454
+ * significant) — so the resulting ORDER is unchanged, which is the point of this
455
+ * NIT. `numeric: true` is deliberately NOT set: it would move `file10` after
456
+ * `file9` (and `v10` after `v2`) — a visible reorder of a tree users already
457
+ * know, not a performance fix.
458
+ */
459
+ const NAME_COLLATOR = new Intl.Collator(undefined, { numeric: false, sensitivity: 'variant' })
460
+
461
+ /** The half-open range of flat rows the tree paints, plus the spacers around it. */
462
+ export interface TreeWindow {
463
+ /** First painted row index into the flat row list. */
464
+ from: number
465
+ /** One past the last painted row index. */
466
+ to: number
467
+ /** Height of the rows above `from`, in px. */
468
+ before: number
469
+ /** Height of the rows below `to`, in px. */
470
+ after: number
471
+ }
472
+
473
+ /**
474
+ * Which flat rows to paint for one scroll position.
475
+ *
476
+ * Pure, so a gate or probe can pin the arithmetic without a layout engine: the
477
+ * tree is one flat pre-order list with a fixed row height, so the first visible
478
+ * row is `offset / height` and the painted count is
479
+ * `ceil(visible height / height) + overscan`. `scrollTop` is the scroller's
480
+ * offset; `headerHeight` is the block ABOVE the rows inside it (the workspace
481
+ * root label, the drop hint, `.rvs-tree`'s top padding), because the offset only
482
+ * starts indexing rows below that block.
483
+ *
484
+ * `viewportHeight <= headerHeight` means there is no room for rows at all
485
+ * (jsdom or a hidden panel): the fallback paints the whole tree while it is
486
+ * small and `TREE_WINDOW_FALLBACK` rows otherwise. The invariant
487
+ * `before + (to - from) * TREE_ROW_HEIGHT + after === total * TREE_ROW_HEIGHT`
488
+ * holds on every branch, which is what keeps the scroll range identical to the
489
+ * fully-mounted tree the window replaced.
490
+ */
491
+ export function computeTreeWindow(
492
+ total: number,
493
+ scrollTop: number,
494
+ viewportHeight: number,
495
+ headerHeight: number,
496
+ overscan: number = TREE_OVERSCAN,
497
+ ): TreeWindow {
498
+ const rows = Number.isFinite(total) ? Math.max(0, Math.trunc(total)) : 0
499
+ if (rows === 0) return { from: 0, to: 0, before: 0, after: 0 }
500
+ const header = Math.max(0, Number.isFinite(headerHeight) ? headerHeight : 0)
501
+ const view = (Number.isFinite(viewportHeight) ? viewportHeight : 0) - header
502
+ if (view <= 0) {
503
+ const painted = rows <= TREE_WINDOW_FALLBACK_ALL ? rows : Math.min(TREE_WINDOW_FALLBACK, rows)
504
+ return { from: 0, to: painted, before: 0, after: (rows - painted) * TREE_ROW_HEIGHT }
505
+ }
506
+ const extra = Math.max(0, Math.trunc(Number.isFinite(overscan) ? overscan : TREE_OVERSCAN))
507
+ const offset = Number.isFinite(scrollTop) ? scrollTop : 0
508
+ // The offset is clamped to the last row, not merely guarded against
509
+ // negatives: a shrinking tree can leave the scroller's offset past the new
510
+ // content (the browser re-clamps it one layout later), and an unclamped slice
511
+ // would ask for rows that no longer exist and lose the bottom spacer.
512
+ const body = Math.max(0, Math.min(offset - header, rows * TREE_ROW_HEIGHT - view))
513
+ const scrolled = Math.min(Math.floor(body / TREE_ROW_HEIGHT), rows - 1)
514
+ const visible = Math.max(1, Math.ceil(view / TREE_ROW_HEIGHT))
515
+ const from = Math.max(0, scrolled - extra)
516
+ const to = Math.min(rows, Math.max(from + 1, scrolled + visible + extra))
517
+ return { from, to, before: from * TREE_ROW_HEIGHT, after: (rows - to) * TREE_ROW_HEIGHT }
518
+ }
519
+
312
520
  /**
313
521
  * Insert one listing as the newest, so "the first key is the oldest" stays
314
522
  * true and `trimListings` can evict from the front.
@@ -353,6 +561,41 @@ function trimListings(
353
561
  return next ?? prev
354
562
  }
355
563
 
564
+ /**
565
+ * Keys of the directories whose rows the flat tree draws RIGHT NOW.
566
+ *
567
+ * The walk is the same one `buildVisibleRows` does, but it only collects the
568
+ * directories: a directory is drawn when it is the root, or when every one of
569
+ * its ancestors is expanded. Those are exactly the listings the renderer needs,
570
+ * so they are the ones that must never be evicted (see `HIDDEN_EXPANDED_KEEP`).
571
+ */
572
+ function drawnDirKeys(input: {
573
+ root: string
574
+ alias: string
575
+ listings: Record<string, RemoteFileEntry[]>
576
+ expanded: Set<string>
577
+ /**
578
+ * Whether an entry is rendered AT ALL — the same hidden-name filter `rowsOf`
579
+ * applies on the render side. A directory the tree does not paint must not
580
+ * count as drawn, or its listing (and its expansion) would be exempt from the
581
+ * eviction cap below for the life of the session.
582
+ */
583
+ visible?: (entry: RemoteFileEntry) => boolean
584
+ }): Set<string> {
585
+ const drawn = new Set<string>()
586
+ if (input.root === '') return drawn
587
+ const walk = (dir: string): void => {
588
+ const key = dirKey(input.alias, dir)
589
+ drawn.add(key)
590
+ for (const entry of input.listings[key] ?? []) {
591
+ if (input.visible !== undefined && !input.visible(entry)) continue
592
+ if (entry.isDir && input.expanded.has(entry.path)) walk(entry.path)
593
+ }
594
+ }
595
+ walk(input.root)
596
+ return drawn
597
+ }
598
+
356
599
  /**
357
600
  * One rendered line of the flattened tree.
358
601
  *
@@ -469,6 +712,36 @@ export function nextFocusPath(rows: readonly ExplorerRow[], focusedPath: string
469
712
  return entries[0]?.entry.path
470
713
  }
471
714
 
715
+ /** Escape a value for a double-quoted CSS attribute selector (`[data-rvs-path="…"]`). */
716
+ function cssAttrValue(value: string): string {
717
+ // Backslash and the quote are the only characters a double-quoted CSS string
718
+ // treats specially; control characters have no literal form, so they become
719
+ // hex escapes (with the trailing space the hex form requires).
720
+ return value.replace(/[\\"\u0000-\u001f\u007f]/g, (ch) =>
721
+ ch === '\\' || ch === '"' ? `\\${ch}` : `\\${ch.charCodeAt(0).toString(16)} `)
722
+ }
723
+
724
+ /**
725
+ * The MOUNTED row element for `target`, or null.
726
+ *
727
+ * Exact attribute selector instead of a document-wide `querySelectorAll` scan:
728
+ * the old form allocated one array over every rendered row on each call, and
729
+ * this helper runs per key-repeat while focus moves — the reveal poll below ran
730
+ * it up to 20 times in a row. `cssAttrValue` keeps any path the shell allows (a
731
+ * quote, a backslash, a control character, a non-ASCII name) inside a single
732
+ * selector, and reading the attribute back proves the selector matched the row
733
+ * this call asked for.
734
+ *
735
+ * With the tree windowed, a row that is in the flat list may still be outside
736
+ * the painted slice, so every DOM lookup by `data-rvs-path` has to be able to
737
+ * come back empty (and the caller then scrolls the row's index into the slice —
738
+ * see `scrollTreeToRow`).
739
+ */
740
+ function rowElement(target: string): HTMLElement | null {
741
+ const row = document.querySelector<HTMLElement>(`[data-rvs-path="${cssAttrValue(target)}"]`)
742
+ return row !== null && row.dataset.rvsPath === target ? row : null
743
+ }
744
+
472
745
  /** Handlers one row needs, held in a ref so a memoized row never re-renders for them. */
473
746
  export interface ExplorerRowActions {
474
747
  select: (entry: RemoteFileEntry, event: React.MouseEvent) => void
@@ -491,6 +764,13 @@ export interface ExplorerRowActions {
491
764
  interface ExplorerRowProps {
492
765
  entry: RemoteFileEntry
493
766
  depth: number
767
+ /**
768
+ * ARIA position among the flattened visible rows. The tree is now WINDOWED, so
769
+ * the DOM sibling count is only the slice; without these two attributes a
770
+ * screen reader announces "5 of 26" for a row that is really "5005 of 20003".
771
+ */
772
+ posinset: number
773
+ setsize: number
494
774
  status: string | undefined
495
775
  ignored: boolean
496
776
  isSelected: boolean
@@ -514,12 +794,14 @@ interface ExplorerRowProps {
514
794
  * the whole expanded tree (a 20 000-entry directory means 20 000 rows).
515
795
  */
516
796
  export const ExplorerRowView = memo(function ExplorerRowView(props: ExplorerRowProps): ReactNode {
517
- const { entry, depth, status, ignored, isSelected, isOpen, isCut, isDropTarget, isRenaming, isFocused, chatEnabled, actions } = props
797
+ const { entry, depth, posinset, setsize, status, ignored, isSelected, isOpen, isCut, isDropTarget, isRenaming, isFocused, chatEnabled, actions } = props
518
798
  const { openMenu } = actions.current
519
799
  return (
520
800
  <div
521
801
  role="treeitem"
522
802
  aria-level={depth + 1}
803
+ aria-posinset={posinset}
804
+ aria-setsize={setsize}
523
805
  aria-selected={isSelected}
524
806
  // Directories expose their expansion; files have no aria-expanded.
525
807
  {...(entry.isDir ? { 'aria-expanded': isOpen } : {})}
@@ -533,7 +815,7 @@ export const ExplorerRowView = memo(function ExplorerRowView(props: ExplorerRowP
533
815
  isDropTarget ? 'drop-target' : '',
534
816
  isFocused ? 'focused' : '',
535
817
  ].filter(Boolean).join(' ')}
536
- style={{ paddingLeft: 8 + depth * 14 }}
818
+ style={{ ...TREE_ROW_BOX, paddingLeft: 8 + depth * 14 }}
537
819
  title={entry.path}
538
820
  // Read by the document-level capture drop listeners, which live
539
821
  // outside React's tree and cannot see component state.
@@ -610,6 +892,20 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
610
892
  /** The host link is down: cached rows stay, new listings cannot load. */
611
893
  const connection = useConnectionStatus()
612
894
  const offline = connection?.state === 'error'
895
+ /**
896
+ * Keep `connection.ts`'s per-alias cache in step with the hosts table.
897
+ *
898
+ * Its `views`/`probes` maps are keyed by alias and nothing there ever removed
899
+ * an entry, so a host deleted (or renamed) in Settings left its record in page
900
+ * memory for the life of the tab. The hosts table is the authoritative list of
901
+ * aliases this page may still ask about; pruning against it on each refresh is
902
+ * enough because panels are parked, never unmounted (see `panelFor`), so this
903
+ * hook stays live for the page.
904
+ */
905
+ useEffect(() => {
906
+ if (!store.ready) return
907
+ pruneConnections(store.hosts.map(host => host.alias))
908
+ }, [store.ready, store.hosts])
613
909
  const ctx = store.ctx
614
910
  const [listings, setListings] = useState<Record<string, RemoteFileEntry[]>>({})
615
911
  /**
@@ -646,6 +942,12 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
646
942
  loaded: number
647
943
  size: number
648
944
  } | undefined>(undefined)
945
+ /**
946
+ * Live delete batch. `done`/`total` count the selection, `name` is the path
947
+ * currently being removed; a multi-minute `rm -rf` used to be a silent,
948
+ * uncancellable wait with no progress at all.
949
+ */
950
+ const [deleteProgress, setDeleteProgress] = useState<{ done: number; total: number; name: string } | undefined>(undefined)
649
951
  const dragPaths = useRef<string[]>([])
650
952
  /** Directory the pending hidden-input pick uploads into. */
651
953
  const uploadInto = useRef<string>('')
@@ -653,8 +955,103 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
653
955
  const folderPickerHandle = useRef<HTMLInputElement | null>(null)
654
956
  /** The scroll container that owns the drop zone (capture listeners attach to document). */
655
957
  const treeRef = useRef<HTMLDivElement>(null)
958
+ /**
959
+ * The sentinel that sits immediately before the first row.
960
+ *
961
+ * Everything above it inside the scroller (workspace root label, drop hint,
962
+ * `.rvs-tree`'s top padding) is HEADER: the rows start below it, so its offset
963
+ * from the top of the scrollable content is exactly the bias the window has to
964
+ * subtract from `scrollTop`. Measuring this node instead of adding up the
965
+ * header's parts means a wrapped root label or a drop hint appearing cannot
966
+ * desync the slice from the scrollbar.
967
+ */
968
+ const rowsTopRef = useRef<HTMLDivElement>(null)
969
+ /**
970
+ * The flat pre-order row list, readable synchronously.
971
+ *
972
+ * Keyboard navigation, the reveal chain and the focus/window upkeep below all
973
+ * need "which index is this path" during an event, where the render-time
974
+ * `visibleRows` value is already current but a state read would be one commit
975
+ * behind.
976
+ */
977
+ const visibleRowsRef = useRef<ExplorerRow[]>([])
978
+ /** Index of the ENTRY row for `path` in the flat list, or -1. */
979
+ const entryRowIndex = useCallback((path: string): number => {
980
+ const rows = visibleRowsRef.current
981
+ for (let index = 0; index < rows.length; index += 1) {
982
+ const row = rows[index]
983
+ if (row !== undefined && row.kind === 'entry' && row.entry.path === path) return index
984
+ }
985
+ return -1
986
+ }, [])
987
+ /**
988
+ * Where the rows start inside the scroll container, and how much room they get.
989
+ *
990
+ * `offsetTop` is relative to an offset parent this panel does not control (the
991
+ * sidebar wrapper), so the sentinel is measured in viewport coordinates and
992
+ * the scroller's own scroll is added back: that is its distance from the top
993
+ * of the scrollable CONTENT. A zero reading is jsdom or a hidden panel — the
994
+ * window's own fallback covers that case.
995
+ */
996
+ const measureTreeRows = useCallback((): { header: number; viewport: number; scrollTop: number } => {
997
+ const scroller = treeRef.current
998
+ const sentinel = rowsTopRef.current
999
+ if (scroller === null) return { header: 0, viewport: 0, scrollTop: 0 }
1000
+ const scrollTop = scroller.scrollTop
1001
+ const viewport = scroller.clientHeight
1002
+ if (sentinel === null) return { header: 0, viewport, scrollTop }
1003
+ const header = sentinel.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scrollTop
1004
+ return { header: Math.max(0, header), viewport, scrollTop }
1005
+ }, [])
1006
+ /**
1007
+ * Scroll the content so row `index` sits about a third of the way down.
1008
+ *
1009
+ * This is the ONLY way to bring a row outside the painted slice into the DOM:
1010
+ * the slice follows `scrollTop`, and the row mounts on the commit after that.
1011
+ * The target is deliberately not clamped against `scrollHeight` — the browser
1012
+ * clamps an over-long assignment itself, and `scrollHeight` is one render
1013
+ * behind the spacers this function is often called to reach past.
1014
+ */
1015
+ const scrollTreeToRow = useCallback((index: number): void => {
1016
+ const scroller = treeRef.current
1017
+ if (scroller === null || index < 0) return
1018
+ const { header, viewport } = measureTreeRows()
1019
+ const body = Math.max(0, viewport - header)
1020
+ const target = Math.max(0, header + index * TREE_ROW_HEIGHT - Math.floor(body / 3))
1021
+ if (Math.abs(target - scroller.scrollTop) < 1) return
1022
+ scroller.scrollTop = target
1023
+ }, [measureTreeRows])
1024
+ /**
1025
+ * Minimal scroll that brings row `index` into the VISIBLE area, with one row
1026
+ * of context on the side it came from.
1027
+ *
1028
+ * Keyboard focus and the inline editors only need the row mounted, and every
1029
+ * row inside the viewport is inside the painted slice (which covers the
1030
+ * viewport plus overscan). Minimal rather than centered: holding ArrowDown at
1031
+ * the bottom edge must scroll the tree by a row, not page it.
1032
+ */
1033
+ const scrollTreeRowIntoView = useCallback((index: number): void => {
1034
+ const scroller = treeRef.current
1035
+ if (scroller === null || index < 0) return
1036
+ const { header, viewport } = measureTreeRows()
1037
+ const body = viewport - header
1038
+ if (body <= 0) return
1039
+ // Same clamp as the window: a shrinking tree can leave `scrollTop` past the
1040
+ // content until the browser re-clamps it one layout later.
1041
+ const maxBody = Math.max(0, visibleRowsRef.current.length * TREE_ROW_HEIGHT - body)
1042
+ const seen = Math.max(0, Math.min(scroller.scrollTop - header, maxBody))
1043
+ const top = index * TREE_ROW_HEIGHT
1044
+ const bottom = top + TREE_ROW_HEIGHT
1045
+ let next = scroller.scrollTop
1046
+ if (top < seen) next = header + Math.max(0, top - TREE_ROW_HEIGHT)
1047
+ else if (bottom > seen + body) next = header + Math.min(maxBody, bottom - body + TREE_ROW_HEIGHT)
1048
+ if (Math.abs(next - scroller.scrollTop) < 1) return
1049
+ scroller.scrollTop = Math.max(0, next)
1050
+ }, [measureTreeRows])
656
1051
  /** Abort handle for the batch on the wire (the upload bar's ✕). */
657
1052
  const uploadAbort = useRef<AbortController | undefined>(undefined)
1053
+ /** Abort handle for the delete batch on the wire (the delete bar's ✕). */
1054
+ const deleteAbort = useRef<AbortController | undefined>(undefined)
658
1055
  /** True while a remote WRITE batch is in flight (upload/paste/delete serialization). */
659
1056
  const transferRef = useRef(false)
660
1057
  /**
@@ -848,17 +1245,22 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
848
1245
  let attempts = 0
849
1246
  const timer = window.setInterval(() => {
850
1247
  attempts += 1
851
- const row = Array.from(document.querySelectorAll<HTMLElement>('[data-rvs-path]'))
852
- .find((candidate) => candidate.dataset.rvsPath === target)
853
- if (row !== undefined) {
1248
+ const row = rowElement(target)
1249
+ if (row !== null) {
854
1250
  window.clearInterval(timer)
855
1251
  row.scrollIntoView({ block: 'center' })
856
1252
  return
857
1253
  }
1254
+ // Windowing: the target can be IN the flat list while being outside the
1255
+ // painted slice, in which case no amount of waiting mounts it. Scroll its
1256
+ // index into the slice — the lookup above stays as the check that it
1257
+ // really arrived, and `scrollIntoView` still does the final centering.
1258
+ const index = entryRowIndex(target)
1259
+ if (index >= 0) scrollTreeToRow(index)
858
1260
  if (attempts > 20) window.clearInterval(timer)
859
1261
  }, 150)
860
1262
  return () => window.clearInterval(timer)
861
- }, [store.revealRequest, root, loadDir])
1263
+ }, [store.revealRequest, root, loadDir, entryRowIndex, scrollTreeToRow])
862
1264
 
863
1265
  // Root listing + refresh on the shared revision bump (git writes, saves...).
864
1266
  const revision = store.revision
@@ -912,6 +1314,52 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
912
1314
  setListings(prev => trimListings(prev, keep))
913
1315
  }, [expanded, alias, listings])
914
1316
 
1317
+ /**
1318
+ * Forget the OLDEST remembered expansions whose rows are not drawn any more.
1319
+ *
1320
+ * `expanded` keeps a directory open across a collapsed ancestor, which is what
1321
+ * makes re-opening the ancestor restore the view the user left. It also means
1322
+ * the trim above can never evict those descendants' listings, and a deep
1323
+ * session would hold every directory it ever opened. Here the ones that are
1324
+ * not currently drawn (see `drawnDirKeys`) are capped at
1325
+ * `HIDDEN_EXPANDED_KEEP`; the oldest are removed from `expanded` itself, which
1326
+ * is the only way to make their listings evictable without ever leaving an
1327
+ * OPEN folder with no rows to draw. On-screen directories are untouched, and
1328
+ * `expanded` preserves insertion order, so "oldest" is well defined.
1329
+ */
1330
+ useEffect(() => {
1331
+ if (root === '') return
1332
+ // Cheap bail-out: `hidden` is a SUBSET of `expanded`, so a tree with no more
1333
+ // open directories than the cap cannot need any of the work below (and this
1334
+ // is the common case — the walk only runs for a deep remembered tree).
1335
+ if (expanded.size <= HIDDEN_EXPANDED_KEEP) return
1336
+ // The same filter `rowsOf` applies on the render side: with `showHidden`
1337
+ // off, a dot-directory is not painted, so its listing is evictable even
1338
+ // though it is still in `expanded`.
1339
+ const drawn = drawnDirKeys({
1340
+ root,
1341
+ alias,
1342
+ listings,
1343
+ expanded,
1344
+ visible: entry => props.showHidden || !entry.name.startsWith('.'),
1345
+ })
1346
+ const hidden: string[] = []
1347
+ for (const dir of expanded) {
1348
+ if (dir !== root && !drawn.has(dirKey(alias, dir))) hidden.push(dir)
1349
+ }
1350
+ if (hidden.length <= HIDDEN_EXPANDED_KEEP) return
1351
+ const forget = new Set(hidden.slice(0, hidden.length - HIDDEN_EXPANDED_KEEP))
1352
+ setExpanded(prev => {
1353
+ let next: Set<string> | undefined
1354
+ for (const dir of forget) {
1355
+ if (!prev.has(dir)) continue
1356
+ if (next === undefined) next = new Set(prev)
1357
+ next.delete(dir)
1358
+ }
1359
+ return next ?? prev
1360
+ })
1361
+ }, [root, alias, listings, expanded, props.showHidden])
1362
+
915
1363
  /** Keep the synchronous cache view in step (prefetch reads it at pointer time). */
916
1364
  useEffect(() => {
917
1365
  listingsRef.current = listings
@@ -958,7 +1406,7 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
958
1406
  const visible = props.showHidden ? rows : rows.filter(entry => !entry.name.startsWith('.'))
959
1407
  sorted = [...visible].sort((a, b) => {
960
1408
  if (a.isDir !== b.isDir) return a.isDir ? -1 : 1
961
- return a.name.localeCompare(b.name)
1409
+ return NAME_COLLATOR.compare(a.name, b.name)
962
1410
  })
963
1411
  }
964
1412
  cache.set(dir, sorted)
@@ -1240,27 +1688,267 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
1240
1688
  okText: t('files.delete'),
1241
1689
  })
1242
1690
  if (!ok) return
1243
- setBusy(true)
1244
- const failed: string[] = []
1245
- /** Entries that really disappeared on the remote — their subtree is pruned. */
1246
- const removed: string[] = []
1691
+ // Validate what the batch command can quote BEFORE any remote write starts,
1692
+ // and keep the rest for the old per-entry route. A name git can store but the
1693
+ // sh script grammar cannot represent (a control character) used to be
1694
+ // deletable through SFTP; it must not turn the whole selection into an error.
1695
+ const batchable: RemoteFileEntry[] = []
1696
+ const unsupported: RemoteFileEntry[] = []
1247
1697
  for (const entry of entries) {
1248
1698
  try {
1249
- await api.fileOp.rm(alias, entry.path, entry.isDir)
1250
- removed.push(entry.path)
1699
+ splitBatchRemovePaths([entry.path])
1700
+ batchable.push(entry)
1701
+ } catch {
1702
+ unsupported.push(entry)
1703
+ }
1704
+ }
1705
+ if (batchable.length === 0 && unsupported.length === 0) return
1706
+ const chunks = batchable.length === 0 ? [] : splitBatchRemovePaths(batchable.map(entry => entry.path))
1707
+ if (chunks.length === 0 && unsupported.length === 0) return
1708
+ const targets = chunks.flat()
1709
+ const total = targets.length + unsupported.length
1710
+ /** The selected rows as they were BEFORE the delete: name, `isDir`, and the git marks all describe that state. */
1711
+ const entryByPath = new Map<string, RemoteFileEntry>()
1712
+ for (const entry of batchable) entryByPath.set(assertRemovablePath(entry.path), entry)
1713
+ const entryFor = (path: string): RemoteFileEntry | undefined => entryByPath.get(assertRemovablePath(path))
1714
+ /** Entries confirmed gone; their subtrees are pruned and their parents refreshed. */
1715
+ const removed: string[] = []
1716
+ /** The same paths normalized, so a covered child is an ancestor walk, not a scan. */
1717
+ const removedSet = new Set<string>()
1718
+ /** Entries whose outcome is known (deleted, or failed with a precise error). */
1719
+ let settled = 0
1720
+ /**
1721
+ * Raw paths already counted in `settled`.
1722
+ *
1723
+ * A parent and a child of it can both be selected: the child's marker is a
1724
+ * FAIL (the parent already took it), so counting only confirmed removals
1725
+ * left `done` short of `total` forever and made a canceled batch overstate
1726
+ * the unfinished count.
1727
+ */
1728
+ const settledPaths = new Set<string>()
1729
+ /** One line per entry that could not be removed, with the precise error. */
1730
+ const failed: string[] = []
1731
+ /** Raw paths behind `failed`, so their parents are re-listed too. */
1732
+ const failedPaths: string[] = []
1733
+ let cancelled = false
1734
+
1735
+ /** A path is gone when it was removed itself or lives under a removed one. */
1736
+ const gone = (path: string): boolean => {
1737
+ let cursor = assertRemovablePath(path)
1738
+ for (;;) {
1739
+ if (removedSet.has(cursor)) return true
1740
+ const cut = cursor.lastIndexOf('/')
1741
+ if (cut <= 0) return false
1742
+ cursor = cursor.slice(0, cut)
1743
+ }
1744
+ }
1745
+
1746
+ /**
1747
+ * Covered-by-a-removed-ancestor check for paths the batch grammar cannot
1748
+ * normalize (a control character in the name). Plain string prefixes; no
1749
+ * validation, because validating is exactly what rejects these names.
1750
+ */
1751
+ const coveredRaw = (path: string): boolean =>
1752
+ removed.some(root => path === root || path.startsWith(`${root}/`))
1753
+
1754
+ const showProgress = (name: string): void => {
1755
+ setDeleteProgress({ done: settled, total, name })
1756
+ }
1757
+
1758
+ const countSettled = (path: string, name: string): void => {
1759
+ if (settledPaths.has(path)) return
1760
+ settledPaths.add(path)
1761
+ settled += 1
1762
+ showProgress(name)
1763
+ }
1764
+
1765
+ /**
1766
+ * Record one confirmed removal.
1767
+ *
1768
+ * A parent and a child of it can both be selected: the batch removes the
1769
+ * parent first, then the child's `rm` finds nothing left — its FAIL marker
1770
+ * (or its missing marker) counts as removed, not as an error.
1771
+ */
1772
+ const noteRemoved = (entry: RemoteFileEntry): void => {
1773
+ const path = assertRemovablePath(entry.path)
1774
+ countSettled(path, entry.name)
1775
+ if (gone(path)) return
1776
+ removed.push(entry.path)
1777
+ removedSet.add(path)
1778
+ }
1779
+
1780
+ /**
1781
+ * Record a removal of a path the batch grammar cannot quote.
1782
+ *
1783
+ * Those entries never enter `removedSet` (the ancestor walk assumes a
1784
+ * normalized path), so the simple duplicate check is enough.
1785
+ */
1786
+ const noteRemovedRaw = (entry: RemoteFileEntry): void => {
1787
+ countSettled(entry.path, entry.name)
1788
+ if (removed.includes(entry.path)) return
1789
+ removed.push(entry.path)
1790
+ }
1791
+
1792
+ const noteFailed = (entry: RemoteFileEntry, message: string): void => {
1793
+ countSettled(entry.path, entry.name)
1794
+ failed.push(`${entry.name}: ${message}`)
1795
+ failedPaths.push(entry.path)
1796
+ }
1797
+
1798
+ /** Apply one streamed marker to the batch bookkeeping. */
1799
+ const applyMarker = (path: string, kind: 'item' | 'ok' | 'fail'): void => {
1800
+ if (kind === 'item') {
1801
+ const entry = entryFor(path)
1802
+ showProgress(entry?.name ?? baseName(path))
1803
+ return
1804
+ }
1805
+ // FAIL stays unconfirmed: the per-entry fallback below either removes the
1806
+ // path (recording it as removed) or reports its exact error. A path a
1807
+ // removed parent already covers is skipped there, so it is never a failure.
1808
+ if (kind !== 'ok') return
1809
+ const entry = entryFor(path)
1810
+ if (entry !== undefined) noteRemoved(entry)
1811
+ }
1812
+
1813
+ /**
1814
+ * Remove one batch through the streamed exec route.
1815
+ *
1816
+ * The script prints `RV_DEL_ITEM`/`RV_DEL_OK`/`RV_DEL_FAIL <index>` lines;
1817
+ * stdout is fed through a line buffer because one marker can arrive split
1818
+ * across two stream chunks. A path the batch did not settle (a FAIL marker,
1819
+ * or a whole batch that failed on the wire) is retried through the old
1820
+ * per-entry route: the FALLBACK answers with that path's exact error, and a
1821
+ * success there is a real removal.
1822
+ */
1823
+ const runBatch = async (chunk: string[]): Promise<void> => {
1824
+ const pathByIndex = new Map<number, string>()
1825
+ chunk.forEach((path, index) => pathByIndex.set(index, path))
1826
+ let pending = ''
1827
+ const feed = (text: string): void => {
1828
+ pending = drainDeleteMarkers(pending, text, (marker) => {
1829
+ const path = pathByIndex.get(marker.index)
1830
+ if (path !== undefined) applyMarker(path, marker.kind)
1831
+ })
1832
+ }
1833
+ try {
1834
+ await api.execStream(alias, batchRemoveScript(chunk), DELETE_BATCH_TIMEOUT_MS, {
1835
+ signal: controller.signal,
1836
+ onData: (stream, text) => {
1837
+ // stderr carries the per-path `rm` diagnostics; markers only ride stdout.
1838
+ if (stream === 'out') feed(text)
1839
+ },
1840
+ })
1251
1841
  } catch (error) {
1252
- failed.push(`${entry.name}: ${error instanceof Error ? error.message : String(error)}`)
1842
+ if (controller.signal.aborted || isAbortError(error)) {
1843
+ cancelled = true
1844
+ return
1845
+ }
1846
+ // The whole batch failed on the wire (link drop, timeout, route error):
1847
+ // every path is unconfirmed, so the FALLBACK below retries them all.
1848
+ }
1849
+ // A final marker without its trailing newline still has to be seen.
1850
+ if (pending !== '') feed('\n')
1851
+ const retry: RemoteFileEntry[] = []
1852
+ for (const path of chunk) {
1853
+ if (gone(path)) {
1854
+ countSettled(path, entryFor(path)?.name ?? baseName(path))
1855
+ continue
1856
+ }
1857
+ const entry = entryFor(path)
1858
+ if (entry !== undefined) retry.push(entry)
1859
+ }
1860
+ for (const entry of retry) {
1861
+ if (controller.signal.aborted) {
1862
+ cancelled = true
1863
+ return
1864
+ }
1865
+ // A parent retried just before this entry may have taken it with it.
1866
+ if (gone(entry.path)) {
1867
+ countSettled(entry.path, entry.name)
1868
+ continue
1869
+ }
1870
+ try {
1871
+ await api.fileOp.rm(alias, entry.path, entry.isDir)
1872
+ noteRemoved(entry)
1873
+ } catch (error) {
1874
+ noteFailed(entry, error instanceof Error ? error.message : String(error))
1875
+ }
1253
1876
  }
1254
1877
  }
1255
- setBusy(false)
1256
- // Drop the removed subtrees from `expanded`/`selected`/`listings` BEFORE any
1257
- // refresh: `store.afterWrite()` bumps the revision, and the root effect
1258
- // re-lists every expanded directory — the deleted ones would each answer
1259
- // with a business error and a toast, on every write for the rest of the
1260
- // session.
1878
+
1879
+ setBusy(true)
1880
+ // Own the single write slot for the whole batch: an upload/paste started
1881
+ // mid-delete would interleave writes with the removals.
1882
+ transferRef.current = true
1883
+ const controller = new AbortController()
1884
+ deleteAbort.current = controller
1885
+ showProgress(baseName(targets[0] ?? ''))
1886
+ try {
1887
+ for (const chunk of chunks) {
1888
+ if (controller.signal.aborted) {
1889
+ cancelled = true
1890
+ break
1891
+ }
1892
+ await runBatch(chunk)
1893
+ if (cancelled) break
1894
+ }
1895
+ // Paths the batch grammar cannot carry (a control character in the name)
1896
+ // keep the old per-entry route instead of failing the whole selection.
1897
+ for (const entry of unsupported) {
1898
+ if (controller.signal.aborted) {
1899
+ cancelled = true
1900
+ break
1901
+ }
1902
+ if (coveredRaw(entry.path)) {
1903
+ countSettled(entry.path, entry.name)
1904
+ continue
1905
+ }
1906
+ showProgress(entry.name)
1907
+ try {
1908
+ await api.fileOp.rm(alias, entry.path, entry.isDir)
1909
+ noteRemovedRaw(entry)
1910
+ } catch (error) {
1911
+ noteFailed(entry, error instanceof Error ? error.message : String(error))
1912
+ }
1913
+ }
1914
+ } catch (error) {
1915
+ // Anything the batch runner did not classify still ends the delete as a
1916
+ // reported failure instead of an unhandled rejection.
1917
+ failed.push(error instanceof Error ? error.message : String(error))
1918
+ } finally {
1919
+ // Clear the bar before any refresh: the tail below must not look stuck.
1920
+ deleteAbort.current = undefined
1921
+ setDeleteProgress(undefined)
1922
+ setBusy(false)
1923
+ transferRef.current = false
1924
+ }
1925
+ // Drop the removed subtrees from `expanded`/`selected`/`listings` BEFORE the
1926
+ // refresh, so no later root re-list asks for a directory that no longer
1927
+ // exists (each such request is a business error and a toast).
1261
1928
  forgetPaths(removed)
1262
- await refreshDirs([...new Set(entries.map(entry => entry.path.split('/').slice(0, -1).join('/') || '/'))])
1263
- await store.afterWrite()
1929
+ // Only the directories a removal actually touched are re-listed — the global
1930
+ // write tail (git status + revision bump re-listing every expanded directory)
1931
+ // is deliberately not run for a delete.
1932
+ const parents = [...new Set(
1933
+ [...removed, ...failedPaths].map(path => path.split('/').slice(0, -1).join('/') || '/'),
1934
+ )]
1935
+ await Promise.all(parents.map(dir => loadDir(dir, true)))
1936
+ if (removed.length > 0) {
1937
+ // Tell the quick-open index cache that paths on the remote changed.
1938
+ noteRemoteWrite()
1939
+ }
1940
+ // Deleting only ignored paths leaves git status identical, so the read
1941
+ // (seconds on a big tree) is skipped; otherwise it is started in the
1942
+ // background and the toast does not wait for it.
1943
+ const allIgnored = removed.every(path => ignoredByTree(path))
1944
+ if (!allIgnored) void refreshGit().catch(() => undefined)
1945
+ if (cancelled) {
1946
+ const copy = t('files.deleteCancelled')
1947
+ .replace('{removed}', String(removed.length))
1948
+ .replace('{left}', String(Math.max(0, total - settled)))
1949
+ toast(failed.length === 0 ? copy : `${copy}\n${failed.join('\n')}`, failed.length > 0)
1950
+ return
1951
+ }
1264
1952
  if (failed.length > 0) toast(failed.join('\n'), true)
1265
1953
  else toast(t('files.deleted'))
1266
1954
  }
@@ -1907,6 +2595,15 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
1907
2595
  label: t('files.findInFolder'),
1908
2596
  onSelect: () => store.requestSearch({ mode: 'content', scope: dir }),
1909
2597
  })
2598
+ // 「在终端中打开」on a DIRECTORY. `dir` is already the folder a terminal
2599
+ // should land in (the row itself for a directory); `store.openTerminalAt`
2600
+ // switches to the terminal page and the panel types a quoted `cd` once the
2601
+ // PTY is ready — the alias travels inside the request, so the new tab
2602
+ // opens on the host this path belongs to. Directories only: "here" is the
2603
+ // folder, and the parent of a file is what "Find in Folder…" already covers.
2604
+ if (entry.isDir) {
2605
+ entries.push({ label: t('files.openInTerminal'), onSelect: () => { store.openTerminalAt(dir) } })
2606
+ }
1910
2607
  if (!entry.isDir) {
1911
2608
  entries.push({ label: t('files.searchNameHere'), onSelect: () => store.requestSearch({ mode: 'name', scope: dir }) })
1912
2609
  }
@@ -1976,6 +2673,27 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
1976
2673
  return entry.isDir ? marks.ignoredDirs.has(rel) : marks.ignored.has(rel)
1977
2674
  }, [repoRoot, marks])
1978
2675
 
2676
+ /**
2677
+ * Whether deleting `path` can leave `git status` byte-identical.
2678
+ *
2679
+ * `git status --ignored` reports an ignored DIRECTORY once, unexpanded, so a
2680
+ * file inside it is not in `marks.ignored` — but deleting that file is still
2681
+ * invisible to git. Walk the ancestors through `ignoredDirs` so an
2682
+ * ignored-only batch really skips the (potentially minutes-long) git read.
2683
+ */
2684
+ const ignoredByTree = useCallback((path: string): boolean => {
2685
+ const rel = repoRelative(repoRoot, path)
2686
+ if (rel === '') return false
2687
+ if (marks.ignored.has(rel) || marks.ignoredDirs.has(rel)) return true
2688
+ const segments = rel.split('/')
2689
+ let acc = ''
2690
+ for (let i = 0; i < segments.length - 1; i += 1) {
2691
+ acc = acc === '' ? (segments[i] as string) : `${acc}/${segments[i]}`
2692
+ if (marks.ignoredDirs.has(acc)) return true
2693
+ }
2694
+ return false
2695
+ }, [repoRoot, marks])
2696
+
1979
2697
  /** The right-click menu's `contextmenu` fallback (touch long-press only). */
1980
2698
  const onRowContextMenu = (e: React.MouseEvent, entry: RemoteFileEntry): void => {
1981
2699
  e.preventDefault()
@@ -1989,20 +2707,33 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
1989
2707
  * the flat visible rows plus a DOM lookup by `data-rvs-path`: before this the
1990
2708
  * tree had no keyboard path at all (no focusable row, no arrow/Enter/Esc
1991
2709
  * handling), which made the explorer unusable without a pointer.
2710
+ *
2711
+ * With the tree windowed the destination row is not necessarily mounted:
2712
+ * `rowKeyboardTarget` walks the WHOLE flat list, so an arrow key can move the
2713
+ * stop past the edge of the slice. The index is scrolled into the slice and
2714
+ * the DOM lookup is retried for a few frames, because the row mounts on the
2715
+ * commit that follows that scroll.
1992
2716
  */
1993
2717
  const [focusedPath, setFocusedPath] = useState<string | undefined>(undefined)
1994
- const visibleRowsRef = useRef<ExplorerRow[]>([])
1995
2718
  const focusRow = (path: string | undefined): void => {
1996
2719
  // `undefined` means an arrow key hit an edge: keep the current stop instead
1997
2720
  // of blanking it (the visibility effect only re-homes a path that stopped
1998
2721
  // existing — a no-op move must not cost the tree its Tab stop).
1999
2722
  if (path === undefined) return
2000
2723
  setFocusedPath(path)
2001
- requestAnimationFrame(() => {
2002
- const row = Array.from(document.querySelectorAll<HTMLElement>('[data-rvs-path]'))
2003
- .find(candidate => candidate.dataset.rvsPath === path)
2004
- row?.focus()
2005
- })
2724
+ let attempts = 0
2725
+ const retry = (): void => {
2726
+ const row = rowElement(path)
2727
+ if (row !== null) {
2728
+ row.focus()
2729
+ return
2730
+ }
2731
+ const index = entryRowIndex(path)
2732
+ if (index >= 0) scrollTreeRowIntoView(index)
2733
+ attempts += 1
2734
+ if (attempts < 16) requestAnimationFrame(retry)
2735
+ }
2736
+ requestAnimationFrame(retry)
2006
2737
  }
2007
2738
  const onRowKeyDown = (entry: RemoteFileEntry, event: React.KeyboardEvent): void => {
2008
2739
  const rows = visibleRowsRef.current
@@ -2052,8 +2783,7 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2052
2783
  }
2053
2784
  if ((key === 'F10' && event.shiftKey) || key === 'ContextMenu') {
2054
2785
  event.preventDefault()
2055
- const row = Array.from(document.querySelectorAll<HTMLElement>('[data-rvs-path]'))
2056
- .find(candidate => candidate.dataset.rvsPath === entry.path)
2786
+ const row = rowElement(entry.path)
2057
2787
  const rect = row?.getBoundingClientRect()
2058
2788
  openMenu({
2059
2789
  preventDefault: () => undefined,
@@ -2182,6 +2912,104 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2182
2912
  // Keyboard navigation reads the current flat list synchronously.
2183
2913
  visibleRowsRef.current = visibleRows
2184
2914
 
2915
+ // -------------------------------------------------------------- windowing
2916
+
2917
+ /**
2918
+ * The slice of the flat list the DOM paints.
2919
+ *
2920
+ * `visibleRows` stays the single source of truth for ORDER (and for keyboard
2921
+ * navigation, which must be able to leave the screen); the scroller only ever
2922
+ * receives one window of it, with a spacer of the exact height of everything
2923
+ * above and below. A fully expanded 20000-entry directory therefore costs a
2924
+ * screenful of row nodes instead of 20000 rows / 12–20万 nodes, while the
2925
+ * scrollbar keeps the range it had when every row was mounted.
2926
+ *
2927
+ * The initial value is the no-viewport fallback (< `TREE_WINDOW_FALLBACK`
2928
+ * rows), so the FIRST paint already renders a screenful and the layout effect
2929
+ * below corrects it before that frame is shown.
2930
+ */
2931
+ const [treeWindow, setTreeWindow] = useState<TreeWindow>({
2932
+ from: 0,
2933
+ to: TREE_WINDOW_FALLBACK,
2934
+ before: 0,
2935
+ after: 0,
2936
+ })
2937
+ const windowRows = useMemo(
2938
+ () => visibleRows.slice(treeWindow.from, treeWindow.to),
2939
+ [visibleRows, treeWindow.from, treeWindow.to],
2940
+ )
2941
+ /**
2942
+ * Recompute the painted slice from the live geometry.
2943
+ *
2944
+ * Called from the scroll handler, from the ResizeObserver and from the layout
2945
+ * effect below. The state update is skipped when the slice did not move —
2946
+ * `computeTreeWindow` answers the same four numbers — so a wheel storm inside
2947
+ * one row costs one measurement and no render.
2948
+ */
2949
+ const syncTreeWindow = useCallback((): void => {
2950
+ const { header, viewport, scrollTop } = measureTreeRows()
2951
+ const next = computeTreeWindow(visibleRowsRef.current.length, scrollTop, viewport, header)
2952
+ setTreeWindow(prev => (
2953
+ prev.from === next.from && prev.to === next.to && prev.before === next.before && prev.after === next.after
2954
+ ? prev
2955
+ : next
2956
+ ))
2957
+ }, [measureTreeRows])
2958
+ /**
2959
+ * Measure AFTER every commit, BEFORE the paint.
2960
+ *
2961
+ * This cannot be a dependency-keyed effect: the geometry depends on what this
2962
+ * very render mounted (the root label can wrap, the drop hint appears or goes,
2963
+ * the panel can come back from `display:none`, an expansion changes the row
2964
+ * count) and only the committed DOM knows any of that. A no-op measurement
2965
+ * does not re-render, so running it every commit does not loop.
2966
+ */
2967
+ useLayoutEffect(() => {
2968
+ syncTreeWindow()
2969
+ })
2970
+ /** A pane resize (sidebar split, window resize, panel shown) re-slices too. */
2971
+ useEffect(() => {
2972
+ const scroller = treeRef.current
2973
+ if (scroller === null || typeof ResizeObserver === 'undefined') return
2974
+ const observer = new ResizeObserver(() => syncTreeWindow())
2975
+ observer.observe(scroller)
2976
+ return () => observer.disconnect()
2977
+ }, [syncTreeWindow])
2978
+
2979
+ /**
2980
+ * Keep the row an in-row EDITOR depends on mounted.
2981
+ *
2982
+ * Two states put an input INSIDE a row — the inline rename and the inline
2983
+ * create row — and with a window an unmounted row means the input never mounts
2984
+ * (create) or unmounts while it is being typed in (rename). The roving Tab
2985
+ * stop has the same problem after `nextFocusPath` re-homes it to a row that is
2986
+ * not in the slice: a `tabIndex=0` row outside the DOM leaves the whole tree
2987
+ * unreachable by keyboard.
2988
+ *
2989
+ * Edge-triggered on the target, never on the slice: a user who scrolls the
2990
+ * focused row out of view must not be dragged back to it on every scroll step.
2991
+ */
2992
+ let pinnedRowKey = ''
2993
+ if (renaming !== undefined) pinnedRowKey = `rename:${renaming}`
2994
+ else if (creating !== undefined) pinnedRowKey = `create:${creating.dir}`
2995
+ else if (focusedPath !== undefined) pinnedRowKey = `focus:${focusedPath}`
2996
+ const keptRowRef = useRef('')
2997
+ useEffect(() => {
2998
+ if (pinnedRowKey === '') {
2999
+ keptRowRef.current = ''
3000
+ return
3001
+ }
3002
+ if (keptRowRef.current === pinnedRowKey) return
3003
+ keptRowRef.current = pinnedRowKey
3004
+ const rows = visibleRowsRef.current
3005
+ let index = -1
3006
+ if (renaming !== undefined) index = rows.findIndex(row => row.kind === 'entry' && row.entry.path === renaming)
3007
+ else if (creating !== undefined) index = rows.findIndex(row => row.kind === 'create' && row.dir === creating.dir)
3008
+ else if (focusedPath !== undefined) index = rows.findIndex(row => row.kind === 'entry' && row.entry.path === focusedPath)
3009
+ if (index < 0 || (index >= treeWindow.from && index < treeWindow.to)) return
3010
+ scrollTreeRowIntoView(index)
3011
+ }, [pinnedRowKey, renaming, creating, focusedPath, visibleRows, treeWindow, scrollTreeRowIntoView])
3012
+
2185
3013
  /**
2186
3014
  * Keep a Tab stop on screen.
2187
3015
  *
@@ -2218,9 +3046,24 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2218
3046
  const referenceTitle = chatEnabled ? t('files.referenceFile') : t('files.refDisabled')
2219
3047
  const symlinkTitle = t('files.symlink')
2220
3048
  const cutPaths = clipboard !== undefined && clipboard.mode === 'cut' ? new Set(clipboard.paths) : undefined
3049
+ // The roving Tab stop: the focused row while it is PAINTED, otherwise the
3050
+ // first painted entry. A row scrolled out of the window is unmounted, and a
3051
+ // tree whose only `tabIndex=0` row is not in the DOM cannot be reached with
3052
+ // Tab at all — the pointer would be the only way back in, which is exactly
3053
+ // what the roving tabindex exists to prevent.
3054
+ const focusedRowPainted = windowRows.some(row => row.kind === 'entry' && row.entry.path === focusedPath)
3055
+ const tabStopPath = focusedRowPainted
3056
+ ? focusedPath
3057
+ : windowRows.find((row): row is Extract<ExplorerRow, { kind: 'entry' }> => row.kind === 'entry')?.entry.path
2221
3058
  return (
2222
3059
  <>
2223
- {visibleRows.map(row => {
3060
+ {/* The rows scrolled past. Height, not transform: the spacer has to leave
3061
+ a real scroll range behind, or the rows below the window are
3062
+ unreachable. It is also why the slice must use one fixed row height. */}
3063
+ {treeWindow.before > 0 && (
3064
+ <div aria-hidden="true" style={{ height: treeWindow.before }} />
3065
+ )}
3066
+ {windowRows.map((row, offset) => {
2224
3067
  if (row.kind === 'create') {
2225
3068
  return (
2226
3069
  <CreateRow
@@ -2241,8 +3084,15 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2241
3084
  }
2242
3085
  if (row.kind === 'pending') {
2243
3086
  // Same copy/order as the root placeholder (offline before loading).
3087
+ // Fixed 28 px like every other row (`.rvs-empty` alone is 18+18 px
3088
+ // of padding): a placeholder that is taller than a row would put the
3089
+ // slice one index off behind it.
2244
3090
  return (
2245
- <div key={`pending:${row.dir}`} className="rvs-empty" style={{ paddingLeft: 12 + row.depth * 14 }}>
3091
+ <div
3092
+ key={`pending:${row.dir}`}
3093
+ className="rvs-empty"
3094
+ style={{ ...TREE_ROW_BOX, paddingLeft: 12 + row.depth * 14 }}
3095
+ >
2246
3096
  {row.reason === 'offline' ? t('files.offline') : t('common.loading')}
2247
3097
  </div>
2248
3098
  )
@@ -2252,6 +3102,8 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2252
3102
  key={row.entry.path}
2253
3103
  entry={row.entry}
2254
3104
  depth={row.depth}
3105
+ posinset={treeWindow.from + offset + 1}
3106
+ setsize={visibleRows.length}
2255
3107
  status={statusFor(row.entry)}
2256
3108
  ignored={ignoredFor(row.entry)}
2257
3109
  isSelected={selected.has(row.entry.path)}
@@ -2259,7 +3111,7 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2259
3111
  isCut={cutPaths !== undefined && cutPaths.has(row.entry.path)}
2260
3112
  isDropTarget={dropTarget === row.entry.path}
2261
3113
  isRenaming={renaming === row.entry.path}
2262
- isFocused={focusedPath === row.entry.path}
3114
+ isFocused={tabStopPath === row.entry.path}
2263
3115
  chatEnabled={chatEnabled}
2264
3116
  referenceTitle={referenceTitle}
2265
3117
  symlinkTitle={symlinkTitle}
@@ -2267,6 +3119,10 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2267
3119
  />
2268
3120
  )
2269
3121
  })}
3122
+ {/* The rows still below the window, same reasoning as the top spacer. */}
3123
+ {treeWindow.after > 0 && (
3124
+ <div aria-hidden="true" style={{ height: treeWindow.after }} />
3125
+ )}
2270
3126
  </>
2271
3127
  )
2272
3128
  }
@@ -2322,6 +3178,22 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2322
3178
  </button>
2323
3179
  </div>
2324
3180
  )}
3181
+ {deleteProgress !== undefined && (
3182
+ <div className="rvs-upload-bar">
3183
+ <MiniSpinner />
3184
+ <span className="rvs-upload-text" title={deleteProgress.name}>
3185
+ {formatDeleteLabel(t, deleteProgress)}
3186
+ </span>
3187
+ <button
3188
+ type="button"
3189
+ className="rvs-hbtn"
3190
+ title={t('files.deleteCancel')}
3191
+ onClick={() => deleteAbort.current?.abort()}
3192
+ >
3193
+ ✕
3194
+ </button>
3195
+ </div>
3196
+ )}
2325
3197
  {/* Hidden pickers for the context-menu / header "Upload…" entries. The
2326
3198
  folder input needs `webkitdirectory`, which React does not type. */}
2327
3199
  <input
@@ -2411,6 +3283,9 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2411
3283
  setDropHint(undefined)
2412
3284
  }}
2413
3285
  onDrop={(e) => handleDrop(root, e)}
3286
+ // The window follows the scroll position; the handler only re-renders
3287
+ // when the slice changes (see `syncTreeWindow`).
3288
+ onScroll={() => syncTreeWindow()}
2414
3289
  >
2415
3290
  <div
2416
3291
  className="rvs-tree"
@@ -2433,6 +3308,11 @@ export function RemoteExplorer(props: { showHidden: boolean; onToggleHidden: ()
2433
3308
  {`${t('files.dropToUpload')} → ${dropTarget.split('/').slice(-1)[0] || dropTarget}`}
2434
3309
  </div>
2435
3310
  )}
3311
+ {/* Sentinel: every node above this one inside the scroller is HEADER
3312
+ (root label, drop hint, `.rvs-tree`'s top padding). `measureTreeRows`
3313
+ reads its offset, so the slice can never drift from the scrollbar
3314
+ when the label wraps or a drop hint appears. Zero height, no box. */}
3315
+ <div ref={rowsTopRef} aria-hidden="true" style={{ height: 0 }} />
2436
3316
  {root !== '' && renderDir(root, 0)}
2437
3317
  {root === '' && <div className="rvs-empty">{t('files.selectWorkspace')}</div>}
2438
3318
  </div>
@@ -2456,7 +3336,7 @@ function CreateRow(props: {
2456
3336
  t: (key: string) => string
2457
3337
  }): ReactNode {
2458
3338
  return (
2459
- <div className="rvs-node" style={{ paddingLeft: 8 + props.depth * 14 }} onClick={(e) => e.stopPropagation()}>
3339
+ <div className="rvs-node" style={{ ...TREE_ROW_BOX, paddingLeft: 8 + props.depth * 14 }} onClick={(e) => e.stopPropagation()}>
2460
3340
  <span className="rvs-node-icon">{props.kind === 'folder' ? props.folderIcon : props.fileIcon}</span>
2461
3341
  <RenameInput
2462
3342
  initial=""
@@ -2509,8 +3389,17 @@ function RenameInput(props: {
2509
3389
  onClick={(e) => e.stopPropagation()}
2510
3390
  onChange={(e) => setValue(e.target.value)}
2511
3391
  onKeyDown={(e) => {
2512
- if (e.key === 'Enter') { e.preventDefault(); commit() } else if (e.key === 'Escape') { e.preventDefault(); cancel() }
3392
+ // An IME candidate window uses Enter to pick a name and Escape to drop
3393
+ // it. Acting on them would rename/create with an uncommitted name, and
3394
+ // preventDefault alone can swallow the candidate commit. Stopping
3395
+ // propagation first keeps the host/tree shortcuts out of the composing
3396
+ // keystroke. `isComposing` is the platform-agnostic signal;
3397
+ // `keyCode === 229` is the fallback for engines that dispatch
3398
+ // compositionend before the keydown of the very same Enter (Chrome), so
3399
+ // that Enter is still dropped instead of committing once more.
2513
3400
  e.stopPropagation()
3401
+ if (e.nativeEvent.isComposing === true || e.keyCode === 229) return
3402
+ if (e.key === 'Enter') { e.preventDefault(); commit() } else if (e.key === 'Escape') { e.preventDefault(); cancel() }
2514
3403
  }}
2515
3404
  onBlur={() => {
2516
3405
  // A blur after Enter/Escape is a no-op; an empty create row is dropped.