dsh-remote-vs 0.24.0 → 0.26.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 (125) hide show
  1. package/README.en.md +50 -16
  2. package/README.md +40 -15
  3. package/THIRD-PARTY-NOTICES.md +188 -0
  4. package/lib/client.js +6512 -77887
  5. package/lib/index.js +1461 -1024
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +25 -0
  8. package/lib/types/client/EditorPane.d.ts +16 -5
  9. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  10. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  11. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  12. package/lib/types/client/RemoteRoot.d.ts +5 -5
  13. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  14. package/lib/types/client/TerminalView.d.ts +1 -1
  15. package/lib/types/client/XTerm.d.ts +33 -0
  16. package/lib/types/client/api.d.ts +37 -2
  17. package/lib/types/client/changes/review-state.d.ts +19 -0
  18. package/lib/types/client/connection.d.ts +16 -0
  19. package/lib/types/client/editor-capability.d.ts +27 -0
  20. package/lib/types/client/i18n.d.ts +1 -1
  21. package/lib/types/client/request-gate.d.ts +110 -0
  22. package/lib/types/client/scm/DiffView.d.ts +45 -7
  23. package/lib/types/client/scm/actions.d.ts +31 -3
  24. package/lib/types/client/store.d.ts +112 -4
  25. package/lib/types/client/terminal-input.d.ts +23 -0
  26. package/lib/types/client/terminal-snippets.d.ts +86 -0
  27. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  28. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  29. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  30. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  31. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  32. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  33. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  34. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  35. package/lib/types/client/vsc/kit.d.ts +13 -0
  36. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  37. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  38. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  39. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  40. package/lib/types/client/vsc/terminal-theme.d.ts +48 -0
  41. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  42. package/lib/types/forward.d.ts +12 -0
  43. package/lib/types/fs-ops.d.ts +42 -0
  44. package/lib/types/http.d.ts +2 -0
  45. package/lib/types/keygen.d.ts +9 -0
  46. package/lib/types/monitor.d.ts +8 -0
  47. package/lib/types/notices.d.ts +16 -1
  48. package/lib/types/p2/helper-rpc.d.ts +45 -0
  49. package/lib/types/pool.d.ts +25 -0
  50. package/lib/types/routes.d.ts +2 -0
  51. package/lib/types/store.d.ts +7 -0
  52. package/lib/types/terminal.d.ts +33 -1
  53. package/lib/types/view-settings.d.ts +5 -0
  54. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  55. package/package.json +2 -1
  56. package/src/client/CodeEditor.tsx +205 -10
  57. package/src/client/DirectoryFlow.tsx +16 -0
  58. package/src/client/DoctorPanel.tsx +70 -7
  59. package/src/client/EditorPane.tsx +545 -118
  60. package/src/client/FloatingPlaceholder.tsx +34 -5
  61. package/src/client/HostsView.tsx +12 -3
  62. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  63. package/src/client/RemoteEditorView.tsx +14 -11
  64. package/src/client/RemoteExplorer.tsx +929 -40
  65. package/src/client/RemoteRoot.tsx +167 -147
  66. package/src/client/SearchView.tsx +8 -0
  67. package/src/client/TerminalSnippets.tsx +432 -0
  68. package/src/client/TerminalView.tsx +50 -1
  69. package/src/client/XTerm.tsx +228 -58
  70. package/src/client/api.ts +106 -13
  71. package/src/client/auto-open-remote.ts +11 -9
  72. package/src/client/changes/ChangesDock.tsx +188 -6
  73. package/src/client/changes/changes.css +10 -3
  74. package/src/client/changes/review-state.ts +34 -0
  75. package/src/client/connection.ts +29 -0
  76. package/src/client/downloads.ts +49 -4
  77. package/src/client/editor-capability.ts +42 -0
  78. package/src/client/i18n.ts +228 -12
  79. package/src/client/index.tsx +22 -6
  80. package/src/client/request-gate.ts +221 -0
  81. package/src/client/scm/CommitPane.tsx +20 -2
  82. package/src/client/scm/DiffView.tsx +343 -117
  83. package/src/client/scm/HistoryPanel.tsx +23 -2
  84. package/src/client/scm/RepoPicker.tsx +1 -1
  85. package/src/client/scm/ScmPanel.tsx +391 -87
  86. package/src/client/scm/actions.ts +95 -12
  87. package/src/client/store.tsx +537 -22
  88. package/src/client/terminal-input.ts +44 -0
  89. package/src/client/terminal-snippets.ts +216 -0
  90. package/src/client/ui.tsx +4 -0
  91. package/src/client/vsc/FindWidget.tsx +24 -9
  92. package/src/client/vsc/breadcrumb.tsx +339 -0
  93. package/src/client/vsc/change-marks.ts +93 -44
  94. package/src/client/vsc/editor-caret.ts +30 -0
  95. package/src/client/vsc/editor-keymap.ts +59 -1
  96. package/src/client/vsc/editor-langs.ts +20 -0
  97. package/src/client/vsc/editor-settings.ts +146 -0
  98. package/src/client/vsc/editor-theme.ts +4 -5
  99. package/src/client/vsc/file-icons.tsx +17 -3
  100. package/src/client/vsc/image-preview.tsx +110 -0
  101. package/src/client/vsc/kit.tsx +46 -10
  102. package/src/client/vsc/save-shortcut.ts +47 -1
  103. package/src/client/vsc/terminal-clipboard.ts +19 -0
  104. package/src/client/vsc/terminal-line.ts +101 -0
  105. package/src/client/vsc/terminal-links.ts +166 -0
  106. package/src/client/vsc/terminal-theme.ts +97 -0
  107. package/src/client/vsc/terminal-writer.ts +112 -0
  108. package/src/client/vsc/vsc.css +1078 -181
  109. package/src/forward.ts +47 -9
  110. package/src/fs-ops.ts +124 -4
  111. package/src/git-ops.ts +20 -3
  112. package/src/http.ts +35 -4
  113. package/src/keygen.ts +55 -4
  114. package/src/monitor.ts +13 -0
  115. package/src/notices.ts +23 -1
  116. package/src/p2/helper-rpc.ts +113 -7
  117. package/src/p2/worlds.ts +14 -1
  118. package/src/pool.ts +99 -27
  119. package/src/routes.ts +212 -43
  120. package/src/sftp.ts +51 -14
  121. package/src/store.ts +10 -0
  122. package/src/terminal.ts +225 -24
  123. package/src/view-settings.ts +50 -10
  124. package/lib/types/client/Dialog.d.ts +0 -14
  125. package/src/client/Dialog.tsx +0 -76
package/src/terminal.ts CHANGED
@@ -20,6 +20,48 @@ interface Session {
20
20
  pending: number
21
21
  /** True while the channel is paused because a socket fell behind. */
22
22
  paused: boolean
23
+ /**
24
+ * Output text waiting for the next coalesced frame, and its flush timer.
25
+ *
26
+ * A burst (a log tail, `cat` of a large file) delivers one ssh2 chunk at a
27
+ * time; sending each chunk as its own JSON frame made the host stringify, the
28
+ * socket frame and the browser parse once per chunk. Coalescing into one frame
29
+ * per short window keeps the byte flow identical while cutting that overhead
30
+ * by roughly an order of magnitude for exactly the commands that felt busy.
31
+ */
32
+ outBuffer: string
33
+ outTimer: ReturnType<typeof setTimeout> | undefined
34
+ /**
35
+ * Recent output already flushed to sockets, replayed to a REATTACHING socket.
36
+ *
37
+ * A PTY lives for ten minutes after its last socket, but the screen state
38
+ * (the prompt, the last command's output) lives only in xterm on the client.
39
+ * When a session switch remounts the sidebar, the new XTerm attaches to the
40
+ * still-running shell and used to start BLANK — the shell was at its prompt,
41
+ * but the prompt had been printed before the socket existed. Keeping the tail
42
+ * of the stream lets `attach` hand the newcomer the screen it missed.
43
+ *
44
+ * Bounded: `REPLAY_MAX_CHARS` is enough for a prompt plus a screenful or two;
45
+ * a `cat` of a huge file must not double the host's memory per session.
46
+ */
47
+ replay: string
48
+ /**
49
+ * When the last `out` frame went out.
50
+ *
51
+ * Used to tell an interactive ECHO from a burst: output that starts after a
52
+ * quiet period is handed over immediately (a keystroke should not wait for the
53
+ * coalescing window), while a continuous stream keeps coalescing.
54
+ */
55
+ lastFlushAt: number
56
+ /**
57
+ * Bytes handed to each socket that have not settled yet.
58
+ *
59
+ * `pending` alone cannot be released when a socket closes with frames still in
60
+ * flight: ws never calls their send callbacks, so the missing bytes kept the
61
+ * channel paused for the rest of the session (no echo at all until a reload).
62
+ * Per-socket bookkeeping lets `detach` return exactly those bytes.
63
+ */
64
+ outstanding: Map<WebSocket, number>
23
65
  /** Fires once the last socket has been gone for EMPTY_SOCKET_TTL_MS. */
24
66
  reap: ReturnType<typeof setTimeout> | undefined
25
67
  /**
@@ -55,12 +97,66 @@ const EMPTY_SOCKET_TTL_MS = 10 * 60_000
55
97
  * The retained ceiling is therefore this mark plus ssh2's window (2 MiB) plus
56
98
  * whatever is in flight — bounded, but not exactly 4 MiB.
57
99
  *
100
+ * The mark is RESPONSIVENESS, not just memory: everything already handed to a
101
+ * socket has to be parsed and painted by the browser before a later keystroke's
102
+ * echo can appear, so a large mark means "type during a huge dump and wait
103
+ * seconds". 2 MiB still absorbs a burst comfortably (a keystroke is bytes) while
104
+ * keeping the worst-case echo delay down; ssh2's own 2 MiB window is the part we
105
+ * cannot shrink from here.
106
+ *
58
107
  * The counter is per session, not per socket: one lagging socket pauses the
59
108
  * channel for every socket attached to that shell. That is deliberate — the
60
109
  * alternative is letting the slowest consumer grow the host process.
61
110
  */
62
- const OUT_HIGH_WATER = 4 * 1024 * 1024
63
- const OUT_LOW_WATER = 1 * 1024 * 1024
111
+ const OUT_HIGH_WATER = 2 * 1024 * 1024
112
+ const OUT_LOW_WATER = 512 * 1024
113
+
114
+ /** Default window for coalescing output frames (0 = one frame per chunk). */
115
+ const OUT_COALESCE_MS = 8
116
+ /**
117
+ * Flush immediately past this much buffered text (measured in UTF-16 code
118
+ * units, i.e. `String.length`): a producer faster than the window must not turn
119
+ * into an unbounded string copy (the channel backpressure bounds the bytes
120
+ * handed to the SOCKETS, not this buffer).
121
+ *
122
+ * Code units rather than bytes on purpose: converting to a byte count would
123
+ * copy the whole buffer on every chunk just to compare a threshold. CJK/emoji
124
+ * output therefore flushes at up to ~3x this many bytes, which is still far
125
+ * below the 1 MiB client-frame cap this path never approaches (it is the
126
+ * client→host direction).
127
+ */
128
+ const OUT_COALESCE_CHARS = 64 * 1024
129
+
130
+ /**
131
+ * How long the output must have been quiet for the NEXT chunk to be sent at once.
132
+ *
133
+ * A terminal echoes what the user types. Holding that echo for the coalescing
134
+ * window is invisible at 8 ms — but under load the window itself is a timer in
135
+ * an event loop shared with the agent, and the delay adds up. After a quiet
136
+ * period the chunk is therefore flushed synchronously; only a running stream
137
+ * (where `lastFlushAt` is fresh) is batched.
138
+ */
139
+ const OUT_ECHO_IDLE_MS = 24
140
+
141
+ /**
142
+ * How much recent output a reattaching socket receives (see `Session.replay`).
143
+ *
144
+ * 128 Ki UTF-16 units is a few screens of logs plus the prompt line; the buffer
145
+ * may grow to twice this between trims, so one terminal costs at most ~512 KiB
146
+ * of the host's memory in replay state.
147
+ */
148
+ const REPLAY_MAX_CHARS = 128 * 1024
149
+
150
+ /** Construction options (the terminal gate drives the registry directly). */
151
+ export interface TerminalRegistryOptions {
152
+ /**
153
+ * Output coalescing window in ms; `0` sends every chunk as its own frame.
154
+ *
155
+ * The existing checks use `0` so their assertions stay synchronous; one
156
+ * dedicated check drives a non-zero window to pin the coalescing itself.
157
+ */
158
+ coalesceMs?: number
159
+ }
64
160
 
65
161
  /**
66
162
  * The largest client frame accepted, in bytes.
@@ -85,7 +181,15 @@ const WS_OPEN = 1
85
181
  export class TerminalSessionRegistry {
86
182
  private readonly sessions = new Map<string, Session>()
87
183
 
88
- constructor(private readonly pool: RemotePool) {}
184
+ constructor(
185
+ private readonly pool: RemotePool,
186
+ private readonly options: TerminalRegistryOptions = {},
187
+ ) {}
188
+
189
+ /** The window this registry coalesces within (`0` = every chunk is a frame). */
190
+ private get coalesceMs(): number {
191
+ return this.options.coalesceMs ?? OUT_COALESCE_MS
192
+ }
89
193
 
90
194
  /** Open a shell and attach the first socket. */
91
195
  async open(ws: WebSocket, alias: string, cols: number, rows: number): Promise<string> {
@@ -111,6 +215,11 @@ export class TerminalSessionRegistry {
111
215
  sockets: new Set(),
112
216
  pending: 0,
113
217
  paused: false,
218
+ outBuffer: '',
219
+ outTimer: undefined,
220
+ replay: '',
221
+ lastFlushAt: 0,
222
+ outstanding: new Map(),
114
223
  reap: undefined,
115
224
  outDecoder: new StringDecoder('utf8'),
116
225
  errDecoder: new StringDecoder('utf8'),
@@ -118,11 +227,11 @@ export class TerminalSessionRegistry {
118
227
  this.sessions.set(id, session)
119
228
  channel.on('data', (chunk: Buffer) => {
120
229
  const text = session.outDecoder.write(chunk)
121
- if (text !== '') this.broadcast(session, { t: 'out', d: text })
230
+ if (text !== '') this.queueOut(session, text)
122
231
  })
123
232
  channel.stderr.on('data', (chunk: Buffer) => {
124
233
  const text = session.errDecoder.write(chunk)
125
- if (text !== '') this.broadcast(session, { t: 'out', d: text })
234
+ if (text !== '') this.queueOut(session, text)
126
235
  })
127
236
  channel.on('close', (code: number | null) => {
128
237
  session.alive = false
@@ -130,8 +239,11 @@ export class TerminalSessionRegistry {
130
239
  // Flush the decoder-held tail BEFORE the exit frame: a command's last
131
240
  // character may still be sitting in the decoder when the channel closes.
132
241
  for (const tail of [session.outDecoder.end(), session.errDecoder.end()]) {
133
- if (tail !== '') this.broadcast(session, { t: 'out', d: tail })
242
+ if (tail !== '') this.queueOut(session, tail)
134
243
  }
244
+ // …and flush anything the coalescing window is still holding, so the exit
245
+ // frame can never overtake the last line the user was meant to see.
246
+ this.flushOut(session)
135
247
  this.broadcast(session, { t: 'exit', code })
136
248
  for (const socket of session.sockets) {
137
249
  try {
@@ -164,6 +276,16 @@ export class TerminalSessionRegistry {
164
276
  const session = this.sessions.get(id)
165
277
  if (session === undefined || !session.alive) return false
166
278
  this.hookSocket(session, ws)
279
+ // Hand the newcomer the output this session produced before it attached
280
+ // (the shell's prompt, the previous command's screen). It goes through the
281
+ // same per-socket accounting as live output, so a huge replay cannot slip
282
+ // past the backpressure ceiling.
283
+ if (session.replay !== '') {
284
+ this.sendOutTo(session, ws, JSON.stringify({ t: 'out', d: session.replay }))
285
+ }
286
+ // Deliver anything the coalescing window still holds to the newcomer too,
287
+ // before its `ready`: it is output the shell already produced.
288
+ this.flushOut(session)
167
289
  this.send(ws, { t: 'ready', id })
168
290
  return true
169
291
  }
@@ -174,6 +296,7 @@ export class TerminalSessionRegistry {
174
296
  if (session === undefined) return false
175
297
  this.sessions.delete(id)
176
298
  this.cancelReap(session)
299
+ this.flushOut(session)
177
300
  try {
178
301
  session.channel.close()
179
302
  } catch {
@@ -187,6 +310,9 @@ export class TerminalSessionRegistry {
187
310
  }
188
311
  }
189
312
  session.sockets.clear()
313
+ // The sockets are gone; their unsettled frames will never settle.
314
+ session.outstanding.clear()
315
+ session.pending = 0
190
316
  return true
191
317
  }
192
318
 
@@ -237,12 +363,25 @@ export class TerminalSessionRegistry {
237
363
  }
238
364
  })
239
365
  const detach = (): void => {
366
+ // Whatever the window is holding was produced while this socket was still
367
+ // attached: hand it over before the socket leaves the set.
368
+ this.flushOut(session)
369
+ // Release the frames this socket never settled. `ws` does not call their
370
+ // send callbacks after a close, and the leaked `pending` bytes used to keep
371
+ // the channel paused for the rest of the session.
372
+ const unsettled = session.outstanding.get(ws)
373
+ if (unsettled !== undefined) {
374
+ session.outstanding.delete(ws)
375
+ session.pending = Math.max(0, session.pending - unsettled)
376
+ if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false)
377
+ }
240
378
  session.sockets.delete(ws)
241
379
  if (session.sockets.size > 0) return
242
380
  // Nobody is watching any more. Release the brake first — a paused channel
243
381
  // would otherwise stay paused with no socket left to resume it — then
244
382
  // start the clock that ends the session (and with it the remote shell).
245
383
  session.pending = 0
384
+ session.outstanding.clear()
246
385
  this.setPaused(session, false)
247
386
  this.armReap(session)
248
387
  }
@@ -280,6 +419,49 @@ export class TerminalSessionRegistry {
280
419
  session.reap = undefined
281
420
  }
282
421
 
422
+ /**
423
+ * Queue one output chunk and schedule the coalesced frame.
424
+ *
425
+ * `coalesceMs === 0` broadcasts immediately (the checks rely on that
426
+ * synchrony). A chunk that arrives after an idle gap is also sent at once —
427
+ * that is the interactive echo path (a keystroke must not wait for the
428
+ * window) — while a stream that keeps producing coalesces.
429
+ */
430
+ private queueOut(session: Session, text: string): void {
431
+ if (text === '') return
432
+ const idle = Date.now() - session.lastFlushAt >= OUT_ECHO_IDLE_MS
433
+ session.outBuffer += text
434
+ if (session.outBuffer.length >= OUT_COALESCE_CHARS || this.coalesceMs <= 0 || idle) {
435
+ this.flushOut(session)
436
+ return
437
+ }
438
+ if (session.outTimer !== undefined) return
439
+ const timer = setTimeout(() => {
440
+ session.outTimer = undefined
441
+ this.flushOut(session)
442
+ }, this.coalesceMs)
443
+ timer.unref?.()
444
+ session.outTimer = timer
445
+ }
446
+
447
+ /** Send the buffered output as ONE `out` frame (no-op when empty). */
448
+ private flushOut(session: Session): void {
449
+ if (session.outTimer !== undefined) {
450
+ clearTimeout(session.outTimer)
451
+ session.outTimer = undefined
452
+ }
453
+ if (session.outBuffer === '') return
454
+ const text = session.outBuffer
455
+ session.outBuffer = ''
456
+ // Remember what was already delivered: a later reattach replays this.
457
+ session.replay += text
458
+ if (session.replay.length > REPLAY_MAX_CHARS * 2) {
459
+ session.replay = session.replay.slice(-REPLAY_MAX_CHARS)
460
+ }
461
+ session.lastFlushAt = Date.now()
462
+ this.broadcast(session, { t: 'out', d: text })
463
+ }
464
+
283
465
  private setPaused(session: Session, paused: boolean): void {
284
466
  if (session.paused === paused) return
285
467
  session.paused = paused
@@ -301,27 +483,46 @@ export class TerminalSessionRegistry {
301
483
 
302
484
  private broadcast(session: Session, frame: TerminalServerFrame): void {
303
485
  const text = JSON.stringify(frame)
486
+ for (const socket of session.sockets) {
487
+ this.sendOutTo(session, socket, text)
488
+ }
489
+ if (session.pending > OUT_HIGH_WATER) this.setPaused(session, true)
490
+ }
491
+
492
+ /**
493
+ * Send one already-stringified `out` frame to ONE socket with accounting.
494
+ *
495
+ * Shared by `broadcast` and by the replay on `attach`; the byte count must be
496
+ * counted once per socket so the session's brake reflects every socket's
497
+ * backlog (see `Session.pending`).
498
+ */
499
+ private sendOutTo(session: Session, socket: WebSocket, text: string): void {
304
500
  // Bytes, not UTF-16 code units: CJK and emoji output would otherwise be
305
501
  // undercounted by up to 3x and the brake would come on too late.
306
502
  const size = Buffer.byteLength(text, 'utf8')
307
- for (const socket of session.sockets) {
308
- let settled = false
309
- // The send callback fires once the frame is on the wire. It is the only
310
- // public signal for "this socket has caught up", and it avoids relying on
311
- // ws internals (bufferedAmount does not report the socket write queue).
312
- const done = (): void => {
313
- if (settled) return
314
- settled = true
315
- session.pending = Math.max(0, session.pending - size)
316
- if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false)
317
- }
318
- session.pending += size
319
- try {
320
- socket.send(text, done)
321
- } catch {
322
- done()
323
- }
503
+ let settled = false
504
+ // The send callback fires once the frame is on the wire. It is the only
505
+ // public signal for "this socket has caught up", and it avoids relying on
506
+ // ws internals (bufferedAmount does not report the socket write queue).
507
+ const done = (): void => {
508
+ if (settled) return
509
+ settled = true
510
+ // A socket that detached already had its outstanding bytes released
511
+ // (its late callback must not decrement them a second time).
512
+ const left = session.outstanding.get(socket)
513
+ if (left === undefined) return
514
+ const remaining = Math.max(0, left - size)
515
+ if (remaining === 0) session.outstanding.delete(socket)
516
+ else session.outstanding.set(socket, remaining)
517
+ session.pending = Math.max(0, session.pending - size)
518
+ if (session.pending <= OUT_LOW_WATER) this.setPaused(session, false)
519
+ }
520
+ session.pending += size
521
+ session.outstanding.set(socket, (session.outstanding.get(socket) ?? 0) + size)
522
+ try {
523
+ socket.send(text, done)
524
+ } catch {
525
+ done()
324
526
  }
325
- if (session.pending > OUT_HIGH_WATER) this.setPaused(session, true)
326
527
  }
327
528
  }
@@ -18,7 +18,7 @@
18
18
  * keys are ignored — the browser is the only writer, and a stale tab must not be
19
19
  * able to corrupt the file with an extra key).
20
20
  */
21
- import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from 'node:fs'
21
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from 'node:fs'
22
22
  import { dirname } from 'node:path'
23
23
  import {
24
24
  REMOTE_VIEW_SETTINGS_DEFAULTS,
@@ -39,6 +39,26 @@ function defaults(): RemoteViewSettings {
39
39
  return { ...REMOTE_VIEW_SETTINGS_DEFAULTS }
40
40
  }
41
41
 
42
+ /** Identity of the settings file at one point in time; `null` = the file is absent. */
43
+ type FileStamp = { mtimeMs: number; size: number } | null
44
+
45
+ /** Same file identity (both absent counts as same). */
46
+ function sameStamp(left: FileStamp, right: FileStamp): boolean {
47
+ if (left === null || right === null) return left === right
48
+ return left.mtimeMs === right.mtimeMs && left.size === right.size
49
+ }
50
+
51
+ /**
52
+ * Replays one read-modify-write before giving up.
53
+ *
54
+ * Desktop and `dsh web` share `$DSH_HOME/dsh-remote-view.json` by design, and
55
+ * every patch rewrites the WHOLE document: a plain read-merge-write let the last
56
+ * window win and silently dropped the other one's preference. A stamp re-check
57
+ * right before the write turns that into a replay on fresh content; a third
58
+ * failed attempt fails loud instead of losing a setting.
59
+ */
60
+ const PATCH_ATTEMPTS = 3
61
+
42
62
  /** A finite width share, clamped into the allowed band; anything else is a miss. */
43
63
  function readWidthRatio(value: unknown): number | undefined {
44
64
  if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
@@ -95,16 +115,36 @@ export class RemoteViewSettingsStore {
95
115
  * @returns the settings as stored.
96
116
  */
97
117
  patch(patch: Record<string, unknown>): RemoteViewSettings {
98
- const current = this.get()
99
- const next: RemoteViewSettings = {
100
- autoOpenRemoteWorkspace: typeof patch.autoOpenRemoteWorkspace === 'boolean'
101
- ? patch.autoOpenRemoteWorkspace
102
- : current.autoOpenRemoteWorkspace,
103
- remoteWorkspaceWidthRatio: readWidthRatio(patch.remoteWorkspaceWidthRatio)
104
- ?? current.remoteWorkspaceWidthRatio,
118
+ for (let attempt = 0; attempt < PATCH_ATTEMPTS; attempt += 1) {
119
+ // Stamp BEFORE the read: a write landing in between leaves the older stamp
120
+ // behind, so the re-check below catches it and replays on the new content.
121
+ const before = this.stampOf()
122
+ const current = this.get()
123
+ const next: RemoteViewSettings = {
124
+ autoOpenRemoteWorkspace: typeof patch.autoOpenRemoteWorkspace === 'boolean'
125
+ ? patch.autoOpenRemoteWorkspace
126
+ : current.autoOpenRemoteWorkspace,
127
+ remoteWorkspaceWidthRatio: readWidthRatio(patch.remoteWorkspaceWidthRatio)
128
+ ?? current.remoteWorkspaceWidthRatio,
129
+ }
130
+ if (!sameStamp(before, this.stampOf())) continue
131
+ this.save(next)
132
+ return next
133
+ }
134
+ throw new Error(`${this.file}: another process keeps editing the view settings; retry the operation`)
135
+ }
136
+
137
+ /**
138
+ * File identity right now; `null` when the file is absent (or cannot be
139
+ * statted — `get()` fails loud on that case anyway).
140
+ */
141
+ private stampOf(): FileStamp {
142
+ try {
143
+ const stat = statSync(this.file, { throwIfNoEntry: false })
144
+ return stat === undefined ? null : { mtimeMs: stat.mtimeMs, size: stat.size }
145
+ } catch {
146
+ return null
105
147
  }
106
- this.save(next)
107
- return next
108
148
  }
109
149
 
110
150
  /** Write one document atomically: a crash never leaves a half-written file. */
@@ -1,14 +0,0 @@
1
- /**
2
- * Small inline input dialog (new file / folder / rename). Rendered as a
3
- * fixed overlay card; Enter confirms, Escape cancels.
4
- */
5
- import { type ReactNode } from 'react';
6
- export declare function InputDialog(props: {
7
- title: string;
8
- label: string;
9
- initial?: string;
10
- placeholder?: string;
11
- okText?: string;
12
- onOk: (value: string) => void;
13
- onCancel: () => void;
14
- }): ReactNode;
@@ -1,76 +0,0 @@
1
- /**
2
- * Small inline input dialog (new file / folder / rename). Rendered as a
3
- * fixed overlay card; Enter confirms, Escape cancels.
4
- */
5
- import { useEffect, useRef, useState, type ReactNode } from 'react'
6
- import { Btn, inputStyle } from './ui.tsx'
7
-
8
- export function InputDialog(props: {
9
- title: string
10
- label: string
11
- initial?: string
12
- placeholder?: string
13
- okText?: string
14
- onOk: (value: string) => void
15
- onCancel: () => void
16
- }): ReactNode {
17
- const [value, setValue] = useState(props.initial ?? '')
18
- const inputRef = useRef<HTMLInputElement>(null)
19
-
20
- useEffect(() => {
21
- inputRef.current?.focus()
22
- inputRef.current?.select()
23
- }, [])
24
-
25
- const commit = (): void => {
26
- const trimmed = value.trim()
27
- if (trimmed === '') return
28
- props.onOk(trimmed)
29
- }
30
-
31
- return (
32
- <div
33
- style={{
34
- position: 'fixed',
35
- inset: 0,
36
- zIndex: 1000,
37
- background: 'rgba(0,0,0,.45)',
38
- display: 'flex',
39
- alignItems: 'center',
40
- justifyContent: 'center',
41
- }}
42
- onClick={props.onCancel}
43
- >
44
- <div
45
- style={{
46
- minWidth: 320,
47
- maxWidth: '90vw',
48
- background: 'Canvas',
49
- color: 'CanvasText',
50
- border: '1px solid rgba(127,127,127,.4)',
51
- borderRadius: 8,
52
- padding: 14,
53
- }}
54
- onClick={(e) => e.stopPropagation()}
55
- onKeyDown={(e) => {
56
- if (e.key === 'Enter') commit()
57
- else if (e.key === 'Escape') props.onCancel()
58
- }}
59
- >
60
- <div style={{ fontWeight: 600, marginBottom: 8 }}>{props.title}</div>
61
- <div style={{ fontSize: 12, opacity: 0.75, marginBottom: 4 }}>{props.label}</div>
62
- <input
63
- ref={inputRef}
64
- value={value}
65
- placeholder={props.placeholder}
66
- onChange={(e) => setValue(e.target.value)}
67
- style={inputStyle}
68
- />
69
- <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
70
- <Btn onClick={props.onCancel}>取消 / Cancel</Btn>
71
- <Btn kind="primary" onClick={commit}>{props.okText ?? '确定 / OK'}</Btn>
72
- </div>
73
- </div>
74
- </div>
75
- )
76
- }