dsh-ris-ide 1.6.11 → 1.7.1

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.
package/lib/index.js CHANGED
@@ -50,7 +50,7 @@
50
50
  *
51
51
  * @module dsh-ris-ide
52
52
  */
53
- import { appendFile, copyFile, cp, mkdir, open, readdir, readFile, rename, rm, stat, truncate, writeFile } from 'node:fs/promises'
53
+ import { appendFile, copyFile, cp, link, lstat, mkdir, open, readdir, readFile, readlink, rename, rm, stat, symlink, truncate, writeFile } from 'node:fs/promises'
54
54
  import { createReadStream, createWriteStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
55
55
  import { watch } from 'node:fs'
56
56
  import { createHash } from 'node:crypto'
@@ -168,6 +168,63 @@ const FS_IMPORT_PATH = `${ROUTE_PREFIX}/fs/import`
168
168
  const FS_UPLOAD_PATH = `${ROUTE_PREFIX}/fs/upload`
169
169
  /** Upload cap: generous for screenshots/zips, small enough to stream, not buffer. */
170
170
  const FS_UPLOAD_MAX_BYTES = 128 * 1024 * 1024
171
+ /** Mirror a tree copy onto the SYSTEM clipboard, so the OS file manager can paste it. */
172
+ const CLIPBOARD_FILES_PATH = `${ROUTE_PREFIX}/clipboard/files`
173
+ /** One copy gesture; a folder of 1000 files is a mistake, not a clipboard write. */
174
+ const CLIPBOARD_MAX_ENTRIES = 200
175
+ /** Upper bound on the "one path per line" stdin payload the backends accept. */
176
+ const CLIPBOARD_MAX_PAYLOAD = 256 * 1024
177
+ /**
178
+ * `GET /dsh-ris-ide/windows` — which standalone IDE windows are alive.
179
+ *
180
+ * A page cannot enumerate other windows, so the host keeps the list: every IDE
181
+ * window's stream declares `window=1`, the connection IS the liveness (a closed
182
+ * window drops its stream, and a `dsh web` restart reconnects it a moment later).
183
+ * That is what lets the ⧉ button focus the window the user already has instead
184
+ * of stacking a second one, and what makes it find that window again after a
185
+ * restart without anyone announcing anything.
186
+ */
187
+ const WINDOWS_PATH = `${ROUTE_PREFIX}/windows`
188
+ /** A window whose stream has been gone this long counts as closed. */
189
+ const IDE_WINDOW_GRACE_MS = 90 * 1000
190
+ /** Live IDE windows, keyed by workspace cwd (one IDE window per workspace). */
191
+ const IDE_WINDOWS = new Map()
192
+
193
+ /**
194
+ * ONE hidden folder for everything the IDE keeps inside a workspace
195
+ * (`<workspace>/.dsh-ris-ide/`): `trash/` for deletes the tree can undo,
196
+ * `cache/` for extracted sources, `stage/` for clipboard publish mirrors.
197
+ * Older builds wrote those as three sibling dot-folders; `ensureIdeStateDir()`
198
+ * folds such leftovers in the first time this workspace is touched.
199
+ */
200
+ export const IDE_STATE_DIR = '.dsh-ris-ide'
201
+ /**
202
+ * Hidden staging area for a COPY publish (`<workspace>/.dsh-ris-ide/stage`).
203
+ *
204
+ * Explorer is free to interpret a cross-`\\wsl.localhost` paste as a MOVE: the
205
+ * files then leave the workspace even though the page published DROPEFFECT_COPY.
206
+ * Publishing a STAGED copy instead keeps the originals out of Explorer's hands —
207
+ * a plain file is hard-linked (O(1), same inode), a directory is copied under a
208
+ * size budget. `cut` still publishes the real paths: a cut IS a move.
209
+ */
210
+ const CLIPBOARD_STAGE_DIR = `${IDE_STATE_DIR}/stage`
211
+ /** Directories are copied for real; this is the budget one copy gesture may spend. */
212
+ const CLIPBOARD_STAGE_MAX_BYTES = 64 * 1024 * 1024
213
+ /** How many recent staging batches survive (older ones are pruned on publish). */
214
+ const CLIPBOARD_STAGE_KEEP_BATCHES = 3
215
+ /** A batch older than this is pruned even when it is one of the recent few. */
216
+ const CLIPBOARD_STAGE_TTL_MS = 24 * 60 * 60 * 1000
217
+ /** Batch record: staged path -> original path, so a read can translate back. */
218
+ const CLIPBOARD_STAGE_MANIFEST = 'manifest.json'
219
+ /**
220
+ * Read the SYSTEM clipboard back (`GET /dsh-ris-ide/clipboard/read`).
221
+ *
222
+ * A page cannot do this either: in WSL a copy made in Explorer never reaches
223
+ * Chromium (WSLg does not bridge the Windows `CF_HDROP` flavour), so the paste
224
+ * event arrives with an EMPTY payload while the clipboard really holds files.
225
+ * Only the Host can look; the route is read-only and writes nothing.
226
+ */
227
+ const CLIPBOARD_READ_PATH = `${ROUTE_PREFIX}/clipboard/read`
171
228
  /**
172
229
  * Lazily-built client chunks (see `tsdown.config.mjs`). Only these names are
173
230
  * served; the file is read from beside this module on every request so a rebuilt
@@ -204,14 +261,24 @@ const CONFIG_PATH = `${ROUTE_PREFIX}/config`
204
261
  const OPENS_PATH = `${ROUTE_PREFIX}/opens`
205
262
  /** Workspace filename search that honours every git repo's .gitignore. */
206
263
  const SEARCH_PATH = `${ROUTE_PREFIX}/search`
264
+ /**
265
+ * Workspace CONTENT search: `git grep` inside every repo root under the cwd, with
266
+ * a plain filesystem walk when there is no git (or git is not installed).
267
+ */
268
+ const CONTENT_SEARCH_PATH = `${ROUTE_PREFIX}/search-content`
269
+ /**
270
+ * Run ONE Maven test (`-Dtest=<name>`) in one module and keep its console in
271
+ * memory, so the IDE can start it and poll without a fake terminal.
272
+ */
273
+ const RUN_TEST_PATH = `${ROUTE_PREFIX}/run-test`
207
274
  /** One directory level for the IDE tree: gitignore-filtered + compact chains folded. */
208
275
  const TREE_PATH = `${ROUTE_PREFIX}/tree`
209
276
  /** Deleted entries park here so the tree's Ctrl+Z can bring them back. */
210
- export const TREE_TRASH_DIR = '.dsh-ris-ide-trash'
277
+ export const TREE_TRASH_DIR = `${IDE_STATE_DIR}/trash`
211
278
  /** Path segments whose churn is never interesting to the file tree. */
212
279
  const TREE_WATCH_IGNORED = new Set([
213
280
  'node_modules', 'target', 'build', 'dist', 'out', 'coverage', '.git',
214
- 'logs', '.dsh', '.dsh-ris-ide-trash', '.gradle', '.idea', '.mvn', '.dsh-ris-ide-cache',
281
+ 'logs', '.dsh', '.dsh-ris-ide', '.gradle', '.idea', '.mvn',
215
282
  ])
216
283
 
217
284
  /**
@@ -231,12 +298,14 @@ const DEBUG_PATH = `${ROUTE_PREFIX}/debug`
231
298
  const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
232
299
  /** Pulls a dependency class's source out of its jar (sources → decompiler → javap). */
233
300
  const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
234
- /** Read/write the IDE-specific settings kept next to `.dsh-ris-ide.json`. */
301
+ /** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
235
302
  const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
236
303
  /** Workspace cache holding extracted sources / decompiled files. */
237
- export const IDE_CACHE_DIR = '.dsh-ris-ide-cache'
304
+ export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
238
305
  /** Where the visual settings dialog persists the decompiler jar. */
239
- const IDE_SETTINGS_FILENAME = '.dsh-ris-ide.settings.json'
306
+ export const IDE_SETTINGS_FILENAME = `${IDE_STATE_DIR}/settings.json`
307
+ /** Older builds kept the settings beside the workspace root: read, never write. */
308
+ const LEGACY_SETTINGS_FILENAME = '.dsh-ris-ide.settings.json'
240
309
  const CLASS_NAME_PATTERN = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/
241
310
  const ZIP_EOCD_SIGNATURE = 0x06054b50
242
311
  const ZIP_CENTRAL_SIGNATURE = 0x02014b50
@@ -244,8 +313,10 @@ const ZIP_LOCAL_SIGNATURE = 0x04034b50
244
313
  const SOURCE_ENTRY_MAX_BYTES = 4 * 1024 * 1024
245
314
  /** One JDWP session per program, shared by the routes, the tool and the workbench UI. */
246
315
  const debugSessions = createDebugSessions()
247
- /** The user-editable program config, in the session workspace root. */
248
- const CONFIG_FILENAME = '.dsh-ris-ide.json'
316
+ /** The user-editable program config, inside the workspace state folder. */
317
+ export const CONFIG_FILENAME = `${IDE_STATE_DIR}/config.json`
318
+ /** Older builds kept the config as a hidden file beside the root: read, never write. */
319
+ const LEGACY_CONFIG_FILENAME = '.dsh-ris-ide.json'
249
320
  /** Header written into a generated config file (JSONC: `parseJsonc` tolerates it). */
250
321
  const CONFIG_HEADER = `// dsh-ris-ide 程序配置(JSONC:允许注释与尾逗号)
251
322
  //
@@ -395,6 +466,14 @@ export function handleRequest(ctx, req, res, options) {
395
466
  function dispatchRequest(ctx, req, res, options) {
396
467
  const method = req.method ?? 'GET'
397
468
  const pathname = requestPathname(req)
469
+ if (pathname === WINDOWS_PATH) {
470
+ if (method !== 'GET') {
471
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
472
+ return
473
+ }
474
+ serveSafely(res, () => serveWindows(ctx, req, res))
475
+ return
476
+ }
398
477
  if (pathname === WINDOW_PAGE_PATH) {
399
478
  if (method !== 'GET') {
400
479
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -460,6 +539,22 @@ function dispatchRequest(ctx, req, res, options) {
460
539
  serveSafely(res, () => serveFsImport(ctx, req, res, options))
461
540
  return
462
541
  }
542
+ if (pathname === CLIPBOARD_FILES_PATH) {
543
+ if (method !== 'POST') {
544
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
545
+ return
546
+ }
547
+ serveSafely(res, () => serveClipboardFiles(ctx, req, res, options))
548
+ return
549
+ }
550
+ if (pathname === CLIPBOARD_READ_PATH) {
551
+ if (method !== 'GET') {
552
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
553
+ return
554
+ }
555
+ serveSafely(res, () => serveClipboardRead(ctx, req, res))
556
+ return
557
+ }
463
558
  if (pathname === FS_READ_PATH || pathname === FS_WRITE_PATH || pathname === FS_FILE_PATH || pathname === FS_WINDOW_PATH) {
464
559
  if (pathname !== FS_WRITE_PATH) {
465
560
  if (method !== 'GET') {
@@ -505,6 +600,14 @@ function dispatchRequest(ctx, req, res, options) {
505
600
  serveSafely(res, () => serveStart(ctx, req, res, options))
506
601
  return
507
602
  }
603
+ if (pathname === RUN_TEST_PATH) {
604
+ if (method !== 'GET' && method !== 'POST') {
605
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET or POST only' })
606
+ return
607
+ }
608
+ serveSafely(res, () => (method === 'POST' ? serveRunTestStart(ctx, req, res, options) : serveRunTestStatus(ctx, req, res, options)))
609
+ return
610
+ }
508
611
  if (pathname === DEBUGS_PATH) {
509
612
  if (method !== 'GET') {
510
613
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -549,6 +652,14 @@ function dispatchRequest(ctx, req, res, options) {
549
652
  serveSafely(res, () => serveSearch(ctx, req, res, options))
550
653
  return
551
654
  }
655
+ if (pathname === CONTENT_SEARCH_PATH) {
656
+ if (method !== 'GET') {
657
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
658
+ return
659
+ }
660
+ serveSafely(res, () => serveContentSearch(ctx, req, res, options))
661
+ return
662
+ }
552
663
  if (pathname === OPENS_PATH) {
553
664
  if (method !== 'GET') {
554
665
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -598,8 +709,9 @@ function runGit(args, cwd, input) {
598
709
  child.on('close', (code) => {
599
710
  if (settled) return
600
711
  settled = true
601
- // `git check-ignore` exits 1 when nothing matched; that is a valid answer.
602
- if (code === 0 || (code === 1 && args[0] === 'check-ignore')) resolvePromise(stdout)
712
+ // `git check-ignore` exits 1 when nothing matched, and `git grep` exits 1
713
+ // when the pattern has no match; both are valid answers, not failures.
714
+ if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) resolvePromise(stdout)
603
715
  else rejectPromise(new Error(stderr || `git exited with ${code}`))
604
716
  })
605
717
  })
@@ -695,7 +807,7 @@ async function searchWorkspaceFiles(cwd, query, limit) {
695
807
  for (const root of roots) {
696
808
  let listing
697
809
  try {
698
- listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z'], root)
810
+ listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root)
699
811
  } catch {
700
812
  // git is absent/broken here: walk this root so filename search still answers.
701
813
  const all = await listRawFiles(root)
@@ -743,6 +855,182 @@ async function serveSearch(ctx, req, res, options) {
743
855
  }
744
856
  }
745
857
 
858
+ /** Content-search clamp: hits returned by one request (`limit`, default 300). */
859
+ const CONTENT_SEARCH_MAX_HITS = 1000
860
+ /** Content-search clamp: matches taken from one file (`perFile`, default 8). */
861
+ const CONTENT_SEARCH_MAX_PER_FILE = 50
862
+ /** Files the no-git fallback walks at most (bounded so a search can never hang). */
863
+ const CONTENT_SEARCH_FALLBACK_MAX_FILES = 2000
864
+ /** Files at least this large are skipped by the no-git fallback. */
865
+ const CONTENT_SEARCH_FALLBACK_MAX_BYTES = 1024 * 1024
866
+ /** Bytes inspected for a NUL byte when deciding whether a fallback file is binary. */
867
+ const CONTENT_SEARCH_BINARY_PROBE_BYTES = 8 * 1024
868
+
869
+ /**
870
+ * Whether `candidate` is `root` itself or lexically inside it. Used on the
871
+ * `path:line:text` records `git grep` prints, whose "path" is repo-relative:
872
+ * a `..` segment (or a quoted/odd name) must never produce a hit outside the
873
+ * repo root the search was scoped to.
874
+ * @param root - absolute repo root.
875
+ * @param candidate - absolute path to test.
876
+ * @returns `true` when the candidate stays inside the root.
877
+ */
878
+ function isContainedIn(root, candidate) {
879
+ const base = resolve(root)
880
+ const target = resolve(candidate)
881
+ return target === base || target.startsWith(base.endsWith(sep) ? base : `${base}${sep}`)
882
+ }
883
+
884
+ /**
885
+ * Parse one `git grep -n` stdout line (`<path>:<line>:<text>`) into a hit.
886
+ * Malformed lines and paths escaping the root are dropped, never thrown.
887
+ * @param root - absolute repo root the grep ran in.
888
+ * @param raw - one stdout line.
889
+ * @returns `{ path, line, text }`, or `undefined` when the line is not a hit.
890
+ */
891
+ function parseGitGrepLine(root, raw) {
892
+ if (typeof raw !== 'string' || raw === '') return undefined
893
+ // Non-greedy: the first `:<digits>:` pair separates path from line number, so
894
+ // a path that itself contains a colon still parses as long as it has no `:1:`.
895
+ const match = /^(.*?):(\d+):(.*)$/.exec(raw)
896
+ if (match === null) return undefined
897
+ const relativePath = match[1]
898
+ if (relativePath === '') return undefined
899
+ const absolutePath = resolve(root, relativePath)
900
+ if (!isContainedIn(root, absolutePath)) return undefined
901
+ const line = Number(match[2])
902
+ if (!Number.isSafeInteger(line) || line <= 0) return undefined
903
+ return { path: absolutePath, line, text: match[3].replace(/\r$/, '').trimEnd() }
904
+ }
905
+
906
+ /**
907
+ * Filesystem fallback for content search: no git repo, or no `git` binary. Walk
908
+ * the workspace ({@link listRawFiles}), read small files, and substring-match
909
+ * case-insensitively (`git grep` itself is case-sensitive unless `-i` is passed;
910
+ * this fallback deliberately leans the other way so it still finds things).
911
+ * @param cwd - workspace root.
912
+ * @param query - the search text (non-empty).
913
+ * @param limit - max hits returned.
914
+ * @param perFile - max hits taken from one file.
915
+ * @returns `{ hits, truncated, files }`.
916
+ */
917
+ async function searchContentRaw(cwd, query, limit, perFile) {
918
+ const needle = String(query).toLowerCase()
919
+ const hits = []
920
+ let files = 0
921
+ const all = await listRawFiles(cwd)
922
+ for (const path of all) {
923
+ if (files >= CONTENT_SEARCH_FALLBACK_MAX_FILES) return { hits, truncated: true, files }
924
+ files += 1
925
+ const info = await stat(path).catch(() => undefined)
926
+ if (info === undefined || !info.isFile()) continue
927
+ if (info.size >= CONTENT_SEARCH_FALLBACK_MAX_BYTES) continue
928
+ let bytes
929
+ try {
930
+ bytes = await readFile(path)
931
+ } catch {
932
+ continue // unreadable (permissions, a race with a delete): skip, never fail the search
933
+ }
934
+ if (bytes.subarray(0, CONTENT_SEARCH_BINARY_PROBE_BYTES).includes(0)) continue
935
+ const text = bytes.toString('utf8')
936
+ let lineNumber = 0
937
+ let perFileCount = 0
938
+ for (const line of text.split('\n')) {
939
+ lineNumber += 1
940
+ if (perFileCount >= perFile) break
941
+ const plain = line.replace(/\r$/, '')
942
+ if (plain.toLowerCase().indexOf(needle) === -1) continue
943
+ hits.push({ path, line: lineNumber, text: plain.trimEnd() })
944
+ perFileCount += 1
945
+ if (hits.length >= limit) return { hits, truncated: true, files }
946
+ }
947
+ }
948
+ return { hits, truncated: false, files }
949
+ }
950
+
951
+ /**
952
+ * Workspace CONTENT search (the IDE's "在文件中查找").
953
+ *
954
+ * One `git grep` per repo root under `cwd` — the only implementation that gets
955
+ * .gitignore, submodule and binary handling right, and it is fast (a repo-wide
956
+ * literal search is a few hundred ms). `-m <perFile>` caps matches per file and
957
+ * `-I` skips binaries; `-F` makes the pattern a fixed string (no regex
958
+ * compilation of user input, no `.`/`*` surprises).
959
+ * Without git (no repo anywhere, or no git binary) it falls back to walking
960
+ * files, which keeps the panel useful on a bare directory.
961
+ * @param cwd - workspace root.
962
+ * @param query - the literal text to look for (non-empty; validated by the route).
963
+ * @param limit - max hits returned (already clamped by the route).
964
+ * @param perFile - max hits per file (already clamped by the route).
965
+ * @returns `{ hits: [{path, line, text}], truncated, roots, files }`.
966
+ */
967
+ async function searchWorkspaceContent(cwd, query, limit, perFile) {
968
+ const needle = String(query ?? '')
969
+ const roots = await searchRoots(cwd)
970
+ if (needle === '') return { hits: [], truncated: false, roots, files: 0 }
971
+ if (roots.length === 0 || gitMissing) {
972
+ return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
973
+ }
974
+ const hits = []
975
+ const paths = new Set()
976
+ let truncated = false
977
+ for (const root of roots) {
978
+ let stdout
979
+ try {
980
+ stdout = await runGit(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle, '--'], root)
981
+ } catch {
982
+ // A root whose git call failed is not fatal (and git may have disappeared
983
+ // mid-search): fall back to the filesystem walk for the whole request.
984
+ if (gitMissing) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
985
+ continue
986
+ }
987
+ for (const raw of stdout.split('\n')) {
988
+ if (hits.length >= limit) {
989
+ truncated = true
990
+ break
991
+ }
992
+ const hit = parseGitGrepLine(root, raw)
993
+ if (hit === undefined) continue
994
+ hits.push(hit)
995
+ paths.add(hit.path)
996
+ }
997
+ if (hits.length >= limit) {
998
+ truncated = true
999
+ break
1000
+ }
1001
+ }
1002
+ return { hits, truncated, roots, files: paths.size }
1003
+ }
1004
+
1005
+ /**
1006
+ * One content-search request. Query parameters: `sessionId` (required),
1007
+ * `cwd`, `q` (required, non-empty), `limit` (default 300, clamped 1..1000) and
1008
+ * `perFile` (default 8, clamped 1..50).
1009
+ * @param ctx - Host context (session cwd lookup).
1010
+ * @param req - Node request face.
1011
+ * @param res - Node response face.
1012
+ * @param options - `{ restrictToCwd }` (see {@link apply}).
1013
+ */
1014
+ async function serveContentSearch(ctx, req, res, options) {
1015
+ try {
1016
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
1017
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
1018
+ const sessionId = url.searchParams.get('sessionId') ?? ''
1019
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
1020
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
1021
+ const query = url.searchParams.get('q') ?? ''
1022
+ if (query.trim() === '') throw new TailError('bad-request', 'q (the text to search for) is required', 400)
1023
+ const rawLimit = Number(url.searchParams.get('limit') ?? '300')
1024
+ const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), CONTENT_SEARCH_MAX_HITS) : 300
1025
+ const rawPerFile = Number(url.searchParams.get('perFile') ?? '8')
1026
+ const perFile = Number.isFinite(rawPerFile) ? Math.min(Math.max(1, Math.floor(rawPerFile)), CONTENT_SEARCH_MAX_PER_FILE) : 8
1027
+ const result = await searchWorkspaceContent(cwd, query, limit, perFile)
1028
+ writeJson(res, 200, { ok: true, root: cwd, ...result })
1029
+ } catch (error) {
1030
+ writeTailError(res, error)
1031
+ }
1032
+ }
1033
+
746
1034
  /** Cache of one repo root's allowed file paths (gitignore-aware), 5s TTL. */
747
1035
  const TREE_ALLOWED_CACHE = new Map()
748
1036
  /** Repo listing caches invalidated in the last second (coalesces save storms). */
@@ -860,7 +1148,7 @@ function relativePathOf(cwd, absolute) {
860
1148
  }
861
1149
 
862
1150
  /** Path segments the watcher always drops (git never reports these as changes). */
863
- const TREE_WATCH_ALWAYS_IGNORED = new Set(['.git', TREE_TRASH_DIR])
1151
+ const TREE_WATCH_ALWAYS_IGNORED = new Set(['.git', IDE_STATE_DIR])
864
1152
 
865
1153
  /**
866
1154
  * Whether a rel path is one the tree never shows for structural reasons.
@@ -972,7 +1260,7 @@ async function repoAllowedPaths(root) {
972
1260
  const dirs = new Set([root])
973
1261
  let listing
974
1262
  try {
975
- listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z'], root)
1263
+ listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root)
976
1264
  } catch {
977
1265
  // Any failure (most often "git is not installed") degrades to no filtering.
978
1266
  TREE_ALLOWED_CACHE.set(root, { at: Date.now(), value: undefined })
@@ -1038,6 +1326,9 @@ async function compactChain(full, allowed, repo) {
1038
1326
  for (const child of children) {
1039
1327
  const childPath = join(current, child.name)
1040
1328
  if (child.isDirectory()) {
1329
+ // A filtered tree hides `.git` too (see listIdeTree): it is metadata, and
1330
+ // it would otherwise count as a visible sibling and block package folding.
1331
+ if (allowed !== undefined && TREE_WATCH_ALWAYS_IGNORED.has(child.name)) continue
1041
1332
  const isRepo = await stat(join(childPath, '.git')).then(() => true).catch(() => false)
1042
1333
  if (isRepo) return { path: current, segments }
1043
1334
  if (allowed !== undefined && !allowed.dirs.has(childPath)) {
@@ -1095,6 +1386,76 @@ async function ignoredTreeDirs(repo, relatives) {
1095
1386
  return ignored
1096
1387
  }
1097
1388
 
1389
+ /** Workspaces whose `.dsh-ris-ide/` folder was already prepared in this process. */
1390
+ const IDE_STATE_READY = new Set()
1391
+
1392
+ /** Legacy config files an older build wrote beside the workspace root. */
1393
+ const LEGACY_STATE_FILES = [
1394
+ ['.dsh-ris-ide.json', 'config.json'],
1395
+ ['.dsh-ris-ide.settings.json', 'settings.json'],
1396
+ ]
1397
+
1398
+ /** Legacy sibling folders an older build wrote straight into the workspace root. */
1399
+ const LEGACY_STATE_DIRS = [
1400
+ ['.dsh-ris-ide-trash', 'trash'],
1401
+ ['.dsh-ris-ide-cache', 'cache'],
1402
+ ['.dsh-ris-ide-stage', 'stage'],
1403
+ ]
1404
+
1405
+ /**
1406
+ * Create `<root>/.dsh-ris-ide/` and fold any legacy dot-folders into it, once per
1407
+ * workspace per process. Earlier builds scattered three sibling folders across the
1408
+ * workspace root (`-trash`, `-cache`, `-stage`), each of which the tree had to hide
1409
+ * by name; one folder is easier to explain and to gitignore. Contents are moved,
1410
+ * not dropped: a parked delete must stay restorable and a cache entry reusable.
1411
+ * @param {string} root - the workspace root.
1412
+ * @returns {Promise<string|undefined>} the state folder, or undefined without a root.
1413
+ */
1414
+ async function ensureIdeStateDir(root) {
1415
+ if (root === undefined || root === null || root === '') return undefined
1416
+ const stateDir = join(root, IDE_STATE_DIR)
1417
+ const key = resolve(stateDir)
1418
+ if (IDE_STATE_READY.has(key)) return stateDir
1419
+ IDE_STATE_READY.add(key)
1420
+ try {
1421
+ await mkdir(stateDir, { recursive: true }).catch(() => undefined)
1422
+ for (const [legacyName, childName] of LEGACY_STATE_DIRS) {
1423
+ const from = join(root, legacyName)
1424
+ const info = await stat(from).catch(() => undefined)
1425
+ if (info === undefined || !info.isDirectory()) continue
1426
+ const target = join(stateDir, childName)
1427
+ await mkdir(target, { recursive: true }).catch(() => undefined)
1428
+ // Parked deletes live in the legacy trash: a folder that could not be
1429
+ // emptied completely must stay where it is, or the failed move becomes a
1430
+ // silent delete of somebody's files.
1431
+ let moved = true
1432
+ for (const name of await readdir(from).catch(() => [])) {
1433
+ const to = join(target, name)
1434
+ const taken = await stat(to).then(() => true).catch(() => false)
1435
+ // Never overwrite same-named leftovers: keep both, the newcomer wins the
1436
+ // plain name and the legacy entry is parked with a suffix.
1437
+ const destination = taken ? join(target, `${name}-legacy-${Date.now()}`) : to
1438
+ await rename(join(from, name), destination).catch(() => { moved = false })
1439
+ }
1440
+ if (moved === true) await rm(from, { recursive: true, force: true }).catch(() => undefined)
1441
+ }
1442
+ for (const [legacyName, childName] of LEGACY_STATE_FILES) {
1443
+ const from = join(root, legacyName)
1444
+ const info = await stat(from).catch(() => undefined)
1445
+ if (info === undefined || !info.isFile()) continue
1446
+ const to = join(stateDir, childName)
1447
+ // A file already at the new place wins: never overwrite the newer config.
1448
+ const taken = await stat(to).then(() => true).catch(() => false)
1449
+ if (!taken) await rename(from, to).catch(() => undefined)
1450
+ }
1451
+ return stateDir
1452
+ } catch (error) {
1453
+ // Let a later call retry the migration instead of remembering a failed one.
1454
+ IDE_STATE_READY.delete(key)
1455
+ throw error
1456
+ }
1457
+ }
1458
+
1098
1459
  /**
1099
1460
  * One directory level for the IDE tree.
1100
1461
  * @param {string} target - absolute directory.
@@ -1102,6 +1463,7 @@ async function ignoredTreeDirs(repo, relatives) {
1102
1463
  * @returns {Promise<{entries: object[], truncated: boolean}>}
1103
1464
  */
1104
1465
  async function listIdeTree(target, cwd, options) {
1466
+ await ensureIdeStateDir(cwd)
1105
1467
  const repo = await findGitRoot(target, cwd)
1106
1468
  // `filter: 'all'` is the tree's "show everything" mode: the gitignore filter is
1107
1469
  // deliberately bypassed, but the plugin's own bookkeeping folders stay hidden.
@@ -1113,7 +1475,7 @@ async function listIdeTree(target, cwd, options) {
1113
1475
  const unknownDirs = []
1114
1476
  if (repo !== undefined && allowed !== undefined) {
1115
1477
  for (const dirent of dirents) {
1116
- if (!dirent.isDirectory() || dirent.name === TREE_TRASH_DIR) continue
1478
+ if (!dirent.isDirectory() || TREE_WATCH_ALWAYS_IGNORED.has(dirent.name)) continue
1117
1479
  const full = join(target, dirent.name)
1118
1480
  if (allowed.dirs.has(full)) continue
1119
1481
  const isRepo = await stat(join(full, '.git')).then(() => true).catch(() => false)
@@ -1124,9 +1486,17 @@ async function listIdeTree(target, cwd, options) {
1124
1486
  const ignoredDirs = await ignoredTreeDirs(repo ?? '', unknownDirs)
1125
1487
  const entries = []
1126
1488
  for (const dirent of dirents) {
1127
- // The undo trash and the dependency-source cache are implementation
1128
- // details, never tree rows.
1129
- if (dirent.name === TREE_TRASH_DIR || dirent.name === IDE_CACHE_DIR) continue
1489
+ // `.dsh-ris-ide/` holds the undo trash, the dependency-source cache and the
1490
+ // clipboard staging batches: implementation details, never tree rows — and
1491
+ // hidden in BOTH filter modes, like the trash row it replaced.
1492
+ if (dirent.name === IDE_STATE_DIR) continue
1493
+ // `.git` is repository metadata, not project content: a filtered tree hides it
1494
+ // exactly like TREE_WATCH_ALWAYS_IGNORED hides its watch events. `git ls-files`
1495
+ // never lists it and `check-ignore` never reports it, so without this line it
1496
+ // would be the one ignored-looking folder the .gitignore filter still showed
1497
+ // (every repo root has one, and a nested repo's `.git` file is the same noise).
1498
+ // "显示所有文件" keeps it visible, like every other hidden entry.
1499
+ if (allowed !== undefined && TREE_WATCH_ALWAYS_IGNORED.has(dirent.name)) continue
1130
1500
  const full = join(target, dirent.name)
1131
1501
  if (dirent.isDirectory()) {
1132
1502
  const isRepo = await stat(join(full, '.git')).then(() => true).catch(() => false)
@@ -1275,7 +1645,7 @@ export async function assertEnoughMemory(minFreeBytes) {
1275
1645
  if (free === 0 || free >= floor) return
1276
1646
  throw new TailError(
1277
1647
  'low-memory',
1278
- `可用内存仅 ${memoryLabel(free)}(低于 ${memoryLabel(floor)}),为避免 swap 抖动已拒绝启动;请先停止不用的服务,或在 .dsh-ris-ide.json 里给程序配小一点的 jvmArgs(如 -Xmx768m)`,
1648
+ `可用内存仅 ${memoryLabel(free)}(低于 ${memoryLabel(floor)}),为避免 swap 抖动已拒绝启动;请先停止不用的服务,或在 .dsh-ris-ide/config.json 里给程序配小一点的 jvmArgs(如 -Xmx768m)`,
1279
1649
  507,
1280
1650
  )
1281
1651
  }
@@ -2373,18 +2743,38 @@ async function serveFsOp(ctx, req, res, options) {
2373
2743
  const notRoot = (target, action) => {
2374
2744
  if (target === root) throw new TailError('bad-request', `不能对工作区根目录执行${action}`, 409)
2375
2745
  }
2746
+ /**
2747
+ * Every mutation stays INSIDE the tree root.
2748
+ *
2749
+ * A path is only a string from the page: `/fs/remove` with `"../../../home"`
2750
+ * would otherwise recurse out of the tree and delete what it never listed.
2751
+ * The lexical check is enough because {@link resolvePath} already normalized
2752
+ * `.`/`..`, and `fs.rm` never follows a symlink to a directory.
2753
+ */
2754
+ const insideRoot = (target, action) => {
2755
+ notRoot(target, action)
2756
+ const base = root.endsWith(sep) ? root : `${root}${sep}`
2757
+ if (!target.startsWith(base)) throw new TailError('outside-workspace', `不能对工作区之外的路径执行${action}`, 403)
2758
+ }
2376
2759
  const exists = async (target) => stat(target).then(() => true).catch(() => false)
2760
+ /** A destination given as a FILE means its directory, same rule as a paste. */
2761
+ const asFolder = async (target) => {
2762
+ const info = await stat(target).catch(() => undefined)
2763
+ return info !== undefined && !info.isDirectory() ? dirname(target) : target
2764
+ }
2377
2765
 
2378
2766
  if (url.pathname === FS_MKDIR_PATH) {
2379
2767
  const target = one(body.path, 'path')
2380
- notRoot(target, '新建文件夹')
2768
+ insideRoot(target, '新建文件夹')
2769
+ checkLeafName(basename(target))
2381
2770
  await mkdir(target, { recursive: true })
2382
2771
  writeJson(res, 200, { ok: true, path: target, created: true })
2383
2772
  return
2384
2773
  }
2385
2774
  if (url.pathname === FS_CREATE_PATH) {
2386
2775
  const target = one(body.path, 'path')
2387
- notRoot(target, '新建文件')
2776
+ insideRoot(target, '新建文件')
2777
+ checkLeafName(basename(target))
2388
2778
  if (await exists(target)) throw new TailError('exists', `「${basename(target)}」已存在`, 409)
2389
2779
  await mkdir(dirname(target), { recursive: true })
2390
2780
  await writeFile(target, typeof body.content === 'string' ? body.content : '', { flag: 'wx' })
@@ -2393,13 +2783,11 @@ async function serveFsOp(ctx, req, res, options) {
2393
2783
  }
2394
2784
  if (url.pathname === FS_COPY_PATH || url.pathname === FS_MOVE_PATH) {
2395
2785
  const from = one(body.from, 'from')
2396
- notRoot(from, '复制或移动')
2397
- const toDir = one(body.toDir !== undefined ? body.toDir : body.to, 'toDir')
2398
- const requested = typeof body.name === 'string' ? body.name.trim() : ''
2399
- if (requested.includes('/') || requested.includes('\\') || requested === '.' || requested === '..') {
2400
- throw new TailError('bad-request', '非法的目标文件名', 400)
2401
- }
2786
+ insideRoot(from, '复制或移动')
2787
+ const toDir = await asFolder(one(body.toDir !== undefined ? body.toDir : body.to, 'toDir'))
2788
+ const requested = leafName(typeof body.name === 'string' ? body.name : '')
2402
2789
  const target = join(toDir, requested === '' ? basename(from) : requested)
2790
+ insideRoot(target, '复制或移动')
2403
2791
  if (target === from) throw new TailError('bad-request', '目标与源相同', 409)
2404
2792
  if (target.startsWith(from.endsWith(sep) ? from : `${from}${sep}`)) {
2405
2793
  throw new TailError('bad-request', '不能把目录复制/移动到它自己内部', 409)
@@ -2424,7 +2812,7 @@ async function serveFsOp(ctx, req, res, options) {
2424
2812
  }
2425
2813
  if (url.pathname === FS_REMOVE_PATH) {
2426
2814
  const target = one(body.path, 'path')
2427
- notRoot(target, '删除')
2815
+ insideRoot(target, '删除')
2428
2816
  const info = await stat(target).catch(() => undefined)
2429
2817
  if (info === undefined) throw new TailError('not-found', `「${basename(target)}」不存在`, 404)
2430
2818
  const recursive = body.recursive === true
@@ -2445,12 +2833,44 @@ async function serveFsOp(ctx, req, res, options) {
2445
2833
  /** Text files bigger than this are refused by the read route (matches the old sidebar). */
2446
2834
  const FS_MAX_TEXT_BYTES = 512 * 1024
2447
2835
 
2448
- /** One sanitized leaf name for an import target (never a path). */
2449
- function importEntryName(raw) {
2836
+ /** Longest leaf name the tree accepts (most Linux filesystems stop at 255 bytes). */
2837
+ const FS_MAX_NAME_LENGTH = 255
2838
+
2839
+ /**
2840
+ * Refuse a leaf name no sane filesystem/UX round-trips: control characters would
2841
+ * break logs and every line-oriented protocol downstream, and 255 is the usual
2842
+ * filesystem cap.
2843
+ * @param name - one path component.
2844
+ */
2845
+ function checkLeafName(name) {
2846
+ if (/[\u0000-\u001f\u007f]/.test(name)) throw new TailError('bad-request', '文件名里不能有控制字符', 400)
2847
+ if (name.length > FS_MAX_NAME_LENGTH) throw new TailError('bad-request', '文件名太长', 400)
2848
+ }
2849
+
2850
+ /**
2851
+ * One sanitized leaf name — never a path, never a control character.
2852
+ *
2853
+ * Names are only ever path components: every external command gets its paths as
2854
+ * argv/stdin and no shell is involved, so `'; rm -rf /'` is a file name and
2855
+ * nothing else. A newline or NUL would still corrupt logs, clipboard flavours and
2856
+ * any line-oriented protocol downstream, so those are refused at the door.
2857
+ * @param raw - requested name ('' means "keep the source name").
2858
+ * @returns the trimmed name, possibly ''.
2859
+ */
2860
+ function leafName(raw) {
2450
2861
  const name = String(raw === undefined || raw === null ? '' : raw).trim()
2451
- if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
2862
+ if (name === '') return ''
2863
+ if (name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
2452
2864
  throw new TailError('bad-request', '非法的文件名', 400)
2453
2865
  }
2866
+ checkLeafName(name)
2867
+ return name
2868
+ }
2869
+
2870
+ /** One sanitized leaf name for an import target (never a path, never empty). */
2871
+ function importEntryName(raw) {
2872
+ const name = leafName(raw)
2873
+ if (name === '') throw new TailError('bad-request', '非法的文件名', 400)
2454
2874
  return name
2455
2875
  }
2456
2876
 
@@ -2478,6 +2898,54 @@ async function pathExists(target) {
2478
2898
  * @param res - Node response face.
2479
2899
  * @param options - `{ restrictToCwd }` from the plugin config.
2480
2900
  */
2901
+ /**
2902
+ * The folder a paste lands in.
2903
+ *
2904
+ * Callers may hand over a FILE as the destination: the tree selection can be a
2905
+ * file row, and 「粘贴」/Ctrl+V on it means "put it NEXT TO this file". Rather
2906
+ * than failing with 「粘贴目标不是目录」, a file target resolves to its own
2907
+ * directory. A target that does not exist at all is still an error.
2908
+ * @param {string} cwd - session working directory.
2909
+ * @param {string} raw - requested destination (absolute or cwd-relative).
2910
+ * @param {boolean} restrict - keep the destination inside `cwd`.
2911
+ * @returns {Promise<string>} an existing directory.
2912
+ */
2913
+ async function resolvePasteDirectory(cwd, raw, restrict) {
2914
+ const root = resolve(cwd)
2915
+ const target = resolvePath(cwd, raw, restrict)
2916
+ const info = await stat(target).catch(() => undefined)
2917
+ if (info === undefined) throw new TailError('bad-request', `粘贴目标「${raw}」不存在`, 400)
2918
+ if (info.isDirectory()) {
2919
+ insideRootDirectory(root, target, raw)
2920
+ return target
2921
+ }
2922
+ const folder = dirname(target)
2923
+ const folderInfo = await stat(folder).catch(() => undefined)
2924
+ if (folderInfo === undefined || !folderInfo.isDirectory()) {
2925
+ throw new TailError('bad-request', '粘贴目标不是目录', 400)
2926
+ }
2927
+ insideRootDirectory(root, folder, raw)
2928
+ return folder
2929
+ }
2930
+
2931
+ /**
2932
+ * A paste only ever lands INSIDE the tree root.
2933
+ *
2934
+ * `dir` arrives as a string from the page; without this check an overwrite paste
2935
+ * (`rm -rf` of the colliding entry) could be aimed at any absolute directory on
2936
+ * the machine. The tree only ever lists its own root, so nothing legitimate is
2937
+ * lost by refusing the rest.
2938
+ * @param root - absolute tree root (the session cwd).
2939
+ * @param dir - resolved destination directory.
2940
+ * @param raw - the requested value, for the error message.
2941
+ */
2942
+ function insideRootDirectory(root, dir, raw) {
2943
+ const base = root.endsWith(sep) ? root : `${root}${sep}`
2944
+ if (dir !== root && !dir.startsWith(base)) {
2945
+ throw new TailError('outside-workspace', `粘贴目标「${raw}」不在工作区里`, 403)
2946
+ }
2947
+ }
2948
+
2481
2949
  async function serveFsImport(ctx, req, res, options) {
2482
2950
  try {
2483
2951
  if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
@@ -2487,9 +2955,7 @@ async function serveFsImport(ctx, req, res, options) {
2487
2955
  if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
2488
2956
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
2489
2957
  const name = importEntryName(url.searchParams.get('name') ?? '')
2490
- const dir = resolvePath(cwd, url.searchParams.get('dir') ?? '', options?.restrictToCwd === true)
2491
- const info = await stat(dir).catch(() => undefined)
2492
- if (info === undefined || !info.isDirectory()) throw new TailError('bad-request', '粘贴目标不是目录', 400)
2958
+ const dir = await resolvePasteDirectory(cwd, url.searchParams.get('dir') ?? '', options?.restrictToCwd === true)
2493
2959
  const target = join(dir, name)
2494
2960
  const overwrite = url.searchParams.get('overwrite') === '1'
2495
2961
  if (!overwrite && await pathExists(target)) throw new TailError('exists', `「${name}」已存在`, 409)
@@ -2527,9 +2993,7 @@ async function serveFsImport(ctx, req, res, options) {
2527
2993
  const source = isAbsolute(rawFrom) ? resolve(rawFrom) : resolvePath(cwd, rawFrom, restrict)
2528
2994
  const sourceInfo = await stat(source).catch(() => undefined)
2529
2995
  if (sourceInfo === undefined) throw new TailError('not-found', `找不到「${rawFrom}」`, 404)
2530
- const dir = resolvePath(cwd, typeof body.dir === 'string' ? body.dir : '', restrict)
2531
- const dirInfo = await stat(dir).catch(() => undefined)
2532
- if (dirInfo === undefined || !dirInfo.isDirectory()) throw new TailError('bad-request', '粘贴目标不是目录', 400)
2996
+ const dir = await resolvePasteDirectory(cwd, typeof body.dir === 'string' ? body.dir : '', restrict)
2533
2997
  const name = importEntryName(typeof body.name === 'string' && body.name.trim() !== '' ? body.name : basename(source))
2534
2998
  const target = join(dir, name)
2535
2999
  if (target === source || target.startsWith(`${source}${sep}`) || source.startsWith(`${target}${sep}`)) {
@@ -2548,6 +3012,562 @@ async function serveFsImport(ctx, req, res, options) {
2548
3012
  }
2549
3013
  }
2550
3014
 
3015
+ /**
3016
+ * Is this Linux really WSL? Then the Windows clipboard is reachable through
3017
+ * interop, which is the ONLY way a web page can hand files to Explorer/desktop:
3018
+ * Chromium refuses `text/uri-list` (and `x-special/gnome-copied-files`) on
3019
+ * `Clipboard.write`, so the browser cannot publish a file list itself.
3020
+ * @returns whether the platform is WSL.
3021
+ */
3022
+ export function isWsl() {
3023
+ if (IS_WINDOWS) return false
3024
+ try {
3025
+ return existsSync('/proc/version') && readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')
3026
+ } catch {
3027
+ return false
3028
+ }
3029
+ }
3030
+
3031
+ /**
3032
+ * PowerShell that puts a FILE LIST on the Windows clipboard (CF_HDROP), with the
3033
+ * copy/move intent Explorer reads from `Preferred DropEffect`. Clipboard.SetDataObject
3034
+ * needs an STA thread, so callers pass `-STA`.
3035
+ *
3036
+ * The paths are NOT part of this text: they arrive on STDIN, one per line, so a
3037
+ * filename can never become PowerShell code (`'; rm -rf /; '` is just a name).
3038
+ * The only interpolated value is the DropEffect integer, chosen from a boolean.
3039
+ * @param cut - `true` for a MOVE intent (Explorer deletes the source on paste).
3040
+ * @returns the script text.
3041
+ */
3042
+ export function windowsClipboardScript(cut) {
3043
+ const effect = cut ? 2 : 1
3044
+ return [
3045
+ // Node writes UTF-8 bytes; decode them here so Windows PowerShell's console
3046
+ // input encoding cannot mangle non-ASCII file names.
3047
+ '$stdin = [Console]::OpenStandardInput()',
3048
+ '$buffer = New-Object System.IO.MemoryStream',
3049
+ '$stdin.CopyTo($buffer)',
3050
+ '$raw = [Text.Encoding]::UTF8.GetString($buffer.ToArray())',
3051
+ // One path per line (CRLF tolerated); a path never contains a line break — the
3052
+ // route rejects those before this script runs.
3053
+ "$lines = @($raw -split \"`n\" | ForEach-Object { $_.TrimEnd(\"`r\") } | Where-Object { $_ -ne '' })",
3054
+ 'if ($lines.Count -eq 0) { exit 2 }',
3055
+ 'Add-Type -AssemblyName System.Windows.Forms',
3056
+ '$data = New-Object System.Windows.Forms.DataObject',
3057
+ "$data.SetData('FileDrop', [string[]]$lines)",
3058
+ `$data.SetData('Preferred DropEffect', [byte[]]@(${effect},0,0,0))`,
3059
+ '[System.Windows.Forms.Clipboard]::SetDataObject($data, $true)',
3060
+ ].join('\n')
3061
+ }
3062
+
3063
+ /**
3064
+ * Run one child process, collecting its output as text.
3065
+ *
3066
+ * `command` and `args` are always fixed program names and flags — request data
3067
+ * travels on stdin, never through a shell, so nothing a user names can be read
3068
+ * as code or as another flag. A hard timeout kills a stuck helper (a clipboard
3069
+ * tool that waits for a display can hang forever).
3070
+ * @param command - executable name or path.
3071
+ * @param args - argument vector.
3072
+ * @param input - optional stdin payload.
3073
+ * @param timeoutMs - give up (and kill) after this long.
3074
+ * @returns `{ ok, stdout, stderr }`; `ok` is `code === 0`.
3075
+ */
3076
+ function runTool(command, args, input, timeoutMs = 15000) {
3077
+ return new Promise((resolvePromise) => {
3078
+ let settled = false
3079
+ const settle = (result) => {
3080
+ if (settled) return
3081
+ settled = true
3082
+ clearTimeout(timer)
3083
+ resolvePromise(result)
3084
+ }
3085
+ let child
3086
+ try {
3087
+ child = spawn(command, args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], windowsHide: true })
3088
+ } catch (error) {
3089
+ settle({ ok: false, stdout: '', stderr: messageOf(error) })
3090
+ return
3091
+ }
3092
+ let stdout = ''
3093
+ let stderr = ''
3094
+ const timer = setTimeout(() => {
3095
+ child.kill('SIGKILL')
3096
+ settle({ ok: false, stdout, stderr: `${stderr}${stderr === '' ? '' : '\n'}${command} 超时(${Math.round(timeoutMs / 1000)}s)` })
3097
+ }, timeoutMs)
3098
+ child.stdout?.on('data', (chunk) => { stdout += chunk })
3099
+ child.stderr?.on('data', (chunk) => { stderr += chunk })
3100
+ child.on('error', (error) => settle({ ok: false, stdout, stderr: messageOf(error) }))
3101
+ child.on('close', (code) => settle({ ok: code === 0, stdout, stderr }))
3102
+ if (input !== undefined) {
3103
+ child.stdin?.on('error', () => {})
3104
+ child.stdin?.end(input)
3105
+ }
3106
+ })
3107
+ }
3108
+
3109
+ /**
3110
+ * Translate one WSL path into the Windows path the clipboard must carry
3111
+ * (`\\wsl.localhost\<distro>\…`). `wslpath` knows better than any guess.
3112
+ * @param path - absolute Linux path.
3113
+ * @returns the Windows path, or `undefined` when `wslpath` refused.
3114
+ */
3115
+ async function wslWindowsPath(path) {
3116
+ const result = await runTool('wslpath', ['-w', path])
3117
+ const converted = result.ok ? result.stdout.trim() : ''
3118
+ return converted === '' ? undefined : converted
3119
+ }
3120
+
3121
+ /**
3122
+ * Put `paths` on the SYSTEM clipboard as a file list, per platform.
3123
+ * @param paths - absolute native paths (files and/or directories).
3124
+ * @param cut - `true` for a MOVE intent.
3125
+ * @returns `{ method }` naming the backend that took it.
3126
+ * @throws TailError `unsupported` when the platform has no way to do it.
3127
+ */
3128
+ export async function writeSystemFileClipboard(paths, cut = false) {
3129
+ if (process.platform === 'win32' || isWsl()) {
3130
+ let windowsPaths = paths
3131
+ if (!IS_WINDOWS) {
3132
+ const converted = await Promise.all(paths.map((path) => wslWindowsPath(path)))
3133
+ if (converted.some((path) => path === undefined)) {
3134
+ throw new TailError('clipboard-failed', '无法把 WSL 路径转换成 Windows 路径(wslpath 不可用)', 500)
3135
+ }
3136
+ windowsPaths = converted
3137
+ }
3138
+ const encoded = Buffer.from(windowsClipboardScript(cut === true), 'utf16le').toString('base64')
3139
+ // The list rides on STDIN — see windowsClipboardScript(): no path is ever
3140
+ // spliced into a command line or a script.
3141
+ const result = await runTool('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded], `${windowsPaths.join('\n')}\n`)
3142
+ if (!result.ok) {
3143
+ throw new TailError('clipboard-failed', `PowerShell 写剪贴板失败:${(result.stderr || result.stdout).trim().split('\n')[0] || '未知错误'}`, 500)
3144
+ }
3145
+ return { method: IS_WINDOWS ? 'windows-powershell' : 'wsl-powershell' }
3146
+ }
3147
+ if (process.platform === 'darwin') {
3148
+ // Paths are argv here too: no path text is parsed as JXA source.
3149
+ const script = [
3150
+ 'function run(argv) {',
3151
+ ' ObjC.import("AppKit")',
3152
+ ' var pb = $.NSPasteboard.generalPasteboard',
3153
+ ' pb.clearContents',
3154
+ ' pb.writeObjects($(argv.map(function (path) { return $.NSURL.fileURLWithPath(path) })))',
3155
+ ' return ""',
3156
+ '}',
3157
+ ].join('\n')
3158
+ const result = await runTool('osascript', ['-l', 'JavaScript', '-e', script, ...paths])
3159
+ if (!result.ok) {
3160
+ throw new TailError('clipboard-failed', `osascript 写剪贴板失败:${result.stderr.trim() || '未知错误'}`, 500)
3161
+ }
3162
+ return { method: 'macos-appkit' }
3163
+ }
3164
+ // Linux desktop: GNOME wants x-special/gnome-copied-files (it carries copy|cut),
3165
+ // wl-clipboard only offers text/uri-list — both are understood by file managers.
3166
+ // The payload is data on stdin: it is never an argument and never shell-parsed.
3167
+ const urls = paths.map((path) => `file://${encodeURI(path)}`)
3168
+ const gnomePayload = `${cut === true ? 'cut' : 'copy'}\n${urls.join('\n')}\n`
3169
+ const xclip = await runTool('xclip', ['-selection', 'clipboard', '-t', 'x-special/gnome-copied-files', '-i'], gnomePayload)
3170
+ if (xclip.ok) return { method: 'linux-xclip' }
3171
+ const uriList = `${urls.join('\r\n')}\r\n`
3172
+ const wlCopy = await runTool('wl-copy', ['--type', 'text/uri-list'], uriList)
3173
+ if (wlCopy.ok) return { method: 'linux-wl-copy' }
3174
+ throw new TailError('unsupported', '这台机器没有 xclip / wl-copy,浏览器也无法直接写文件剪贴板', 501)
3175
+ }
3176
+
3177
+ /**
3178
+ * Create `target` as a mirror of `source` using HARD LINKS wherever one is
3179
+ * possible: a staged directory costs inodes, not bytes, and Explorer moving a
3180
+ * staged link out of the stage never touches the original path.
3181
+ *
3182
+ * Links only fail across filesystems (`EXDEV`); then — and only then — the entry
3183
+ * is copied for real, which is still safe (a copy of the original) and is charged
3184
+ * against the byte budget of one copy gesture.
3185
+ * @param {string} source - entry to mirror (file, directory or symlink).
3186
+ * @param {string} target - staged path to create.
3187
+ * @param {{budget: number}} meter - remaining bytes for real copies.
3188
+ */
3189
+ async function mirrorStagedEntry(source, target, meter) {
3190
+ const info = await lstat(source)
3191
+ if (info.isSymbolicLink()) {
3192
+ await symlink(await readlink(source), target)
3193
+ return
3194
+ }
3195
+ if (info.isDirectory()) {
3196
+ await mkdir(target, { recursive: true })
3197
+ const entries = await readdir(source, { withFileTypes: true })
3198
+ for (const entry of entries) {
3199
+ await mirrorStagedEntry(join(source, entry.name), join(target, entry.name), meter)
3200
+ }
3201
+ return
3202
+ }
3203
+ try {
3204
+ await link(source, target)
3205
+ } catch (error) {
3206
+ if (error === null || error === undefined || error.code !== 'EXDEV') throw error
3207
+ meter.budget -= info.size
3208
+ if (meter.budget < 0) throw clipboardStageTooLarge()
3209
+ await copyFile(source, target)
3210
+ }
3211
+ }
3212
+
3213
+ /** Delete staging batches that are old or beyond the keep window. */
3214
+ async function pruneClipboardStage(root) {
3215
+ await ensureIdeStateDir(root)
3216
+ const base = join(root, CLIPBOARD_STAGE_DIR)
3217
+ const entries = await readdir(base, { withFileTypes: true }).catch(() => [])
3218
+ const batches = []
3219
+ for (const entry of entries) {
3220
+ if (!entry.isDirectory()) continue
3221
+ const path = join(base, entry.name)
3222
+ const info = await stat(path).catch(() => undefined)
3223
+ if (info !== undefined) batches.push({ path, at: info.mtimeMs })
3224
+ }
3225
+ batches.sort((left, right) => right.at - left.at)
3226
+ const now = Date.now()
3227
+ for (let index = 0; index < batches.length; index += 1) {
3228
+ if (index < CLIPBOARD_STAGE_KEEP_BATCHES && now - batches[index].at < CLIPBOARD_STAGE_TTL_MS) continue
3229
+ await rm(batches[index].path, { recursive: true, force: true }).catch(() => {})
3230
+ }
3231
+ }
3232
+
3233
+ /** The staged copy cannot be expressed within the budget. Never fall back to the originals. */
3234
+ function clipboardStageTooLarge() {
3235
+ const megabytes = Math.round(CLIPBOARD_STAGE_MAX_BYTES / (1024 * 1024))
3236
+ // Short on purpose: this string ends up in a toast.
3237
+ return new TailError('too-large', `超过 ${megabytes} MB,已取消复制到系统剪贴板`, 413)
3238
+ }
3239
+
3240
+ /**
3241
+ * Stage a COPY publish: every entry gets its own numbered folder inside a fresh
3242
+ * batch, so two same-named files from different folders do not collide and the
3243
+ * names Explorer pastes are the original ones. Entries are hard-link mirrors — a
3244
+ * staged path is a different NAME for the same inode, so the originals stay put
3245
+ * whatever Explorer does with the pasted files.
3246
+ *
3247
+ * A failure is an ERROR, never a quiet "publish the originals instead": silently
3248
+ * handing the real paths to Explorer is exactly how files disappear.
3249
+ * @returns {Promise<{staged: string[], originals: string[], batchDir: string}>} the staged paths.
3250
+ */
3251
+ async function stageClipboardCopy(root, paths) {
3252
+ await ensureIdeStateDir(root)
3253
+ const base = join(root, CLIPBOARD_STAGE_DIR)
3254
+ const batch = `${Date.now()}-${process.pid.toString(36)}${Math.random().toString(36).slice(2, 8)}`
3255
+ const batchDir = join(base, batch)
3256
+ const staged = []
3257
+ const originals = []
3258
+ const meter = { budget: CLIPBOARD_STAGE_MAX_BYTES }
3259
+ try {
3260
+ await mkdir(batchDir, { recursive: true })
3261
+ for (let index = 0; index < paths.length; index += 1) {
3262
+ const source = paths[index]
3263
+ const entryDir = join(batchDir, String(index))
3264
+ await mkdir(entryDir, { recursive: true })
3265
+ const target = join(entryDir, basename(source))
3266
+ await mirrorStagedEntry(source, target, meter)
3267
+ staged.push(target)
3268
+ originals.push(resolve(source))
3269
+ }
3270
+ await writeFile(join(batchDir, CLIPBOARD_STAGE_MANIFEST), JSON.stringify({ at: Date.now(), originals, staged }), 'utf8')
3271
+ return { staged, originals, batchDir }
3272
+ } catch (error) {
3273
+ await rm(batchDir, { recursive: true, force: true }).catch(() => {})
3274
+ if (error instanceof TailError) throw error
3275
+ throw new TailError('clipboard-failed', `暂存这批内容失败:${messageOf(error)}`, 500)
3276
+ }
3277
+ }
3278
+
3279
+ /** staged path → original path for every batch still on disk. */
3280
+ async function clipboardStageMapping(root) {
3281
+ await ensureIdeStateDir(root)
3282
+ const base = join(root, CLIPBOARD_STAGE_DIR)
3283
+ const mapping = new Map()
3284
+ const entries = await readdir(base, { withFileTypes: true }).catch(() => [])
3285
+ for (const entry of entries) {
3286
+ if (!entry.isDirectory()) continue
3287
+ const manifest = await readFile(join(base, entry.name, CLIPBOARD_STAGE_MANIFEST), 'utf8').catch(() => undefined)
3288
+ if (manifest === undefined) continue
3289
+ let parsed
3290
+ try {
3291
+ parsed = JSON.parse(manifest)
3292
+ } catch {
3293
+ continue
3294
+ }
3295
+ if (parsed === null || typeof parsed !== 'object') continue
3296
+ const staged = Array.isArray(parsed.staged) ? parsed.staged : []
3297
+ const originals = Array.isArray(parsed.originals) ? parsed.originals : []
3298
+ for (let index = 0; index < staged.length; index += 1) {
3299
+ if (typeof staged[index] === 'string' && typeof originals[index] === 'string') {
3300
+ mapping.set(resolve(staged[index]), originals[index])
3301
+ }
3302
+ }
3303
+ }
3304
+ return mapping
3305
+ }
3306
+
3307
+ /** Workspace root for one clipboard call, or undefined when the scope is unknown. */
3308
+ function clipboardRoot(ctx, sessionId, cwd) {
3309
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined
3310
+ try {
3311
+ return resolveCwd(ctx, sessionId, typeof cwd === 'string' && cwd !== '' ? cwd : undefined)
3312
+ } catch {
3313
+ return undefined
3314
+ }
3315
+ }
3316
+
3317
+ /**
3318
+ * Read the workspace scope of a clipboard request.
3319
+ *
3320
+ * The page sends it as a QUERY string (`?sessionId=…&cwd=…`), same as every other
3321
+ * tree route; the POST body may carry the same two fields for old clients. Reading
3322
+ * only one of them is what made copy answer "复制到系统剪贴板需要 sessionId".
3323
+ * @param {object} body - the parsed JSON body (may be empty).
3324
+ * @param {URL} url - the request URL.
3325
+ * @returns {{sessionId: string, cwd: string}} whatever the request actually carried.
3326
+ */
3327
+ export function clipboardScope(body, url) {
3328
+ const pick = (key) => {
3329
+ const fromBody = body !== null && typeof body === 'object' && typeof body[key] === 'string' ? body[key] : ''
3330
+ if (fromBody !== '') return fromBody
3331
+ return url.searchParams.get(key) ?? ''
3332
+ }
3333
+ return { sessionId: pick('sessionId'), cwd: pick('cwd') }
3334
+ }
3335
+
3336
+ /**
3337
+ * `POST /dsh-ris-ide/clipboard/files` — the tree's copy/cut mirrors the selection
3338
+ * onto the SYSTEM clipboard so it can be pasted into an OS file manager. The page
3339
+ * cannot do this itself (see {@link isWsl}); the Host owns the platform call.
3340
+ */
3341
+ async function serveClipboardFiles(ctx, req, res, options) {
3342
+ try {
3343
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
3344
+ const body = await readJsonBody(req)
3345
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
3346
+ const scope = clipboardScope(body, url)
3347
+ const raw = Array.isArray(body.paths) ? body.paths : []
3348
+ const requested = raw.filter((path) => typeof path === 'string' && path.trim() !== '')
3349
+ if (requested.length === 0) throw new TailError('bad-request', 'paths is required', 400)
3350
+ // The OS clipboard can only describe REAL locations: a relative path has no
3351
+ // meaning outside the tree, so refuse it instead of stat-ing the plugin's cwd.
3352
+ const paths = requested.map((path) => (isAbsolute(path) ? resolve(path) : ''))
3353
+ if (paths.some((path) => path === '')) throw new TailError('bad-request', '复制到系统剪贴板需要绝对路径', 400)
3354
+ if (paths.length > CLIPBOARD_MAX_ENTRIES) throw new TailError('bad-request', `一次最多复制 ${CLIPBOARD_MAX_ENTRIES} 项`, 400)
3355
+ // The backends carry the list as "one path per line" data (never as code or as
3356
+ // flags). A name containing a line break or a NUL cannot be expressed that way,
3357
+ // and silently splitting it into two entries would put a wrong path on the
3358
+ // clipboard — refuse it instead.
3359
+ if (paths.some((path) => /[\u0000\r\n]/.test(path))) {
3360
+ throw new TailError('bad-request', '复制到系统剪贴板不支持路径里的换行或控制字符', 400)
3361
+ }
3362
+ if (Buffer.byteLength(`${paths.join('\n')}\n`, 'utf8') > CLIPBOARD_MAX_PAYLOAD) {
3363
+ throw new TailError('bad-request', '一次复制的路径总长度超出上限', 400)
3364
+ }
3365
+ for (const path of paths) {
3366
+ const info = await stat(path).catch(() => undefined)
3367
+ if (info === undefined) throw new TailError('not-found', `找不到「${path}」`, 404)
3368
+ }
3369
+ // A COPY goes out as a staged HARD-LINK mirror (see CLIPBOARD_STAGE_DIR): the
3370
+ // clipboard hands Explorer a different name for the same inode, so whatever it
3371
+ // does with the pasted files, the originals stay where they are. A CUT keeps
3372
+ // the real paths — cut means move, not "move a link".
3373
+ //
3374
+ // When the copy cannot be staged the route FAILS. Publishing the originals
3375
+ // instead would be a silent downgrade to exactly the behavior that lost files.
3376
+ const root = clipboardRoot(ctx, scope.sessionId, scope.cwd)
3377
+ let published = paths
3378
+ let staged = false
3379
+ if (body.cut !== true) {
3380
+ if (root === undefined) {
3381
+ throw new TailError('bad-request', '复制到系统剪贴板需要 sessionId', 400)
3382
+ }
3383
+ const rootInfo = await stat(root).catch(() => undefined)
3384
+ if (rootInfo === undefined || !rootInfo.isDirectory()) {
3385
+ throw new TailError('bad-request', `工作区不是目录:「${root}」`, 400)
3386
+ }
3387
+ const stage = await stageClipboardCopy(root, paths)
3388
+ published = stage.staged
3389
+ staged = true
3390
+ await pruneClipboardStage(root)
3391
+ }
3392
+ const result = await writeSystemFileClipboard(published, body.cut === true)
3393
+ writeJson(res, 200, { ok: true, count: published.length, method: result.method, staged, paths: published })
3394
+ } catch (error) {
3395
+ writeTailError(res, error)
3396
+ }
3397
+ }
3398
+
3399
+ /**
3400
+ * PowerShell that PRINTS the clipboard's file list and text flavour — the reverse
3401
+ * of {@link windowsClipboardScript}. The output is line based (`F:<path>` per
3402
+ * file, one `T:<base64 utf8>` line), so nothing has to be re-escaped as code.
3403
+ */
3404
+ export function windowsClipboardReadScript() {
3405
+ return [
3406
+ '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
3407
+ 'Add-Type -AssemblyName System.Windows.Forms',
3408
+ '$data = [System.Windows.Forms.Clipboard]::GetDataObject()',
3409
+ '$files = @()',
3410
+ '$text = ""',
3411
+ 'if ($data -ne $null -and $data.GetDataPresent("FileDrop")) { $files = @($data.GetData("FileDrop")) }',
3412
+ 'if ($data -ne $null -and $data.GetDataPresent("UnicodeText")) { $text = [string]$data.GetData("UnicodeText") }',
3413
+ 'foreach ($file in $files) { [Console]::Out.WriteLine("F:" + [string]$file) }',
3414
+ '[Console]::Out.WriteLine("T:" + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$text)))',
3415
+ ].join('\n')
3416
+ }
3417
+
3418
+ /**
3419
+ * Split {@link windowsClipboardReadScript}'s stdout into paths and text.
3420
+ * @param stdout - the script output.
3421
+ * @returns `{ files, text }` (paths are the raw Windows strings).
3422
+ */
3423
+ export function parseClipboardRead(stdout) {
3424
+ const files = []
3425
+ let text = ''
3426
+ for (const rawLine of String(stdout ?? '').split('\n')) {
3427
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
3428
+ if (line.startsWith('F:')) files.push(line.slice(2))
3429
+ else if (line.startsWith('T:')) text = Buffer.from(line.slice(2), 'base64').toString('utf8')
3430
+ }
3431
+ return { files, text }
3432
+ }
3433
+
3434
+ /**
3435
+ * Map Windows clipboard paths onto this WSL filesystem — `/fs/import` needs a
3436
+ * real Linux path. Entries that cannot be mapped are dropped, never guessed.
3437
+ * @param rawPaths - paths as Windows wrote them (`\\wsl.localhost\…`, `C:\…`).
3438
+ * @param options - `distro` overrides `$WSL_DISTRO_NAME` (tests).
3439
+ * @returns absolute Linux paths, de-duplicated and capped.
3440
+ */
3441
+ export function clipboardPathsToLinux(rawPaths, options = {}) {
3442
+ if (!Array.isArray(rawPaths)) return []
3443
+ const distro = String(options.distro ?? process.env.WSL_DISTRO_NAME ?? '').toLowerCase()
3444
+ const mapped = []
3445
+ const seen = new Set()
3446
+ for (const raw of rawPaths) {
3447
+ if (typeof raw !== 'string') continue
3448
+ const value = raw.trim()
3449
+ if (value === '') continue
3450
+ let path
3451
+ if (value.startsWith('/')) path = value
3452
+ else {
3453
+ const wsl = /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)\\(.*)$/i.exec(value)
3454
+ const drive = /^([A-Za-z]):\\(.*)$/.exec(value)
3455
+ if (wsl !== null) {
3456
+ // A different distro's filesystem is not visible from here.
3457
+ if (distro !== '' && wsl[1].toLowerCase() !== distro) continue
3458
+ path = '/' + wsl[2].replace(/\\/g, '/')
3459
+ } else if (drive !== null) {
3460
+ path = '/mnt/' + drive[1].toLowerCase() + '/' + drive[2].replace(/\\/g, '/')
3461
+ } else continue
3462
+ }
3463
+ if (seen.has(path)) continue
3464
+ seen.add(path)
3465
+ mapped.push(path)
3466
+ if (mapped.length >= CLIPBOARD_MAX_ENTRIES) break
3467
+ }
3468
+ return mapped
3469
+ }
3470
+
3471
+ /** Extract `file://` URIs from a gnome-copied-files / text/uri-list payload. */
3472
+ function fileUrlsToPaths(text) {
3473
+ const files = []
3474
+ for (const rawLine of String(text ?? '').split('\n')) {
3475
+ const line = rawLine.trim()
3476
+ if (line === '' || line === 'copy' || line === 'cut') continue
3477
+ if (!line.startsWith('file://')) continue
3478
+ try {
3479
+ const url = new URL(line)
3480
+ if (url.protocol !== 'file:') continue
3481
+ files.push(decodeURIComponent(url.pathname))
3482
+ } catch {
3483
+ // An unparsable line is not a file; the next line still is.
3484
+ }
3485
+ if (files.length >= CLIPBOARD_MAX_ENTRIES) break
3486
+ }
3487
+ return files
3488
+ }
3489
+
3490
+ /**
3491
+ * Read the SYSTEM clipboard: the file list it carries plus its text flavour.
3492
+ * @returns `{ files, text, method }` — `files` are native (Linux) absolute paths.
3493
+ */
3494
+ export async function readSystemFileClipboard() {
3495
+ if (process.platform === 'win32' || isWsl()) {
3496
+ const encoded = Buffer.from(windowsClipboardReadScript(), 'utf16le').toString('base64')
3497
+ const result = await runTool('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded])
3498
+ if (!result.ok) {
3499
+ throw new TailError('clipboard-failed', `PowerShell 读剪贴板失败:${(result.stderr || result.stdout).trim().split('\n')[0] || '未知错误'}`, 500)
3500
+ }
3501
+ const parsed = parseClipboardRead(result.stdout)
3502
+ return {
3503
+ files: IS_WINDOWS ? parsed.files : clipboardPathsToLinux(parsed.files),
3504
+ text: parsed.text,
3505
+ method: IS_WINDOWS ? 'windows-powershell' : 'wsl-powershell',
3506
+ }
3507
+ }
3508
+ if (process.platform === 'darwin') {
3509
+ // JXA: the file list is whatever NSURL objects the pasteboard exposes.
3510
+ const script = [
3511
+ 'function run() {',
3512
+ ' ObjC.import("AppKit")',
3513
+ ' var pasteboard = $.NSPasteboard.generalPasteboard',
3514
+ ' var files = []',
3515
+ ' var urls = pasteboard.readObjectsForClassesOptions($([$.NSURL]), $({}))',
3516
+ ' var count = urls ? Number(urls.count) : 0',
3517
+ ' for (var index = 0; index < count; index += 1) { files.push(ObjC.unwrap(urls.objectAtIndex(index).path)) }',
3518
+ ' var text = ObjC.unwrap(pasteboard.stringForType("public.utf8-plain-text"))',
3519
+ ' return JSON.stringify({ files: files, text: text || "" })',
3520
+ '}',
3521
+ ].join('\n')
3522
+ const result = await runTool('osascript', ['-l', 'JavaScript', '-e', script], undefined, 8000)
3523
+ if (!result.ok) {
3524
+ throw new TailError('clipboard-failed', `osascript 读剪贴板失败:${result.stderr.trim() || '未知错误'}`, 500)
3525
+ }
3526
+ let parsed = { files: [], text: '' }
3527
+ try {
3528
+ parsed = JSON.parse(result.stdout.trim() || '{}')
3529
+ } catch {
3530
+ parsed = { files: [], text: '' }
3531
+ }
3532
+ return {
3533
+ files: Array.isArray(parsed.files) ? parsed.files.filter((path) => typeof path === 'string' && path !== '') : [],
3534
+ text: typeof parsed.text === 'string' ? parsed.text : '',
3535
+ method: 'macos-appkit',
3536
+ }
3537
+ }
3538
+ // Linux desktop: xclip / wl-paste expose the SAME flavours the writer sets.
3539
+ const xclip = await runTool('xclip', ['-selection', 'clipboard', '-o', '-t', 'x-special/gnome-copied-files'], undefined, 8000)
3540
+ if (xclip.ok) return { files: fileUrlsToPaths(xclip.stdout), text: '', method: 'linux-xclip' }
3541
+ const wlPaste = await runTool('wl-paste', ['--type', 'text/uri-list'], undefined, 8000)
3542
+ if (wlPaste.ok) return { files: fileUrlsToPaths(wlPaste.stdout), text: '', method: 'linux-wl-paste' }
3543
+ return { files: [], text: '', method: 'unsupported' }
3544
+ }
3545
+
3546
+ /**
3547
+ * `GET /dsh-ris-ide/clipboard/read` — what the SYSTEM clipboard holds right now.
3548
+ * Read-only: it never writes the clipboard and never touches the filesystem.
3549
+ */
3550
+ async function serveClipboardRead(ctx, req, res) {
3551
+ try {
3552
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
3553
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
3554
+ const root = clipboardRoot(ctx, url.searchParams.get('sessionId') ?? '', url.searchParams.get('cwd') ?? '')
3555
+ const state = await readSystemFileClipboard()
3556
+ // A copy the tree published sits on the clipboard as a STAGED path. Translate
3557
+ // it back: the page compares against what the tree copied, so a round-trip must
3558
+ // look like the original selection (otherwise Ctrl+C → Ctrl+V would import a
3559
+ // second copy of files the tree already has).
3560
+ let files = state.files
3561
+ if (root !== undefined) {
3562
+ const mapping = await clipboardStageMapping(root)
3563
+ if (mapping.size > 0) files = files.map((path) => mapping.get(resolve(path)) ?? path)
3564
+ }
3565
+ writeJson(res, 200, { ok: true, files, text: state.text, method: state.method })
3566
+ } catch (error) {
3567
+ writeTailError(res, error)
3568
+ }
3569
+ }
3570
+
2551
3571
  /** Content types the media route can serve inline (`<img>`, `<iframe>`). */
2552
3572
  const FS_MEDIA_TYPES = {
2553
3573
  png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
@@ -2768,6 +3788,141 @@ async function readFileRange(path, start, end) {
2768
3788
  * grows, `: ping` comments keep proxies quiet. EventSource reconnects by itself,
2769
3789
  * so a restart of `dsh web` self-heals; the JSON routes remain as fallbacks.
2770
3790
  */
3791
+ /**
3792
+ * Drop window entries whose stream has been gone for a while. A plain reload
3793
+ * closes and reopens the stream within a second, so the grace period keeps the
3794
+ * entry alive across it instead of flickering "no window".
3795
+ * @param now - current epoch ms (tests pass a fixed clock).
3796
+ */
3797
+ function sweepIdeWindows(now = Date.now()) {
3798
+ for (const [key, entry] of IDE_WINDOWS) {
3799
+ if (entry.streams <= 0 && now - entry.at > IDE_WINDOW_GRACE_MS) IDE_WINDOWS.delete(key)
3800
+ }
3801
+ }
3802
+
3803
+ /** The registry key of one IDE window: its name when the page knows it, else its cwd. */
3804
+ function ideWindowKey(name, cwd) {
3805
+ if (typeof name === 'string' && name !== '') return `name:${name}`
3806
+ if (typeof cwd === 'string' && cwd !== '') return `cwd:${resolve(cwd)}`
3807
+ return undefined
3808
+ }
3809
+
3810
+ /** One IDE window's stream opened: remember it (the stream IS the liveness). */
3811
+ function ideWindowOpened(key, info) {
3812
+ if (typeof key !== 'string' || key === '') return
3813
+ const previous = IDE_WINDOWS.get(key)
3814
+ IDE_WINDOWS.set(key, {
3815
+ key,
3816
+ name: typeof info?.name === 'string' ? info.name : previous !== undefined ? previous.name : '',
3817
+ cwd: typeof info?.cwd === 'string' ? info.cwd : previous !== undefined ? previous.cwd : undefined,
3818
+ sessionId: typeof info?.sessionId === 'string' && info.sessionId !== ''
3819
+ ? info.sessionId
3820
+ : previous !== undefined ? previous.sessionId : '',
3821
+ at: Date.now(),
3822
+ streams: (previous !== undefined ? previous.streams : 0) + 1,
3823
+ })
3824
+ }
3825
+
3826
+ /** One IDE window's stream closed (the entry survives until the grace expires). */
3827
+ function ideWindowClosed(key) {
3828
+ if (typeof key !== 'string' || key === '') return
3829
+ const entry = IDE_WINDOWS.get(key)
3830
+ if (entry === undefined) return
3831
+ entry.streams = Math.max(0, entry.streams - 1)
3832
+ entry.at = Date.now()
3833
+ }
3834
+
3835
+ /**
3836
+ * List live IDE windows, optionally only one window name or one workspace.
3837
+ * @param {{name?: string, cwd?: string}} [filter] - narrow by window name and/or cwd.
3838
+ * @returns `[{ name, cwd, sessionId, alive, idleMs }]`, most recently seen first.
3839
+ */
3840
+ export function listIdeWindows(filter) {
3841
+ sweepIdeWindows()
3842
+ const wantedName = typeof filter?.name === 'string' && filter.name !== '' ? filter.name : undefined
3843
+ const wantedCwd = typeof filter?.cwd === 'string' && filter.cwd !== '' ? resolve(filter.cwd) : undefined
3844
+ const now = Date.now()
3845
+ const out = []
3846
+ for (const entry of IDE_WINDOWS.values()) {
3847
+ if (wantedName !== undefined && entry.name !== wantedName) continue
3848
+ if (wantedCwd !== undefined && entry.cwd !== wantedCwd) continue
3849
+ out.push({
3850
+ name: entry.name,
3851
+ cwd: entry.cwd,
3852
+ sessionId: entry.sessionId,
3853
+ alive: entry.streams > 0,
3854
+ idleMs: now - entry.at,
3855
+ })
3856
+ }
3857
+ out.sort((a, b) => a.idleMs - b.idleMs)
3858
+ return out
3859
+ }
3860
+
3861
+ /**
3862
+ * The DSH session a workspace currently belongs to: the newest LIVE session whose
3863
+ * header cwd is that workspace. A window that outlived its session (or the host
3864
+ * restart) uses this to hop onto the current one instead of staying on a dead id.
3865
+ * @param ctx - the Host context (`ctx.sessions` is the session store).
3866
+ * @param cwd - the workspace.
3867
+ * @returns `{ id }`, or `null` when no live session sits in that workspace.
3868
+ */
3869
+ export function liveSessionFor(ctx, cwd) {
3870
+ if (typeof cwd !== 'string' || cwd === '') return null
3871
+ let live
3872
+ try {
3873
+ live = ctx?.sessions?.list?.()
3874
+ } catch {
3875
+ return null
3876
+ }
3877
+ if (!Array.isArray(live)) return null
3878
+ const root = resolve(cwd)
3879
+ // The IDE is workspace-level: a window opened inside a program folder still
3880
+ // belongs to the workspace's session, so an ancestor cwd matches too — but an
3881
+ // exact match always wins over an ancestor one.
3882
+ let ancestor
3883
+ for (let index = live.length - 1; index >= 0; index -= 1) {
3884
+ const session = live[index]
3885
+ const sessionCwd = session?.header?.cwd
3886
+ if (typeof sessionCwd !== 'string' || sessionCwd === '') continue
3887
+ const base = resolve(sessionCwd)
3888
+ if (base === root) return { id: session.id }
3889
+ if (ancestor === undefined && root.startsWith(base.endsWith('/') ? base : `${base}/`)) ancestor = { id: session.id }
3890
+ }
3891
+ return ancestor ?? null
3892
+ }
3893
+
3894
+ /** Whether `id` is still a live session here (a stale window id stops being one). */
3895
+ function isLiveSession(ctx, id) {
3896
+ if (typeof id !== 'string' || id === '') return false
3897
+ try {
3898
+ return ctx?.sessions?.get?.(id) !== undefined
3899
+ } catch {
3900
+ // A detached id throws instead of answering: treat it as gone.
3901
+ return false
3902
+ }
3903
+ }
3904
+
3905
+ /** `GET /dsh-ris-ide/windows` — the live windows, and the session of one workspace. */
3906
+ async function serveWindows(ctx, req, res) {
3907
+ try {
3908
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
3909
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
3910
+ const rawCwd = url.searchParams.get('cwd') ?? ''
3911
+ if (rawCwd !== '' && !isAbsolute(expandHome(rawCwd))) {
3912
+ throw new TailError('bad-request', 'cwd must be an absolute workspace path', 400)
3913
+ }
3914
+ const cwd = rawCwd === '' ? undefined : resolve(expandHome(rawCwd))
3915
+ const name = (url.searchParams.get('name') ?? '').trim()
3916
+ writeJson(res, 200, {
3917
+ ok: true,
3918
+ windows: listIdeWindows({ name: name === '' ? undefined : name, cwd }),
3919
+ session: cwd === undefined ? null : liveSessionFor(ctx, cwd),
3920
+ })
3921
+ } catch (error) {
3922
+ writeTailError(res, error)
3923
+ }
3924
+ }
3925
+
2771
3926
  async function serveStream(ctx, req, res, options) {
2772
3927
  let url
2773
3928
  try {
@@ -2812,7 +3967,38 @@ async function serveStream(ctx, req, res, options) {
2812
3967
  })
2813
3968
  res.flushHeaders?.()
2814
3969
 
3970
+ // A standalone IDE window keeps ONE stream for its whole lifetime, so that
3971
+ // connection IS its liveness: `dsh web` restarts, the page reconnects, the
3972
+ // window re-registers by itself — no heartbeat, no stored state to go stale.
3973
+ const isIdeWindow = url.searchParams.get('window') === '1'
3974
+ // The window's workspace does NOT depend on the requested topics: a window whose
3975
+ // first connection only asks for `hello` never needs a resolved cwd, yet it must
3976
+ // still register (otherwise the ⧉ button sees no window and opens a second one).
3977
+ const rawWindowCwd = isIdeWindow ? (url.searchParams.get('cwd') ?? '').trim() : ''
3978
+ const windowCwd = isIdeWindow
3979
+ ? (typeof cwd === 'string' ? cwd : (rawWindowCwd !== '' && isAbsolute(rawWindowCwd) ? resolve(rawWindowCwd) : undefined))
3980
+ : undefined
3981
+ const helloCwd = typeof cwd === 'string' ? cwd : windowCwd
3982
+ const streamWindowName = (url.searchParams.get('wname') ?? '').trim()
3983
+ const windowKey = windowCwd !== undefined ? ideWindowKey(streamWindowName, windowCwd) : undefined
3984
+ if (windowKey !== undefined) {
3985
+ ideWindowOpened(windowKey, {
3986
+ name: streamWindowName,
3987
+ cwd: windowCwd,
3988
+ sessionId: (url.searchParams.get('sessionId') ?? '').trim(),
3989
+ })
3990
+ }
3991
+
2815
3992
  let closed = false
3993
+ // The window entry must be released exactly once: an aborted SSE connection may
3994
+ // report 'error' and then 'close' (and a clean reload only reports 'close'), and
3995
+ // double-decrementing would hide a real second stream.
3996
+ let windowSettled = false
3997
+ const settleWindow = () => {
3998
+ if (windowSettled === true) return
3999
+ windowSettled = true
4000
+ if (windowKey !== undefined) ideWindowClosed(windowKey)
4001
+ }
2816
4002
  const cleanups = []
2817
4003
  const send = (event, payload) => {
2818
4004
  if (closed) return false
@@ -2829,7 +4015,22 @@ async function serveStream(ctx, req, res, options) {
2829
4015
  return false
2830
4016
  }
2831
4017
  }
2832
- send('hello', { ok: true, version: PKG_VERSION, root: cwd, topics })
4018
+ const streamSession = (url.searchParams.get('sessionId') ?? '').trim()
4019
+ send('hello', {
4020
+ ok: true,
4021
+ version: PKG_VERSION,
4022
+ root: cwd,
4023
+ topics,
4024
+ window: windowCwd !== undefined,
4025
+ // The session this workspace is on RIGHT NOW. A window left open across a
4026
+ // `dsh web` restart reads this and follows the new session instead of
4027
+ // keeping the dead id it was opened with.
4028
+ session: helloCwd === undefined ? null : liveSessionFor(ctx, helloCwd),
4029
+ // Whether the id this stream asked for is still a live session here: false
4030
+ // means "the page may switch to `session`", null means it never had one.
4031
+ windowSession: streamSession === '' ? null
4032
+ : { id: streamSession, live: isLiveSession(ctx, streamSession) },
4033
+ })
2833
4034
 
2834
4035
  const heartbeat = setInterval(() => {
2835
4036
  if (closed) return
@@ -2843,12 +4044,16 @@ async function serveStream(ctx, req, res, options) {
2843
4044
 
2844
4045
  res.on('error', () => {
2845
4046
  // An aborted SSE connection emits 'error'; without a listener Node would
2846
- // treat it as an uncaught exception.
4047
+ // treat it as an uncaught exception. The stream is gone either way, so free
4048
+ // the window registration here too (a window stuck "alive" would make the next
4049
+ // ⧉ wait out its close handshake against a window that is not there).
2847
4050
  closed = true
4051
+ settleWindow()
2848
4052
  })
2849
4053
  res.on('close', () => {
2850
4054
  closed = true
2851
4055
  clearInterval(heartbeat)
4056
+ settleWindow()
2852
4057
  for (const cleanup of cleanups) {
2853
4058
  try {
2854
4059
  cleanup()
@@ -3181,7 +4386,7 @@ function sourcesJarOf(jar) {
3181
4386
  }
3182
4387
 
3183
4388
  /**
3184
- * The dependency-source cache (`<cwd>/.dsh-ris-ide-cache/`) is keyed by a
4389
+ * The dependency-source cache (`<cwd>/.dsh-ris-ide/cache/`) is keyed by a
3185
4390
  * FINGERPRINT of its inputs (jar path+size+mtime and the entry's name/size/crc,
3186
4391
  * plus the decompiler jar+args), not by file age: a rebuilt jar invalidates its
3187
4392
  * derived files immediately. `manifest.json` remembers those fingerprints, and a
@@ -3255,7 +4460,7 @@ async function cacheFiles(root) {
3255
4460
  /**
3256
4461
  * Drop aged files first, then the least-recently-written ones until the cache
3257
4462
  * fits its size/file budget. Rate-limited so a burst of resolves prunes once.
3258
- * @param {string} root - the `.dsh-ris-ide-cache` directory.
4463
+ * @param {string} root - the `.dsh-ris-ide/cache` directory.
3259
4464
  * @param {{maxBytes?: number, maxFiles?: number, maxAgeMs?: number, force?: boolean}} [options]
3260
4465
  */
3261
4466
  export async function pruneIdeCache(root, options) {
@@ -3304,6 +4509,7 @@ export async function pruneIdeCache(root, options) {
3304
4509
  * still exists, otherwise produced and written (then the cache GC may run).
3305
4510
  */
3306
4511
  async function cachedSource(cwd, kind, className, suffix, key, produce) {
4512
+ await ensureIdeStateDir(cwd)
3307
4513
  const root = join(cwd, IDE_CACHE_DIR)
3308
4514
  const rel = kind + '/' + className + suffix
3309
4515
  const target = join(root, rel)
@@ -3343,10 +4549,10 @@ function runCapture(command, args, cwd) {
3343
4549
  })
3344
4550
  }
3345
4551
 
3346
- /** The user's decompiler choice: `.dsh-ris-ide.settings.json` first, then `.dsh-ris-ide.json`. */
4552
+ /** The user's decompiler choice: `.dsh-ris-ide/settings.json` first, then `.dsh-ris-ide/config.json`. */
3347
4553
  async function readDecompilerConfig(cwd) {
3348
- const settingsPath = resolve(cwd, IDE_SETTINGS_FILENAME)
3349
- const settingsText = await readTextIfSmall(settingsPath)
4554
+ let settingsText = await readTextIfSmall(resolve(cwd, IDE_SETTINGS_FILENAME))
4555
+ if (settingsText === undefined) settingsText = await readTextIfSmall(resolve(cwd, LEGACY_SETTINGS_FILENAME))
3350
4556
  if (settingsText !== undefined) {
3351
4557
  const parsed = parseJsonc(settingsText)
3352
4558
  if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
@@ -3356,7 +4562,8 @@ async function readDecompilerConfig(cwd) {
3356
4562
  }
3357
4563
  }
3358
4564
  }
3359
- const configText = await readTextIfSmall(resolve(cwd, CONFIG_FILENAME))
4565
+ let configText = await readTextIfSmall(resolve(cwd, CONFIG_FILENAME))
4566
+ if (configText === undefined) configText = await readTextIfSmall(resolve(cwd, LEGACY_CONFIG_FILENAME))
3360
4567
  if (configText === undefined) return undefined
3361
4568
  const parsed = parseJsonc(configText)
3362
4569
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
@@ -3468,7 +4675,7 @@ async function serveDebugSource(ctx, req, res, options) {
3468
4675
 
3469
4676
  /**
3470
4677
  * `/dsh-ris-ide/settings`: GET returns the visual debug settings, POST saves the
3471
- * decompiler jar into `.dsh-ris-ide.settings.json` (the program config stays
4678
+ * decompiler jar into `.dsh-ris-ide/settings.json` (the program config stays
3472
4679
  * untouched — rewriting JSONC would drop the user's comments).
3473
4680
  */
3474
4681
  async function serveSettings(ctx, req, res, options) {
@@ -3482,6 +4689,7 @@ async function serveSettings(ctx, req, res, options) {
3482
4689
  const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
3483
4690
  if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3484
4691
  const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
4692
+ await ensureIdeStateDir(cwd)
3485
4693
  const path = settingsPathOf(cwd)
3486
4694
  const existingText = await readTextIfSmall(path)
3487
4695
  const existing = existingText === undefined ? {} : parseJsonc(existingText)
@@ -3497,6 +4705,7 @@ async function serveSettings(ctx, req, res, options) {
3497
4705
  const sessionId = url.searchParams.get('sessionId') ?? ''
3498
4706
  if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3499
4707
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
4708
+ await ensureIdeStateDir(cwd)
3500
4709
  const config = await readDecompilerConfig(cwd)
3501
4710
  writeJson(res, 200, {
3502
4711
  ok: true,
@@ -3635,13 +4844,19 @@ async function serveDebug(ctx, req, res, options) {
3635
4844
  }
3636
4845
 
3637
4846
  /**
3638
- * One request: start one discovered program. The body is
3639
- * `{ sessionId, id, cwd?, dir? }` — only the program id identifies what to run,
3640
- * and the host re-scans before composing the command.
4847
+ * One request: start (or restart) one discovered program. The body is
4848
+ * `{ sessionId, id, cwd?, dir?, restart? }` — only the program id identifies
4849
+ * what to run, and the host re-scans before composing the command.
4850
+ *
4851
+ * `restart: true` is the panel's "重启" button: stop whatever owns this program's
4852
+ * log first (with the SAME stop grace as `/stop`), then start it again and report
4853
+ * `restarted` so the caller knows a stop really happened. A program that is not
4854
+ * running is simply started (there is no pidfile to honour, and treating that as
4855
+ * a failed restart would make the button useless on a stopped row).
3641
4856
  * @param ctx - Host context (session cwd lookup).
3642
4857
  * @param req - Node request face (POST).
3643
4858
  * @param res - Node response face.
3644
- * @param options - `{ restrictToCwd }` (see {@link apply}).
4859
+ * @param options - `{ restrictToCwd, stopGraceMs }` (see {@link apply}).
3645
4860
  */
3646
4861
  async function serveStart(ctx, req, res, options) {
3647
4862
  try {
@@ -3659,6 +4874,15 @@ async function serveStart(ctx, req, res, options) {
3659
4874
  if (program === undefined) {
3660
4875
  throw new TailError('unknown-program', `no runnable program "${id}" was found under ${cwd}`, 404)
3661
4876
  }
4877
+ if (body.restart === true) {
4878
+ const wasRunning = program.running !== null && program.running !== undefined && program.running.alive === true
4879
+ if (wasRunning) await stopLogPath(program.logPath, options?.stopGraceMs)
4880
+ // A stale `running` row must not make startProgram answer `alreadyRunning`
4881
+ // for a process we just stopped (or never found).
4882
+ const started = await startProgram(cwd, logsDir, Object.assign({}, program, { running: null }), options)
4883
+ writeJson(res, 200, { ok: true, restarted: wasRunning, ...started })
4884
+ return
4885
+ }
3662
4886
  writeJson(res, 200, { ok: true, ...await startProgram(cwd, logsDir, program, options) })
3663
4887
  } catch (error) {
3664
4888
  writeTailError(res, error)
@@ -3841,6 +5065,314 @@ export async function stopLogPath(logPath, fallbackGraceMs) {
3841
5065
  return outcome
3842
5066
  }
3843
5067
 
5068
+ /** One captured run's console: keep the first 4 KiB (mvn's real error often comes
5069
+ * first) plus the LAST 400k characters (the failing test's stack trace). */
5070
+ const RUN_TEST_HEAD_CHARS = 4096
5071
+ const RUN_TEST_TAIL_CHARS = 400000
5072
+ /** A single-test run is killed (TERM, then KILL) after this long. */
5073
+ const RUN_TEST_TIMEOUT_MS = 900000
5074
+ /** Grace between SIGTERM and SIGKILL when a run times out. */
5075
+ const RUN_TEST_KILL_GRACE_MS = 2000
5076
+ /** In-memory run records kept; the oldest is dropped past this (see {@link rememberRunTest}). */
5077
+ const RUN_TEST_MAX_RECORDS = 10
5078
+ /** Characters allowed in a Maven profile id / `-Dtest` selector / one module segment. */
5079
+ const RUN_TEST_NAME_RE = /^[A-Za-z0-9_.\-$#]+$/
5080
+ /** id → run record (bounded, oldest dropped). */
5081
+ const RUN_TEST_RECORDS = new Map()
5082
+ /** Monotonic suffix so two runs in the same millisecond still get distinct ids. */
5083
+ let runTestSequence = 0
5084
+
5085
+ /** Allocate a short, unique, human-scannable run id. */
5086
+ function nextRunTestId() {
5087
+ runTestSequence += 1
5088
+ return `rt-${Date.now().toString(36)}-${runTestSequence.toString(36)}`
5089
+ }
5090
+
5091
+ /**
5092
+ * Validate one Maven module path: relative, `/`-separated segments of the same
5093
+ * safe charset. `..` is refused outright (containment is enforced again by
5094
+ * {@link resolvePath}), and `.` means "the cwd itself".
5095
+ * @param value - the request's `module`.
5096
+ * @returns the normalized relative module path.
5097
+ * @throws {TailError} `bad-request` when it is missing, absolute, or unsafe.
5098
+ */
5099
+ function validateRunTestModule(value) {
5100
+ if (typeof value !== 'string' || value.trim() === '') {
5101
+ throw new TailError('bad-request', 'module is required (a path relative to cwd)', 400)
5102
+ }
5103
+ const raw = value.trim()
5104
+ if (isAbsolute(raw)) {
5105
+ throw new TailError('bad-request', 'module must be a path relative to cwd, not an absolute path', 400)
5106
+ }
5107
+ const segments = raw.split('/').filter((segment) => segment !== '' && segment !== '.')
5108
+ if (segments.length === 0) return '.'
5109
+ for (const segment of segments) {
5110
+ if (segment === '..' || !RUN_TEST_NAME_RE.test(segment)) {
5111
+ throw new TailError('bad-request', `module segment "${segment}" is not a safe Maven module name`, 400)
5112
+ }
5113
+ }
5114
+ return segments.join('/')
5115
+ }
5116
+
5117
+ /**
5118
+ * Validate one `-Dtest` selector. `shell: false` already makes injection
5119
+ * impossible, but a stray `;`, space or `(` is a caller bug worth a clear 400.
5120
+ * @param value - the request's `test`.
5121
+ * @returns the selector.
5122
+ * @throws {TailError} `bad-request` when it is missing or unsafe.
5123
+ */
5124
+ function validateRunTestSelector(value) {
5125
+ if (typeof value !== 'string' || value === '' || !RUN_TEST_NAME_RE.test(value)) {
5126
+ throw new TailError('bad-request', 'test must match /^[A-Za-z0-9_.\\-$#]+$/ (a Maven -Dtest selector)', 400)
5127
+ }
5128
+ return value
5129
+ }
5130
+
5131
+ /**
5132
+ * The Maven profile for one run: `-Pdev` unless the caller named one.
5133
+ * @param body - the parsed request body.
5134
+ * @returns the validated profile id.
5135
+ * @throws {TailError} `bad-request` for a profile that is not a plain id.
5136
+ */
5137
+ function runTestProfile(body) {
5138
+ const raw = typeof body.profile === 'string' ? body.profile.trim() : ''
5139
+ if (raw === '') return 'dev'
5140
+ if (!RUN_TEST_NAME_RE.test(raw)) {
5141
+ throw new TailError('bad-request', 'profile must be a Maven profile id (letters, digits, _ . - $ #)', 400)
5142
+ }
5143
+ return raw
5144
+ }
5145
+
5146
+ /** `mvn` is a `.cmd` shim on Windows; `spawn` with `shell: false` needs that name. */
5147
+ function mavenExecutable() {
5148
+ return IS_WINDOWS ? 'mvn.cmd' : 'mvn'
5149
+ }
5150
+
5151
+ /**
5152
+ * Append one console chunk while BOTH ends stay bounded: the head is kept as
5153
+ * the first {@link RUN_TEST_HEAD_CHARS} characters, the tail as the last
5154
+ * {@link RUN_TEST_TAIL_CHARS}. `total` remembers how much was dropped.
5155
+ * @param record - the run record being filled.
5156
+ * @param chunk - a stdout/stderr chunk (Buffer or string).
5157
+ */
5158
+ function appendRunTestOutput(record, chunk) {
5159
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8')
5160
+ record.total += text.length
5161
+ if (record.head.length < RUN_TEST_HEAD_CHARS) {
5162
+ record.head += text.slice(0, RUN_TEST_HEAD_CHARS - record.head.length)
5163
+ }
5164
+ record.tail += text
5165
+ if (record.tail.length > RUN_TEST_TAIL_CHARS) {
5166
+ record.tail = record.tail.slice(record.tail.length - RUN_TEST_TAIL_CHARS)
5167
+ }
5168
+ }
5169
+
5170
+ /**
5171
+ * The console text handed back to the panel: whole output when it fits, and
5172
+ * `head + "…(省略 N 字符)…" + tail` when the caps had to bite.
5173
+ * @param record - the run record.
5174
+ * @returns the (possibly elided) console text.
5175
+ */
5176
+ function runTestOutput(record) {
5177
+ if (record.total <= RUN_TEST_HEAD_CHARS) return record.head
5178
+ if (record.total <= RUN_TEST_TAIL_CHARS) return record.tail
5179
+ const tailStart = record.total - record.tail.length
5180
+ if (tailStart <= RUN_TEST_HEAD_CHARS) return record.head.slice(0, tailStart) + record.tail
5181
+ const dropped = tailStart - record.head.length
5182
+ return `${record.head}…(省略 ${dropped} 字符)…${record.tail}`
5183
+ }
5184
+
5185
+ /**
5186
+ * Remember one run, dropping the oldest past {@link RUN_TEST_MAX_RECORDS}.
5187
+ * @param record - the record to store (its `id` is the key).
5188
+ */
5189
+ function rememberRunTest(record) {
5190
+ RUN_TEST_RECORDS.set(record.id, record)
5191
+ while (RUN_TEST_RECORDS.size > RUN_TEST_MAX_RECORDS) {
5192
+ const oldest = RUN_TEST_RECORDS.keys().next().value
5193
+ if (oldest === undefined) break
5194
+ RUN_TEST_RECORDS.delete(oldest)
5195
+ }
5196
+ }
5197
+
5198
+ /**
5199
+ * Finalize one run exactly once (the close handler and the timeout race for it).
5200
+ * @param record - the run record.
5201
+ * @param code - the child's exit code, when it exited normally.
5202
+ * @param status - `done` | `failed` | `timeout`.
5203
+ * @param extra - optional console text appended first (a spawn failure note).
5204
+ */
5205
+ function finishRunTest(record, code, status, extra) {
5206
+ if (record.status !== 'running') return
5207
+ if (record.timer !== null) {
5208
+ clearTimeout(record.timer)
5209
+ record.timer = null
5210
+ }
5211
+ if (typeof extra === 'string' && extra !== '') appendRunTestOutput(record, extra)
5212
+ record.status = status
5213
+ record.exitCode = Number.isInteger(code) ? code : null
5214
+ record.durationMs = Date.now() - record.startedAt
5215
+ }
5216
+
5217
+ /**
5218
+ * Kill a timed-out `mvn` and its children: on POSIX the group TERM→KILL (the
5219
+ * spawn was detached, so `mvn → java → surefire` share one pgid), on Windows
5220
+ * `taskkill /T`. Same escalation the service stop path uses.
5221
+ * @param record - the run record holding the child.
5222
+ */
5223
+ function killRunTestTree(record) {
5224
+ const child = record.child
5225
+ if (child === null || child === undefined) return
5226
+ if (IS_WINDOWS) {
5227
+ if (Number.isInteger(child.pid)) void taskkillTree(child.pid)
5228
+ return
5229
+ }
5230
+ const pgid = Number.isInteger(child.pid) ? child.pid : undefined
5231
+ const signal = (name) => {
5232
+ try {
5233
+ if (pgid !== undefined) process.kill(-pgid, name)
5234
+ else child.kill(name)
5235
+ } catch {
5236
+ // already gone
5237
+ }
5238
+ }
5239
+ signal('SIGTERM')
5240
+ record.killTimer = setTimeout(() => signal('SIGKILL'), RUN_TEST_KILL_GRACE_MS)
5241
+ record.killTimer.unref?.()
5242
+ }
5243
+
5244
+ /**
5245
+ * One POST: start `mvn -P<profile> -q -pl <module> test -Dtest=<test>` and answer
5246
+ * at once; the console is polled through {@link serveRunTestStatus}.
5247
+ *
5248
+ * `cwd` is the Maven reactor root (the directory holding the top `pom.xml`):
5249
+ * Maven resolves `-pl` relative to it, so a nested module such as
5250
+ * `ris-model/ris-model-biz` is addressed from the reactor root, not from itself.
5251
+ * @param ctx - Host context (session cwd lookup).
5252
+ * @param req - Node request face (POST).
5253
+ * @param res - Node response face.
5254
+ * @param options - `{ restrictToCwd }` (see {@link apply}).
5255
+ */
5256
+ async function serveRunTestStart(ctx, req, res, options) {
5257
+ try {
5258
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
5259
+ const body = await readJsonBody(req)
5260
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
5261
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
5262
+ const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
5263
+ const module = validateRunTestModule(body.module)
5264
+ const test = validateRunTestSelector(body.test)
5265
+ const profile = runTestProfile(body)
5266
+ // The module has to be a real Maven module INSIDE the session cwd: strict
5267
+ // containment even when the plugin runs unrestricted, because this value
5268
+ // ends up in a spawn argument.
5269
+ const moduleDir = resolvePath(cwd, module, true)
5270
+ const pom = await stat(join(moduleDir, 'pom.xml')).catch(() => undefined)
5271
+ if (pom === undefined || !pom.isFile()) {
5272
+ throw new TailError('unknown-module', `no pom.xml under "${module}" (not a Maven module of ${cwd})`, 404)
5273
+ }
5274
+ const args = [`-P${profile}`, '-q', '-pl', module, 'test', `-Dtest=${test}`, '-DfailIfNoTests=false', '-DskipITs']
5275
+ const command = `mvn ${args.map((arg) => quoteShell(arg)).join(' ')}`
5276
+ const record = {
5277
+ id: nextRunTestId(),
5278
+ status: 'running',
5279
+ exitCode: null,
5280
+ startedAt: Date.now(),
5281
+ durationMs: 0,
5282
+ command,
5283
+ module,
5284
+ test,
5285
+ profile,
5286
+ child: null,
5287
+ timer: null,
5288
+ killTimer: null,
5289
+ head: '',
5290
+ tail: '',
5291
+ total: 0,
5292
+ }
5293
+ rememberRunTest(record)
5294
+ let child
5295
+ try {
5296
+ child = spawn(mavenExecutable(), args, {
5297
+ cwd,
5298
+ windowsHide: true,
5299
+ shell: false,
5300
+ stdio: ['ignore', 'pipe', 'pipe'],
5301
+ // POSIX: its own process group, so a timeout can stop the whole tree.
5302
+ detached: !IS_WINDOWS,
5303
+ })
5304
+ } catch (error) {
5305
+ const reason = error instanceof Error ? error.message : String(error)
5306
+ finishRunTest(record, null, 'failed', `\n[spawn failed] ${reason}\n`)
5307
+ writeJson(res, 200, { ok: true, id: record.id, command, startedAt: record.startedAt })
5308
+ return
5309
+ }
5310
+ record.child = child
5311
+ child.stdout?.on('data', (chunk) => appendRunTestOutput(record, chunk))
5312
+ // Interleaved on purpose: Maven writes errors and the test log to two
5313
+ // streams, and the user reads them as one console.
5314
+ child.stderr?.on('data', (chunk) => appendRunTestOutput(record, chunk))
5315
+ child.on('error', (error) => {
5316
+ const reason = isMissingExecutable(error)
5317
+ ? 'mvn not found on PATH (install Maven, or put mvn/mvn.cmd on the PATH the host was started with)'
5318
+ : (error instanceof Error ? error.message : String(error))
5319
+ finishRunTest(record, null, 'failed', `\n[spawn failed] ${reason}\n`)
5320
+ })
5321
+ child.on('close', (code) => {
5322
+ // The timeout path finalizes first; a late close must not rewrite it.
5323
+ if (record.status !== 'running') return
5324
+ finishRunTest(record, code, code === 0 ? 'done' : 'failed')
5325
+ })
5326
+ record.timer = setTimeout(() => {
5327
+ if (record.status !== 'running') return
5328
+ killRunTestTree(record)
5329
+ finishRunTest(record, child.exitCode, 'timeout')
5330
+ }, RUN_TEST_TIMEOUT_MS)
5331
+ record.timer.unref?.()
5332
+ writeJson(res, 200, { ok: true, id: record.id, command, startedAt: record.startedAt })
5333
+ } catch (error) {
5334
+ writeTailError(res, error)
5335
+ }
5336
+ }
5337
+
5338
+ /**
5339
+ * One GET: the state and (capped) console of one run. Query parameters
5340
+ * `sessionId`, `cwd`, `id`.
5341
+ * @param ctx - Host context (session cwd lookup).
5342
+ * @param req - Node request face (GET).
5343
+ * @param res - Node response face.
5344
+ * @param options - `{ restrictToCwd }` (see {@link apply}).
5345
+ */
5346
+ async function serveRunTestStatus(ctx, req, res, options) {
5347
+ try {
5348
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
5349
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
5350
+ const sessionId = url.searchParams.get('sessionId') ?? ''
5351
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
5352
+ // Resolved only to validate the session (records are host-wide, keyed by id).
5353
+ resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
5354
+ const id = url.searchParams.get('id') ?? ''
5355
+ if (id === '') throw new TailError('bad-request', 'id is required', 400)
5356
+ const record = RUN_TEST_RECORDS.get(id)
5357
+ if (record === undefined) {
5358
+ throw new TailError('not-found', `no run-test record "${id}" (a host restart clears them, and only the last ${RUN_TEST_MAX_RECORDS} are kept)`, 404)
5359
+ }
5360
+ const running = record.status === 'running'
5361
+ writeJson(res, 200, {
5362
+ ok: true,
5363
+ id: record.id,
5364
+ status: record.status,
5365
+ exitCode: record.exitCode,
5366
+ output: runTestOutput(record),
5367
+ startedAt: record.startedAt,
5368
+ durationMs: running ? Date.now() - record.startedAt : record.durationMs,
5369
+ running,
5370
+ })
5371
+ } catch (error) {
5372
+ writeTailError(res, error)
5373
+ }
5374
+ }
5375
+
3844
5376
  /**
3845
5377
  * Scan one workspace root for runnable programs.
3846
5378
  *
@@ -4263,7 +5795,7 @@ export function buildStartSpec(program, context) {
4263
5795
  ? program.mainClass
4264
5796
  : (launchMainClass ?? program.mainClass)
4265
5797
  const args = resolveSpringArgs(program, workspace)
4266
- // User JVM flags (memory, GC, agents) come from `.dsh-ris-ide.json`; they sit
5798
+ // User JVM flags (memory, GC, agents) come from `.dsh-ris-ide/config.json`; they sit
4267
5799
  // after the plugin's required -D flags so a deliberate override still wins.
4268
5800
  const jvmArgs = normalizeStringArray(program.jvmArgs) ?? []
4269
5801
  // Debug mode adds the JDWP agent before the user's own JVM flags.
@@ -4656,7 +6188,7 @@ export function parseJsonc(text) {
4656
6188
 
4657
6189
  // ── User program config (generated from a scan, then user-maintained) ────────
4658
6190
  //
4659
- // The panel can write `<workspace>/.dsh-ris-ide.json` from what it discovered.
6191
+ // The panel can write `<workspace>/.dsh-ris-ide/config.json` from what it discovered.
4660
6192
  // After that the file belongs to the user: entries override discovered programs
4661
6193
  // by id (then dir, then name), entries that match nothing become user-added
4662
6194
  // programs, `disabled: true` hides a row, and `startCommand` replaces the
@@ -4669,8 +6201,16 @@ export function parseJsonc(text) {
4669
6201
  * @returns `{ path, exists, entries, error }`; `entries` only holds valid rows.
4670
6202
  */
4671
6203
  export async function readProgramConfig(cwd) {
4672
- const path = resolve(cwd, CONFIG_FILENAME)
4673
- const text = await readTextIfSmall(path)
6204
+ let path = resolve(cwd, CONFIG_FILENAME)
6205
+ let text = await readTextIfSmall(path)
6206
+ if (text === undefined) {
6207
+ const legacy = resolve(cwd, LEGACY_CONFIG_FILENAME)
6208
+ const legacyText = await readTextIfSmall(legacy)
6209
+ if (legacyText !== undefined) {
6210
+ path = legacy
6211
+ text = legacyText
6212
+ }
6213
+ }
4674
6214
  if (text === undefined) return { path, exists: false, entries: [], error: undefined }
4675
6215
  const parsed = parseJsonc(text)
4676
6216
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
@@ -4949,6 +6489,7 @@ export function buildConfigDocument(programs, workspace) {
4949
6489
  /** Write the generated config (refuses to clobber an existing file unless asked). */
4950
6490
  async function writeProgramConfig(cwd, logsDir, mode, fresh = false) {
4951
6491
  if (fresh) discoveryCache.delete(resolve(cwd))
6492
+ await ensureIdeStateDir(cwd)
4952
6493
  const path = resolve(cwd, CONFIG_FILENAME)
4953
6494
  const exists = existsSync(path)
4954
6495
  if (exists && mode !== 'update' && mode !== 'overwrite') {
@@ -5247,7 +6788,7 @@ export function registerAgentTools(ctx, options) {
5247
6788
  description: 'Start one discovered program (Spring Boot: mvn -Pdev compile then exec java; frontend: exec <pm> run <script>), wrapped by run-with-log.sh so it gets a log file, a pidfile and the sidebar stop button. '
5248
6789
  + 'Resolve the program with ris_dev_programs and check ris_dev_status first; give its id, or a unique name fragment. '
5249
6790
  + 'Starting an already-running program is NOT an error: it returns alreadyRunning=true without touching it; use ris_dev_restart to restart it. '
5250
- + 'JVM options (memory, GC) come from the workspace config `.dsh-ris-ide.json` (`defaults.jvmArgs` / per-program `jvmArgs`), not from this call.',
6791
+ + 'JVM options (memory, GC) come from the workspace config `.dsh-ris-ide/config.json` (`defaults.jvmArgs` / per-program `jvmArgs`), not from this call.',
5251
6792
  parameters: {
5252
6793
  type: 'object',
5253
6794
  additionalProperties: false,
@@ -5956,6 +7497,19 @@ export const __test = {
5956
7497
  LOG_ROTATE_BYTES,
5957
7498
  searchRoots,
5958
7499
  searchWorkspaceFiles,
7500
+ // git-grep CONTENT search (workspace fallback is a plain substring scan)
7501
+ CONTENT_SEARCH_PATH,
7502
+ searchWorkspaceContent,
7503
+ serveContentSearch,
7504
+ // one-module `mvn test` runner (poll the console through GET ?id=)
7505
+ RUN_TEST_PATH,
7506
+ serveRunTestStart,
7507
+ serveRunTestStatus,
7508
+ RUN_TEST_MAX_RECORDS,
7509
+ RUN_TEST_TIMEOUT_MS,
7510
+ RUN_TEST_HEAD_CHARS,
7511
+ RUN_TEST_TAIL_CHARS,
7512
+ runTestOutput,
5959
7513
  // gitignore-aware, compact-chain-folding tree level
5960
7514
  findGitRoot,
5961
7515
  repoAllowedPaths,
@@ -6079,6 +7633,12 @@ export const __test = {
6079
7633
  STREAM_PATH,
6080
7634
  BUNDLE_PATH,
6081
7635
  WINDOW_PAGE_PATH,
7636
+ WINDOWS_PATH,
7637
+ serveWindows,
7638
+ listIdeWindows,
7639
+ liveSessionFor,
7640
+ ideWindowOpened,
7641
+ ideWindowClosed,
6082
7642
  WINDOW_APP_PATH,
6083
7643
  WINDOW_VENDOR_PREFIX,
6084
7644
  WINDOW_VENDOR_FILES,
@@ -6094,6 +7654,27 @@ export const __test = {
6094
7654
  FS_UPLOAD_MAX_BYTES,
6095
7655
  serveFsOp,
6096
7656
  serveFsImport,
7657
+ // the tree's copy mirrored onto the OS clipboard (paste in Explorer/Finder/…)
7658
+ CLIPBOARD_FILES_PATH,
7659
+ CLIPBOARD_MAX_ENTRIES,
7660
+ CLIPBOARD_MAX_PAYLOAD,
7661
+ CLIPBOARD_STAGE_DIR,
7662
+ CLIPBOARD_STAGE_MAX_BYTES,
7663
+ stageClipboardCopy,
7664
+ pruneClipboardStage,
7665
+ clipboardStageMapping,
7666
+ serveClipboardFiles,
7667
+ writeSystemFileClipboard,
7668
+ windowsClipboardScript,
7669
+ isWsl,
7670
+ // …and reading it back (Desktop → tree pastes: WSLg hides CF_HDROP from the page)
7671
+ CLIPBOARD_READ_PATH,
7672
+ clipboardScope,
7673
+ serveClipboardRead,
7674
+ readSystemFileClipboard,
7675
+ windowsClipboardReadScript,
7676
+ parseClipboardRead,
7677
+ clipboardPathsToLinux,
6097
7678
  CLIENT_CHUNKS,
6098
7679
  serveBundle,
6099
7680
  FS_READ_PATH,