dsh-remote-vs 0.21.0 → 0.22.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,94 @@
1
+ /**
2
+ * Terminal clipboard chords and the paste fallback, as testable logic.
3
+ *
4
+ * Why this module exists
5
+ * ----------------------
6
+ * The terminal's copy/paste handling used to be an inline `attachCustomKeyEventHandler`
7
+ * with three problems the UI tests could not see:
8
+ *
9
+ * 1. **Double paste on Ctrl+Shift+V.** The handler pasted through
10
+ * `navigator.clipboard.readText()` and returned `false`, but returning false only
11
+ * stops xterm's own handling — the browser still performed its default paste
12
+ * (Chrome maps Ctrl+Shift+V to "paste as plain text"), so both paths inserted the
13
+ * text. Handled chords must call `preventDefault()` themselves.
14
+ * 2. **Ctrl+V depended entirely on the browser's native paste.** When the host page
15
+ * or a wrapper swallows the paste event (desktop shells, non-standard clipboard
16
+ * permissions), the terminal silently received nothing. It now falls back to the
17
+ * Clipboard API only when no paste event arrived shortly after the key press.
18
+ * 3. **Right-click copied/pasted immediately with no visible affordance.** It is now
19
+ * a small menu (copy / paste / select all) so the action is discoverable and the
20
+ * copy item can be disabled when nothing is selected.
21
+ *
22
+ * The chord table and the fallback watcher are pure so a gate can pin all of it.
23
+ */
24
+ /** What one key press asks the terminal to do. */
25
+ export type TerminalClipboardChord =
26
+ /** Copy the current selection, then clear it (menu action). */
27
+ 'copy'
28
+ /** Paste immediately through the Clipboard API. */
29
+ | 'paste'
30
+ /** Let the browser's native paste run; fall back to the Clipboard API when no paste event arrives. */
31
+ | 'paste-native'
32
+ /** Plain Ctrl+C: copy when a selection exists, otherwise stay SIGINT. */
33
+ | 'copy-interrupt';
34
+ /** The keyboard state the chord table reads. */
35
+ export interface TerminalChordInput {
36
+ key: string;
37
+ ctrl: boolean;
38
+ shift: boolean;
39
+ alt: boolean;
40
+ meta: boolean;
41
+ }
42
+ /**
43
+ * Map one keydown to a clipboard chord.
44
+ *
45
+ * Conventions: Ctrl+Shift+C / Ctrl+Insert / Cmd+C copy, Ctrl+Shift+V / Cmd+V /
46
+ * Shift+Insert paste. Plain Ctrl+V is left to the browser first (`paste-native`),
47
+ * and plain Ctrl+C always stays SIGINT.
48
+ */
49
+ export declare function clipboardChordFor(input: TerminalChordInput): TerminalClipboardChord | undefined;
50
+ /** Copy and paste chords take the key over; the native-paste chord must not. */
51
+ export declare function chordTakesKey(chord: TerminalClipboardChord): boolean;
52
+ /** Dependencies of {@link createPasteFallback}. */
53
+ export interface PasteFallbackDeps {
54
+ /** Clipboard read; `undefined` when the browser denies it. */
55
+ read: () => Promise<string | undefined>;
56
+ /** Insert text into the terminal. */
57
+ paste: (text: string) => void;
58
+ /** Report a denied clipboard read (shown in the terminal). */
59
+ onDenied: () => void;
60
+ /** Timer injection (tests use a fake clock). */
61
+ schedule?: (run: () => void, ms: number) => unknown;
62
+ }
63
+ /** How long to wait for a native paste event before falling back to the API. */
64
+ export declare const PASTE_FALLBACK_MS = 180;
65
+ /**
66
+ * Watches one Ctrl+V press: the browser's native paste wins when its event arrives,
67
+ * otherwise the Clipboard API inserts the text after {@link PASTE_FALLBACK_MS}.
68
+ *
69
+ * The watcher is a single slot: arming again (a held/repeated key) replaces the
70
+ * pending window instead of stacking pastes.
71
+ */
72
+ export declare function createPasteFallback(deps: PasteFallbackDeps): {
73
+ arm: () => void;
74
+ /** The terminal saw a native paste for this window: cancel the fallback. */
75
+ observed: () => void;
76
+ };
77
+ /** Menu entry state for the right-click menu. */
78
+ export declare function terminalMenuState(input: {
79
+ hasSelection: boolean;
80
+ }): {
81
+ copyDisabled: boolean;
82
+ };
83
+ /**
84
+ * Remove ONE bracketed-paste wrapper from an input chunk.
85
+ *
86
+ * xterm wraps `Terminal.paste()`/native pastes while the remote application has
87
+ * bracketed paste enabled. When that mode is stale (an app that enabled it was
88
+ * killed, or the shell never enabled it) the wrapper is displayed literally as
89
+ * `^[[200~...^[[201~` and the text is not executed — a field screenshot showed
90
+ * exactly that. The host-side input path strips one wrapper before forwarding,
91
+ * so the PTY only ever receives the user's text. Apps that expect the wrapper
92
+ * still accept raw text, like a classic terminal.
93
+ */
94
+ export declare function stripBracketedPasteMarkers(data: string): string;
@@ -471,6 +471,18 @@ export interface RemoteChangedFile {
471
471
  oversized?: true;
472
472
  /** Change kind from --name-status; undefined when git gave none. */
473
473
  status?: 'A' | 'M' | 'D' | 'R' | 'C' | 'T' | 'U';
474
+ /**
475
+ * What "undo this file" may do, decided by the HOST (the client never guesses).
476
+ *
477
+ * - `patch`: a real reverse patch exists — reverting restores the session
478
+ * baseline in one `git apply -R`.
479
+ * - `delete`: the file is a whole-file CREATION git has a copy of (a tracked
480
+ * addition), so the only reverse is deleting it. Recoverable from the index,
481
+ * but still a destructive write, so the client must confirm it.
482
+ * - absent: nothing can be undone — an UNTRACKED creation (git holds no copy),
483
+ * a binary, or a file whose bytes were withheld by the size caps.
484
+ */
485
+ revert?: 'patch' | 'delete';
474
486
  }
475
487
  /**
476
488
  * What one session changed on its remote host since the session's baseline.
@@ -492,8 +504,23 @@ export interface RemoteChangesSummary {
492
504
  deleted: number;
493
505
  /** Wall-clock ms when this summary was last recomputed. */
494
506
  at: number;
495
- /** More files than the cap: `files` is truncated but the totals are whole. */
507
+ /**
508
+ * More files than the cap: `files` is truncated and so are `added` / `deleted`.
509
+ *
510
+ * The totals are summed from the rows that made it into `files` (the cost of
511
+ * counting the rest is a read per path), which is why the panel says "N files
512
+ * changed" about a subset and must not present the counts as whole-tree
513
+ * totals.
514
+ */
496
515
  truncated?: true;
516
+ /**
517
+ * Directory names the new-file scan was told to skip (build output, caches).
518
+ *
519
+ * Present only when the exclusion ran, and listed rather than merely applied:
520
+ * a file the user expected to see must never be missing without a reason. The
521
+ * SCM panel stays the surface that shows every path.
522
+ */
523
+ excludedDirs?: string[];
497
524
  /** A scan is running right now (the slow one counts); the list will refresh. */
498
525
  pending: boolean;
499
526
  /** Why this session has no ledger (local session, no git, timeout, …). */
@@ -507,6 +534,15 @@ export interface RemoteChangesDiff {
507
534
  display: string;
508
535
  /** Text hunks (empty for binary/missing). */
509
536
  hunks: UnifiedHunk[];
537
+ /**
538
+ * The WHOLE file as one reverse-applicable patch (`git apply -R`).
539
+ *
540
+ * One write instead of one per hunk, which is what "revert everything this
541
+ * session did to this file" needs. Empty when the reverse is not expressible
542
+ * as a patch (see `RemoteChangedFile.revert`), which is the fail-closed answer
543
+ * the client must not try to build itself.
544
+ */
545
+ patch?: string;
510
546
  /** File status at turn end (A/M/D/…), when git reported one. */
511
547
  status?: 'A' | 'M' | 'D' | 'R' | 'C' | 'T' | 'U';
512
548
  /** The diff was cut at the byte cap: `hunks` is a prefix. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-remote-vs",
3
3
  "description": "VSCode-style remote development for DSH: SSH host manager (key/password), helper deploy pipeline with version check, remote file explorer + editor + terminal in dsh-better-sidebar.",
4
- "version": "0.21.0",
4
+ "version": "0.22.0",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
7
7
  "dsh",
@@ -40,6 +40,7 @@ import type {
40
40
  import type { RemotePool } from '../pool.ts'
41
41
  import type { RemoteWorlds, WorldRoute } from '../p2/worlds.ts'
42
42
  import {
43
+ excludeDirNames,
43
44
  parseReads,
44
45
  parseStatusZ,
45
46
  parseUntrackedZ,
@@ -47,12 +48,13 @@ import {
47
48
  readWorktreeCommand,
48
49
  reposBelowCommand,
49
50
  trackedStatusCommand,
51
+ UNTRACKED_EXCLUDED_DIRECTORIES,
50
52
  untrackedCommand,
51
53
  type ChangeStatus,
52
54
  type ReadResult,
53
55
  type StatusEntry,
54
56
  } from './status.ts'
55
- import { diffText, hunkPatch } from './text-diff.ts'
57
+ import { diffText, filePatch, hunkPatch } from './text-diff.ts'
56
58
 
57
59
  /** The two facts a turn boundary needs from a Session, kept cordis-free. */
58
60
  export interface LedgerTarget {
@@ -78,6 +80,12 @@ export interface SessionChangesDeps {
78
80
  untrackedBudgetMs?: number
79
81
  /** How often the untracked scan may run again (default five seconds). */
80
82
  untrackedRefreshMs?: number
83
+ /**
84
+ * Directory names the untracked scan leaves out (build output, dependency
85
+ * caches). Defaults to {@link UNTRACKED_EXCLUDED_DIRECTORIES}; an explicit
86
+ * empty array turns the exclusion off.
87
+ */
88
+ excludeDirs?: readonly string[]
81
89
  /**
82
90
  * Override the per-exec budget outright.
83
91
  *
@@ -111,18 +119,17 @@ interface FileRecord {
111
119
  binary: boolean
112
120
  truncated: boolean
113
121
  /**
114
- * Whether {@link SessionChanges.diff} may hand out a real reverse patch.
122
+ * Which side the `before` bytes came from.
115
123
  *
116
- * A record with no old side is a whole-file creation, and the only reverse of
117
- * its patch is deleting the file. That is recoverable when git holds the
118
- * content (a tracked addition — the index still has it) and unrecoverable when
119
- * it does not: an untracked file exists only in the worktree, so a revert
120
- * would destroy its single copy. A missing old side (a failed read) is not
121
- * evidence either, and a creation patch built from missing evidence is a
122
- * guess. Both cases are still served for display; only the patch is withheld,
123
- * which makes the client's undo path fail closed instead of deleting.
124
+ * `baseline` is the content a file already carried when the session started
125
+ * (pre-existing dirt), `head` is git's committed blob. The distinction is
126
+ * load-bearing for big files: a HEAD read can be taken again at a larger cap
127
+ * when the user asks for one file, while the baseline snapshot cannot be
128
+ * retaken — it described the worktree at session start, which has moved on.
129
+ * Re-reading `HEAD` for a baseline-backed record would silently build a
130
+ * revert that discards the user's own pre-session edits.
124
131
  */
125
- undoable: boolean
132
+ beforeFrom: 'baseline' | 'head' | 'none'
126
133
  }
127
134
 
128
135
  /** Grace added to an exec budget before the watchdog gives up on it. */
@@ -130,6 +137,19 @@ const WATCHDOG_GRACE_MS = 5_000
130
137
  /** Sentinel for "the host call never came back". */
131
138
  const WATCHDOG_FIRED = 'watchdog-fired' as const
132
139
 
140
+ /**
141
+ * Per-file budget for the ONE read a click asks for (`diff`).
142
+ *
143
+ * A scan compares hundreds of paths and stays at 256 KiB; a single file the user
144
+ * asked to review is a different trade — 2 MiB is enough for the large sources
145
+ * a monorepo carries while keeping the base64 reply (≈2.7 MB) inside what one
146
+ * exec comfortably returns.
147
+ */
148
+ const DIFF_MAX_FILE_BYTES = 2 * 1024 * 1024
149
+
150
+ /** The single-file read budget, as `readPaths` wants it. */
151
+ const DIFF_LIMITS = { perFile: DIFF_MAX_FILE_BYTES, total: DIFF_MAX_FILE_BYTES } as const
152
+
133
153
  /** One session's bookkeeping. */
134
154
  interface Ledger {
135
155
  sessionId: string
@@ -277,6 +297,10 @@ export class SessionChanges {
277
297
  ?? (ledger.untrackedFailure === undefined
278
298
  ? undefined
279
299
  : `new-file scan unavailable: ${ledger.untrackedFailure} (use the refresh button to retry)`)
300
+ // Which paths the scan was told to skip. Said out loud (not silently
301
+ // filtered) so a file the user expected to see is never "missing" for an
302
+ // unknown reason; the SCM panel is the surface that shows everything.
303
+ const excludedDirs = this.excludedDirs()
280
304
  return {
281
305
  alias: ledger.alias,
282
306
  root: ledger.root,
@@ -285,6 +309,7 @@ export class SessionChanges {
285
309
  added: ledger.added,
286
310
  deleted: ledger.deleted,
287
311
  at: ledger.at,
312
+ ...(excludedDirs.length === 0 ? {} : { excludedDirs }),
288
313
  /*
289
314
  * What "pending" is allowed to mean to the panel.
290
315
  *
@@ -314,6 +339,14 @@ export class SessionChanges {
314
339
  * change the file between scans, and replaying a cached copy against a fresh
315
340
  * buffer is exactly how the painted lines end up at the wrong places.
316
341
  *
342
+ * This is the ONE read a user asks for by clicking a row, so it is allowed a
343
+ * larger per-file budget than a scan (`DIFF_MAX_FILE_BYTES`): a file the list
344
+ * had to withhold as "too large" can still be reviewed and reverted here,
345
+ * while a scan stays cheap. A withheld HEAD side is retaken at that budget
346
+ * (git has the bytes); a withheld BASELINE side is not — that snapshot
347
+ * described the session's own starting point and cannot be reconstructed, so
348
+ * the file stays display-only rather than guessing a wrong reverse.
349
+ *
317
350
  * @param sessionId - live session owning the ledger.
318
351
  * @param path - the file's remote absolute path (as listed in the summary).
319
352
  * @returns hunks for decorations, or null when the session/file is unknown.
@@ -329,7 +362,7 @@ export class SessionChanges {
329
362
  let afterText = record.after
330
363
  let binary = record.binary
331
364
  let truncated = record.truncated
332
- const fresh = await this.readPaths(ledger, [record.display], 'worktree')
365
+ const fresh = await this.readPaths(ledger, [record.display], 'worktree', DIFF_LIMITS)
333
366
  if (ledger.disposed) return null
334
367
  const side = fresh.get(record.display)
335
368
  if (side !== undefined) {
@@ -341,7 +374,24 @@ export class SessionChanges {
341
374
  if (binary) {
342
375
  return { kind: 'binary', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
343
376
  }
344
- const result = diffText(record.before ?? '', afterText ?? '')
377
+ // A HEAD side the scan had to withhold is worth one more read at the larger
378
+ // budget; the baseline side is not (see the note above).
379
+ let beforeText = record.before
380
+ if (beforeText === null && record.beforeFrom === 'head') {
381
+ const head = await this.readPaths(ledger, [record.display], 'head', DIFF_LIMITS)
382
+ if (ledger.disposed) return null
383
+ beforeText = head.get(record.display)?.text ?? null
384
+ }
385
+ const result = diffText(beforeText ?? '', afterText ?? '')
386
+ /**
387
+ * The reverse patch exists only when the comparison is complete and has an
388
+ * old side. A whole-file creation has no old side: its reverse is "delete the
389
+ * file", which a patch cannot express (the client uses
390
+ * `RemoteChangedFile.revert` for that case instead). Withheld bytes are not
391
+ * evidence either, so a truncated after side gets no patch — the client's
392
+ * undo path then refuses (`changes.undoMissing`) instead of guessing.
393
+ */
394
+ const reverse = beforeText !== null && !truncated ? filePatch(record.display, result.hunks) : ''
345
395
  const hunks: UnifiedHunk[] = result.hunks.map(hunk => ({
346
396
  oldStart: hunk.oldStart,
347
397
  oldCount: hunk.oldLines,
@@ -353,9 +403,8 @@ export class SessionChanges {
353
403
  // change", so it must be a real patch, not a display artifact. Empty
354
404
  // means "display only": the client's undo path refuses an empty patch
355
405
  // (`changes.undoMissing`), which is the fail-closed answer for a record
356
- // whose reverse would delete a file git has no copy of (see
357
- // `FileRecord.undoable`).
358
- patch: record.undoable ? hunkPatch(record.display, hunk) : '',
406
+ // whose reverse would delete a file git has no copy of.
407
+ patch: reverse === '' ? '' : hunkPatch(record.display, hunk),
359
408
  }))
360
409
  if (hunks.length === 0) {
361
410
  return { kind: 'missing', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
@@ -365,6 +414,7 @@ export class SessionChanges {
365
414
  path,
366
415
  display: record.display,
367
416
  hunks,
417
+ ...(reverse === '' ? {} : { patch: reverse }),
368
418
  ...(status === undefined ? {} : { status }),
369
419
  ...(truncated ? { truncated: true as const } : {}),
370
420
  }
@@ -692,7 +742,9 @@ export class SessionChanges {
692
742
  let added = 0
693
743
  let deleted = 0
694
744
  for (const entry of listed) {
695
- const beforeSide = baseline.get(entry.path) ?? head.get(entry.path)
745
+ const fromBaseline = baseline.get(entry.path)
746
+ const fromHead = head.get(entry.path)
747
+ const beforeSide = fromBaseline ?? fromHead
696
748
  const afterSide = after.get(entry.path)
697
749
  const before = beforeSide?.text ?? null
698
750
  const afterText = afterSide?.text ?? null
@@ -711,14 +763,15 @@ export class SessionChanges {
711
763
  if ((binary || fileTruncated) && sameStat(beforeSide, afterSide)) continue
712
764
  const oversized = fileTruncated && !binary
713
765
  // No old side = whole-file creation, and the only reverse of its patch is
714
- // deleting the file. git holds the content only for a TRACKED addition (the
715
- // index has it); an untracked one exists nowhere else, and a "before side"
716
- // that a failed read could not see is not evidence either. A reverse patch
717
- // cannot express "un-add" anyway, so no creation is offered one — the hunk
718
- // is still served for display (the client's undo path refuses an empty
719
- // patch: `changes.undoMissing`).
766
+ // deleting the file. That is recoverable when git holds the content — a
767
+ // tracked addition, where the index still has the bytes — and not when it
768
+ // does not: an untracked file exists only in the worktree, so "undo" would
769
+ // destroy its single copy. The summary therefore tells the client which
770
+ // action (if any) it may offer, instead of letting the browser guess.
720
771
  const creation = before === null
721
- const undoable = !binary && !oversized && beforeSide !== undefined && !creation
772
+ const revert: 'patch' | 'delete' | undefined = !binary && !oversized && beforeSide !== undefined && !creation
773
+ ? 'patch'
774
+ : (entry.status === 'A' ? 'delete' : undefined)
722
775
  const diff = binary || oversized ? { added: 0, deleted: 0 } : diffText(before ?? '', afterText ?? '')
723
776
  const status = panelStatus(entry.status)
724
777
  const absolute = posixJoin(ledger.root, entry.path)
@@ -730,7 +783,7 @@ export class SessionChanges {
730
783
  after: afterText,
731
784
  binary,
732
785
  truncated: fileTruncated,
733
- undoable,
786
+ beforeFrom: fromBaseline !== undefined ? 'baseline' : fromHead !== undefined ? 'head' : 'none',
734
787
  })
735
788
  added += diff.added
736
789
  deleted += diff.deleted
@@ -742,6 +795,7 @@ export class SessionChanges {
742
795
  ...(binary ? { binary: true as const } : {}),
743
796
  ...(oversized ? { oversized: true as const } : {}),
744
797
  ...(status === undefined ? {} : { status }),
798
+ ...(revert === undefined ? {} : { revert }),
745
799
  })
746
800
  }
747
801
  files.sort((left, right) => left.display.localeCompare(right.display))
@@ -884,7 +938,7 @@ export class SessionChanges {
884
938
  ledger.untrackedAt = Date.now()
885
939
  const job = (async () => {
886
940
  const started = Date.now()
887
- const scan = await this.run(ledger.alias, untrackedCommand(root), this.untrackedBudget())
941
+ const scan = await this.run(ledger.alias, untrackedCommand(root, this.excludedDirs()), this.untrackedBudget())
888
942
  ledger.untrackedMs = Date.now() - started
889
943
  if (ledger.disposed) return
890
944
  if (ledger.root !== root) return
@@ -993,10 +1047,11 @@ export class SessionChanges {
993
1047
  ledger: Ledger,
994
1048
  paths: readonly string[],
995
1049
  side: 'worktree' | 'head',
1050
+ limits?: { perFile: number; total: number },
996
1051
  ): Promise<Map<string, ReadResult>> {
997
1052
  if (paths.length === 0) return new Map()
998
- const perFile = this.deps.maxFileBytes ?? 256 * 1024
999
- const total = this.deps.maxTotalBytes ?? 8 * 1024 * 1024
1053
+ const perFile = limits?.perFile ?? this.deps.maxFileBytes ?? 256 * 1024
1054
+ const total = limits?.total ?? this.deps.maxTotalBytes ?? 8 * 1024 * 1024
1000
1055
  const command = side === 'worktree'
1001
1056
  ? readWorktreeCommand(ledger.root, paths, perFile, total)
1002
1057
  : readHeadCommand(ledger.root, paths, perFile, total)
@@ -1065,6 +1120,16 @@ export class SessionChanges {
1065
1120
  return this.deps.untrackedBudgetMs ?? this.budget(this.deps.timeouts().gitMs, 10_000, 180_000)
1066
1121
  }
1067
1122
 
1123
+ /**
1124
+ * The exclusions this ledger scans with, normalized once per call.
1125
+ *
1126
+ * `??` and not `||`: an explicit empty array is a caller saying "count
1127
+ * everything", which must stay distinguishable from "not configured".
1128
+ */
1129
+ private excludedDirs(): string[] {
1130
+ return excludeDirNames(this.deps.excludeDirs ?? UNTRACKED_EXCLUDED_DIRECTORIES)
1131
+ }
1132
+
1068
1133
  private budget(configured: number, floor: number, ceiling: number): number {
1069
1134
  const value = Number.isFinite(configured) && configured > 0 ? configured : 30_000
1070
1135
  return Math.max(floor, Math.min(value, ceiling))
@@ -170,14 +170,81 @@ export function trackedStatusCommand(root: string): string {
170
170
  return [cdLine(root), 'git --no-pager status --porcelain -z -uno -- .'].join('\n')
171
171
  }
172
172
 
173
+ /**
174
+ * Directory names the ledger does not count as session changes.
175
+ *
176
+ * Build output and dependency caches are the two things a build leaves behind,
177
+ * and neither is this session's work. `--exclude-standard` only covers what the
178
+ * repository's own ignore rules name, so a checkout whose build directory is NOT
179
+ * ignored pays twice: thousands of paths fill the 500-row list (sorted, and
180
+ * `build/`/`out/` sort BEFORE `src/`, so the real changes get truncated away) and
181
+ * every listed path costs a read out of the 8 MiB transfer budget.
182
+ *
183
+ * The names mirror the three lists the plugin already prunes by elsewhere
184
+ * (`client/quickopen-model.ts` `EXCLUDED_DIRECTORIES`, `p2/file-refs.ts`
185
+ * `REMOTE_FILE_SEARCH_EXCLUDED_DIRECTORIES`, `search-ops.ts` `PRUNE_DIRS`). One
186
+ * vocabulary, four consumers: fold them into a shared module when one of those
187
+ * surfaces is next touched, instead of adding a fifth spelling here.
188
+ */
189
+ export const UNTRACKED_EXCLUDED_DIRECTORIES: readonly string[] = [
190
+ '.git', 'node_modules', 'dist', 'build', 'out', 'coverage', 'target',
191
+ '.next', '.nuxt', '.turbo', '.venv', '__pycache__', '.pytest_cache',
192
+ '.mypy_cache', '.gradle',
193
+ ]
194
+
195
+ /** Ceiling on the pathspecs one command carries (a cap, not a policy). */
196
+ const MAX_EXCLUDE_DIRS = 32
197
+
198
+ /**
199
+ * Keep only directory names a pathspec may name safely.
200
+ *
201
+ * A value that is absolute, carries a separator, walks up or looks like a flag
202
+ * is DROPPED rather than rejected: the list is configuration, and one bad entry
203
+ * must not stop the scan — the scan's job is to say what changed, not to police
204
+ * a setting. Dropping is also the conservative direction: a name that is not
205
+ * excluded is merely visible, while a malformed pathspec would hide paths the
206
+ * user never asked to hide (or turn `--exclude` into another flag).
207
+ *
208
+ * @param dirs - candidate names (undefined = none).
209
+ * @returns the usable names, deduplicated, in the given order.
210
+ */
211
+ export function excludeDirNames(dirs: readonly string[] | undefined): string[] {
212
+ const kept: string[] = []
213
+ for (const raw of dirs ?? []) {
214
+ const name = raw.trim()
215
+ if (name === '' || name === '.' || name === '..') continue
216
+ if (name.includes('/') || name.includes('\\') || name.includes('\0')) continue
217
+ // A pathspec is a PATTERN: `a*b` would exclude far more than the name says,
218
+ // and the panel would report that pattern as if it were a directory.
219
+ if (/[*?[\]]/.test(name)) continue
220
+ // A leading `-` would reach git as a flag, not a pathspec.
221
+ if (name.startsWith('-')) continue
222
+ if (kept.includes(name)) continue
223
+ if (kept.length >= MAX_EXCLUDE_DIRS) break
224
+ kept.push(name)
225
+ }
226
+ return kept
227
+ }
228
+
173
229
  /**
174
230
  * New files git is not tracking yet (the ones a session usually creates).
175
231
  *
232
+ * The exclusions are pushed down as pathspecs (`:(exclude)out`) rather than
233
+ * filtered after the fact, so those paths never cross the wire and never enter
234
+ * the 500-row cap. Measured on a tree with 3000 build outputs + 300 sources:
235
+ * 3300 records / 61.5 KB unfiltered versus 300 records / 6.8 KB with two
236
+ * exclusions — the walk itself costs the same either way (git still descends
237
+ * those directories), so the win is wire bytes, parse time and the read budget,
238
+ * not scan latency.
239
+ *
176
240
  * @param root - remote absolute POSIX directory (the session cwd).
241
+ * @param excludeDirs - directory names to leave out (see {@link excludeDirNames}).
177
242
  * @returns a `sh` script printing NUL-separated paths.
178
243
  */
179
- export function untrackedCommand(root: string): string {
180
- return [cdLine(root), 'git ls-files --others --exclude-standard -z -- .'].join('\n')
244
+ export function untrackedCommand(root: string, excludeDirs: readonly string[] = []): string {
245
+ const excludes = excludeDirNames(excludeDirs).map(name => shq(`:(exclude)${name}`))
246
+ const pathspec = ['--', '.', ...excludes].join(' ')
247
+ return [cdLine(root), `git ls-files --others --exclude-standard -z ${pathspec}`].join('\n')
181
248
  }
182
249
 
183
250
  /**
@@ -375,3 +375,45 @@ function lastLineOfSide(lines: string[], tag: '-' | '+'): number {
375
375
  }
376
376
  return -1
377
377
  }
378
+
379
+ /**
380
+ * Serialize a WHOLE file comparison as ONE patch (one header, every hunk).
381
+ *
382
+ * "Revert everything this session did to this file" is `git apply -R` of the
383
+ * file's complete diff, and that is a single write instead of one write per
384
+ * hunk. Concatenating `hunkPatch` output would also apply (git tolerates the
385
+ * repeated headers and re-anchors each block by offset), but it says the same
386
+ * file begins twice and depends on offset guessing — a real unified diff names
387
+ * the file once and lets git place every hunk against one picture.
388
+ *
389
+ * Verified against git 2.x: the result reverse-applies to a file whose content
390
+ * is `hunks`' new side, and leaves it byte-identical to the old side.
391
+ *
392
+ * @param displayPath - repo-relative path, as the panel shows it.
393
+ * @param hunks - every hunk of the comparison, in ascending order.
394
+ * @returns the patch, or '' when there is nothing to write (no hunks).
395
+ */
396
+ export function filePatch(displayPath: string, hunks: readonly TextHunk[]): string {
397
+ if (hunks.length === 0) return ''
398
+ const out: string[] = [`--- a/${displayPath}`, `+++ b/${displayPath}`]
399
+ for (const hunk of hunks) {
400
+ out.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`)
401
+ // The marker follows the last line of the side that lacks a final newline.
402
+ // A per-file comparison has at most one such line per side and it is inside
403
+ // the last hunk, so the same rule as `hunkPatch` applies hunk by hunk.
404
+ const markers = new Set<number>()
405
+ if (hunk.oldNoEol === true) {
406
+ const at = lastLineOfSide(hunk.lines, '-')
407
+ if (at >= 0) markers.add(at)
408
+ }
409
+ if (hunk.newNoEol === true) {
410
+ const at = lastLineOfSide(hunk.lines, '+')
411
+ if (at >= 0) markers.add(at)
412
+ }
413
+ for (let index = 0; index < hunk.lines.length; index += 1) {
414
+ out.push(hunk.lines[index] ?? '')
415
+ if (markers.has(index)) out.push('\')
416
+ }
417
+ }
418
+ return `${out.join('\n')}\n`
419
+ }
@@ -480,6 +480,7 @@ export function TerminalView(props: {
480
480
  rows: 24,
481
481
  })}
482
482
  visible={props.visible && tab.id === active?.id}
483
+ t={t}
483
484
  {...(tab.initialCommand === undefined ? {} : { initialInput: tab.initialCommand })}
484
485
  onReady={(id) => patchTab(tab.id, { session: id, connected: true, note: undefined })}
485
486
  onExit={(code, message) => {