dsh-ris-ide 1.8.1 → 1.8.2

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 (47) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +311 -72
  3. package/lib/debug/vendor/README.md +14 -0
  4. package/lib/debug/vendor/jdwp/client.js +9 -4
  5. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  6. package/lib/index.js +794 -48
  7. package/lib/redirector.js +42 -2
  8. package/lib/risd/lifecycle.js +9 -3
  9. package/lib/risd/server.js +308 -13
  10. package/lib/risd/ui.js +149 -112
  11. package/lib/risd-client.js +4 -1
  12. package/lib/startup.js +27 -7
  13. package/package.json +2 -2
  14. package/test/client-viewer.test.mjs +188 -95
  15. package/test/clipboard.test.mjs +259 -0
  16. package/test/debug-engine.test.mjs +3 -1
  17. package/test/dsh-origin.test.mjs +4 -11
  18. package/test/dsh-window-refresh.test.mjs +166 -1
  19. package/test/harness.test.mjs +1 -1
  20. package/test/helpers/cmd.mjs +29 -0
  21. package/test/helpers/tgz.mjs +71 -0
  22. package/test/host-search.test.mjs +18 -11
  23. package/test/host-tail.test.mjs +119 -24
  24. package/test/proxy-route.test.mjs +61 -0
  25. package/test/proxy-window.test.mjs +5 -0
  26. package/test/proxy.test.mjs +13 -1
  27. package/test/proxybridge-bundle.test.mjs +1 -59
  28. package/test/redirector-bundle.test.mjs +21 -67
  29. package/test/redirector.test.mjs +41 -4
  30. package/test/risd-api.test.mjs +81 -28
  31. package/test/risd-bridge-degrade.test.mjs +3 -29
  32. package/test/risd-engine.test.mjs +13 -50
  33. package/test/risd-entry.test.mjs +0 -37
  34. package/test/risd-follow-start.test.mjs +101 -0
  35. package/test/risd-git.test.mjs +7 -5
  36. package/test/risd-handoff.test.mjs +6 -50
  37. package/test/risd-helpers.mjs +150 -3
  38. package/test/risd-host-p2.test.mjs +2 -30
  39. package/test/risd-lifecycle.test.mjs +25 -0
  40. package/test/risd-programs.test.mjs +4 -34
  41. package/test/risd-review-p2.test.mjs +0 -13
  42. package/test/risd-shutdown.test.mjs +5 -38
  43. package/test/risd-teardown.test.mjs +8 -27
  44. package/test/risd-ui.test.mjs +169 -13
  45. package/test/risd-write.test.mjs +2 -1
  46. package/test/startup-reconcile.test.mjs +44 -8
  47. package/test/proxy-restart.test.mjs +0 -39
package/lib/index.js CHANGED
@@ -51,7 +51,7 @@
51
51
  * @module dsh-ris-ide
52
52
  */
53
53
  import { appendFile, copyFile, cp, link, lstat, mkdir, open, readdir, readFile, readlink, rename, rm, stat, symlink, truncate, writeFile } from 'node:fs/promises'
54
- import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
54
+ import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
55
55
  import { watch } from 'node:fs'
56
56
  import { createHash } from 'node:crypto'
57
57
  import { spawn, spawnSync } from 'node:child_process'
@@ -259,6 +259,15 @@ const CLIPBOARD_MAX_PAYLOAD = 256 * 1024
259
259
  * restart without anyone announcing anything.
260
260
  */
261
261
  const WINDOWS_PATH = `${ROUTE_PREFIX}/windows`
262
+ /**
263
+ * `GET /dsh-ris-ide/workspaces` — this host's live sidebar snapshot (m00186).
264
+ *
265
+ * The daemon normally reads `dsh-window.json`, but that document is shared by every
266
+ * dsh on the machine and is only its last written answer. This route answers from
267
+ * the running host itself, so the page can stay usable while the document is
268
+ * missing, stale, or written by another instance.
269
+ */
270
+ const WORKSPACES_PATH = `${ROUTE_PREFIX}/workspaces`
262
271
  /** A window whose stream has been gone this long counts as closed. */
263
272
  const IDE_WINDOW_GRACE_MS = 90 * 1000
264
273
  /** Live IDE windows, keyed by workspace cwd (one IDE window per workspace). */
@@ -785,15 +794,233 @@ const DSH_WINDOW_FILENAME = 'dsh-window.json'
785
794
  const DSH_WINDOW_THROTTLE_MS = 3000
786
795
  /** Keep the list short: the page only needs the workspaces someone is working in. */
787
796
  const DSH_WINDOW_MAX_ENTRIES = 8
797
+ /** Upper bound for the registry snapshot: a machine with hundreds of workspaces must not bloat the file. */
798
+ const DSH_WINDOW_MAX_WORKSPACES = 50
788
799
  let dshWindowNote = { at: 0, host: '', sessionId: '', cwd: '' }
800
+ /**
801
+ * The last loopback origin a browser used to reach this host (m00186).
802
+ *
803
+ * dsh-window.json must name an origin the daemon page can embed, and for a while
804
+ * the only writer was a window request, so a dsh started without ever opening the
805
+ * IDE panel left no origin behind at all. Whatever address the bound server reports
806
+ * may also be a LAN IP while the page was opened on 127.0.0.1; the request's Host is
807
+ * the address that actually worked, so it wins.
808
+ */
809
+ let dshWindowOrigin = ''
810
+
811
+ /**
812
+ * Remember the origin of a loopback request. Called on every plugin route: a dsh
813
+ * page that only loads the sidebar is enough to teach the refresh tick where the
814
+ * IDE can be embedded (see {@link dshWindowOriginFor}).
815
+ * @param req - the incoming HTTP request.
816
+ */
817
+ function rememberDshOrigin(req) {
818
+ try {
819
+ // The same admission rule as every route: a cross-site request must not be able
820
+ // to point the daemon page's iframe at another host (review A-P2-10).
821
+ if (!isLoopbackRequest(req)) return
822
+ const host = String(req?.headers?.host ?? '')
823
+ if (host !== '') dshWindowOrigin = `http://${host}`
824
+ } catch { /* a malformed request keeps the previous origin */ }
825
+ }
826
+
827
+ /**
828
+ * The host's workspace registry, when this dsh version provides one.
829
+ *
830
+ * Read through `ctx.get` instead of the `inject` list: the plugin is installable on
831
+ * older hosts that have no workspace service, and a missing registry only costs the
832
+ * title (the daemon page falls back to the folder name).
833
+ * @param ctx - Host context.
834
+ * @returns the registry service, or null.
835
+ */
836
+ function workspaceRegistryOf(ctx) {
837
+ try {
838
+ const registry = ctx?.get?.('workspaceRegistry', false)
839
+ return registry !== null && typeof registry === 'object' && typeof registry.list === 'function' ? registry : null
840
+ } catch {
841
+ return null
842
+ }
843
+ }
844
+
845
+ /**
846
+ * One path spelling that can be compared across `dsh-window.json` rows, session
847
+ * headers and registry records: the real path when it still exists, else a lexical
848
+ * spelling without a trailing slash.
849
+ *
850
+ * The registry stores `fs.realpath` output, so a symlinked workspace path (or one
851
+ * with a trailing slash) must not cost the title.
852
+ * @param value - Candidate absolute path.
853
+ * @returns the canonical spelling, or `''`.
854
+ */
855
+ function canonicalWorkspacePath(value) {
856
+ const raw = typeof value === 'string' ? value : ''
857
+ if (raw === '') return ''
858
+ try {
859
+ return realpathSync.native(raw)
860
+ } catch { /* gone, or not a directory: compare lexically */ }
861
+ const trimmed = raw.replace(/[\\/]+$/, '')
862
+ return trimmed === '' ? raw : trimmed
863
+ }
864
+
865
+ /** Path → title index per host context; short TTL so a burst of IDE requests does
866
+ * not run `realpath` over every workspace on each one (a rename still lands within
867
+ * this window — a label two seconds late is invisible). */
868
+ const workspaceTitleIndexes = new WeakMap()
869
+ /** How long a resolved path → title index is reused. */
870
+ const WORKSPACE_TITLE_TTL_MS = 2000
871
+
872
+ /**
873
+ * Canonical path → sidebar title for one host context, cached briefly.
874
+ * @param ctx - Host context.
875
+ * @returns {Map<string, string>} the index (empty when there is no registry).
876
+ */
877
+ function workspaceTitleIndex(ctx) {
878
+ const now = Date.now()
879
+ const cached = typeof ctx === 'object' && ctx !== null ? workspaceTitleIndexes.get(ctx) : undefined
880
+ if (cached !== undefined && now - cached.at <= WORKSPACE_TITLE_TTL_MS) return cached.byPath
881
+ const byPath = new Map()
882
+ const registry = workspaceRegistryOf(ctx)
883
+ if (registry !== null) {
884
+ let listed
885
+ try {
886
+ listed = registry.list()
887
+ } catch {
888
+ listed = []
889
+ }
890
+ for (const workspace of Array.isArray(listed) ? listed : []) {
891
+ if (workspace === null || typeof workspace !== 'object') continue
892
+ const path = typeof workspace.path === 'string' ? workspace.path : ''
893
+ const key = canonicalWorkspacePath(path)
894
+ if (key === '') continue
895
+ byPath.set(key, typeof workspace.title === 'string' ? workspace.title : '')
896
+ }
897
+ }
898
+ if (typeof ctx === 'object' && ctx !== null) workspaceTitleIndexes.set(ctx, { at: now, byPath })
899
+ return byPath
900
+ }
901
+
902
+ /**
903
+ * Title sync has ONE key: the workspace path. Renaming a workspace only changes its
904
+ * `title` (dsh-workspace `setTitle` never touches `path`), so a path → title lookup
905
+ * keeps the daemon page's labels equal to the sidebar's after a rename (m13800).
906
+ * @param ctx - Host context.
907
+ * @param cwd - Workspace path as recorded in a window row.
908
+ * @returns the title, or `''` when unknown (older dsh, no registry, unknown path).
909
+ */
910
+ export function workspaceTitleFor(ctx, cwd) {
911
+ const wanted = canonicalWorkspacePath(cwd)
912
+ if (wanted === '') return ''
913
+ return workspaceTitleIndex(ctx).get(wanted) ?? ''
914
+ }
915
+
916
+ /**
917
+ * A session id the IDE can boot on for one workspace: dsh's live session for that
918
+ * cwd when there is one (`liveSessionFor`), else the last recorded session id, else
919
+ * `''` (the panel then opens the workspace without a session — the host routes fall
920
+ * back to the cwd).
921
+ * @param ctx - Host context.
922
+ * @param path - Workspace path.
923
+ * @param workspace - Registry entity.
924
+ * @returns a session id, possibly `''`.
925
+ */
926
+ function workspaceSessionFor(ctx, path, workspace) {
927
+ const live = liveSessionFor(ctx, path)
928
+ if (live !== null && typeof live.id === 'string' && live.id !== '') return live.id
929
+ try {
930
+ const ids = workspace?.sessionIds
931
+ if (Array.isArray(ids) && ids.length > 0 && typeof ids[ids.length - 1] === 'string') return ids[ids.length - 1]
932
+ } catch { /* a broken entity only costs the session */ }
933
+ return ''
934
+ }
935
+
936
+ /**
937
+ * Every workspace the dsh sidebar shows, in the user's own order, with its title.
938
+ *
939
+ * Written next to the window rows so the daemon page can mirror the sidebar even for
940
+ * a workspace nobody opened the IDE for yet, and so a rename reaches the page without
941
+ * anyone clicking in that workspace (m13800).
942
+ * @param ctx - Host context.
943
+ * @returns {Array<{cwd: string, title: string, sessionId: string, active: boolean}>}
944
+ */
945
+ export function dshWorkspaceRows(ctx) {
946
+ const registry = workspaceRegistryOf(ctx)
947
+ if (registry === null) return []
948
+ let listed
949
+ try {
950
+ listed = registry.list()
951
+ } catch {
952
+ return []
953
+ }
954
+ if (!Array.isArray(listed)) return []
955
+ const rows = []
956
+ for (const workspace of listed) {
957
+ if (rows.length >= DSH_WINDOW_MAX_WORKSPACES) break
958
+ if (workspace === null || typeof workspace !== 'object') continue
959
+ const path = typeof workspace.path === 'string' ? workspace.path : ''
960
+ if (path === '') continue
961
+ const sessionId = workspaceSessionFor(ctx, path, workspace)
962
+ rows.push({
963
+ cwd: path,
964
+ title: typeof workspace.title === 'string' ? workspace.title : '',
965
+ sessionId,
966
+ // Whether this workspace currently holds a live session. A workspace without
967
+ // one is still openable (the host routes fall back to the cwd), so this only
968
+ // feeds the page's per-row hint instead of gating the list (m00186).
969
+ active: sessionId !== '' && isLiveSession(ctx, sessionId),
970
+ })
971
+ }
972
+ return rows
973
+ }
974
+
975
+ /**
976
+ * The whole document `dsh-window.json` carries: remembered windows (where to embed
977
+ * the IDE), the sidebar's workspace list (what to call the entries) and the last
978
+ * answer this host gave. `at` proves the writer is still alive, so the daemon can
979
+ * drop the title snapshot when dsh has been gone for long enough.
980
+ * @param ctx - Host context.
981
+ * @param windows - The window rows about to be written.
982
+ * @param now - Epoch ms of the answer.
983
+ * @param url - The origin this host answered on (preferred over the newest row).
984
+ * @returns the document to persist.
985
+ */
986
+ function dshWindowDocument(ctx, windows, now, url) {
987
+ const origin = typeof url === 'string' && url !== ''
988
+ ? url
989
+ : (Array.isArray(windows) ? windows.reduce((found, row) => found !== '' ? found : (row !== null && typeof row === 'object' && typeof row.url === 'string' ? row.url : ''), '') : '')
990
+ return {
991
+ windows: Array.isArray(windows) ? windows : [],
992
+ workspaces: dshWorkspaceRows(ctx),
993
+ url: origin,
994
+ at: new Date(now).toISOString(),
995
+ }
996
+ }
997
+
998
+ /**
999
+ * The origin the daemon page should embed the IDE at: the address a browser really
1000
+ * used when one has ever reached this host, else the address the server is bound to.
1001
+ * @param ctx - Host context.
1002
+ * @returns `http://host:port`, or `''` when neither is known (an old host whose
1003
+ * server is not bound yet, and no page has been served).
1004
+ */
1005
+ function dshWindowOriginFor(ctx) {
1006
+ if (dshWindowOrigin !== '') return dshWindowOrigin
1007
+ try {
1008
+ // getOrigin() throws before the server is bound; the timer can fire that early,
1009
+ // and a missing method on an older host must only cost the origin.
1010
+ const origin = ctx?.webServer?.getOrigin?.()
1011
+ if (typeof origin === 'string' && origin !== '') return origin
1012
+ } catch { /* not bound yet */ }
1013
+ return ''
1014
+ }
789
1015
 
790
1016
  /**
791
1017
  * Upsert one dsh window record (origin + sessionId per workspace). A daemon page
792
1018
  * can then offer every workspace's IDE in one window instead of one page per cwd.
793
1019
  * Loopback Hosts only, best effort, never throws.
1020
+ * @param ctx - Host context (workspace titles for the daemon page's labels).
794
1021
  * @param req - the incoming HTTP request.
795
1022
  */
796
- function noteDshWindow(req) {
1023
+ function noteDshWindow(ctx, req) {
797
1024
  // `node --test` runs against the developer's real home unless a test isolates
798
1025
  // DSH_RIS_IDE_PROXY_HOME. Fake contexts with /tmp workspaces used to collect
799
1026
  // entries in dsh-window.json and the daemon page listed them as workspaces
@@ -846,6 +1073,11 @@ function noteDshWindow(req) {
846
1073
  url: `http://${host}`,
847
1074
  sessionId,
848
1075
  cwd,
1076
+ // The sidebar's title for this path (m13800). Renaming only changes the title,
1077
+ // so the daemon page can label a workspace the way dsh does and follow a rename
1078
+ // without losing the workspace; '' means "no registry on this host" and the page
1079
+ // falls back to the folder name.
1080
+ title: workspaceTitleFor(ctx, cwd),
849
1081
  // Which plugin process wrote this row: another dsh (same home) refreshes and
850
1082
  // prunes only its own rows (review C2-P2-2).
851
1083
  ownerPid: process.pid,
@@ -855,35 +1087,97 @@ function noteDshWindow(req) {
855
1087
  windows.unshift(entry)
856
1088
  const trimmed = windows.slice(0, DSH_WINDOW_MAX_ENTRIES)
857
1089
  // Atomic replace: a half-written file reads as "no windows" in the daemon
858
- // (review C2-P2-1 / A2-P2-17).
859
- writeStateAtomic(path, { windows: trimmed })
1090
+ // (review C2-P2-1 / A2-P2-17). The document also carries the sidebar's workspace
1091
+ // list (title per path) and the origin that answered (m13800).
1092
+ writeStateAtomic(path, dshWindowDocument(ctx, trimmed, now, `http://${host}`))
860
1093
  } catch { /* the daemon page simply greys the IDE tab out */ }
861
1094
  }
862
1095
  /** How often the plugin refreshes the liveness of remembered dsh windows. */
863
1096
  const DSH_WINDOW_REFRESH_MS = 10_000
864
1097
 
1098
+ /**
1099
+ * Whether two sidebar snapshots say the same thing, in the same order.
1100
+ *
1101
+ * Order is the dsh sidebar's own order, so it is part of the equality: a reordered
1102
+ * sidebar is a new truth for the daemon page, not a cosmetic difference.
1103
+ * @param left - Rows about to be written.
1104
+ * @param right - Rows already on disk.
1105
+ * @returns whether a write would change nothing.
1106
+ */
1107
+ function sameWorkspaceRows(left, right) {
1108
+ if (!Array.isArray(left) || !Array.isArray(right)) return false
1109
+ if (left.length !== right.length) return false
1110
+ for (let index = 0; index < left.length; index += 1) {
1111
+ const a = left[index]
1112
+ const b = right[index]
1113
+ if (a === null || typeof a !== 'object' || b === null || typeof b !== 'object') return false
1114
+ const aCwd = typeof a.cwd === 'string' ? a.cwd : ''
1115
+ const bCwd = typeof b.cwd === 'string' ? b.cwd : ''
1116
+ const aTitle = typeof a.title === 'string' ? a.title : ''
1117
+ const bTitle = typeof b.title === 'string' ? b.title : ''
1118
+ const aSession = typeof a.sessionId === 'string' ? a.sessionId : ''
1119
+ const bSession = typeof b.sessionId === 'string' ? b.sessionId : ''
1120
+ if (aCwd !== bCwd || aTitle !== bTitle || aSession !== bSession) return false
1121
+ }
1122
+ return true
1123
+ }
1124
+
865
1125
  /**
866
1126
  * Keep the remembered windows' `at` fresh while dsh still knows their session, so
867
1127
  * the daemon page lists every workspace that is currently open instead of only the
868
1128
  * one that happened to hit an endpoint within the freshness window (m08228).
869
1129
  * The plugin is the only writer of dsh-window.json; a daemon-side timer cannot
870
1130
  * answer "does this session still exist" because it has no host context.
871
- * @param ctx - Host context (`ctx.sessions.get(id)`).
872
- * @returns {{changed:number, windows:number}} how many entries were refreshed.
1131
+ *
1132
+ * Since m00186 this tick also publishes the sidebar's workspace list and this host's
1133
+ * origin on its own, even before any window row exists: a dsh started as a service
1134
+ * (or simply never asked for the IDE panel) used to leave the daemon page stuck at
1135
+ * 「dsh 未运行(没有记住的工作区窗口)」 although dsh was running. The mirror of the
1136
+ * registry is enough for that page to offer every workspace and switch between them.
1137
+ * @param ctx - Host context (`ctx.sessions.get(id)`, workspace registry).
1138
+ * @returns {{changed:number, windows:number, dropped:number}} how many entries were refreshed.
873
1139
  */
874
1140
  export function refreshDshWindows(ctx) {
875
1141
  const result = { changed: 0, windows: 0, dropped: 0 }
876
1142
  try {
877
1143
  const path = join(proxyHomeDir(), DSH_WINDOW_FILENAME)
1144
+ let document = null
878
1145
  let windows = []
1146
+ let sidebar = []
1147
+ let documentOrigin = ''
1148
+ let documentAt = Number.NaN
879
1149
  try {
880
- const parsed = JSON.parse(readFileSync(path, 'utf8'))
881
- if (Array.isArray(parsed?.windows)) windows = parsed.windows
882
- } catch { return result }
883
- if (windows.length === 0) return result
1150
+ document = JSON.parse(readFileSync(path, 'utf8'))
1151
+ if (Array.isArray(document?.windows)) windows = document.windows
1152
+ if (Array.isArray(document?.workspaces)) sidebar = document.workspaces
1153
+ if (typeof document?.url === 'string') documentOrigin = document.url
1154
+ documentAt = Date.parse(String(document?.at ?? ''))
1155
+ } catch { /* absent or unreadable: this tick may write the first version */ }
884
1156
  const now = Date.now()
1157
+ // The sidebar mirror is news even when no window row exists, and it can only be
1158
+ // produced while this process still holds the registry — which is exactly the
1159
+ // liveness the document's `at` promises to the daemon.
1160
+ const mirror = dshWorkspaceRows(ctx)
1161
+ const origin = dshWindowOriginFor(ctx)
885
1162
  const canVerify = typeof ctx?.sessions?.get === 'function'
886
1163
  let dirty = false
1164
+ /**
1165
+ * Re-resolve one row's sidebar title (m13800). A rename never touches the path,
1166
+ * so the path keeps the row and only the label moves — and it moves even while
1167
+ * nobody is working in that workspace, because this timer keeps running.
1168
+ * @param row - A window row that belongs to this process.
1169
+ * @returns the row, with a fresh/removed `title` when it changed.
1170
+ */
1171
+ const retitle = (row) => {
1172
+ const title = workspaceTitleFor(ctx, typeof row.cwd === 'string' ? row.cwd : '')
1173
+ const current = typeof row.title === 'string' ? row.title : ''
1174
+ if (title === current) return row
1175
+ dirty = true
1176
+ const next = Object.assign({}, row)
1177
+ if (title === '') delete next.title
1178
+ else next.title = title
1179
+ return next
1180
+ }
887
1181
  const next = windows.reduce((out, row) => {
888
1182
  if (row === null || typeof row !== 'object') return out
889
1183
  // Another dsh process owns this row (same machine-level home): its own plugin
@@ -897,7 +1191,7 @@ export function refreshDshWindows(ctx) {
897
1191
  const sessionId = typeof row.sessionId === 'string' ? row.sessionId : ''
898
1192
  // An empty session id cannot be verified (legacy rows); keep it and let the
899
1193
  // daemon's retain TTL retire it.
900
- if (sessionId === '' || !canVerify) { out.push(row); return out }
1194
+ if (sessionId === '' || !canVerify) { out.push(retitle(row)); return out }
901
1195
  const session = ctx.sessions.get(sessionId)
902
1196
  const sessionCwd = typeof session?.header?.cwd === 'string' ? session.header.cwd : ''
903
1197
  // "Session exists" is not enough: a session may have been reopened on another
@@ -909,16 +1203,75 @@ export function refreshDshWindows(ctx) {
909
1203
  }
910
1204
  dirty = true
911
1205
  result.changed += 1
912
- out.push(Object.assign({}, row, { at: new Date(now).toISOString() }))
1206
+ out.push(Object.assign({}, retitle(row), { at: new Date(now).toISOString() }))
913
1207
  return out
914
1208
  }, [])
915
1209
  // Report the surviving size: the pre-prune number misled callers/tests (review E P2-2).
916
1210
  result.windows = next.length
917
- if (dirty) writeStateAtomic(path, { windows: next })
1211
+ // Write when a window row changed, when the sidebar snapshot (title/order/session)
1212
+ // changed, or when there is something to keep alive and this tick is the first to
1213
+ // publish it / learned the origin / has to re-stamp `at`. When BOTH halves are
1214
+ // empty there is nothing to offer: this process must not create the document, or
1215
+ // an older host sharing the home would erase a newer instance's snapshot.
1216
+ const keepAlive = mirror.length > 0 || next.length > 0
1217
+ // An empty mirror means "this host cannot list workspaces", not "the sidebar is
1218
+ // empty": an older dsh sharing the home has no registry and must not publish an
1219
+ // empty list over another instance's snapshot. A real shrink (some workspaces
1220
+ // left, none right) is still news, because the mirror itself is non-empty.
1221
+ const mirrorChanged = mirror.length > 0 && !sameWorkspaceRows(mirror, sidebar)
1222
+ const originChanged = origin !== '' && origin !== documentOrigin
1223
+ const documentAgeMs = Number.isFinite(documentAt) ? now - documentAt : Number.POSITIVE_INFINITY
1224
+ if (dirty || mirrorChanged || (keepAlive && (document === null || originChanged || documentAgeMs >= DSH_WINDOW_REFRESH_MS))) {
1225
+ // The document also carries the sidebar's workspace list + the origin (m13800);
1226
+ // an empty origin falls back to the newest window row inside the helper.
1227
+ writeStateAtomic(path, dshWindowDocument(ctx, next, now, origin))
1228
+ }
1229
+ // Advertise this live host on its own origin file (m00186): the shared document
1230
+ // is a single last-writer snapshot, so a daemon that cannot use it must still be
1231
+ // able to ask a running dsh directly instead of declaring it gone.
1232
+ if (origin !== '') publishDshInstance(now, origin)
918
1233
  } catch { /* best effort: the page keeps showing what it last knew */ }
919
1234
  return result
920
1235
  }
921
1236
 
1237
+ /**
1238
+ * Where a running plugin advertises its origin: `instances/dsh-<pid>.json`
1239
+ * (m00186). The shared `dsh-window.json` is one last-writer snapshot and cannot
1240
+ * name two live hosts; one file per pid lets the daemon probe each of them.
1241
+ */
1242
+ const DSH_INSTANCE_DIRNAME = 'instances'
1243
+ /** An instance file this old belongs to a process that is gone (or a reused pid). */
1244
+ const DSH_INSTANCE_RETAIN_MS = 24 * 60 * 60 * 1000
1245
+
1246
+ /**
1247
+ * Publish (or refresh) this process's origin file. Best effort: a read-only home
1248
+ * only costs the daemon's direct-probe path — the shared document still carries an
1249
+ * origin whenever a browser reaches this host.
1250
+ * @param now - Epoch ms of this refresh tick.
1251
+ * @param origin - Loopback origin this host answers on.
1252
+ */
1253
+ function publishDshInstance(now, origin) {
1254
+ try {
1255
+ const dir = join(proxyHomeDir(), DSH_INSTANCE_DIRNAME)
1256
+ writeStateAtomic(join(dir, `dsh-${process.pid}.json`), {
1257
+ pid: process.pid,
1258
+ url: origin,
1259
+ at: new Date(now).toISOString(),
1260
+ })
1261
+ // A crashed dsh never deletes its own file, so drop the ones nothing can own now:
1262
+ // a short candidate list keeps the daemon's probes cheap.
1263
+ for (const name of readdirSync(dir)) {
1264
+ if (!/^dsh-\d+\.json$/.test(name) || name === `dsh-${process.pid}.json`) continue
1265
+ try {
1266
+ const parsed = JSON.parse(readFileSync(join(dir, name), 'utf8'))
1267
+ const at = Date.parse(String(parsed?.at ?? ''))
1268
+ if (Number.isFinite(at) && now - at <= DSH_INSTANCE_RETAIN_MS) continue
1269
+ } catch { /* half-written: nobody can use it */ }
1270
+ try { rmSync(join(dir, name), { force: true }) } catch { /* best effort */ }
1271
+ }
1272
+ } catch { /* best effort: see the doc comment */ }
1273
+ }
1274
+
922
1275
  export function handleRequest(ctx, req, res, options) {
923
1276
  try {
924
1277
  dispatchRequest(ctx, req, res, options)
@@ -935,7 +1288,10 @@ export function handleRequest(ctx, req, res, options) {
935
1288
 
936
1289
  /** The actual router behind {@link handleRequest}'s exception fence. */
937
1290
  function dispatchRequest(ctx, req, res, options) {
938
- noteDshWindow(req)
1291
+ // Any request from the dsh page is proof of the origin to advertise — not just a
1292
+ // window request (`noteDshWindow` needs ?sessionId=&?cwd= and may never come).
1293
+ rememberDshOrigin(req)
1294
+ noteDshWindow(ctx, req)
939
1295
  const method = req.method ?? 'GET'
940
1296
  const pathname = requestPathname(req)
941
1297
  if (pathname === WINDOWS_PATH) {
@@ -946,6 +1302,14 @@ function dispatchRequest(ctx, req, res, options) {
946
1302
  serveSafely(res, () => serveWindows(ctx, req, res))
947
1303
  return
948
1304
  }
1305
+ if (pathname === WORKSPACES_PATH) {
1306
+ if (method !== 'GET') {
1307
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1308
+ return
1309
+ }
1310
+ serveSafely(res, () => serveWorkspaces(ctx, req, res))
1311
+ return
1312
+ }
949
1313
  if (pathname === WINDOW_PAGE_PATH) {
950
1314
  if (method !== 'GET') {
951
1315
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -3202,12 +3566,88 @@ function serveSafely(res, run) {
3202
3566
  })
3203
3567
  }
3204
3568
 
3569
+ /** How long the known-workspace path list is reused before it is rebuilt. */
3570
+ const KNOWN_WORKSPACES_TTL_MS = 2000
3571
+ /** `ctx` → `{ at, paths }`: the last {@link knownWorkspacePaths} answer per host. */
3572
+ const KNOWN_WORKSPACES_CACHE = new WeakMap()
3573
+
3574
+ /**
3575
+ * Paths of every workspace this host knows: the dsh workspace registry plus the
3576
+ * window/workspace rows the plugin itself stamped into `dsh-window.json`. Cached
3577
+ * because {@link resolveCwd} runs on nearly every `/fs` and `/tail` request.
3578
+ *
3579
+ * Both sources are "this machine's workspaces as dsh shows them", never an
3580
+ * arbitrary absolute path: a page may only widen its fence to a workspace dsh
3581
+ * itself has registered (see {@link insideKnownWorkspace}).
3582
+ * @param ctx - Host context carrying the workspace registry.
3583
+ * @returns canonical absolute workspace paths.
3584
+ */
3585
+ function knownWorkspacePaths(ctx) {
3586
+ const cached = KNOWN_WORKSPACES_CACHE.get(ctx)
3587
+ if (cached !== undefined && Date.now() - cached.at < KNOWN_WORKSPACES_TTL_MS) return cached.paths
3588
+ const paths = new Set()
3589
+ const add = (value) => {
3590
+ if (typeof value !== 'string' || value === '' || !isAbsolute(value)) return
3591
+ paths.add(canonicalWorkspacePath(value))
3592
+ }
3593
+ try {
3594
+ const registry = workspaceRegistryOf(ctx)
3595
+ const rows = registry === undefined ? [] : registry.list()
3596
+ for (const row of Array.isArray(rows) ? rows : []) add(row !== null && typeof row === 'object' ? row.path : row)
3597
+ } catch {
3598
+ // No workspace registry on this host: the dsh-window rows below still count.
3599
+ }
3600
+ try {
3601
+ const document = JSON.parse(readFileSync(join(proxyHomeDir(), DSH_WINDOW_FILENAME), 'utf8'))
3602
+ for (const key of ['windows', 'workspaces']) {
3603
+ const rows = Array.isArray(document?.[key]) ? document[key] : []
3604
+ for (const row of rows) add(row !== null && typeof row === 'object' ? row.cwd : row)
3605
+ }
3606
+ } catch {
3607
+ // No remembered windows yet (first run / another user's home).
3608
+ }
3609
+ const list = Array.from(paths)
3610
+ KNOWN_WORKSPACES_CACHE.set(ctx, { at: Date.now(), paths: list })
3611
+ return list
3612
+ }
3613
+
3205
3614
  /**
3206
- * The session's working directory, from the live session header first and the
3207
- * caller-supplied absolute cwd second — the same order the sidebar's own
3208
- * `sessionCwdOf` uses (the header is authoritative once the session hydrates;
3209
- * `cwd` covers a request that arrives while it is still hydrating).
3210
- * @param ctx - Host context carrying `sessions`.
3615
+ * Whether `target` is one of this host's workspaces or lives inside one.
3616
+ *
3617
+ * The realpath form is checked too: a registered path is canonical while the page
3618
+ * may still spell a symlinked ancestor, and a copy source that exists resolves to
3619
+ * the same inode either way.
3620
+ * @param ctx - Host context carrying the workspace registry.
3621
+ * @param target - absolute, already normalized path.
3622
+ * @returns whether the path belongs to a known workspace.
3623
+ */
3624
+ function insideKnownWorkspace(ctx, target) {
3625
+ const roots = knownWorkspacePaths(ctx)
3626
+ if (roots.length === 0) return false
3627
+ const lexical = (root) => target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)
3628
+ if (roots.some(lexical)) return true
3629
+ let real = ''
3630
+ try {
3631
+ real = realpathSync.native(target)
3632
+ } catch {
3633
+ return false
3634
+ }
3635
+ return roots.some((root) => real === root || real.startsWith(root.endsWith(sep) ? root : `${root}${sep}`))
3636
+ }
3637
+
3638
+ /**
3639
+ * The working directory a request runs against, from the live session header or
3640
+ * the caller-supplied absolute cwd — the page acts on the workspace it SHOWS.
3641
+ *
3642
+ * The header used to win unconditionally. A window opened while dsh was switching
3643
+ * workspaces can show workspace A while carrying a session whose header names B
3644
+ * (the header button fell back to the last workspace, or the window kept a session
3645
+ * from another workspace), and every mutation in A's tree then died with
3646
+ * 「不能对工作区之外的路径执行新建文件夹」. When the declared cwd is a workspace this
3647
+ * host knows, the page is inside its own rights and the declared cwd wins; any
3648
+ * other declared cwd keeps the header fence (it is never a licence for an
3649
+ * arbitrary absolute path).
3650
+ * @param ctx - Host context carrying `sessions` and the workspace registry.
3211
3651
  * @param sessionId - owning Session identity.
3212
3652
  * @param clientCwd - optional absolute cwd from the browser.
3213
3653
  * @returns the absolute working directory.
@@ -3215,8 +3655,14 @@ function serveSafely(res, run) {
3215
3655
  function resolveCwd(ctx, sessionId, clientCwd) {
3216
3656
  const session = ctx.sessions?.get?.(sessionId)
3217
3657
  const headerCwd = session?.header?.cwd
3218
- if (typeof headerCwd === 'string' && headerCwd !== '') return headerCwd
3219
- if (typeof clientCwd === 'string' && clientCwd !== '' && isAbsolute(clientCwd)) return clientCwd
3658
+ const header = typeof headerCwd === 'string' && headerCwd !== '' ? headerCwd : ''
3659
+ const declared = typeof clientCwd === 'string' && clientCwd !== '' && isAbsolute(clientCwd) ? clientCwd : ''
3660
+ // Same answer as the header costs nothing: leave the registry/file read to the
3661
+ // requests that actually disagree (the workspace-switch case).
3662
+ if (declared !== '' && declared === header) return header
3663
+ if (declared !== '' && insideKnownWorkspace(ctx, declared)) return declared
3664
+ if (header !== '') return header
3665
+ if (declared !== '') return declared
3220
3666
  throw new TailError('bad-request', `no working directory for session "${sessionId}"`, 400)
3221
3667
  }
3222
3668
 
@@ -3689,6 +4135,19 @@ async function serveFsOp(ctx, req, res, options) {
3689
4135
  const base = root.endsWith(sep) ? root : `${root}${sep}`
3690
4136
  if (!target.startsWith(base)) throw new TailError('outside-workspace', `不能对工作区之外的路径执行${action}`, 403)
3691
4137
  }
4138
+ /**
4139
+ * A COPY may read from another workspace: the tree keeps absolute source paths
4140
+ * after the user switches workspace, and 「跨工作区复制粘贴」 is the same gesture as
4141
+ * copying a file to the desktop (user口径 m00220). Only READ side widens, only to
4142
+ * a workspace this host knows; writes below stay inside THIS tree, and a move
4143
+ * never crosses a workspace (it would relocate a tree out of its git boundary).
4144
+ */
4145
+ const insideCopySource = (target, action) => {
4146
+ notRoot(target, action)
4147
+ const base = root.endsWith(sep) ? root : `${root}${sep}`
4148
+ if (target.startsWith(base) || insideKnownWorkspace(ctx, target)) return
4149
+ throw new TailError('outside-workspace', `不能对工作区之外的路径执行${action}`, 403)
4150
+ }
3692
4151
  const exists = async (target) => stat(target).then(() => true).catch(() => false)
3693
4152
  /** A destination given as a FILE means its directory, same rule as a paste. */
3694
4153
  const asFolder = async (target) => {
@@ -3715,8 +4174,10 @@ async function serveFsOp(ctx, req, res, options) {
3715
4174
  return
3716
4175
  }
3717
4176
  if (url.pathname === FS_COPY_PATH || url.pathname === FS_MOVE_PATH) {
4177
+ const copying = url.pathname === FS_COPY_PATH
3718
4178
  const from = one(body.from, 'from')
3719
- insideRoot(from, '复制或移动')
4179
+ if (copying) insideCopySource(from, '复制或移动')
4180
+ else insideRoot(from, '复制或移动')
3720
4181
  const toDir = await asFolder(one(body.toDir !== undefined ? body.toDir : body.to, 'toDir'))
3721
4182
  const requested = leafName(typeof body.name === 'string' ? body.name : '')
3722
4183
  const target = join(toDir, requested === '' ? basename(from) : requested)
@@ -3726,20 +4187,12 @@ async function serveFsOp(ctx, req, res, options) {
3726
4187
  throw new TailError('bad-request', '不能把目录复制/移动到它自己内部', 409)
3727
4188
  }
3728
4189
  const overwrite = body.overwrite === true
3729
- if (await exists(target)) {
3730
- if (!overwrite) throw new TailError('exists', `目标位置已有「${basename(target)}」`, 409)
3731
- // The user explicitly chose 覆盖 in the conflict dialog: the old entry is
3732
- // gone afterwards (the dialog says so), so remove it before the operation
3733
- // rather than letting `cp`/`rename` fail on it.
3734
- await rm(target, { recursive: true, force: false })
3735
- }
3736
- await mkdir(dirname(target), { recursive: true })
3737
- if (url.pathname === FS_COPY_PATH) {
3738
- // Node's cp keeps the tree shape and refuses to merge into anything.
3739
- await cp(from, target, { recursive: true, errorOnExist: true, force: false })
3740
- } else {
3741
- await rename(from, target)
3742
- }
4190
+ // Deleting the old target first is how a "copy" could destroy its own source:
4191
+ // `assertReplacementIsSafe` refuses the aliasing cases (same inode, same real
4192
+ // path, target containing the source) and `replaceEntry` builds the new entry
4193
+ // beside the target and swaps it in with an atomic rename instead.
4194
+ await assertReplacementIsSafe(from, target, url.pathname === FS_COPY_PATH ? '复制' : '移动')
4195
+ await replaceEntry(from, target, { move: url.pathname === FS_MOVE_PATH, overwrite })
3743
4196
  writeJson(res, 200, { ok: true, path: target, from, [url.pathname === FS_COPY_PATH ? 'copied' : 'moved']: true })
3744
4197
  return
3745
4198
  }
@@ -3903,13 +4356,18 @@ async function serveFsImport(ctx, req, res, options) {
3903
4356
  callback(null, chunk)
3904
4357
  },
3905
4358
  })
4359
+ const temp = replacementTempPath(target, 'new')
3906
4360
  try {
3907
4361
  // Stream: a 100 MB upload must not be buffered in memory just to be written.
3908
- await pipeline(req, gate, createWriteStream(target, { flags: overwrite ? 'w' : 'wx' }))
4362
+ // Never into the target itself: a failed or oversized upload used to truncate
4363
+ // the old file and then delete it. The bytes land in a same-directory temp
4364
+ // file, and only a COMPLETED upload is renamed over the target.
4365
+ await pipeline(req, gate, createWriteStream(temp, { flags: 'wx' }))
3909
4366
  } catch (error) {
3910
- await rm(target, { force: true }).catch(() => {})
4367
+ await rm(temp, { force: true }).catch(() => {})
3911
4368
  throw error
3912
4369
  }
4370
+ await installReplacement(temp, target, { overwrite })
3913
4371
  writeJson(res, 200, { ok: true, path: target, name, bytes: written })
3914
4372
  return
3915
4373
  }
@@ -3933,12 +4391,11 @@ async function serveFsImport(ctx, req, res, options) {
3933
4391
  throw new TailError('bad-request', '不能把目录导入到它自己内部', 409)
3934
4392
  }
3935
4393
  const overwrite = body.overwrite === true
3936
- if (await pathExists(target)) {
3937
- if (!overwrite) throw new TailError('exists', `「${name}」已存在`, 409)
3938
- await rm(target, { recursive: true, force: false })
3939
- }
3940
- if (sourceInfo.isDirectory()) await cp(source, target, { recursive: true })
3941
- else await copyFile(source, target)
4394
+ // An import can name a destination that aliases the source (symlinked folder,
4395
+ // case-insensitive mount, same inode) or that CONTAINS it: deleting the old
4396
+ // target first would delete the thing being imported.
4397
+ await assertReplacementIsSafe(source, target, '导入')
4398
+ await replaceEntry(source, target, { overwrite, followLinks: true })
3942
4399
  writeJson(res, 200, { ok: true, path: target, name })
3943
4400
  } catch (error) {
3944
4401
  writeTailError(res, error)
@@ -4188,6 +4645,10 @@ async function stageClipboardCopy(root, paths) {
4188
4645
  const batchDir = join(base, batch)
4189
4646
  const staged = []
4190
4647
  const originals = []
4648
+ // Identity of every original AT PUBLISH TIME. The manifest is what makes a later
4649
+ // loss provable: dev/ino says whether the same file is still under that name,
4650
+ // size/mtime whether it was rewritten. See verifyClipboardStageOriginals.
4651
+ const snapshot = []
4191
4652
  const meter = { budget: CLIPBOARD_STAGE_MAX_BYTES }
4192
4653
  try {
4193
4654
  await mkdir(batchDir, { recursive: true })
@@ -4196,11 +4657,20 @@ async function stageClipboardCopy(root, paths) {
4196
4657
  const entryDir = join(batchDir, String(index))
4197
4658
  await mkdir(entryDir, { recursive: true })
4198
4659
  const target = join(entryDir, basename(source))
4660
+ const info = await lstat(source)
4199
4661
  await mirrorStagedEntry(source, target, meter)
4200
4662
  staged.push(target)
4201
4663
  originals.push(resolve(source))
4664
+ snapshot.push({
4665
+ path: resolve(source),
4666
+ dev: info.dev,
4667
+ ino: info.ino,
4668
+ size: info.size,
4669
+ mtimeMs: info.mtimeMs,
4670
+ kind: info.isDirectory() ? 'dir' : info.isSymbolicLink() ? 'symlink' : 'file',
4671
+ })
4202
4672
  }
4203
- await writeFile(join(batchDir, CLIPBOARD_STAGE_MANIFEST), JSON.stringify({ at: Date.now(), originals, staged }), 'utf8')
4673
+ await writeFile(join(batchDir, CLIPBOARD_STAGE_MANIFEST), JSON.stringify({ at: Date.now(), originals, staged, snapshot }), 'utf8')
4204
4674
  return { staged, originals, batchDir }
4205
4675
  } catch (error) {
4206
4676
  await rm(batchDir, { recursive: true, force: true }).catch(() => {})
@@ -4209,6 +4679,72 @@ async function stageClipboardCopy(root, paths) {
4209
4679
  }
4210
4680
  }
4211
4681
 
4682
+ /** Findings already surfaced in this process, so a paste loop does not repeat them. */
4683
+ const clipboardIntegrityNoted = new Set()
4684
+
4685
+ /** Where staging-integrity findings are appended (inside the plugin state dir). */
4686
+ const CLIPBOARD_STAGE_INTEGRITY_LOG = 'integrity.log'
4687
+
4688
+ /**
4689
+ * Compare every staged batch's ORIGINALS with the snapshot taken when the copy was
4690
+ * published, and turn a vanished original into evidence.
4691
+ *
4692
+ * This is the trail for 「复制之后源文件不见了」. At publish time the plugin knows
4693
+ * each original's dev/ino/size/mtime; a later paste (or the next copy) re-checks
4694
+ * them. A `missing`/`replaced` finding is appended to
4695
+ * `.dsh-ris-ide/stage/integrity.log` with a timestamp, reported to the page once,
4696
+ * and carries the STAGED path — a hard link to the same inode, so the bytes are
4697
+ * still on disk and can be copied back by hand. The plugin's own deletions always
4698
+ * land in `.dsh-ris-ide/trash`, so a `missing` original here was moved or removed
4699
+ * by something outside the tree.
4700
+ * @param root - workspace root.
4701
+ * @returns {Promise<object[]>} findings for this call, each with a ready message.
4702
+ */
4703
+ async function verifyClipboardStageOriginals(root) {
4704
+ await ensureIdeStateDir(root)
4705
+ const base = join(root, CLIPBOARD_STAGE_DIR)
4706
+ const findings = []
4707
+ const entries = await readdir(base, { withFileTypes: true }).catch(() => [])
4708
+ for (const entry of entries) {
4709
+ if (!entry.isDirectory()) continue
4710
+ const manifest = await readFile(join(base, entry.name, CLIPBOARD_STAGE_MANIFEST), 'utf8').catch(() => undefined)
4711
+ if (manifest === undefined) continue
4712
+ let parsed
4713
+ try {
4714
+ parsed = JSON.parse(manifest)
4715
+ } catch {
4716
+ continue
4717
+ }
4718
+ if (parsed === null || typeof parsed !== 'object') continue
4719
+ const snapshot = Array.isArray(parsed.snapshot) ? parsed.snapshot : []
4720
+ const staged = Array.isArray(parsed.staged) ? parsed.staged : []
4721
+ for (let index = 0; index < snapshot.length; index += 1) {
4722
+ const record = snapshot[index]
4723
+ if (record === null || typeof record !== 'object' || typeof record.path !== 'string') continue
4724
+ const info = await lstat(record.path).catch(() => undefined)
4725
+ let status = 'ok'
4726
+ if (info === undefined) status = 'missing'
4727
+ else if (info.dev !== record.dev || info.ino !== record.ino) status = 'replaced'
4728
+ else if (info.size !== record.size || Math.abs(info.mtimeMs - record.mtimeMs) > 1) status = 'changed'
4729
+ if (status === 'ok' || status === 'changed') continue
4730
+ const stagedPath = typeof staged[index] === 'string' ? staged[index] : undefined
4731
+ const key = `${entry.name}\u0000${record.path}\u0000${status}`
4732
+ if (clipboardIntegrityNoted.has(key)) continue
4733
+ clipboardIntegrityNoted.add(key)
4734
+ const name = basename(record.path)
4735
+ const message = status === 'missing'
4736
+ ? `复制到系统剪贴板后,源文件「${name}」不见了。插件删除一律进 .dsh-ris-ide/trash,所以不是插件删的;暂存副本还在(${stagedPath ?? '已清理'}),可直接复制回来。`
4737
+ : `源文件「${name}」在复制后被换成了另一个文件(inode 从 ${record.ino} 变成 ${info.ino}),请确认这是什么操作做的。`
4738
+ findings.push({ batch: entry.name, path: record.path, status, staged: stagedPath, at: Date.now(), message })
4739
+ }
4740
+ }
4741
+ if (findings.length > 0) {
4742
+ const lines = findings.map((finding) => JSON.stringify(finding)).join('\n') + '\n'
4743
+ await appendFile(join(base, CLIPBOARD_STAGE_INTEGRITY_LOG), lines, 'utf8').catch(() => {})
4744
+ }
4745
+ return findings
4746
+ }
4747
+
4212
4748
  /** staged path → original path for every batch still on disk. */
4213
4749
  async function clipboardStageMapping(root) {
4214
4750
  await ensureIdeStateDir(root)
@@ -4491,11 +5027,16 @@ async function serveClipboardRead(ctx, req, res) {
4491
5027
  // look like the original selection (otherwise Ctrl+C → Ctrl+V would import a
4492
5028
  // second copy of files the tree already has).
4493
5029
  let files = state.files
5030
+ let warnings = []
4494
5031
  if (root !== undefined) {
4495
5032
  const mapping = await clipboardStageMapping(root)
4496
5033
  if (mapping.size > 0) files = files.map((path) => mapping.get(resolve(path)) ?? path)
5034
+ // A staged original that vanished between Ctrl+C and Ctrl+V is the exact
5035
+ // symptom this route exists to explain: say so once, with the staged path
5036
+ // that still holds the bytes, and leave a line in stage/integrity.log.
5037
+ warnings = (await verifyClipboardStageOriginals(root)).map((finding) => finding.message)
4497
5038
  }
4498
- writeJson(res, 200, { ok: true, files, text: state.text, method: state.method })
5039
+ writeJson(res, 200, { ok: true, files, text: state.text, method: state.method, warnings })
4499
5040
  } catch (error) {
4500
5041
  writeTailError(res, error)
4501
5042
  }
@@ -4626,6 +5167,158 @@ async function writeChunk(target, body) {
4626
5167
  if (body.final !== false) await rename(staging, target)
4627
5168
  }
4628
5169
 
5170
+ /** Infix of the throwaway sibling every REPLACE builds in before it takes the target's name. */
5171
+ const FS_REPLACE_TEMP_SUFFIX = '.dsh-ris-ide-replace'
5172
+
5173
+ /**
5174
+ * One throwaway path in `target`'s OWN directory.
5175
+ *
5176
+ * Same directory means same filesystem, so the final `rename` is atomic. The name
5177
+ * ends with the save-temp suffix, which the tree listing already skips, so a
5178
+ * replacement never shows up as a row. The leaf is cut to 60 chars: a long target
5179
+ * name must not push the temp name past the usual 255-byte component cap.
5180
+ * @param target - the entry being replaced.
5181
+ * @param kind - `'new'` (content being built) or `'old'` (previous entry, kept until the swap).
5182
+ */
5183
+ function replacementTempPath(target, kind) {
5184
+ const leaf = basename(target).slice(0, 60)
5185
+ const random = Math.random().toString(36).slice(2, 8)
5186
+ return join(dirname(target), `.${leaf}${FS_REPLACE_TEMP_SUFFIX}-${kind}-${process.pid.toString(36)}${random}${FS_WRITE_TEMP_SUFFIX}`)
5187
+ }
5188
+
5189
+ /** dev/ino of an existing path, or undefined when nothing is there. */
5190
+ async function entryIdentity(path) {
5191
+ const info = await stat(path).catch(() => undefined)
5192
+ return info === undefined ? undefined : { dev: info.dev, ino: info.ino }
5193
+ }
5194
+
5195
+ /** Real path of `path`, or its lexical form when it does not exist (yet). */
5196
+ function resolvedRealPath(path) {
5197
+ try {
5198
+ return realpathSync(path)
5199
+ } catch {
5200
+ return resolve(path)
5201
+ }
5202
+ }
5203
+
5204
+ /**
5205
+ * Refuse a replacement that would destroy the thing being copied or moved.
5206
+ *
5207
+ * Overwrite used to delete `target` FIRST and only then copy/rename onto the empty
5208
+ * name, so a target that is the source under another name destroyed the source:
5209
+ * - the SAME inode under two names (hard link; a staged clipboard copy is exactly that);
5210
+ * - the same REAL path (a destination directory that is a symlink into the source's
5211
+ * own directory, or a case-insensitive mount such as `/mnt/c`);
5212
+ * - a directory that CONTAINS the source — `rm(target)` takes the source with it,
5213
+ * and the copy then fails on a source that no longer exists.
5214
+ * The routes compare paths as strings, which cannot see any of those.
5215
+ * @param source - entry being copied/moved/imported.
5216
+ * @param target - entry it would replace.
5217
+ * @param action - verb for the message (`复制`/`移动`/`导入`).
5218
+ */
5219
+ async function assertReplacementIsSafe(source, target, action) {
5220
+ const from = await entryIdentity(source)
5221
+ const to = await entryIdentity(target)
5222
+ if (from !== undefined && to !== undefined && from.dev === to.dev && from.ino === to.ino) {
5223
+ throw new TailError('same-entry', `「${basename(source)}」和「${basename(target)}」是同一个条目,拒绝覆盖以免丢数据`, 409)
5224
+ }
5225
+ const realSource = resolvedRealPath(source)
5226
+ const realTarget = resolvedRealPath(target)
5227
+ if (realSource === realTarget) {
5228
+ throw new TailError('same-entry', `目标「${basename(target)}」就是源本身,已拒绝${action}`, 409)
5229
+ }
5230
+ if (realTarget.startsWith(`${realSource}${sep}`)) {
5231
+ throw new TailError('bad-request', `不能把「${basename(source)}」${action}到它自己内部`, 409)
5232
+ }
5233
+ if (realSource.startsWith(`${realTarget}${sep}`)) {
5234
+ throw new TailError('bad-request', `「${basename(target)}」是包含源的目录:覆盖它会连源一起删掉,已拒绝`, 409)
5235
+ }
5236
+ }
5237
+
5238
+ /**
5239
+ * Put a completed temporary entry at `target`.
5240
+ *
5241
+ * The previous entry is renamed to a sibling backup name first (a same-directory
5242
+ * rename, never a delete), the new entry takes the name with one atomic rename,
5243
+ * and only then is the backup dropped. A failure at any step restores the backup
5244
+ * and leaves the temporary file for the caller to remove.
5245
+ * @param temp - fully written sibling of `target`.
5246
+ * @param target - name the new content should end up under.
5247
+ * @param options - `{overwrite}`: without it, an existing target is a 409.
5248
+ */
5249
+ async function installReplacement(temp, target, { overwrite = false } = {}) {
5250
+ const existing = await pathExists(target)
5251
+ if (existing && !overwrite) {
5252
+ // The caller may already have built the new content (a full copy of the source):
5253
+ // it must never linger next to the target as debris.
5254
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5255
+ throw new TailError('exists', `「${basename(target)}」已存在`, 409)
5256
+ }
5257
+ const backup = existing ? replacementTempPath(target, 'old') : undefined
5258
+ if (backup !== undefined) {
5259
+ try {
5260
+ await rename(target, backup)
5261
+ } catch (error) {
5262
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5263
+ throw error
5264
+ }
5265
+ }
5266
+ try {
5267
+ await rename(temp, target)
5268
+ } catch (error) {
5269
+ if (backup !== undefined) await rename(backup, target).catch(() => {})
5270
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5271
+ throw error
5272
+ }
5273
+ if (backup !== undefined) await rm(backup, { recursive: true, force: true }).catch(() => {})
5274
+ }
5275
+
5276
+ /**
5277
+ * Copy or move `source` onto `target`, replacing an existing target only on
5278
+ * explicit `overwrite`.
5279
+ *
5280
+ * The old target is never deleted before the new content exists, so a failed copy
5281
+ * leaves both entries intact, and a reader never sees the target half-written.
5282
+ * @param source - entry to copy (`move: false`) or move (`move: true`).
5283
+ * @param target - destination name.
5284
+ * @param options - `{move, overwrite, followLinks}`; `followLinks` keeps the
5285
+ * import route's historical "copy what the symlink points at" behaviour.
5286
+ */
5287
+ async function replaceEntry(source, target, { move = false, overwrite = false, followLinks = false } = {}) {
5288
+ await mkdir(dirname(target), { recursive: true })
5289
+ if (move) {
5290
+ const existing = await pathExists(target)
5291
+ if (existing && !overwrite) throw new TailError('exists', `目标位置已有「${basename(target)}」`, 409)
5292
+ const backup = existing ? replacementTempPath(target, 'old') : undefined
5293
+ if (backup !== undefined) await rename(target, backup)
5294
+ try {
5295
+ await rename(source, target)
5296
+ } catch (error) {
5297
+ // The old entry is still under the backup name: put it back, nothing lost.
5298
+ if (backup !== undefined) await rename(backup, target).catch(() => {})
5299
+ throw error
5300
+ }
5301
+ if (backup !== undefined) await rm(backup, { recursive: true, force: true }).catch(() => {})
5302
+ return
5303
+ }
5304
+ const temp = replacementTempPath(target, 'new')
5305
+ try {
5306
+ const info = await (followLinks ? stat(source) : lstat(source))
5307
+ if (info.isDirectory()) {
5308
+ // Node's cp keeps the tree shape and refuses to merge into anything.
5309
+ await cp(source, temp, { recursive: true, errorOnExist: true, force: false, dereference: followLinks })
5310
+ } else if (info.isSymbolicLink()) {
5311
+ await symlink(await readlink(source), temp)
5312
+ } else {
5313
+ await copyFile(source, temp)
5314
+ }
5315
+ } catch (error) {
5316
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5317
+ throw error
5318
+ }
5319
+ await installReplacement(temp, target, { overwrite })
5320
+ }
5321
+
4629
5322
  /**
4630
5323
  * The IDE's own workspace file API — no `dsh-better-sidebar` involved.
4631
5324
  *
@@ -4894,6 +5587,31 @@ function isLiveSession(ctx, id) {
4894
5587
  }
4895
5588
  }
4896
5589
 
5590
+ /**
5591
+ * `GET /dsh-ris-ide/workspaces` — the sidebar rows and this host's origin, straight
5592
+ * from the live context (m00186).
5593
+ *
5594
+ * Loopback only like every other route, and read-only: a dsh page (or the daemon
5595
+ * probing a per-instance origin file) gets the authoritative list without any file
5596
+ * on disk being involved.
5597
+ * @param ctx - Host context.
5598
+ * @param req - Node request face.
5599
+ * @param res - Node response face.
5600
+ */
5601
+ function serveWorkspaces(ctx, req, res) {
5602
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
5603
+ const now = Date.now()
5604
+ // Answering proves this host is alive, so republish the shared document on the way
5605
+ // out: a reader that only knows the file then sees the same answer.
5606
+ refreshDshWindows(ctx)
5607
+ writeJson(res, 200, {
5608
+ ok: true,
5609
+ url: dshWindowOriginFor(ctx),
5610
+ at: new Date(now).toISOString(),
5611
+ workspaces: dshWorkspaceRows(ctx),
5612
+ })
5613
+ }
5614
+
4897
5615
  /** `GET /dsh-ris-ide/windows` — the live windows, and the session of one workspace. */
4898
5616
  async function serveWindows(ctx, req, res) {
4899
5617
  try {
@@ -5994,6 +6712,9 @@ function startRisdBridge(ctx, cwd) {
5994
6712
  return
5995
6713
  }
5996
6714
  await attachBridgeState(ensured.state, cwd)
6715
+ // No extra call for 「代理引擎跟随 dsh」: the lease acquired above IS the start
6716
+ // signal (the daemon starts the engine when the first lease arrives and tears it
6717
+ // down when the last one leaves — one signal, one policy, m13950).
5997
6718
  })().finally(() => {
5998
6719
  if (bridge === risdBridge) bridge.pending = null
5999
6720
  })
@@ -6526,6 +7247,9 @@ async function serveProxyAction(ctx, req, res, options) {
6526
7247
  const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
6527
7248
  const action = typeof body.action === 'string' ? body.action : 'status'
6528
7249
  const gitHost = typeof body.gitHost === 'string' ? body.gitHost : undefined
7250
+ // The maintenance page is the only elevation entry point; an auto-start (save
7251
+ // rules / dsh start) calls the same route without this flag (m13910).
7252
+ const interactive = body.interactive === true
6529
7253
  // Engine + bridge + git are the daemon's once it owns the proxy; the per-rule
6530
7254
  // 启动/停止 buttons stay here because they launch a child of THIS process (the
6531
7255
  // injection only works on a child we spawn ourselves).
@@ -6538,7 +7262,7 @@ async function serveProxyAction(ctx, req, res, options) {
6538
7262
  }
6539
7263
  }
6540
7264
  if (actionState !== null && daemonActions.has(action)) {
6541
- const call = await proxyAction(actionState, { cwd, action, gitHost })
7265
+ const call = await proxyAction(actionState, { cwd, action, gitHost, interactive })
6542
7266
  if (call.ok !== true) {
6543
7267
  // No answer at all (network error / timeout) is not a business failure: the
6544
7268
  // action did not run, and the panel has no second entry point for the engine
@@ -6566,7 +7290,7 @@ async function serveProxyAction(ctx, req, res, options) {
6566
7290
  // otherwise rely on the daemon to provide (review C2-P1-3).
6567
7291
  armLocalProxyCleanup()
6568
7292
  const engine = await startProxy(cwd)
6569
- const redirector = await startRedirectors()
7293
+ const redirector = await startRedirectors({ interactive })
6570
7294
  const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
6571
7295
  if (engine.ok === true) inheritedEngine = null
6572
7296
  result = Object.assign({}, engine, { redirector, git })
@@ -6662,6 +7386,7 @@ function windowsProgramNames() {
6662
7386
  // the picker silently drop every Windows entry. Cache it and give it room.
6663
7387
  const cached = windowsProgramCache
6664
7388
  if (cached !== null && Date.now() - cached.at < WINDOWS_PROGRAM_TTL_MS) return Promise.resolve(new Set(cached.names))
7389
+ if (windowsProgramProbe !== null) return Promise.resolve(new Set(windowsProgramProbe()))
6665
7390
  return new Promise((resolvePromise) => {
6666
7391
  const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
6667
7392
  'Get-Process | Select-Object -ExpandProperty ProcessName -Unique'], { windowsHide: true })
@@ -6683,6 +7408,22 @@ function windowsProgramNames() {
6683
7408
  /** Last successful Windows process list (the probe is too slow to repeat per open). */
6684
7409
  let windowsProgramCache = null
6685
7410
 
7411
+ /**
7412
+ * Test seam for the Windows process listing.
7413
+ *
7414
+ * The real probe spawns `powershell.exe` (3-4.5 s on WSL, and it enumerates the
7415
+ * developer's actual desktop). Tests that only need *some* names set this instead,
7416
+ * so a test run neither waits for PowerShell nor depends on what is running.
7417
+ * @type {null | (() => Iterable<string>)}
7418
+ */
7419
+ let windowsProgramProbe = null
7420
+
7421
+ /** Install (or clear, with `null`) the Windows program-listing probe used by tests. */
7422
+ export function setWindowsProgramProbe(probe) {
7423
+ windowsProgramProbe = typeof probe === 'function' ? probe : null
7424
+ windowsProgramCache = null
7425
+ }
7426
+
6686
7427
  /** Drop the cached Windows process list (tests, or after a program was installed). */
6687
7428
  export function resetWindowsProgramCache() {
6688
7429
  windowsProgramCache = null
@@ -10122,10 +10863,12 @@ export const __test = {
10122
10863
  setRisdBridge: (bridge) => { risdBridge = bridge },
10123
10864
  resolvePath,
10124
10865
  refreshDshWindows,
10866
+ rememberDshOrigin,
10125
10867
  detectCompanionPlugin,
10126
10868
  renderProgramList,
10127
10869
  windowsProgramNames,
10128
10870
  resetWindowsProgramCache,
10871
+ setWindowsProgramProbe,
10129
10872
  // Proxy rules + engine (the dialog's three routes).
10130
10873
  PROXY_PATH,
10131
10874
  RISD_ENSURE_PATH,
@@ -10327,6 +11070,7 @@ export const __test = {
10327
11070
  BUNDLE_PATH,
10328
11071
  WINDOW_PAGE_PATH,
10329
11072
  WINDOWS_PATH,
11073
+ WORKSPACES_PATH,
10330
11074
  serveWindows,
10331
11075
  listIdeWindows,
10332
11076
  liveSessionFor,
@@ -10356,6 +11100,8 @@ export const __test = {
10356
11100
  stageClipboardCopy,
10357
11101
  pruneClipboardStage,
10358
11102
  clipboardStageMapping,
11103
+ verifyClipboardStageOriginals,
11104
+ CLIPBOARD_STAGE_INTEGRITY_LOG,
10359
11105
  serveClipboardFiles,
10360
11106
  writeSystemFileClipboard,
10361
11107
  windowsClipboardScript,