dsh-ris-ide 1.8.1 → 1.8.3

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 (50) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +569 -98
  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 +963 -64
  7. package/lib/redirector.js +76 -4
  8. package/lib/risd/lifecycle.js +54 -10
  9. package/lib/risd/ping.js +136 -17
  10. package/lib/risd/server.js +424 -22
  11. package/lib/risd/ui.js +218 -129
  12. package/lib/risd-client.js +4 -1
  13. package/lib/startup.js +27 -7
  14. package/package.json +2 -2
  15. package/test/client-viewer.test.mjs +268 -93
  16. package/test/clipboard.test.mjs +259 -0
  17. package/test/debug-engine.test.mjs +3 -1
  18. package/test/dsh-origin.test.mjs +4 -11
  19. package/test/dsh-window-refresh.test.mjs +166 -1
  20. package/test/harness.test.mjs +1 -1
  21. package/test/helpers/cmd.mjs +29 -0
  22. package/test/helpers/tgz.mjs +71 -0
  23. package/test/host-search.test.mjs +18 -11
  24. package/test/host-tail.test.mjs +190 -25
  25. package/test/proxy-route.test.mjs +61 -0
  26. package/test/proxy-window.test.mjs +5 -0
  27. package/test/proxy.test.mjs +40 -11
  28. package/test/proxybridge-bundle.test.mjs +1 -59
  29. package/test/redirector-bundle.test.mjs +21 -67
  30. package/test/redirector.test.mjs +71 -4
  31. package/test/risd-api.test.mjs +83 -29
  32. package/test/risd-bridge-degrade.test.mjs +3 -29
  33. package/test/risd-cli-home.test.mjs +41 -4
  34. package/test/risd-engine.test.mjs +13 -50
  35. package/test/risd-entry.test.mjs +0 -37
  36. package/test/risd-follow-start.test.mjs +102 -0
  37. package/test/risd-git.test.mjs +7 -5
  38. package/test/risd-handoff.test.mjs +6 -50
  39. package/test/risd-helpers.mjs +150 -3
  40. package/test/risd-host-p2.test.mjs +2 -30
  41. package/test/risd-lifecycle.test.mjs +203 -33
  42. package/test/risd-ping.test.mjs +77 -1
  43. package/test/risd-programs.test.mjs +4 -34
  44. package/test/risd-review-p2.test.mjs +0 -13
  45. package/test/risd-shutdown.test.mjs +5 -38
  46. package/test/risd-teardown.test.mjs +8 -27
  47. package/test/risd-ui.test.mjs +205 -14
  48. package/test/risd-write.test.mjs +2 -1
  49. package/test/startup-reconcile.test.mjs +44 -8
  50. 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'
@@ -218,6 +218,8 @@ const TAIL_PATH = `${ROUTE_PREFIX}/tail`
218
218
  const STOP_PATH = `${ROUTE_PREFIX}/stop`
219
219
  const INSTANCES_PATH = `${ROUTE_PREFIX}/instances`
220
220
  const PROGRAMS_PATH = `${ROUTE_PREFIX}/programs`
221
+ /** Where a program's browser URL is resolved (dev server first, yds' injecting proxy second). */
222
+ const OPEN_TARGET_PATH = `${ROUTE_PREFIX}/open-target`
221
223
  /**
222
224
  * Server-sent events for what the panel otherwise polls: `programs` (the console
223
225
  * rows) and `tail` (one log file, pushed as it grows). One long-lived response per
@@ -259,6 +261,15 @@ const CLIPBOARD_MAX_PAYLOAD = 256 * 1024
259
261
  * restart without anyone announcing anything.
260
262
  */
261
263
  const WINDOWS_PATH = `${ROUTE_PREFIX}/windows`
264
+ /**
265
+ * `GET /dsh-ris-ide/workspaces` — this host's live sidebar snapshot (m00186).
266
+ *
267
+ * The daemon normally reads `dsh-window.json`, but that document is shared by every
268
+ * dsh on the machine and is only its last written answer. This route answers from
269
+ * the running host itself, so the page can stay usable while the document is
270
+ * missing, stale, or written by another instance.
271
+ */
272
+ const WORKSPACES_PATH = `${ROUTE_PREFIX}/workspaces`
262
273
  /** A window whose stream has been gone this long counts as closed. */
263
274
  const IDE_WINDOW_GRACE_MS = 90 * 1000
264
275
  /** Live IDE windows, keyed by workspace cwd (one IDE window per workspace). */
@@ -785,15 +796,233 @@ const DSH_WINDOW_FILENAME = 'dsh-window.json'
785
796
  const DSH_WINDOW_THROTTLE_MS = 3000
786
797
  /** Keep the list short: the page only needs the workspaces someone is working in. */
787
798
  const DSH_WINDOW_MAX_ENTRIES = 8
799
+ /** Upper bound for the registry snapshot: a machine with hundreds of workspaces must not bloat the file. */
800
+ const DSH_WINDOW_MAX_WORKSPACES = 50
788
801
  let dshWindowNote = { at: 0, host: '', sessionId: '', cwd: '' }
802
+ /**
803
+ * The last loopback origin a browser used to reach this host (m00186).
804
+ *
805
+ * dsh-window.json must name an origin the daemon page can embed, and for a while
806
+ * the only writer was a window request, so a dsh started without ever opening the
807
+ * IDE panel left no origin behind at all. Whatever address the bound server reports
808
+ * may also be a LAN IP while the page was opened on 127.0.0.1; the request's Host is
809
+ * the address that actually worked, so it wins.
810
+ */
811
+ let dshWindowOrigin = ''
812
+
813
+ /**
814
+ * Remember the origin of a loopback request. Called on every plugin route: a dsh
815
+ * page that only loads the sidebar is enough to teach the refresh tick where the
816
+ * IDE can be embedded (see {@link dshWindowOriginFor}).
817
+ * @param req - the incoming HTTP request.
818
+ */
819
+ function rememberDshOrigin(req) {
820
+ try {
821
+ // The same admission rule as every route: a cross-site request must not be able
822
+ // to point the daemon page's iframe at another host (review A-P2-10).
823
+ if (!isLoopbackRequest(req)) return
824
+ const host = String(req?.headers?.host ?? '')
825
+ if (host !== '') dshWindowOrigin = `http://${host}`
826
+ } catch { /* a malformed request keeps the previous origin */ }
827
+ }
828
+
829
+ /**
830
+ * The host's workspace registry, when this dsh version provides one.
831
+ *
832
+ * Read through `ctx.get` instead of the `inject` list: the plugin is installable on
833
+ * older hosts that have no workspace service, and a missing registry only costs the
834
+ * title (the daemon page falls back to the folder name).
835
+ * @param ctx - Host context.
836
+ * @returns the registry service, or null.
837
+ */
838
+ function workspaceRegistryOf(ctx) {
839
+ try {
840
+ const registry = ctx?.get?.('workspaceRegistry', false)
841
+ return registry !== null && typeof registry === 'object' && typeof registry.list === 'function' ? registry : null
842
+ } catch {
843
+ return null
844
+ }
845
+ }
846
+
847
+ /**
848
+ * One path spelling that can be compared across `dsh-window.json` rows, session
849
+ * headers and registry records: the real path when it still exists, else a lexical
850
+ * spelling without a trailing slash.
851
+ *
852
+ * The registry stores `fs.realpath` output, so a symlinked workspace path (or one
853
+ * with a trailing slash) must not cost the title.
854
+ * @param value - Candidate absolute path.
855
+ * @returns the canonical spelling, or `''`.
856
+ */
857
+ function canonicalWorkspacePath(value) {
858
+ const raw = typeof value === 'string' ? value : ''
859
+ if (raw === '') return ''
860
+ try {
861
+ return realpathSync.native(raw)
862
+ } catch { /* gone, or not a directory: compare lexically */ }
863
+ const trimmed = raw.replace(/[\\/]+$/, '')
864
+ return trimmed === '' ? raw : trimmed
865
+ }
866
+
867
+ /** Path → title index per host context; short TTL so a burst of IDE requests does
868
+ * not run `realpath` over every workspace on each one (a rename still lands within
869
+ * this window — a label two seconds late is invisible). */
870
+ const workspaceTitleIndexes = new WeakMap()
871
+ /** How long a resolved path → title index is reused. */
872
+ const WORKSPACE_TITLE_TTL_MS = 2000
873
+
874
+ /**
875
+ * Canonical path → sidebar title for one host context, cached briefly.
876
+ * @param ctx - Host context.
877
+ * @returns {Map<string, string>} the index (empty when there is no registry).
878
+ */
879
+ function workspaceTitleIndex(ctx) {
880
+ const now = Date.now()
881
+ const cached = typeof ctx === 'object' && ctx !== null ? workspaceTitleIndexes.get(ctx) : undefined
882
+ if (cached !== undefined && now - cached.at <= WORKSPACE_TITLE_TTL_MS) return cached.byPath
883
+ const byPath = new Map()
884
+ const registry = workspaceRegistryOf(ctx)
885
+ if (registry !== null) {
886
+ let listed
887
+ try {
888
+ listed = registry.list()
889
+ } catch {
890
+ listed = []
891
+ }
892
+ for (const workspace of Array.isArray(listed) ? listed : []) {
893
+ if (workspace === null || typeof workspace !== 'object') continue
894
+ const path = typeof workspace.path === 'string' ? workspace.path : ''
895
+ const key = canonicalWorkspacePath(path)
896
+ if (key === '') continue
897
+ byPath.set(key, typeof workspace.title === 'string' ? workspace.title : '')
898
+ }
899
+ }
900
+ if (typeof ctx === 'object' && ctx !== null) workspaceTitleIndexes.set(ctx, { at: now, byPath })
901
+ return byPath
902
+ }
903
+
904
+ /**
905
+ * Title sync has ONE key: the workspace path. Renaming a workspace only changes its
906
+ * `title` (dsh-workspace `setTitle` never touches `path`), so a path → title lookup
907
+ * keeps the daemon page's labels equal to the sidebar's after a rename (m13800).
908
+ * @param ctx - Host context.
909
+ * @param cwd - Workspace path as recorded in a window row.
910
+ * @returns the title, or `''` when unknown (older dsh, no registry, unknown path).
911
+ */
912
+ export function workspaceTitleFor(ctx, cwd) {
913
+ const wanted = canonicalWorkspacePath(cwd)
914
+ if (wanted === '') return ''
915
+ return workspaceTitleIndex(ctx).get(wanted) ?? ''
916
+ }
917
+
918
+ /**
919
+ * A session id the IDE can boot on for one workspace: dsh's live session for that
920
+ * cwd when there is one (`liveSessionFor`), else the last recorded session id, else
921
+ * `''` (the panel then opens the workspace without a session — the host routes fall
922
+ * back to the cwd).
923
+ * @param ctx - Host context.
924
+ * @param path - Workspace path.
925
+ * @param workspace - Registry entity.
926
+ * @returns a session id, possibly `''`.
927
+ */
928
+ function workspaceSessionFor(ctx, path, workspace) {
929
+ const live = liveSessionFor(ctx, path)
930
+ if (live !== null && typeof live.id === 'string' && live.id !== '') return live.id
931
+ try {
932
+ const ids = workspace?.sessionIds
933
+ if (Array.isArray(ids) && ids.length > 0 && typeof ids[ids.length - 1] === 'string') return ids[ids.length - 1]
934
+ } catch { /* a broken entity only costs the session */ }
935
+ return ''
936
+ }
937
+
938
+ /**
939
+ * Every workspace the dsh sidebar shows, in the user's own order, with its title.
940
+ *
941
+ * Written next to the window rows so the daemon page can mirror the sidebar even for
942
+ * a workspace nobody opened the IDE for yet, and so a rename reaches the page without
943
+ * anyone clicking in that workspace (m13800).
944
+ * @param ctx - Host context.
945
+ * @returns {Array<{cwd: string, title: string, sessionId: string, active: boolean}>}
946
+ */
947
+ export function dshWorkspaceRows(ctx) {
948
+ const registry = workspaceRegistryOf(ctx)
949
+ if (registry === null) return []
950
+ let listed
951
+ try {
952
+ listed = registry.list()
953
+ } catch {
954
+ return []
955
+ }
956
+ if (!Array.isArray(listed)) return []
957
+ const rows = []
958
+ for (const workspace of listed) {
959
+ if (rows.length >= DSH_WINDOW_MAX_WORKSPACES) break
960
+ if (workspace === null || typeof workspace !== 'object') continue
961
+ const path = typeof workspace.path === 'string' ? workspace.path : ''
962
+ if (path === '') continue
963
+ const sessionId = workspaceSessionFor(ctx, path, workspace)
964
+ rows.push({
965
+ cwd: path,
966
+ title: typeof workspace.title === 'string' ? workspace.title : '',
967
+ sessionId,
968
+ // Whether this workspace currently holds a live session. A workspace without
969
+ // one is still openable (the host routes fall back to the cwd), so this only
970
+ // feeds the page's per-row hint instead of gating the list (m00186).
971
+ active: sessionId !== '' && isLiveSession(ctx, sessionId),
972
+ })
973
+ }
974
+ return rows
975
+ }
976
+
977
+ /**
978
+ * The whole document `dsh-window.json` carries: remembered windows (where to embed
979
+ * the IDE), the sidebar's workspace list (what to call the entries) and the last
980
+ * answer this host gave. `at` proves the writer is still alive, so the daemon can
981
+ * drop the title snapshot when dsh has been gone for long enough.
982
+ * @param ctx - Host context.
983
+ * @param windows - The window rows about to be written.
984
+ * @param now - Epoch ms of the answer.
985
+ * @param url - The origin this host answered on (preferred over the newest row).
986
+ * @returns the document to persist.
987
+ */
988
+ function dshWindowDocument(ctx, windows, now, url) {
989
+ const origin = typeof url === 'string' && url !== ''
990
+ ? url
991
+ : (Array.isArray(windows) ? windows.reduce((found, row) => found !== '' ? found : (row !== null && typeof row === 'object' && typeof row.url === 'string' ? row.url : ''), '') : '')
992
+ return {
993
+ windows: Array.isArray(windows) ? windows : [],
994
+ workspaces: dshWorkspaceRows(ctx),
995
+ url: origin,
996
+ at: new Date(now).toISOString(),
997
+ }
998
+ }
999
+
1000
+ /**
1001
+ * The origin the daemon page should embed the IDE at: the address a browser really
1002
+ * used when one has ever reached this host, else the address the server is bound to.
1003
+ * @param ctx - Host context.
1004
+ * @returns `http://host:port`, or `''` when neither is known (an old host whose
1005
+ * server is not bound yet, and no page has been served).
1006
+ */
1007
+ function dshWindowOriginFor(ctx) {
1008
+ if (dshWindowOrigin !== '') return dshWindowOrigin
1009
+ try {
1010
+ // getOrigin() throws before the server is bound; the timer can fire that early,
1011
+ // and a missing method on an older host must only cost the origin.
1012
+ const origin = ctx?.webServer?.getOrigin?.()
1013
+ if (typeof origin === 'string' && origin !== '') return origin
1014
+ } catch { /* not bound yet */ }
1015
+ return ''
1016
+ }
789
1017
 
790
1018
  /**
791
1019
  * Upsert one dsh window record (origin + sessionId per workspace). A daemon page
792
1020
  * can then offer every workspace's IDE in one window instead of one page per cwd.
793
1021
  * Loopback Hosts only, best effort, never throws.
1022
+ * @param ctx - Host context (workspace titles for the daemon page's labels).
794
1023
  * @param req - the incoming HTTP request.
795
1024
  */
796
- function noteDshWindow(req) {
1025
+ function noteDshWindow(ctx, req) {
797
1026
  // `node --test` runs against the developer's real home unless a test isolates
798
1027
  // DSH_RIS_IDE_PROXY_HOME. Fake contexts with /tmp workspaces used to collect
799
1028
  // entries in dsh-window.json and the daemon page listed them as workspaces
@@ -846,6 +1075,11 @@ function noteDshWindow(req) {
846
1075
  url: `http://${host}`,
847
1076
  sessionId,
848
1077
  cwd,
1078
+ // The sidebar's title for this path (m13800). Renaming only changes the title,
1079
+ // so the daemon page can label a workspace the way dsh does and follow a rename
1080
+ // without losing the workspace; '' means "no registry on this host" and the page
1081
+ // falls back to the folder name.
1082
+ title: workspaceTitleFor(ctx, cwd),
849
1083
  // Which plugin process wrote this row: another dsh (same home) refreshes and
850
1084
  // prunes only its own rows (review C2-P2-2).
851
1085
  ownerPid: process.pid,
@@ -855,35 +1089,97 @@ function noteDshWindow(req) {
855
1089
  windows.unshift(entry)
856
1090
  const trimmed = windows.slice(0, DSH_WINDOW_MAX_ENTRIES)
857
1091
  // 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 })
1092
+ // (review C2-P2-1 / A2-P2-17). The document also carries the sidebar's workspace
1093
+ // list (title per path) and the origin that answered (m13800).
1094
+ writeStateAtomic(path, dshWindowDocument(ctx, trimmed, now, `http://${host}`))
860
1095
  } catch { /* the daemon page simply greys the IDE tab out */ }
861
1096
  }
862
1097
  /** How often the plugin refreshes the liveness of remembered dsh windows. */
863
1098
  const DSH_WINDOW_REFRESH_MS = 10_000
864
1099
 
1100
+ /**
1101
+ * Whether two sidebar snapshots say the same thing, in the same order.
1102
+ *
1103
+ * Order is the dsh sidebar's own order, so it is part of the equality: a reordered
1104
+ * sidebar is a new truth for the daemon page, not a cosmetic difference.
1105
+ * @param left - Rows about to be written.
1106
+ * @param right - Rows already on disk.
1107
+ * @returns whether a write would change nothing.
1108
+ */
1109
+ function sameWorkspaceRows(left, right) {
1110
+ if (!Array.isArray(left) || !Array.isArray(right)) return false
1111
+ if (left.length !== right.length) return false
1112
+ for (let index = 0; index < left.length; index += 1) {
1113
+ const a = left[index]
1114
+ const b = right[index]
1115
+ if (a === null || typeof a !== 'object' || b === null || typeof b !== 'object') return false
1116
+ const aCwd = typeof a.cwd === 'string' ? a.cwd : ''
1117
+ const bCwd = typeof b.cwd === 'string' ? b.cwd : ''
1118
+ const aTitle = typeof a.title === 'string' ? a.title : ''
1119
+ const bTitle = typeof b.title === 'string' ? b.title : ''
1120
+ const aSession = typeof a.sessionId === 'string' ? a.sessionId : ''
1121
+ const bSession = typeof b.sessionId === 'string' ? b.sessionId : ''
1122
+ if (aCwd !== bCwd || aTitle !== bTitle || aSession !== bSession) return false
1123
+ }
1124
+ return true
1125
+ }
1126
+
865
1127
  /**
866
1128
  * Keep the remembered windows' `at` fresh while dsh still knows their session, so
867
1129
  * the daemon page lists every workspace that is currently open instead of only the
868
1130
  * one that happened to hit an endpoint within the freshness window (m08228).
869
1131
  * The plugin is the only writer of dsh-window.json; a daemon-side timer cannot
870
1132
  * 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.
1133
+ *
1134
+ * Since m00186 this tick also publishes the sidebar's workspace list and this host's
1135
+ * origin on its own, even before any window row exists: a dsh started as a service
1136
+ * (or simply never asked for the IDE panel) used to leave the daemon page stuck at
1137
+ * 「dsh 未运行(没有记住的工作区窗口)」 although dsh was running. The mirror of the
1138
+ * registry is enough for that page to offer every workspace and switch between them.
1139
+ * @param ctx - Host context (`ctx.sessions.get(id)`, workspace registry).
1140
+ * @returns {{changed:number, windows:number, dropped:number}} how many entries were refreshed.
873
1141
  */
874
1142
  export function refreshDshWindows(ctx) {
875
1143
  const result = { changed: 0, windows: 0, dropped: 0 }
876
1144
  try {
877
1145
  const path = join(proxyHomeDir(), DSH_WINDOW_FILENAME)
1146
+ let document = null
878
1147
  let windows = []
1148
+ let sidebar = []
1149
+ let documentOrigin = ''
1150
+ let documentAt = Number.NaN
879
1151
  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
1152
+ document = JSON.parse(readFileSync(path, 'utf8'))
1153
+ if (Array.isArray(document?.windows)) windows = document.windows
1154
+ if (Array.isArray(document?.workspaces)) sidebar = document.workspaces
1155
+ if (typeof document?.url === 'string') documentOrigin = document.url
1156
+ documentAt = Date.parse(String(document?.at ?? ''))
1157
+ } catch { /* absent or unreadable: this tick may write the first version */ }
884
1158
  const now = Date.now()
1159
+ // The sidebar mirror is news even when no window row exists, and it can only be
1160
+ // produced while this process still holds the registry — which is exactly the
1161
+ // liveness the document's `at` promises to the daemon.
1162
+ const mirror = dshWorkspaceRows(ctx)
1163
+ const origin = dshWindowOriginFor(ctx)
885
1164
  const canVerify = typeof ctx?.sessions?.get === 'function'
886
1165
  let dirty = false
1166
+ /**
1167
+ * Re-resolve one row's sidebar title (m13800). A rename never touches the path,
1168
+ * so the path keeps the row and only the label moves — and it moves even while
1169
+ * nobody is working in that workspace, because this timer keeps running.
1170
+ * @param row - A window row that belongs to this process.
1171
+ * @returns the row, with a fresh/removed `title` when it changed.
1172
+ */
1173
+ const retitle = (row) => {
1174
+ const title = workspaceTitleFor(ctx, typeof row.cwd === 'string' ? row.cwd : '')
1175
+ const current = typeof row.title === 'string' ? row.title : ''
1176
+ if (title === current) return row
1177
+ dirty = true
1178
+ const next = Object.assign({}, row)
1179
+ if (title === '') delete next.title
1180
+ else next.title = title
1181
+ return next
1182
+ }
887
1183
  const next = windows.reduce((out, row) => {
888
1184
  if (row === null || typeof row !== 'object') return out
889
1185
  // Another dsh process owns this row (same machine-level home): its own plugin
@@ -897,7 +1193,7 @@ export function refreshDshWindows(ctx) {
897
1193
  const sessionId = typeof row.sessionId === 'string' ? row.sessionId : ''
898
1194
  // An empty session id cannot be verified (legacy rows); keep it and let the
899
1195
  // daemon's retain TTL retire it.
900
- if (sessionId === '' || !canVerify) { out.push(row); return out }
1196
+ if (sessionId === '' || !canVerify) { out.push(retitle(row)); return out }
901
1197
  const session = ctx.sessions.get(sessionId)
902
1198
  const sessionCwd = typeof session?.header?.cwd === 'string' ? session.header.cwd : ''
903
1199
  // "Session exists" is not enough: a session may have been reopened on another
@@ -909,16 +1205,75 @@ export function refreshDshWindows(ctx) {
909
1205
  }
910
1206
  dirty = true
911
1207
  result.changed += 1
912
- out.push(Object.assign({}, row, { at: new Date(now).toISOString() }))
1208
+ out.push(Object.assign({}, retitle(row), { at: new Date(now).toISOString() }))
913
1209
  return out
914
1210
  }, [])
915
1211
  // Report the surviving size: the pre-prune number misled callers/tests (review E P2-2).
916
1212
  result.windows = next.length
917
- if (dirty) writeStateAtomic(path, { windows: next })
1213
+ // Write when a window row changed, when the sidebar snapshot (title/order/session)
1214
+ // changed, or when there is something to keep alive and this tick is the first to
1215
+ // publish it / learned the origin / has to re-stamp `at`. When BOTH halves are
1216
+ // empty there is nothing to offer: this process must not create the document, or
1217
+ // an older host sharing the home would erase a newer instance's snapshot.
1218
+ const keepAlive = mirror.length > 0 || next.length > 0
1219
+ // An empty mirror means "this host cannot list workspaces", not "the sidebar is
1220
+ // empty": an older dsh sharing the home has no registry and must not publish an
1221
+ // empty list over another instance's snapshot. A real shrink (some workspaces
1222
+ // left, none right) is still news, because the mirror itself is non-empty.
1223
+ const mirrorChanged = mirror.length > 0 && !sameWorkspaceRows(mirror, sidebar)
1224
+ const originChanged = origin !== '' && origin !== documentOrigin
1225
+ const documentAgeMs = Number.isFinite(documentAt) ? now - documentAt : Number.POSITIVE_INFINITY
1226
+ if (dirty || mirrorChanged || (keepAlive && (document === null || originChanged || documentAgeMs >= DSH_WINDOW_REFRESH_MS))) {
1227
+ // The document also carries the sidebar's workspace list + the origin (m13800);
1228
+ // an empty origin falls back to the newest window row inside the helper.
1229
+ writeStateAtomic(path, dshWindowDocument(ctx, next, now, origin))
1230
+ }
1231
+ // Advertise this live host on its own origin file (m00186): the shared document
1232
+ // is a single last-writer snapshot, so a daemon that cannot use it must still be
1233
+ // able to ask a running dsh directly instead of declaring it gone.
1234
+ if (origin !== '') publishDshInstance(now, origin)
918
1235
  } catch { /* best effort: the page keeps showing what it last knew */ }
919
1236
  return result
920
1237
  }
921
1238
 
1239
+ /**
1240
+ * Where a running plugin advertises its origin: `instances/dsh-<pid>.json`
1241
+ * (m00186). The shared `dsh-window.json` is one last-writer snapshot and cannot
1242
+ * name two live hosts; one file per pid lets the daemon probe each of them.
1243
+ */
1244
+ const DSH_INSTANCE_DIRNAME = 'instances'
1245
+ /** An instance file this old belongs to a process that is gone (or a reused pid). */
1246
+ const DSH_INSTANCE_RETAIN_MS = 24 * 60 * 60 * 1000
1247
+
1248
+ /**
1249
+ * Publish (or refresh) this process's origin file. Best effort: a read-only home
1250
+ * only costs the daemon's direct-probe path — the shared document still carries an
1251
+ * origin whenever a browser reaches this host.
1252
+ * @param now - Epoch ms of this refresh tick.
1253
+ * @param origin - Loopback origin this host answers on.
1254
+ */
1255
+ function publishDshInstance(now, origin) {
1256
+ try {
1257
+ const dir = join(proxyHomeDir(), DSH_INSTANCE_DIRNAME)
1258
+ writeStateAtomic(join(dir, `dsh-${process.pid}.json`), {
1259
+ pid: process.pid,
1260
+ url: origin,
1261
+ at: new Date(now).toISOString(),
1262
+ })
1263
+ // A crashed dsh never deletes its own file, so drop the ones nothing can own now:
1264
+ // a short candidate list keeps the daemon's probes cheap.
1265
+ for (const name of readdirSync(dir)) {
1266
+ if (!/^dsh-\d+\.json$/.test(name) || name === `dsh-${process.pid}.json`) continue
1267
+ try {
1268
+ const parsed = JSON.parse(readFileSync(join(dir, name), 'utf8'))
1269
+ const at = Date.parse(String(parsed?.at ?? ''))
1270
+ if (Number.isFinite(at) && now - at <= DSH_INSTANCE_RETAIN_MS) continue
1271
+ } catch { /* half-written: nobody can use it */ }
1272
+ try { rmSync(join(dir, name), { force: true }) } catch { /* best effort */ }
1273
+ }
1274
+ } catch { /* best effort: see the doc comment */ }
1275
+ }
1276
+
922
1277
  export function handleRequest(ctx, req, res, options) {
923
1278
  try {
924
1279
  dispatchRequest(ctx, req, res, options)
@@ -935,7 +1290,10 @@ export function handleRequest(ctx, req, res, options) {
935
1290
 
936
1291
  /** The actual router behind {@link handleRequest}'s exception fence. */
937
1292
  function dispatchRequest(ctx, req, res, options) {
938
- noteDshWindow(req)
1293
+ // Any request from the dsh page is proof of the origin to advertise — not just a
1294
+ // window request (`noteDshWindow` needs ?sessionId=&?cwd= and may never come).
1295
+ rememberDshOrigin(req)
1296
+ noteDshWindow(ctx, req)
939
1297
  const method = req.method ?? 'GET'
940
1298
  const pathname = requestPathname(req)
941
1299
  if (pathname === WINDOWS_PATH) {
@@ -946,6 +1304,14 @@ function dispatchRequest(ctx, req, res, options) {
946
1304
  serveSafely(res, () => serveWindows(ctx, req, res))
947
1305
  return
948
1306
  }
1307
+ if (pathname === WORKSPACES_PATH) {
1308
+ if (method !== 'GET') {
1309
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1310
+ return
1311
+ }
1312
+ serveSafely(res, () => serveWorkspaces(ctx, req, res))
1313
+ return
1314
+ }
949
1315
  if (pathname === WINDOW_PAGE_PATH) {
950
1316
  if (method !== 'GET') {
951
1317
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -1064,6 +1430,14 @@ function dispatchRequest(ctx, req, res, options) {
1064
1430
  serveSafely(res, () => servePrograms(ctx, req, res, options))
1065
1431
  return
1066
1432
  }
1433
+ if (pathname === OPEN_TARGET_PATH) {
1434
+ if (method !== 'GET') {
1435
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1436
+ return
1437
+ }
1438
+ serveSafely(res, () => serveOpenTarget(ctx, req, res, options))
1439
+ return
1440
+ }
1067
1441
  if (pathname === START_PATH) {
1068
1442
  if (method !== 'POST') {
1069
1443
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
@@ -1219,16 +1593,51 @@ function dispatchRequest(ctx, req, res, options) {
1219
1593
  }
1220
1594
 
1221
1595
  /**
1222
- * True once a `git` spawn failed with ENOENT: a bare machine may not have git,
1223
- * and the plugin must still list/search files instead of showing an empty tree.
1596
+ * When the plugin stops trusting `git` (epoch ms; 0 = git is fine).
1597
+ *
1598
+ * A spawn error with ENOENT does NOT prove git is missing: node reports a
1599
+ * missing executable and a DELETED cwd identically (`error.path === 'git'`,
1600
+ * `errno === -2`). The plugin runs git inside tree folders, so one folder
1601
+ * deleted mid-command used to latch a module-level boolean forever — from then
1602
+ * on every tree answered `git:false`, the .gitignore filter was off and its
1603
+ * toggle greyed out, with no way back short of restarting dsh.
1604
+ * A failed spawn now only starts a short quarantine and a probe run from a
1605
+ * directory that always exists has to confirm the binary really is gone; any
1606
+ * later successful git command clears the verdict immediately.
1224
1607
  */
1225
- let gitMissing = false
1608
+ let gitMissingUntil = 0
1609
+
1610
+ /** How long one confirmed "git is absent" verdict is trusted before re-trying. */
1611
+ const GIT_MISSING_TTL_MS = 60_000
1612
+
1613
+ /** Whether git is currently assumed to be absent (the .gitignore filter is off). */
1614
+ function gitUnavailable() {
1615
+ return Date.now() < gitMissingUntil
1616
+ }
1226
1617
 
1227
1618
  /** Whether a spawn/exec error means the executable itself is absent. */
1228
1619
  function isMissingExecutable(error) {
1229
1620
  return error !== undefined && error !== null && (error.code === 'ENOENT' || error.errno === -2)
1230
1621
  }
1231
1622
 
1623
+ /**
1624
+ * A git spawn failed with ENOENT: decide whether git itself is gone.
1625
+ *
1626
+ * The probe runs from `tmpdir()` — a cwd that exists even when the tree folder
1627
+ * that triggered the failure does not. If git answers there, the failure was
1628
+ * the caller's cwd and git stays trusted.
1629
+ */
1630
+ function noteGitSpawnFailure() {
1631
+ const probe = spawnSync('git', ['--version'], { cwd: tmpdir(), windowsHide: true, timeout: 4000, stdio: 'ignore' })
1632
+ const missing = probe.error !== undefined ? isMissingExecutable(probe.error) : probe.status !== 0
1633
+ if (missing) gitMissingUntil = Date.now() + GIT_MISSING_TTL_MS
1634
+ }
1635
+
1636
+ /** A git command answered: git is usable wherever the last failure came from. */
1637
+ function noteGitSuccess() {
1638
+ gitMissingUntil = 0
1639
+ }
1640
+
1232
1641
  /** Run one git command and return its stdout (rejects on a non-zero exit). */
1233
1642
  function runGit(args, cwd, input) {
1234
1643
  return new Promise((resolvePromise, rejectPromise) => {
@@ -1239,7 +1648,7 @@ function runGit(args, cwd, input) {
1239
1648
  child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8') })
1240
1649
  child.stderr?.on('data', (chunk) => { if (stderr.length < 8192) stderr += chunk.toString('utf8') })
1241
1650
  child.on('error', (error) => {
1242
- if (isMissingExecutable(error)) gitMissing = true
1651
+ if (isMissingExecutable(error)) noteGitSpawnFailure()
1243
1652
  if (!settled) { settled = true; rejectPromise(error) }
1244
1653
  })
1245
1654
  if (input !== undefined) {
@@ -1250,8 +1659,10 @@ function runGit(args, cwd, input) {
1250
1659
  settled = true
1251
1660
  // `git check-ignore` exits 1 when nothing matched, and `git grep` exits 1
1252
1661
  // when the pattern has no match; both are valid answers, not failures.
1253
- if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) resolvePromise(stdout)
1254
- else rejectPromise(new Error(stderr || `git exited with ${code}`))
1662
+ if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) {
1663
+ noteGitSuccess()
1664
+ resolvePromise(stdout)
1665
+ } else rejectPromise(new Error(stderr || `git exited with ${code}`))
1255
1666
  })
1256
1667
  })
1257
1668
  }
@@ -1507,7 +1918,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
1507
1918
  const needle = String(query ?? '')
1508
1919
  const roots = await searchRoots(cwd)
1509
1920
  if (needle === '') return { hits: [], truncated: false, roots, files: 0 }
1510
- if (roots.length === 0 || gitMissing) {
1921
+ if (roots.length === 0 || gitUnavailable()) {
1511
1922
  return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1512
1923
  }
1513
1924
  const hits = []
@@ -1520,7 +1931,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
1520
1931
  } catch {
1521
1932
  // A root whose git call failed is not fatal (and git may have disappeared
1522
1933
  // mid-search): fall back to the filesystem walk for the whole request.
1523
- if (gitMissing) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1934
+ if (gitUnavailable()) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1524
1935
  continue
1525
1936
  }
1526
1937
  for (const raw of stdout.split('\n')) {
@@ -1601,7 +2012,7 @@ function streamGitStdout(args, cwd, onText, stream) {
1601
2012
  else rejectPromise(error)
1602
2013
  }
1603
2014
  child.on('error', (error) => {
1604
- if (isMissingExecutable(error)) gitMissing = true
2015
+ if (isMissingExecutable(error)) noteGitSpawnFailure()
1605
2016
  settle(error)
1606
2017
  })
1607
2018
  child.on('close', (code) => {
@@ -1609,7 +2020,7 @@ function streamGitStdout(args, cwd, onText, stream) {
1609
2020
  // error: treating it as one made every fallback walk the whole root again.
1610
2021
  if (child.killed === true) settle(undefined)
1611
2022
  else if (stream !== undefined && stream.aborted === true) settle(undefined)
1612
- else if (code === 0 || code === 1) settle(undefined)
2023
+ else if (code === 0 || code === 1) { noteGitSuccess(); settle(undefined) }
1613
2024
  else settle(new Error(stderr || `git exited with ${code}`))
1614
2025
  })
1615
2026
  })
@@ -1799,7 +2210,7 @@ async function searchWorkspaceFilesStream(cwd, roots, query, options) {
1799
2210
  if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) return
1800
2211
  emitter.push(index, [path])
1801
2212
  }
1802
- if (roots.length === 0 || gitMissing === true) {
2213
+ if (roots.length === 0 || gitUnavailable()) {
1803
2214
  // No repo anywhere (or no git binary): walk and page the fallback listing.
1804
2215
  const all = await listRawFiles(cwd)
1805
2216
  const matches = []
@@ -1863,7 +2274,7 @@ async function searchWorkspaceContentStream(cwd, roots, query, options) {
1863
2274
  paths.add(hit.path)
1864
2275
  emitter.push(index, [hit])
1865
2276
  }
1866
- if (roots.length === 0 || gitMissing === true) {
2277
+ if (roots.length === 0 || gitUnavailable()) {
1867
2278
  const fallback = await searchContentRaw(cwd, needle, limit, perFile)
1868
2279
  const hits = fallback.hits
1869
2280
  for (let offset = 0; offset < hits.length; offset += pageSize) onPage(hits.slice(offset, offset + pageSize))
@@ -2182,7 +2593,7 @@ async function findGitRoot(from, stopAt) {
2182
2593
  async function repoAllowedPaths(root) {
2183
2594
  // No git installed (or a broken repo): return undefined so callers fall back to
2184
2595
  // "the filesystem is the whitelist" instead of hiding every file.
2185
- if (gitMissing) return undefined
2596
+ if (gitUnavailable()) return undefined
2186
2597
  const cached = TREE_ALLOWED_CACHE.get(root)
2187
2598
  if (cached !== undefined && Date.now() - cached.at < TREE_ALLOWED_TTL_MS) return cached.value
2188
2599
  const files = new Set()
@@ -2462,7 +2873,7 @@ async function listIdeTree(target, cwd, options) {
2462
2873
  // `git`: a repo (and a working git) is behind this path; `filtered`: the
2463
2874
  // listing currently applies .gitignore. The client's title-bar toggle reads
2464
2875
  // both (no git → nothing to toggle; git → default ON).
2465
- git: repo !== undefined && gitMissing !== true,
2876
+ git: repo !== undefined && gitUnavailable() !== true,
2466
2877
  filtered: allowed !== undefined,
2467
2878
  }
2468
2879
  }
@@ -3202,12 +3613,88 @@ function serveSafely(res, run) {
3202
3613
  })
3203
3614
  }
3204
3615
 
3616
+ /** How long the known-workspace path list is reused before it is rebuilt. */
3617
+ const KNOWN_WORKSPACES_TTL_MS = 2000
3618
+ /** `ctx` → `{ at, paths }`: the last {@link knownWorkspacePaths} answer per host. */
3619
+ const KNOWN_WORKSPACES_CACHE = new WeakMap()
3620
+
3621
+ /**
3622
+ * Paths of every workspace this host knows: the dsh workspace registry plus the
3623
+ * window/workspace rows the plugin itself stamped into `dsh-window.json`. Cached
3624
+ * because {@link resolveCwd} runs on nearly every `/fs` and `/tail` request.
3625
+ *
3626
+ * Both sources are "this machine's workspaces as dsh shows them", never an
3627
+ * arbitrary absolute path: a page may only widen its fence to a workspace dsh
3628
+ * itself has registered (see {@link insideKnownWorkspace}).
3629
+ * @param ctx - Host context carrying the workspace registry.
3630
+ * @returns canonical absolute workspace paths.
3631
+ */
3632
+ function knownWorkspacePaths(ctx) {
3633
+ const cached = KNOWN_WORKSPACES_CACHE.get(ctx)
3634
+ if (cached !== undefined && Date.now() - cached.at < KNOWN_WORKSPACES_TTL_MS) return cached.paths
3635
+ const paths = new Set()
3636
+ const add = (value) => {
3637
+ if (typeof value !== 'string' || value === '' || !isAbsolute(value)) return
3638
+ paths.add(canonicalWorkspacePath(value))
3639
+ }
3640
+ try {
3641
+ const registry = workspaceRegistryOf(ctx)
3642
+ const rows = registry === undefined ? [] : registry.list()
3643
+ for (const row of Array.isArray(rows) ? rows : []) add(row !== null && typeof row === 'object' ? row.path : row)
3644
+ } catch {
3645
+ // No workspace registry on this host: the dsh-window rows below still count.
3646
+ }
3647
+ try {
3648
+ const document = JSON.parse(readFileSync(join(proxyHomeDir(), DSH_WINDOW_FILENAME), 'utf8'))
3649
+ for (const key of ['windows', 'workspaces']) {
3650
+ const rows = Array.isArray(document?.[key]) ? document[key] : []
3651
+ for (const row of rows) add(row !== null && typeof row === 'object' ? row.cwd : row)
3652
+ }
3653
+ } catch {
3654
+ // No remembered windows yet (first run / another user's home).
3655
+ }
3656
+ const list = Array.from(paths)
3657
+ KNOWN_WORKSPACES_CACHE.set(ctx, { at: Date.now(), paths: list })
3658
+ return list
3659
+ }
3660
+
3661
+ /**
3662
+ * Whether `target` is one of this host's workspaces or lives inside one.
3663
+ *
3664
+ * The realpath form is checked too: a registered path is canonical while the page
3665
+ * may still spell a symlinked ancestor, and a copy source that exists resolves to
3666
+ * the same inode either way.
3667
+ * @param ctx - Host context carrying the workspace registry.
3668
+ * @param target - absolute, already normalized path.
3669
+ * @returns whether the path belongs to a known workspace.
3670
+ */
3671
+ function insideKnownWorkspace(ctx, target) {
3672
+ const roots = knownWorkspacePaths(ctx)
3673
+ if (roots.length === 0) return false
3674
+ const lexical = (root) => target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)
3675
+ if (roots.some(lexical)) return true
3676
+ let real = ''
3677
+ try {
3678
+ real = realpathSync.native(target)
3679
+ } catch {
3680
+ return false
3681
+ }
3682
+ return roots.some((root) => real === root || real.startsWith(root.endsWith(sep) ? root : `${root}${sep}`))
3683
+ }
3684
+
3205
3685
  /**
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`.
3686
+ * The working directory a request runs against, from the live session header or
3687
+ * the caller-supplied absolute cwd — the page acts on the workspace it SHOWS.
3688
+ *
3689
+ * The header used to win unconditionally. A window opened while dsh was switching
3690
+ * workspaces can show workspace A while carrying a session whose header names B
3691
+ * (the header button fell back to the last workspace, or the window kept a session
3692
+ * from another workspace), and every mutation in A's tree then died with
3693
+ * 「不能对工作区之外的路径执行新建文件夹」. When the declared cwd is a workspace this
3694
+ * host knows, the page is inside its own rights and the declared cwd wins; any
3695
+ * other declared cwd keeps the header fence (it is never a licence for an
3696
+ * arbitrary absolute path).
3697
+ * @param ctx - Host context carrying `sessions` and the workspace registry.
3211
3698
  * @param sessionId - owning Session identity.
3212
3699
  * @param clientCwd - optional absolute cwd from the browser.
3213
3700
  * @returns the absolute working directory.
@@ -3215,8 +3702,14 @@ function serveSafely(res, run) {
3215
3702
  function resolveCwd(ctx, sessionId, clientCwd) {
3216
3703
  const session = ctx.sessions?.get?.(sessionId)
3217
3704
  const headerCwd = session?.header?.cwd
3218
- if (typeof headerCwd === 'string' && headerCwd !== '') return headerCwd
3219
- if (typeof clientCwd === 'string' && clientCwd !== '' && isAbsolute(clientCwd)) return clientCwd
3705
+ const header = typeof headerCwd === 'string' && headerCwd !== '' ? headerCwd : ''
3706
+ const declared = typeof clientCwd === 'string' && clientCwd !== '' && isAbsolute(clientCwd) ? clientCwd : ''
3707
+ // Same answer as the header costs nothing: leave the registry/file read to the
3708
+ // requests that actually disagree (the workspace-switch case).
3709
+ if (declared !== '' && declared === header) return header
3710
+ if (declared !== '' && insideKnownWorkspace(ctx, declared)) return declared
3711
+ if (header !== '') return header
3712
+ if (declared !== '') return declared
3220
3713
  throw new TailError('bad-request', `no working directory for session "${sessionId}"`, 400)
3221
3714
  }
3222
3715
 
@@ -3473,6 +3966,92 @@ function describe(error) {
3473
3966
  * @param res - Node response face.
3474
3967
  * @param options - `{ restrictToCwd }` (see {@link apply}).
3475
3968
  */
3969
+ /**
3970
+ * Resolve the URL "open in browser" should use for one program.
3971
+ *
3972
+ * Two sources, in this order: the dev-server URL the program printed into its own
3973
+ * log (webpack/vite always do), then dsh-ris-yds' injecting proxy — which is only
3974
+ * used when that plugin answers, so ris-ide keeps working without it.
3975
+ */
3976
+ async function serveOpenTarget(ctx, req, res, options) {
3977
+ try {
3978
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
3979
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
3980
+ const sessionId = url.searchParams.get('sessionId') ?? ''
3981
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3982
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
3983
+ const rawDir = url.searchParams.get('dir')
3984
+ const logsDir = resolvePath(cwd, typeof rawDir === 'string' && rawDir !== '' ? rawDir : 'logs', true)
3985
+ const wanted = { id: url.searchParams.get('id') ?? '', name: url.searchParams.get('name') ?? '' }
3986
+ let program = await findProgramById(cwd, logsDir, wanted)
3987
+ if (program === null) throw new TailError('not-found', `没有找到程序「${wanted.id || wanted.name}」,刷新程序列表后再试`, 404)
3988
+ const devUrl = await logUrl(program.logPath)
3989
+ if (devUrl === undefined) {
3990
+ writeJson(res, 200, {
3991
+ ok: false,
3992
+ code: 'no-url',
3993
+ message: '这个程序还没打印出访问地址:先启动它,日志里出现 Local: http://localhost:<端口> 后再点',
3994
+ })
3995
+ return
3996
+ }
3997
+ // Preferred path for a yds project: yds starts its private debugging browser
3998
+ // (extension preloaded, CDP on). The page there carries rdbga, so its requests
3999
+ // reach the local backend; the old loopback proxy only rewrites the bundles.
4000
+ const debug = await askYdsToWrap(req, cwd, devUrl, { mode: 'debug' })
4001
+ if (debug !== null && debug.ok === true && debug.mode === 'debug') {
4002
+ writeJson(res, 200, debug)
4003
+ return
4004
+ }
4005
+ const wrapped = await askYdsToWrap(req, cwd, devUrl)
4006
+ if (wrapped !== null) {
4007
+ if (wrapped.ok === true) writeJson(res, 200, wrapped)
4008
+ else writeJson(res, 200, { ok: false, code: wrapped.code ?? 'yds', message: wrapped.reason ?? 'dsh-ris-yds 无法代理这个地址' })
4009
+ return
4010
+ }
4011
+ writeJson(res, 200, { ok: true, url: devUrl, source: 'dev-server' })
4012
+ } catch (error) {
4013
+ writeTailError(res, error)
4014
+ }
4015
+ }
4016
+
4017
+ /** One program by id (config first, then a scan): the browser URL lives on its log. */
4018
+ async function findProgramById(cwd, logsDir, ref) {
4019
+ const config = await readProgramConfig(cwd)
4020
+ if (config.exists === true && config.entries.length > 0) {
4021
+ const fromConfig = programsFromConfigEntries(cwd, config.entries, config.defaults)
4022
+ const hit = resolveProgramRef(await decoratePrograms(cwd, logsDir, fromConfig), ref)
4023
+ if (hit !== undefined) return hit
4024
+ }
4025
+ const scanned = await scanPrograms(cwd, logsDir, false).catch(() => [])
4026
+ return resolveProgramRef(scanned, ref) ?? null
4027
+ }
4028
+
4029
+ /**
4030
+ * Ask dsh-ris-yds to serve this URL through its injecting proxy.
4031
+ * @returns {Promise<object|null>} the yds answer, or null when the plugin is absent.
4032
+ */
4033
+ async function askYdsToWrap(req, cwd, devUrl, options = {}) {
4034
+ const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4035
+ if (host === '') return null
4036
+ const controller = new AbortController()
4037
+ const timer = setTimeout(() => controller.abort(), 5000)
4038
+ try {
4039
+ const response = await fetch(`http://${host}/dsh-ris-yds/open`, {
4040
+ method: 'POST',
4041
+ headers: { 'content-type': 'application/json' },
4042
+ body: JSON.stringify({ workspace: cwd, devUrl, ...(options.mode === 'debug' ? { mode: 'debug' } : {}) }),
4043
+ signal: controller.signal,
4044
+ })
4045
+ if (response.status === 404) return null
4046
+ const parsed = await response.json().catch(() => null)
4047
+ return parsed === null ? null : parsed
4048
+ } catch {
4049
+ return null
4050
+ } finally {
4051
+ clearTimeout(timer)
4052
+ }
4053
+ }
4054
+
3476
4055
  async function servePrograms(ctx, req, res, options) {
3477
4056
  try {
3478
4057
  if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
@@ -3689,6 +4268,19 @@ async function serveFsOp(ctx, req, res, options) {
3689
4268
  const base = root.endsWith(sep) ? root : `${root}${sep}`
3690
4269
  if (!target.startsWith(base)) throw new TailError('outside-workspace', `不能对工作区之外的路径执行${action}`, 403)
3691
4270
  }
4271
+ /**
4272
+ * A COPY may read from another workspace: the tree keeps absolute source paths
4273
+ * after the user switches workspace, and 「跨工作区复制粘贴」 is the same gesture as
4274
+ * copying a file to the desktop (user口径 m00220). Only READ side widens, only to
4275
+ * a workspace this host knows; writes below stay inside THIS tree, and a move
4276
+ * never crosses a workspace (it would relocate a tree out of its git boundary).
4277
+ */
4278
+ const insideCopySource = (target, action) => {
4279
+ notRoot(target, action)
4280
+ const base = root.endsWith(sep) ? root : `${root}${sep}`
4281
+ if (target.startsWith(base) || insideKnownWorkspace(ctx, target)) return
4282
+ throw new TailError('outside-workspace', `不能对工作区之外的路径执行${action}`, 403)
4283
+ }
3692
4284
  const exists = async (target) => stat(target).then(() => true).catch(() => false)
3693
4285
  /** A destination given as a FILE means its directory, same rule as a paste. */
3694
4286
  const asFolder = async (target) => {
@@ -3715,8 +4307,10 @@ async function serveFsOp(ctx, req, res, options) {
3715
4307
  return
3716
4308
  }
3717
4309
  if (url.pathname === FS_COPY_PATH || url.pathname === FS_MOVE_PATH) {
4310
+ const copying = url.pathname === FS_COPY_PATH
3718
4311
  const from = one(body.from, 'from')
3719
- insideRoot(from, '复制或移动')
4312
+ if (copying) insideCopySource(from, '复制或移动')
4313
+ else insideRoot(from, '复制或移动')
3720
4314
  const toDir = await asFolder(one(body.toDir !== undefined ? body.toDir : body.to, 'toDir'))
3721
4315
  const requested = leafName(typeof body.name === 'string' ? body.name : '')
3722
4316
  const target = join(toDir, requested === '' ? basename(from) : requested)
@@ -3726,20 +4320,12 @@ async function serveFsOp(ctx, req, res, options) {
3726
4320
  throw new TailError('bad-request', '不能把目录复制/移动到它自己内部', 409)
3727
4321
  }
3728
4322
  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
- }
4323
+ // Deleting the old target first is how a "copy" could destroy its own source:
4324
+ // `assertReplacementIsSafe` refuses the aliasing cases (same inode, same real
4325
+ // path, target containing the source) and `replaceEntry` builds the new entry
4326
+ // beside the target and swaps it in with an atomic rename instead.
4327
+ await assertReplacementIsSafe(from, target, url.pathname === FS_COPY_PATH ? '复制' : '移动')
4328
+ await replaceEntry(from, target, { move: url.pathname === FS_MOVE_PATH, overwrite })
3743
4329
  writeJson(res, 200, { ok: true, path: target, from, [url.pathname === FS_COPY_PATH ? 'copied' : 'moved']: true })
3744
4330
  return
3745
4331
  }
@@ -3903,13 +4489,18 @@ async function serveFsImport(ctx, req, res, options) {
3903
4489
  callback(null, chunk)
3904
4490
  },
3905
4491
  })
4492
+ const temp = replacementTempPath(target, 'new')
3906
4493
  try {
3907
4494
  // 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' }))
4495
+ // Never into the target itself: a failed or oversized upload used to truncate
4496
+ // the old file and then delete it. The bytes land in a same-directory temp
4497
+ // file, and only a COMPLETED upload is renamed over the target.
4498
+ await pipeline(req, gate, createWriteStream(temp, { flags: 'wx' }))
3909
4499
  } catch (error) {
3910
- await rm(target, { force: true }).catch(() => {})
4500
+ await rm(temp, { force: true }).catch(() => {})
3911
4501
  throw error
3912
4502
  }
4503
+ await installReplacement(temp, target, { overwrite })
3913
4504
  writeJson(res, 200, { ok: true, path: target, name, bytes: written })
3914
4505
  return
3915
4506
  }
@@ -3933,12 +4524,11 @@ async function serveFsImport(ctx, req, res, options) {
3933
4524
  throw new TailError('bad-request', '不能把目录导入到它自己内部', 409)
3934
4525
  }
3935
4526
  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)
4527
+ // An import can name a destination that aliases the source (symlinked folder,
4528
+ // case-insensitive mount, same inode) or that CONTAINS it: deleting the old
4529
+ // target first would delete the thing being imported.
4530
+ await assertReplacementIsSafe(source, target, '导入')
4531
+ await replaceEntry(source, target, { overwrite, followLinks: true })
3942
4532
  writeJson(res, 200, { ok: true, path: target, name })
3943
4533
  } catch (error) {
3944
4534
  writeTailError(res, error)
@@ -4188,6 +4778,10 @@ async function stageClipboardCopy(root, paths) {
4188
4778
  const batchDir = join(base, batch)
4189
4779
  const staged = []
4190
4780
  const originals = []
4781
+ // Identity of every original AT PUBLISH TIME. The manifest is what makes a later
4782
+ // loss provable: dev/ino says whether the same file is still under that name,
4783
+ // size/mtime whether it was rewritten. See verifyClipboardStageOriginals.
4784
+ const snapshot = []
4191
4785
  const meter = { budget: CLIPBOARD_STAGE_MAX_BYTES }
4192
4786
  try {
4193
4787
  await mkdir(batchDir, { recursive: true })
@@ -4196,11 +4790,20 @@ async function stageClipboardCopy(root, paths) {
4196
4790
  const entryDir = join(batchDir, String(index))
4197
4791
  await mkdir(entryDir, { recursive: true })
4198
4792
  const target = join(entryDir, basename(source))
4793
+ const info = await lstat(source)
4199
4794
  await mirrorStagedEntry(source, target, meter)
4200
4795
  staged.push(target)
4201
4796
  originals.push(resolve(source))
4797
+ snapshot.push({
4798
+ path: resolve(source),
4799
+ dev: info.dev,
4800
+ ino: info.ino,
4801
+ size: info.size,
4802
+ mtimeMs: info.mtimeMs,
4803
+ kind: info.isDirectory() ? 'dir' : info.isSymbolicLink() ? 'symlink' : 'file',
4804
+ })
4202
4805
  }
4203
- await writeFile(join(batchDir, CLIPBOARD_STAGE_MANIFEST), JSON.stringify({ at: Date.now(), originals, staged }), 'utf8')
4806
+ await writeFile(join(batchDir, CLIPBOARD_STAGE_MANIFEST), JSON.stringify({ at: Date.now(), originals, staged, snapshot }), 'utf8')
4204
4807
  return { staged, originals, batchDir }
4205
4808
  } catch (error) {
4206
4809
  await rm(batchDir, { recursive: true, force: true }).catch(() => {})
@@ -4209,6 +4812,72 @@ async function stageClipboardCopy(root, paths) {
4209
4812
  }
4210
4813
  }
4211
4814
 
4815
+ /** Findings already surfaced in this process, so a paste loop does not repeat them. */
4816
+ const clipboardIntegrityNoted = new Set()
4817
+
4818
+ /** Where staging-integrity findings are appended (inside the plugin state dir). */
4819
+ const CLIPBOARD_STAGE_INTEGRITY_LOG = 'integrity.log'
4820
+
4821
+ /**
4822
+ * Compare every staged batch's ORIGINALS with the snapshot taken when the copy was
4823
+ * published, and turn a vanished original into evidence.
4824
+ *
4825
+ * This is the trail for 「复制之后源文件不见了」. At publish time the plugin knows
4826
+ * each original's dev/ino/size/mtime; a later paste (or the next copy) re-checks
4827
+ * them. A `missing`/`replaced` finding is appended to
4828
+ * `.dsh-ris-ide/stage/integrity.log` with a timestamp, reported to the page once,
4829
+ * and carries the STAGED path — a hard link to the same inode, so the bytes are
4830
+ * still on disk and can be copied back by hand. The plugin's own deletions always
4831
+ * land in `.dsh-ris-ide/trash`, so a `missing` original here was moved or removed
4832
+ * by something outside the tree.
4833
+ * @param root - workspace root.
4834
+ * @returns {Promise<object[]>} findings for this call, each with a ready message.
4835
+ */
4836
+ async function verifyClipboardStageOriginals(root) {
4837
+ await ensureIdeStateDir(root)
4838
+ const base = join(root, CLIPBOARD_STAGE_DIR)
4839
+ const findings = []
4840
+ const entries = await readdir(base, { withFileTypes: true }).catch(() => [])
4841
+ for (const entry of entries) {
4842
+ if (!entry.isDirectory()) continue
4843
+ const manifest = await readFile(join(base, entry.name, CLIPBOARD_STAGE_MANIFEST), 'utf8').catch(() => undefined)
4844
+ if (manifest === undefined) continue
4845
+ let parsed
4846
+ try {
4847
+ parsed = JSON.parse(manifest)
4848
+ } catch {
4849
+ continue
4850
+ }
4851
+ if (parsed === null || typeof parsed !== 'object') continue
4852
+ const snapshot = Array.isArray(parsed.snapshot) ? parsed.snapshot : []
4853
+ const staged = Array.isArray(parsed.staged) ? parsed.staged : []
4854
+ for (let index = 0; index < snapshot.length; index += 1) {
4855
+ const record = snapshot[index]
4856
+ if (record === null || typeof record !== 'object' || typeof record.path !== 'string') continue
4857
+ const info = await lstat(record.path).catch(() => undefined)
4858
+ let status = 'ok'
4859
+ if (info === undefined) status = 'missing'
4860
+ else if (info.dev !== record.dev || info.ino !== record.ino) status = 'replaced'
4861
+ else if (info.size !== record.size || Math.abs(info.mtimeMs - record.mtimeMs) > 1) status = 'changed'
4862
+ if (status === 'ok' || status === 'changed') continue
4863
+ const stagedPath = typeof staged[index] === 'string' ? staged[index] : undefined
4864
+ const key = `${entry.name}\u0000${record.path}\u0000${status}`
4865
+ if (clipboardIntegrityNoted.has(key)) continue
4866
+ clipboardIntegrityNoted.add(key)
4867
+ const name = basename(record.path)
4868
+ const message = status === 'missing'
4869
+ ? `复制到系统剪贴板后,源文件「${name}」不见了。插件删除一律进 .dsh-ris-ide/trash,所以不是插件删的;暂存副本还在(${stagedPath ?? '已清理'}),可直接复制回来。`
4870
+ : `源文件「${name}」在复制后被换成了另一个文件(inode 从 ${record.ino} 变成 ${info.ino}),请确认这是什么操作做的。`
4871
+ findings.push({ batch: entry.name, path: record.path, status, staged: stagedPath, at: Date.now(), message })
4872
+ }
4873
+ }
4874
+ if (findings.length > 0) {
4875
+ const lines = findings.map((finding) => JSON.stringify(finding)).join('\n') + '\n'
4876
+ await appendFile(join(base, CLIPBOARD_STAGE_INTEGRITY_LOG), lines, 'utf8').catch(() => {})
4877
+ }
4878
+ return findings
4879
+ }
4880
+
4212
4881
  /** staged path → original path for every batch still on disk. */
4213
4882
  async function clipboardStageMapping(root) {
4214
4883
  await ensureIdeStateDir(root)
@@ -4491,11 +5160,16 @@ async function serveClipboardRead(ctx, req, res) {
4491
5160
  // look like the original selection (otherwise Ctrl+C → Ctrl+V would import a
4492
5161
  // second copy of files the tree already has).
4493
5162
  let files = state.files
5163
+ let warnings = []
4494
5164
  if (root !== undefined) {
4495
5165
  const mapping = await clipboardStageMapping(root)
4496
5166
  if (mapping.size > 0) files = files.map((path) => mapping.get(resolve(path)) ?? path)
5167
+ // A staged original that vanished between Ctrl+C and Ctrl+V is the exact
5168
+ // symptom this route exists to explain: say so once, with the staged path
5169
+ // that still holds the bytes, and leave a line in stage/integrity.log.
5170
+ warnings = (await verifyClipboardStageOriginals(root)).map((finding) => finding.message)
4497
5171
  }
4498
- writeJson(res, 200, { ok: true, files, text: state.text, method: state.method })
5172
+ writeJson(res, 200, { ok: true, files, text: state.text, method: state.method, warnings })
4499
5173
  } catch (error) {
4500
5174
  writeTailError(res, error)
4501
5175
  }
@@ -4626,6 +5300,158 @@ async function writeChunk(target, body) {
4626
5300
  if (body.final !== false) await rename(staging, target)
4627
5301
  }
4628
5302
 
5303
+ /** Infix of the throwaway sibling every REPLACE builds in before it takes the target's name. */
5304
+ const FS_REPLACE_TEMP_SUFFIX = '.dsh-ris-ide-replace'
5305
+
5306
+ /**
5307
+ * One throwaway path in `target`'s OWN directory.
5308
+ *
5309
+ * Same directory means same filesystem, so the final `rename` is atomic. The name
5310
+ * ends with the save-temp suffix, which the tree listing already skips, so a
5311
+ * replacement never shows up as a row. The leaf is cut to 60 chars: a long target
5312
+ * name must not push the temp name past the usual 255-byte component cap.
5313
+ * @param target - the entry being replaced.
5314
+ * @param kind - `'new'` (content being built) or `'old'` (previous entry, kept until the swap).
5315
+ */
5316
+ function replacementTempPath(target, kind) {
5317
+ const leaf = basename(target).slice(0, 60)
5318
+ const random = Math.random().toString(36).slice(2, 8)
5319
+ return join(dirname(target), `.${leaf}${FS_REPLACE_TEMP_SUFFIX}-${kind}-${process.pid.toString(36)}${random}${FS_WRITE_TEMP_SUFFIX}`)
5320
+ }
5321
+
5322
+ /** dev/ino of an existing path, or undefined when nothing is there. */
5323
+ async function entryIdentity(path) {
5324
+ const info = await stat(path).catch(() => undefined)
5325
+ return info === undefined ? undefined : { dev: info.dev, ino: info.ino }
5326
+ }
5327
+
5328
+ /** Real path of `path`, or its lexical form when it does not exist (yet). */
5329
+ function resolvedRealPath(path) {
5330
+ try {
5331
+ return realpathSync(path)
5332
+ } catch {
5333
+ return resolve(path)
5334
+ }
5335
+ }
5336
+
5337
+ /**
5338
+ * Refuse a replacement that would destroy the thing being copied or moved.
5339
+ *
5340
+ * Overwrite used to delete `target` FIRST and only then copy/rename onto the empty
5341
+ * name, so a target that is the source under another name destroyed the source:
5342
+ * - the SAME inode under two names (hard link; a staged clipboard copy is exactly that);
5343
+ * - the same REAL path (a destination directory that is a symlink into the source's
5344
+ * own directory, or a case-insensitive mount such as `/mnt/c`);
5345
+ * - a directory that CONTAINS the source — `rm(target)` takes the source with it,
5346
+ * and the copy then fails on a source that no longer exists.
5347
+ * The routes compare paths as strings, which cannot see any of those.
5348
+ * @param source - entry being copied/moved/imported.
5349
+ * @param target - entry it would replace.
5350
+ * @param action - verb for the message (`复制`/`移动`/`导入`).
5351
+ */
5352
+ async function assertReplacementIsSafe(source, target, action) {
5353
+ const from = await entryIdentity(source)
5354
+ const to = await entryIdentity(target)
5355
+ if (from !== undefined && to !== undefined && from.dev === to.dev && from.ino === to.ino) {
5356
+ throw new TailError('same-entry', `「${basename(source)}」和「${basename(target)}」是同一个条目,拒绝覆盖以免丢数据`, 409)
5357
+ }
5358
+ const realSource = resolvedRealPath(source)
5359
+ const realTarget = resolvedRealPath(target)
5360
+ if (realSource === realTarget) {
5361
+ throw new TailError('same-entry', `目标「${basename(target)}」就是源本身,已拒绝${action}`, 409)
5362
+ }
5363
+ if (realTarget.startsWith(`${realSource}${sep}`)) {
5364
+ throw new TailError('bad-request', `不能把「${basename(source)}」${action}到它自己内部`, 409)
5365
+ }
5366
+ if (realSource.startsWith(`${realTarget}${sep}`)) {
5367
+ throw new TailError('bad-request', `「${basename(target)}」是包含源的目录:覆盖它会连源一起删掉,已拒绝`, 409)
5368
+ }
5369
+ }
5370
+
5371
+ /**
5372
+ * Put a completed temporary entry at `target`.
5373
+ *
5374
+ * The previous entry is renamed to a sibling backup name first (a same-directory
5375
+ * rename, never a delete), the new entry takes the name with one atomic rename,
5376
+ * and only then is the backup dropped. A failure at any step restores the backup
5377
+ * and leaves the temporary file for the caller to remove.
5378
+ * @param temp - fully written sibling of `target`.
5379
+ * @param target - name the new content should end up under.
5380
+ * @param options - `{overwrite}`: without it, an existing target is a 409.
5381
+ */
5382
+ async function installReplacement(temp, target, { overwrite = false } = {}) {
5383
+ const existing = await pathExists(target)
5384
+ if (existing && !overwrite) {
5385
+ // The caller may already have built the new content (a full copy of the source):
5386
+ // it must never linger next to the target as debris.
5387
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5388
+ throw new TailError('exists', `「${basename(target)}」已存在`, 409)
5389
+ }
5390
+ const backup = existing ? replacementTempPath(target, 'old') : undefined
5391
+ if (backup !== undefined) {
5392
+ try {
5393
+ await rename(target, backup)
5394
+ } catch (error) {
5395
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5396
+ throw error
5397
+ }
5398
+ }
5399
+ try {
5400
+ await rename(temp, target)
5401
+ } catch (error) {
5402
+ if (backup !== undefined) await rename(backup, target).catch(() => {})
5403
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5404
+ throw error
5405
+ }
5406
+ if (backup !== undefined) await rm(backup, { recursive: true, force: true }).catch(() => {})
5407
+ }
5408
+
5409
+ /**
5410
+ * Copy or move `source` onto `target`, replacing an existing target only on
5411
+ * explicit `overwrite`.
5412
+ *
5413
+ * The old target is never deleted before the new content exists, so a failed copy
5414
+ * leaves both entries intact, and a reader never sees the target half-written.
5415
+ * @param source - entry to copy (`move: false`) or move (`move: true`).
5416
+ * @param target - destination name.
5417
+ * @param options - `{move, overwrite, followLinks}`; `followLinks` keeps the
5418
+ * import route's historical "copy what the symlink points at" behaviour.
5419
+ */
5420
+ async function replaceEntry(source, target, { move = false, overwrite = false, followLinks = false } = {}) {
5421
+ await mkdir(dirname(target), { recursive: true })
5422
+ if (move) {
5423
+ const existing = await pathExists(target)
5424
+ if (existing && !overwrite) throw new TailError('exists', `目标位置已有「${basename(target)}」`, 409)
5425
+ const backup = existing ? replacementTempPath(target, 'old') : undefined
5426
+ if (backup !== undefined) await rename(target, backup)
5427
+ try {
5428
+ await rename(source, target)
5429
+ } catch (error) {
5430
+ // The old entry is still under the backup name: put it back, nothing lost.
5431
+ if (backup !== undefined) await rename(backup, target).catch(() => {})
5432
+ throw error
5433
+ }
5434
+ if (backup !== undefined) await rm(backup, { recursive: true, force: true }).catch(() => {})
5435
+ return
5436
+ }
5437
+ const temp = replacementTempPath(target, 'new')
5438
+ try {
5439
+ const info = await (followLinks ? stat(source) : lstat(source))
5440
+ if (info.isDirectory()) {
5441
+ // Node's cp keeps the tree shape and refuses to merge into anything.
5442
+ await cp(source, temp, { recursive: true, errorOnExist: true, force: false, dereference: followLinks })
5443
+ } else if (info.isSymbolicLink()) {
5444
+ await symlink(await readlink(source), temp)
5445
+ } else {
5446
+ await copyFile(source, temp)
5447
+ }
5448
+ } catch (error) {
5449
+ await rm(temp, { recursive: true, force: true }).catch(() => {})
5450
+ throw error
5451
+ }
5452
+ await installReplacement(temp, target, { overwrite })
5453
+ }
5454
+
4629
5455
  /**
4630
5456
  * The IDE's own workspace file API — no `dsh-better-sidebar` involved.
4631
5457
  *
@@ -4894,6 +5720,31 @@ function isLiveSession(ctx, id) {
4894
5720
  }
4895
5721
  }
4896
5722
 
5723
+ /**
5724
+ * `GET /dsh-ris-ide/workspaces` — the sidebar rows and this host's origin, straight
5725
+ * from the live context (m00186).
5726
+ *
5727
+ * Loopback only like every other route, and read-only: a dsh page (or the daemon
5728
+ * probing a per-instance origin file) gets the authoritative list without any file
5729
+ * on disk being involved.
5730
+ * @param ctx - Host context.
5731
+ * @param req - Node request face.
5732
+ * @param res - Node response face.
5733
+ */
5734
+ function serveWorkspaces(ctx, req, res) {
5735
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
5736
+ const now = Date.now()
5737
+ // Answering proves this host is alive, so republish the shared document on the way
5738
+ // out: a reader that only knows the file then sees the same answer.
5739
+ refreshDshWindows(ctx)
5740
+ writeJson(res, 200, {
5741
+ ok: true,
5742
+ url: dshWindowOriginFor(ctx),
5743
+ at: new Date(now).toISOString(),
5744
+ workspaces: dshWorkspaceRows(ctx),
5745
+ })
5746
+ }
5747
+
4897
5748
  /** `GET /dsh-ris-ide/windows` — the live windows, and the session of one workspace. */
4898
5749
  async function serveWindows(ctx, req, res) {
4899
5750
  try {
@@ -5994,6 +6845,9 @@ function startRisdBridge(ctx, cwd) {
5994
6845
  return
5995
6846
  }
5996
6847
  await attachBridgeState(ensured.state, cwd)
6848
+ // No extra call for 「代理引擎跟随 dsh」: the lease acquired above IS the start
6849
+ // signal (the daemon starts the engine when the first lease arrives and tears it
6850
+ // down when the last one leaves — one signal, one policy, m13950).
5997
6851
  })().finally(() => {
5998
6852
  if (bridge === risdBridge) bridge.pending = null
5999
6853
  })
@@ -6526,6 +7380,9 @@ async function serveProxyAction(ctx, req, res, options) {
6526
7380
  const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
6527
7381
  const action = typeof body.action === 'string' ? body.action : 'status'
6528
7382
  const gitHost = typeof body.gitHost === 'string' ? body.gitHost : undefined
7383
+ // The maintenance page is the only elevation entry point; an auto-start (save
7384
+ // rules / dsh start) calls the same route without this flag (m13910).
7385
+ const interactive = body.interactive === true
6529
7386
  // Engine + bridge + git are the daemon's once it owns the proxy; the per-rule
6530
7387
  // 启动/停止 buttons stay here because they launch a child of THIS process (the
6531
7388
  // injection only works on a child we spawn ourselves).
@@ -6538,7 +7395,7 @@ async function serveProxyAction(ctx, req, res, options) {
6538
7395
  }
6539
7396
  }
6540
7397
  if (actionState !== null && daemonActions.has(action)) {
6541
- const call = await proxyAction(actionState, { cwd, action, gitHost })
7398
+ const call = await proxyAction(actionState, { cwd, action, gitHost, interactive })
6542
7399
  if (call.ok !== true) {
6543
7400
  // No answer at all (network error / timeout) is not a business failure: the
6544
7401
  // action did not run, and the panel has no second entry point for the engine
@@ -6566,7 +7423,7 @@ async function serveProxyAction(ctx, req, res, options) {
6566
7423
  // otherwise rely on the daemon to provide (review C2-P1-3).
6567
7424
  armLocalProxyCleanup()
6568
7425
  const engine = await startProxy(cwd)
6569
- const redirector = await startRedirectors()
7426
+ const redirector = await startRedirectors({ interactive })
6570
7427
  const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
6571
7428
  if (engine.ok === true) inheritedEngine = null
6572
7429
  result = Object.assign({}, engine, { redirector, git })
@@ -6662,6 +7519,7 @@ function windowsProgramNames() {
6662
7519
  // the picker silently drop every Windows entry. Cache it and give it room.
6663
7520
  const cached = windowsProgramCache
6664
7521
  if (cached !== null && Date.now() - cached.at < WINDOWS_PROGRAM_TTL_MS) return Promise.resolve(new Set(cached.names))
7522
+ if (windowsProgramProbe !== null) return Promise.resolve(new Set(windowsProgramProbe()))
6665
7523
  return new Promise((resolvePromise) => {
6666
7524
  const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
6667
7525
  'Get-Process | Select-Object -ExpandProperty ProcessName -Unique'], { windowsHide: true })
@@ -6683,6 +7541,22 @@ function windowsProgramNames() {
6683
7541
  /** Last successful Windows process list (the probe is too slow to repeat per open). */
6684
7542
  let windowsProgramCache = null
6685
7543
 
7544
+ /**
7545
+ * Test seam for the Windows process listing.
7546
+ *
7547
+ * The real probe spawns `powershell.exe` (3-4.5 s on WSL, and it enumerates the
7548
+ * developer's actual desktop). Tests that only need *some* names set this instead,
7549
+ * so a test run neither waits for PowerShell nor depends on what is running.
7550
+ * @type {null | (() => Iterable<string>)}
7551
+ */
7552
+ let windowsProgramProbe = null
7553
+
7554
+ /** Install (or clear, with `null`) the Windows program-listing probe used by tests. */
7555
+ export function setWindowsProgramProbe(probe) {
7556
+ windowsProgramProbe = typeof probe === 'function' ? probe : null
7557
+ windowsProgramCache = null
7558
+ }
7559
+
6686
7560
  /** Drop the cached Windows process list (tests, or after a program was installed). */
6687
7561
  export function resetWindowsProgramCache() {
6688
7562
  windowsProgramCache = null
@@ -9830,12 +10704,27 @@ function hasRef(ref) {
9830
10704
  }
9831
10705
 
9832
10706
  /** The localhost URL a dev server wrote into its log, when it did. */
10707
+ /**
10708
+ * The dev server address a program printed in its log.
10709
+ *
10710
+ * Only LOCAL addresses count: the point is to open the page this program serves,
10711
+ * and picking up a gateway URL from the same line (MDF prints the Java address
10712
+ * next to the node one) would open the wrong site. Hosts like 0.0.0.0 and the
10713
+ * `<HOST地址>` placeholder some scaffolds print are rewritten to 127.0.0.1,
10714
+ * because the browser must dial a concrete loopback address (m03945).
10715
+ */
9833
10716
  async function logUrl(logPath) {
9834
10717
  if (!existsSync(logPath)) return undefined
9835
10718
  const tail = await readTail(logPath, 16 * 1024).catch(() => undefined)
9836
10719
  if (tail === undefined || typeof tail.content !== 'string') return undefined
9837
- const matches = tail.content.match(/https?:\/\/localhost:\d+[^\s)"']*/g)
9838
- return matches === null || matches.length === 0 ? undefined : matches[matches.length - 1]
10720
+ // eslint-disable-next-line no-control-regex
10721
+ const text = tail.content.replace(/\u001b\[[0-9;]*m/g, '')
10722
+ const pattern = /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|\[::\]|<[^>\s]{1,40}>):\d+[^\s)"',。;]*/gi
10723
+ const matches = text.match(pattern)
10724
+ if (matches === null || matches.length === 0) return undefined
10725
+ const last = matches[matches.length - 1]
10726
+ // A wildcard/placeholder host is a listening address, not a dialable one.
10727
+ return last.replace(/^(https?):\/\/(?:0\.0\.0\.0|\[::\]|<[^>]+>|\[::1\]):/i, '$1://127.0.0.1:')
9839
10728
  }
9840
10729
 
9841
10730
  /** Status of one log path (a program's fixed log, or an ad-hoc instance log). */
@@ -10122,10 +11011,12 @@ export const __test = {
10122
11011
  setRisdBridge: (bridge) => { risdBridge = bridge },
10123
11012
  resolvePath,
10124
11013
  refreshDshWindows,
11014
+ rememberDshOrigin,
10125
11015
  detectCompanionPlugin,
10126
11016
  renderProgramList,
10127
11017
  windowsProgramNames,
10128
11018
  resetWindowsProgramCache,
11019
+ setWindowsProgramProbe,
10129
11020
  // Proxy rules + engine (the dialog's three routes).
10130
11021
  PROXY_PATH,
10131
11022
  RISD_ENSURE_PATH,
@@ -10206,6 +11097,10 @@ export const __test = {
10206
11097
  findGitRoot,
10207
11098
  repoAllowedPaths,
10208
11099
  listIdeTree,
11100
+ // git availability is a quarantine, not a latch (m03193)
11101
+ gitUnavailable,
11102
+ noteGitSpawnFailure,
11103
+ noteGitSuccess,
10209
11104
  serveTree,
10210
11105
  bundledSkillPath,
10211
11106
  findProjectRoot,
@@ -10327,6 +11222,7 @@ export const __test = {
10327
11222
  BUNDLE_PATH,
10328
11223
  WINDOW_PAGE_PATH,
10329
11224
  WINDOWS_PATH,
11225
+ WORKSPACES_PATH,
10330
11226
  serveWindows,
10331
11227
  listIdeWindows,
10332
11228
  liveSessionFor,
@@ -10356,6 +11252,8 @@ export const __test = {
10356
11252
  stageClipboardCopy,
10357
11253
  pruneClipboardStage,
10358
11254
  clipboardStageMapping,
11255
+ verifyClipboardStageOriginals,
11256
+ CLIPBOARD_STAGE_INTEGRITY_LOG,
10359
11257
  serveClipboardFiles,
10360
11258
  writeSystemFileClipboard,
10361
11259
  windowsClipboardScript,
@@ -10386,6 +11284,7 @@ export const __test = {
10386
11284
  MAX_PROGRAMS,
10387
11285
  MAX_INSTANCES,
10388
11286
  ROUTE_PREFIX,
11287
+ OPEN_TARGET_PATH,
10389
11288
  DEFAULT_BYTES,
10390
11289
  HARD_MAX_BYTES,
10391
11290
  FS_WRITE_MAX_BODY_BYTES,