dsh-ris-ide 1.7.0 → 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
@@ -217,11 +274,11 @@ const RUN_TEST_PATH = `${ROUTE_PREFIX}/run-test`
217
274
  /** One directory level for the IDE tree: gitignore-filtered + compact chains folded. */
218
275
  const TREE_PATH = `${ROUTE_PREFIX}/tree`
219
276
  /** Deleted entries park here so the tree's Ctrl+Z can bring them back. */
220
- export const TREE_TRASH_DIR = '.dsh-ris-ide-trash'
277
+ export const TREE_TRASH_DIR = `${IDE_STATE_DIR}/trash`
221
278
  /** Path segments whose churn is never interesting to the file tree. */
222
279
  const TREE_WATCH_IGNORED = new Set([
223
280
  'node_modules', 'target', 'build', 'dist', 'out', 'coverage', '.git',
224
- 'logs', '.dsh', '.dsh-ris-ide-trash', '.gradle', '.idea', '.mvn', '.dsh-ris-ide-cache',
281
+ 'logs', '.dsh', '.dsh-ris-ide', '.gradle', '.idea', '.mvn',
225
282
  ])
226
283
 
227
284
  /**
@@ -241,12 +298,14 @@ const DEBUG_PATH = `${ROUTE_PREFIX}/debug`
241
298
  const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
242
299
  /** Pulls a dependency class's source out of its jar (sources → decompiler → javap). */
243
300
  const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
244
- /** 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`. */
245
302
  const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
246
303
  /** Workspace cache holding extracted sources / decompiled files. */
247
- export const IDE_CACHE_DIR = '.dsh-ris-ide-cache'
304
+ export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
248
305
  /** Where the visual settings dialog persists the decompiler jar. */
249
- 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'
250
309
  const CLASS_NAME_PATTERN = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/
251
310
  const ZIP_EOCD_SIGNATURE = 0x06054b50
252
311
  const ZIP_CENTRAL_SIGNATURE = 0x02014b50
@@ -254,8 +313,10 @@ const ZIP_LOCAL_SIGNATURE = 0x04034b50
254
313
  const SOURCE_ENTRY_MAX_BYTES = 4 * 1024 * 1024
255
314
  /** One JDWP session per program, shared by the routes, the tool and the workbench UI. */
256
315
  const debugSessions = createDebugSessions()
257
- /** The user-editable program config, in the session workspace root. */
258
- 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'
259
320
  /** Header written into a generated config file (JSONC: `parseJsonc` tolerates it). */
260
321
  const CONFIG_HEADER = `// dsh-ris-ide 程序配置(JSONC:允许注释与尾逗号)
261
322
  //
@@ -405,6 +466,14 @@ export function handleRequest(ctx, req, res, options) {
405
466
  function dispatchRequest(ctx, req, res, options) {
406
467
  const method = req.method ?? 'GET'
407
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
+ }
408
477
  if (pathname === WINDOW_PAGE_PATH) {
409
478
  if (method !== 'GET') {
410
479
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
@@ -470,6 +539,22 @@ function dispatchRequest(ctx, req, res, options) {
470
539
  serveSafely(res, () => serveFsImport(ctx, req, res, options))
471
540
  return
472
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
+ }
473
558
  if (pathname === FS_READ_PATH || pathname === FS_WRITE_PATH || pathname === FS_FILE_PATH || pathname === FS_WINDOW_PATH) {
474
559
  if (pathname !== FS_WRITE_PATH) {
475
560
  if (method !== 'GET') {
@@ -722,7 +807,7 @@ async function searchWorkspaceFiles(cwd, query, limit) {
722
807
  for (const root of roots) {
723
808
  let listing
724
809
  try {
725
- listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z'], root)
810
+ listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root)
726
811
  } catch {
727
812
  // git is absent/broken here: walk this root so filename search still answers.
728
813
  const all = await listRawFiles(root)
@@ -892,7 +977,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
892
977
  for (const root of roots) {
893
978
  let stdout
894
979
  try {
895
- stdout = await runGit(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle], root)
980
+ stdout = await runGit(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle, '--'], root)
896
981
  } catch {
897
982
  // A root whose git call failed is not fatal (and git may have disappeared
898
983
  // mid-search): fall back to the filesystem walk for the whole request.
@@ -1063,7 +1148,7 @@ function relativePathOf(cwd, absolute) {
1063
1148
  }
1064
1149
 
1065
1150
  /** Path segments the watcher always drops (git never reports these as changes). */
1066
- const TREE_WATCH_ALWAYS_IGNORED = new Set(['.git', TREE_TRASH_DIR])
1151
+ const TREE_WATCH_ALWAYS_IGNORED = new Set(['.git', IDE_STATE_DIR])
1067
1152
 
1068
1153
  /**
1069
1154
  * Whether a rel path is one the tree never shows for structural reasons.
@@ -1175,7 +1260,7 @@ async function repoAllowedPaths(root) {
1175
1260
  const dirs = new Set([root])
1176
1261
  let listing
1177
1262
  try {
1178
- listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z'], root)
1263
+ listing = await runGit(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root)
1179
1264
  } catch {
1180
1265
  // Any failure (most often "git is not installed") degrades to no filtering.
1181
1266
  TREE_ALLOWED_CACHE.set(root, { at: Date.now(), value: undefined })
@@ -1241,6 +1326,9 @@ async function compactChain(full, allowed, repo) {
1241
1326
  for (const child of children) {
1242
1327
  const childPath = join(current, child.name)
1243
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
1244
1332
  const isRepo = await stat(join(childPath, '.git')).then(() => true).catch(() => false)
1245
1333
  if (isRepo) return { path: current, segments }
1246
1334
  if (allowed !== undefined && !allowed.dirs.has(childPath)) {
@@ -1298,6 +1386,76 @@ async function ignoredTreeDirs(repo, relatives) {
1298
1386
  return ignored
1299
1387
  }
1300
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
+
1301
1459
  /**
1302
1460
  * One directory level for the IDE tree.
1303
1461
  * @param {string} target - absolute directory.
@@ -1305,6 +1463,7 @@ async function ignoredTreeDirs(repo, relatives) {
1305
1463
  * @returns {Promise<{entries: object[], truncated: boolean}>}
1306
1464
  */
1307
1465
  async function listIdeTree(target, cwd, options) {
1466
+ await ensureIdeStateDir(cwd)
1308
1467
  const repo = await findGitRoot(target, cwd)
1309
1468
  // `filter: 'all'` is the tree's "show everything" mode: the gitignore filter is
1310
1469
  // deliberately bypassed, but the plugin's own bookkeeping folders stay hidden.
@@ -1316,7 +1475,7 @@ async function listIdeTree(target, cwd, options) {
1316
1475
  const unknownDirs = []
1317
1476
  if (repo !== undefined && allowed !== undefined) {
1318
1477
  for (const dirent of dirents) {
1319
- if (!dirent.isDirectory() || dirent.name === TREE_TRASH_DIR) continue
1478
+ if (!dirent.isDirectory() || TREE_WATCH_ALWAYS_IGNORED.has(dirent.name)) continue
1320
1479
  const full = join(target, dirent.name)
1321
1480
  if (allowed.dirs.has(full)) continue
1322
1481
  const isRepo = await stat(join(full, '.git')).then(() => true).catch(() => false)
@@ -1327,9 +1486,17 @@ async function listIdeTree(target, cwd, options) {
1327
1486
  const ignoredDirs = await ignoredTreeDirs(repo ?? '', unknownDirs)
1328
1487
  const entries = []
1329
1488
  for (const dirent of dirents) {
1330
- // The undo trash and the dependency-source cache are implementation
1331
- // details, never tree rows.
1332
- 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
1333
1500
  const full = join(target, dirent.name)
1334
1501
  if (dirent.isDirectory()) {
1335
1502
  const isRepo = await stat(join(full, '.git')).then(() => true).catch(() => false)
@@ -1478,7 +1645,7 @@ export async function assertEnoughMemory(minFreeBytes) {
1478
1645
  if (free === 0 || free >= floor) return
1479
1646
  throw new TailError(
1480
1647
  'low-memory',
1481
- `可用内存仅 ${memoryLabel(free)}(低于 ${memoryLabel(floor)}),为避免 swap 抖动已拒绝启动;请先停止不用的服务,或在 .dsh-ris-ide.json 里给程序配小一点的 jvmArgs(如 -Xmx768m)`,
1648
+ `可用内存仅 ${memoryLabel(free)}(低于 ${memoryLabel(floor)}),为避免 swap 抖动已拒绝启动;请先停止不用的服务,或在 .dsh-ris-ide/config.json 里给程序配小一点的 jvmArgs(如 -Xmx768m)`,
1482
1649
  507,
1483
1650
  )
1484
1651
  }
@@ -2576,18 +2743,38 @@ async function serveFsOp(ctx, req, res, options) {
2576
2743
  const notRoot = (target, action) => {
2577
2744
  if (target === root) throw new TailError('bad-request', `不能对工作区根目录执行${action}`, 409)
2578
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
+ }
2579
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
+ }
2580
2765
 
2581
2766
  if (url.pathname === FS_MKDIR_PATH) {
2582
2767
  const target = one(body.path, 'path')
2583
- notRoot(target, '新建文件夹')
2768
+ insideRoot(target, '新建文件夹')
2769
+ checkLeafName(basename(target))
2584
2770
  await mkdir(target, { recursive: true })
2585
2771
  writeJson(res, 200, { ok: true, path: target, created: true })
2586
2772
  return
2587
2773
  }
2588
2774
  if (url.pathname === FS_CREATE_PATH) {
2589
2775
  const target = one(body.path, 'path')
2590
- notRoot(target, '新建文件')
2776
+ insideRoot(target, '新建文件')
2777
+ checkLeafName(basename(target))
2591
2778
  if (await exists(target)) throw new TailError('exists', `「${basename(target)}」已存在`, 409)
2592
2779
  await mkdir(dirname(target), { recursive: true })
2593
2780
  await writeFile(target, typeof body.content === 'string' ? body.content : '', { flag: 'wx' })
@@ -2596,13 +2783,11 @@ async function serveFsOp(ctx, req, res, options) {
2596
2783
  }
2597
2784
  if (url.pathname === FS_COPY_PATH || url.pathname === FS_MOVE_PATH) {
2598
2785
  const from = one(body.from, 'from')
2599
- notRoot(from, '复制或移动')
2600
- const toDir = one(body.toDir !== undefined ? body.toDir : body.to, 'toDir')
2601
- const requested = typeof body.name === 'string' ? body.name.trim() : ''
2602
- if (requested.includes('/') || requested.includes('\\') || requested === '.' || requested === '..') {
2603
- throw new TailError('bad-request', '非法的目标文件名', 400)
2604
- }
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 : '')
2605
2789
  const target = join(toDir, requested === '' ? basename(from) : requested)
2790
+ insideRoot(target, '复制或移动')
2606
2791
  if (target === from) throw new TailError('bad-request', '目标与源相同', 409)
2607
2792
  if (target.startsWith(from.endsWith(sep) ? from : `${from}${sep}`)) {
2608
2793
  throw new TailError('bad-request', '不能把目录复制/移动到它自己内部', 409)
@@ -2627,7 +2812,7 @@ async function serveFsOp(ctx, req, res, options) {
2627
2812
  }
2628
2813
  if (url.pathname === FS_REMOVE_PATH) {
2629
2814
  const target = one(body.path, 'path')
2630
- notRoot(target, '删除')
2815
+ insideRoot(target, '删除')
2631
2816
  const info = await stat(target).catch(() => undefined)
2632
2817
  if (info === undefined) throw new TailError('not-found', `「${basename(target)}」不存在`, 404)
2633
2818
  const recursive = body.recursive === true
@@ -2648,12 +2833,44 @@ async function serveFsOp(ctx, req, res, options) {
2648
2833
  /** Text files bigger than this are refused by the read route (matches the old sidebar). */
2649
2834
  const FS_MAX_TEXT_BYTES = 512 * 1024
2650
2835
 
2651
- /** One sanitized leaf name for an import target (never a path). */
2652
- 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) {
2653
2861
  const name = String(raw === undefined || raw === null ? '' : raw).trim()
2654
- if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
2862
+ if (name === '') return ''
2863
+ if (name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
2655
2864
  throw new TailError('bad-request', '非法的文件名', 400)
2656
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)
2657
2874
  return name
2658
2875
  }
2659
2876
 
@@ -2681,6 +2898,54 @@ async function pathExists(target) {
2681
2898
  * @param res - Node response face.
2682
2899
  * @param options - `{ restrictToCwd }` from the plugin config.
2683
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
+
2684
2949
  async function serveFsImport(ctx, req, res, options) {
2685
2950
  try {
2686
2951
  if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
@@ -2690,9 +2955,7 @@ async function serveFsImport(ctx, req, res, options) {
2690
2955
  if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
2691
2956
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
2692
2957
  const name = importEntryName(url.searchParams.get('name') ?? '')
2693
- const dir = resolvePath(cwd, url.searchParams.get('dir') ?? '', options?.restrictToCwd === true)
2694
- const info = await stat(dir).catch(() => undefined)
2695
- if (info === undefined || !info.isDirectory()) throw new TailError('bad-request', '粘贴目标不是目录', 400)
2958
+ const dir = await resolvePasteDirectory(cwd, url.searchParams.get('dir') ?? '', options?.restrictToCwd === true)
2696
2959
  const target = join(dir, name)
2697
2960
  const overwrite = url.searchParams.get('overwrite') === '1'
2698
2961
  if (!overwrite && await pathExists(target)) throw new TailError('exists', `「${name}」已存在`, 409)
@@ -2730,9 +2993,7 @@ async function serveFsImport(ctx, req, res, options) {
2730
2993
  const source = isAbsolute(rawFrom) ? resolve(rawFrom) : resolvePath(cwd, rawFrom, restrict)
2731
2994
  const sourceInfo = await stat(source).catch(() => undefined)
2732
2995
  if (sourceInfo === undefined) throw new TailError('not-found', `找不到「${rawFrom}」`, 404)
2733
- const dir = resolvePath(cwd, typeof body.dir === 'string' ? body.dir : '', restrict)
2734
- const dirInfo = await stat(dir).catch(() => undefined)
2735
- if (dirInfo === undefined || !dirInfo.isDirectory()) throw new TailError('bad-request', '粘贴目标不是目录', 400)
2996
+ const dir = await resolvePasteDirectory(cwd, typeof body.dir === 'string' ? body.dir : '', restrict)
2736
2997
  const name = importEntryName(typeof body.name === 'string' && body.name.trim() !== '' ? body.name : basename(source))
2737
2998
  const target = join(dir, name)
2738
2999
  if (target === source || target.startsWith(`${source}${sep}`) || source.startsWith(`${target}${sep}`)) {
@@ -2751,6 +3012,562 @@ async function serveFsImport(ctx, req, res, options) {
2751
3012
  }
2752
3013
  }
2753
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
+
2754
3571
  /** Content types the media route can serve inline (`<img>`, `<iframe>`). */
2755
3572
  const FS_MEDIA_TYPES = {
2756
3573
  png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
@@ -2971,6 +3788,141 @@ async function readFileRange(path, start, end) {
2971
3788
  * grows, `: ping` comments keep proxies quiet. EventSource reconnects by itself,
2972
3789
  * so a restart of `dsh web` self-heals; the JSON routes remain as fallbacks.
2973
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
+
2974
3926
  async function serveStream(ctx, req, res, options) {
2975
3927
  let url
2976
3928
  try {
@@ -3015,7 +3967,38 @@ async function serveStream(ctx, req, res, options) {
3015
3967
  })
3016
3968
  res.flushHeaders?.()
3017
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
+
3018
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
+ }
3019
4002
  const cleanups = []
3020
4003
  const send = (event, payload) => {
3021
4004
  if (closed) return false
@@ -3032,7 +4015,22 @@ async function serveStream(ctx, req, res, options) {
3032
4015
  return false
3033
4016
  }
3034
4017
  }
3035
- 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
+ })
3036
4034
 
3037
4035
  const heartbeat = setInterval(() => {
3038
4036
  if (closed) return
@@ -3046,12 +4044,16 @@ async function serveStream(ctx, req, res, options) {
3046
4044
 
3047
4045
  res.on('error', () => {
3048
4046
  // An aborted SSE connection emits 'error'; without a listener Node would
3049
- // 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).
3050
4050
  closed = true
4051
+ settleWindow()
3051
4052
  })
3052
4053
  res.on('close', () => {
3053
4054
  closed = true
3054
4055
  clearInterval(heartbeat)
4056
+ settleWindow()
3055
4057
  for (const cleanup of cleanups) {
3056
4058
  try {
3057
4059
  cleanup()
@@ -3384,7 +4386,7 @@ function sourcesJarOf(jar) {
3384
4386
  }
3385
4387
 
3386
4388
  /**
3387
- * 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
3388
4390
  * FINGERPRINT of its inputs (jar path+size+mtime and the entry's name/size/crc,
3389
4391
  * plus the decompiler jar+args), not by file age: a rebuilt jar invalidates its
3390
4392
  * derived files immediately. `manifest.json` remembers those fingerprints, and a
@@ -3458,7 +4460,7 @@ async function cacheFiles(root) {
3458
4460
  /**
3459
4461
  * Drop aged files first, then the least-recently-written ones until the cache
3460
4462
  * fits its size/file budget. Rate-limited so a burst of resolves prunes once.
3461
- * @param {string} root - the `.dsh-ris-ide-cache` directory.
4463
+ * @param {string} root - the `.dsh-ris-ide/cache` directory.
3462
4464
  * @param {{maxBytes?: number, maxFiles?: number, maxAgeMs?: number, force?: boolean}} [options]
3463
4465
  */
3464
4466
  export async function pruneIdeCache(root, options) {
@@ -3507,6 +4509,7 @@ export async function pruneIdeCache(root, options) {
3507
4509
  * still exists, otherwise produced and written (then the cache GC may run).
3508
4510
  */
3509
4511
  async function cachedSource(cwd, kind, className, suffix, key, produce) {
4512
+ await ensureIdeStateDir(cwd)
3510
4513
  const root = join(cwd, IDE_CACHE_DIR)
3511
4514
  const rel = kind + '/' + className + suffix
3512
4515
  const target = join(root, rel)
@@ -3546,10 +4549,10 @@ function runCapture(command, args, cwd) {
3546
4549
  })
3547
4550
  }
3548
4551
 
3549
- /** 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`. */
3550
4553
  async function readDecompilerConfig(cwd) {
3551
- const settingsPath = resolve(cwd, IDE_SETTINGS_FILENAME)
3552
- 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))
3553
4556
  if (settingsText !== undefined) {
3554
4557
  const parsed = parseJsonc(settingsText)
3555
4558
  if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
@@ -3559,7 +4562,8 @@ async function readDecompilerConfig(cwd) {
3559
4562
  }
3560
4563
  }
3561
4564
  }
3562
- 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))
3563
4567
  if (configText === undefined) return undefined
3564
4568
  const parsed = parseJsonc(configText)
3565
4569
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
@@ -3671,7 +4675,7 @@ async function serveDebugSource(ctx, req, res, options) {
3671
4675
 
3672
4676
  /**
3673
4677
  * `/dsh-ris-ide/settings`: GET returns the visual debug settings, POST saves the
3674
- * 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
3675
4679
  * untouched — rewriting JSONC would drop the user's comments).
3676
4680
  */
3677
4681
  async function serveSettings(ctx, req, res, options) {
@@ -3685,6 +4689,7 @@ async function serveSettings(ctx, req, res, options) {
3685
4689
  const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
3686
4690
  if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3687
4691
  const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
4692
+ await ensureIdeStateDir(cwd)
3688
4693
  const path = settingsPathOf(cwd)
3689
4694
  const existingText = await readTextIfSmall(path)
3690
4695
  const existing = existingText === undefined ? {} : parseJsonc(existingText)
@@ -3700,6 +4705,7 @@ async function serveSettings(ctx, req, res, options) {
3700
4705
  const sessionId = url.searchParams.get('sessionId') ?? ''
3701
4706
  if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3702
4707
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
4708
+ await ensureIdeStateDir(cwd)
3703
4709
  const config = await readDecompilerConfig(cwd)
3704
4710
  writeJson(res, 200, {
3705
4711
  ok: true,
@@ -4789,7 +5795,7 @@ export function buildStartSpec(program, context) {
4789
5795
  ? program.mainClass
4790
5796
  : (launchMainClass ?? program.mainClass)
4791
5797
  const args = resolveSpringArgs(program, workspace)
4792
- // 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
4793
5799
  // after the plugin's required -D flags so a deliberate override still wins.
4794
5800
  const jvmArgs = normalizeStringArray(program.jvmArgs) ?? []
4795
5801
  // Debug mode adds the JDWP agent before the user's own JVM flags.
@@ -5182,7 +6188,7 @@ export function parseJsonc(text) {
5182
6188
 
5183
6189
  // ── User program config (generated from a scan, then user-maintained) ────────
5184
6190
  //
5185
- // 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.
5186
6192
  // After that the file belongs to the user: entries override discovered programs
5187
6193
  // by id (then dir, then name), entries that match nothing become user-added
5188
6194
  // programs, `disabled: true` hides a row, and `startCommand` replaces the
@@ -5195,8 +6201,16 @@ export function parseJsonc(text) {
5195
6201
  * @returns `{ path, exists, entries, error }`; `entries` only holds valid rows.
5196
6202
  */
5197
6203
  export async function readProgramConfig(cwd) {
5198
- const path = resolve(cwd, CONFIG_FILENAME)
5199
- 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
+ }
5200
6214
  if (text === undefined) return { path, exists: false, entries: [], error: undefined }
5201
6215
  const parsed = parseJsonc(text)
5202
6216
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
@@ -5475,6 +6489,7 @@ export function buildConfigDocument(programs, workspace) {
5475
6489
  /** Write the generated config (refuses to clobber an existing file unless asked). */
5476
6490
  async function writeProgramConfig(cwd, logsDir, mode, fresh = false) {
5477
6491
  if (fresh) discoveryCache.delete(resolve(cwd))
6492
+ await ensureIdeStateDir(cwd)
5478
6493
  const path = resolve(cwd, CONFIG_FILENAME)
5479
6494
  const exists = existsSync(path)
5480
6495
  if (exists && mode !== 'update' && mode !== 'overwrite') {
@@ -5773,7 +6788,7 @@ export function registerAgentTools(ctx, options) {
5773
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. '
5774
6789
  + 'Resolve the program with ris_dev_programs and check ris_dev_status first; give its id, or a unique name fragment. '
5775
6790
  + 'Starting an already-running program is NOT an error: it returns alreadyRunning=true without touching it; use ris_dev_restart to restart it. '
5776
- + '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.',
5777
6792
  parameters: {
5778
6793
  type: 'object',
5779
6794
  additionalProperties: false,
@@ -6618,6 +7633,12 @@ export const __test = {
6618
7633
  STREAM_PATH,
6619
7634
  BUNDLE_PATH,
6620
7635
  WINDOW_PAGE_PATH,
7636
+ WINDOWS_PATH,
7637
+ serveWindows,
7638
+ listIdeWindows,
7639
+ liveSessionFor,
7640
+ ideWindowOpened,
7641
+ ideWindowClosed,
6621
7642
  WINDOW_APP_PATH,
6622
7643
  WINDOW_VENDOR_PREFIX,
6623
7644
  WINDOW_VENDOR_FILES,
@@ -6633,6 +7654,27 @@ export const __test = {
6633
7654
  FS_UPLOAD_MAX_BYTES,
6634
7655
  serveFsOp,
6635
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,
6636
7678
  CLIENT_CHUNKS,
6637
7679
  serveBundle,
6638
7680
  FS_READ_PATH,