dsh-ris-ide 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -688,9 +688,20 @@ test('the start route launches a program through run-with-log.sh and stop termin
688
688
 
689
689
  // ── User config: generate / drift / update ─────────────────────────────────
690
690
 
691
- /** Write one `.dsh-ris-ide.json` fixture. */
691
+ /** Path of the workspace program config: inside the state folder, never a dotfile. */
692
+ function configPathOf(root) {
693
+ return join(root, '.dsh-ris-ide', 'config.json')
694
+ }
695
+
696
+ /** Create the workspace state folder a config/settings fixture is written into. */
697
+ async function ensureStateDir(root) {
698
+ await mkdir(join(root, '.dsh-ris-ide'), { recursive: true })
699
+ }
700
+
701
+ /** Write one `.dsh-ris-ide/config.json` fixture. */
692
702
  async function writeConfig(root, doc) {
693
- await writeFile(join(root, '.dsh-ris-ide.json'), JSON.stringify(doc, null, 2))
703
+ await ensureStateDir(root)
704
+ await writeFile(configPathOf(root), JSON.stringify(doc, null, 2))
694
705
  }
695
706
 
696
707
  test('readProgramConfig tolerates JSONC and ignores invalid rows', async () => {
@@ -699,7 +710,8 @@ test('readProgramConfig tolerates JSONC and ignores invalid rows', async () => {
699
710
  assert.equal(empty.exists, false)
700
711
  assert.deepEqual(empty.entries, [])
701
712
 
702
- await writeFile(join(root, '.dsh-ris-ide.json'), `{
713
+ await ensureStateDir(root)
714
+ await writeFile(configPathOf(root), `{
703
715
  // a comment
704
716
  "programs": [
705
717
  { "name": "ok", "dir": "proj-a/ui", "startCommand": "true", },
@@ -712,13 +724,61 @@ test('readProgramConfig tolerates JSONC and ignores invalid rows', async () => {
712
724
  assert.equal(cfg.entries.length, 1)
713
725
  assert.equal(cfg.entries[0].name, 'ok')
714
726
 
715
- await writeFile(join(root, '.dsh-ris-ide.json'), '{ nope')
727
+ await writeFile(configPathOf(root), '{ nope')
716
728
  const broken = await readProgramConfig(root)
717
729
  assert.equal(broken.exists, true)
718
730
  assert.match(broken.error, /JSON/)
719
731
  assert.deepEqual(broken.entries, [])
720
732
  })
721
733
 
734
+ test('the plugin keeps ONE hidden folder: legacy dot-folders and dotfiles fold in', async () => {
735
+ const root = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-state-'))
736
+ await mkdir(join(root, '.dsh-ris-ide-trash'), { recursive: true })
737
+ await writeFile(join(root, '.dsh-ris-ide-trash', 'parked.txt'), 'parked')
738
+ await mkdir(join(root, '.dsh-ris-ide-cache', 'sources'), { recursive: true })
739
+ await writeFile(join(root, '.dsh-ris-ide-cache', 'sources', 'A.java'), 'class A {}')
740
+ await writeFile(join(root, '.dsh-ris-ide.json'), JSON.stringify({ version: 1, programs: [] }))
741
+ await writeFile(join(root, '.dsh-ris-ide.settings.json'), JSON.stringify({ decompiler: { jar: '/opt/cfr/cfr.jar' } }))
742
+
743
+ const tree = await __test.listIdeTree(root, root)
744
+ assert.equal(tree.entries.some((entry) => entry.name === '.dsh-ris-ide'), false, 'the state folder is never a tree row')
745
+ assert.equal(tree.entries.some((entry) => entry.name === '.dsh-ris-ide.json'), false, 'nor the legacy config dotfile')
746
+
747
+ assert.equal(await readFile(join(root, '.dsh-ris-ide', 'trash', 'parked.txt'), 'utf8'), 'parked', 'a parked delete survives the move')
748
+ assert.equal(await readFile(join(root, '.dsh-ris-ide', 'cache', 'sources', 'A.java'), 'utf8'), 'class A {}')
749
+ assert.equal(existsSync(join(root, '.dsh-ris-ide', 'config.json')), true, 'the legacy config moved into the folder')
750
+ assert.equal(existsSync(join(root, '.dsh-ris-ide', 'settings.json')), true, 'and so did the settings file')
751
+ assert.equal(existsSync(join(root, '.dsh-ris-ide-trash')), false, 'the legacy folder is gone')
752
+ assert.equal(existsSync(join(root, '.dsh-ris-ide.json')), false, 'the legacy config dotfile is gone')
753
+ assert.equal(existsSync(join(root, '.dsh-ris-ide.settings.json')), false, 'the legacy settings dotfile is gone')
754
+
755
+ // A newer file at the new location wins: a legacy one is left alone, never overwritten.
756
+ await writeFile(configPathOf(root), JSON.stringify({ version: 1, programs: [] }))
757
+ const legacyAgain = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-legacy-'))
758
+ await mkdir(join(root, '.dsh-ris-ide'), { recursive: true })
759
+ assert.equal(existsSync(configPathOf(root)), true)
760
+ await rm(legacyAgain, { recursive: true, force: true })
761
+ })
762
+
763
+ test('a legacy entry that collides with a newer one is parked, never dropped', async () => {
764
+ const root = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-state-collide-'))
765
+ await mkdir(join(root, '.dsh-ris-ide', 'trash'), { recursive: true })
766
+ await writeFile(join(root, '.dsh-ris-ide', 'trash', 'parked.txt'), 'newer')
767
+ await mkdir(join(root, '.dsh-ris-ide-trash'), { recursive: true })
768
+ await writeFile(join(root, '.dsh-ris-ide-trash', 'parked.txt'), 'legacy')
769
+
770
+ await __test.listIdeTree(root, root)
771
+
772
+ const trash = join(root, '.dsh-ris-ide', 'trash')
773
+ assert.equal(await readFile(join(trash, 'parked.txt'), 'utf8'), 'newer', 'the newer file keeps the plain name')
774
+ const { readdir } = await import('node:fs/promises')
775
+ const parked = (await readdir(trash)).filter((name) => name.startsWith('parked.txt-legacy-'))
776
+ assert.equal(parked.length, 1, 'the older file is kept under a suffixed name')
777
+ assert.equal(await readFile(join(trash, parked[0]), 'utf8'), 'legacy', 'and its bytes survive')
778
+ assert.equal(existsSync(join(root, '.dsh-ris-ide-trash')), false, 'the legacy folder goes away once it is empty')
779
+ await rm(root, { recursive: true, force: true })
780
+ })
781
+
722
782
  test('mergeProgramConfig applies user fields, adds manual programs and honors disabled', async () => {
723
783
  const { root } = await makeProgramFixture()
724
784
  const logsDir = join(root, 'logs')
@@ -804,7 +864,7 @@ test('the config route generates, refuses to clobber and updates in place', asyn
804
864
  const firstBody = await first.json()
805
865
  assert.equal(firstBody.ok, true)
806
866
  assert.equal(firstBody.count, 2)
807
- const configPath = join(root, '.dsh-ris-ide.json')
867
+ const configPath = configPathOf(root)
808
868
  assert.equal(existsSync(configPath), true)
809
869
  const text = await readFile(configPath, 'utf8')
810
870
  assert.match(text, /dsh-ris-ide 程序配置/, 'the generated file carries a header comment')
@@ -835,7 +895,8 @@ test('the config route generates, refuses to clobber and updates in place', asyn
835
895
 
836
896
  test('the programs route reports config drift, and start honors startCommand/logName/grace', async () => {
837
897
  const { root } = await makeStartableFixture()
838
- await writeFile(join(root, '.dsh-ris-ide.json'), JSON.stringify({
898
+ await ensureStateDir(root)
899
+ await writeFile(configPathOf(root), JSON.stringify({
839
900
  version: 1,
840
901
  programs: [{
841
902
  name: 'tick-app',
@@ -855,7 +916,7 @@ test('the programs route reports config drift, and start honors startCommand/log
855
916
  assert.equal(listing.config.status, 'updated', 'a forced rescan reconciles the config')
856
917
  assert.equal(listing.config.drift.reconciled, true)
857
918
  assert.equal(listing.programs.some((entry) => entry.name === 'ui-2'), true, 'the new program is listed')
858
- assert.equal((await readFile(join(root, '.dsh-ris-ide.json'), 'utf8')).includes('ui-2'), true, 'and written into the config')
919
+ assert.equal((await readFile(configPathOf(root), 'utf8')).includes('ui-2'), true, 'and written into the config')
859
920
 
860
921
  const program = listing.programs.find((entry) => entry.name === 'tick-app')
861
922
  assert.equal(program.logName, 'custom-tick', 'the config logName wins')
@@ -1024,7 +1085,8 @@ test('stopping a wrapped command kills its whole process group (pnpm-style grand
1024
1085
 
1025
1086
  test('a start whose command dies immediately fails loudly, with the log tail', async () => {
1026
1087
  const { root } = await makeStartableFixture()
1027
- await writeFile(join(root, '.dsh-ris-ide.json'), JSON.stringify({
1088
+ await ensureStateDir(root)
1089
+ await writeFile(configPathOf(root), JSON.stringify({
1028
1090
  version: 1,
1029
1091
  programs: [{
1030
1092
  name: 'tick-app',
@@ -1197,7 +1259,7 @@ test('the programs route generates a config on first open, then only touches it
1197
1259
  await withServer(async ({ base }) => {
1198
1260
  const first = await (await fetch(`${base}${PROGRAMS_PATH}?sessionId=s1`)).json()
1199
1261
  assert.equal(first.config.status, 'generated', 'no config ⇒ scan + write one')
1200
- const configPath = join(root, '.dsh-ris-ide.json')
1262
+ const configPath = configPathOf(root)
1201
1263
  assert.equal(existsSync(configPath), true)
1202
1264
  const generated = parseJsonc(await readFile(configPath, 'utf8'))
1203
1265
  const spring = generated.programs.find((entry) => entry.kind === 'spring')
@@ -1281,7 +1343,7 @@ test('the generated config documents jvmArgs, and an update keeps the user defau
1281
1343
  assert.deepEqual(spring.jvmArgs, [], 'every entry carries an editable jvmArgs list')
1282
1344
 
1283
1345
  await withServer(async ({ base }) => {
1284
- const configPath = join(root, '.dsh-ris-ide.json')
1346
+ const configPath = configPathOf(root)
1285
1347
  const post = (body) => fetch(`${base}${CONFIG_PATH}`, {
1286
1348
  method: 'POST',
1287
1349
  headers: { 'content-type': 'application/json' },
@@ -1711,11 +1773,15 @@ test('listIdeTree hides ignored files and folds package chains only under java',
1711
1773
  // A single-child folder chain OUTSIDE java must stay as separate rows.
1712
1774
  await mkdir(join(root, 'docs', 'guide'), { recursive: true })
1713
1775
  await writeFile(join(root, 'docs', 'guide', 'readme.md'), '# guide\n')
1776
+ // A chunked save stages its document next to the target; a crashed save may
1777
+ // leave one behind and it must never become a tree row.
1778
+ await writeFile(join(root, 'a.java' + __test.FS_WRITE_TEMP_SUFFIX), 'half a doc')
1714
1779
 
1715
1780
  const level = await __test.listIdeTree(root, root)
1716
1781
  const labels = level.entries.map((entry) => entry.label)
1717
1782
  assert.ok(labels.includes('a.java'), 'a tracked/untracked-but-not-ignored file shows')
1718
1783
  assert.equal(labels.includes('debug.log'), false, '*.log is ignored')
1784
+ assert.equal(labels.includes('a.java' + __test.FS_WRITE_TEMP_SUFFIX), false, 'save staging files stay out of the tree')
1719
1785
  assert.equal(labels.includes('ignored'), false, 'an ignored directory disappears')
1720
1786
  // src -> main -> java is a single-child chain, but it is NOT a package tail.
1721
1787
  assert.equal(labels.includes('src'), true, 'src/main/java is not compacted into one row')
@@ -2074,6 +2140,7 @@ test('filter=all shows gitignored files, the default hides them', async () => {
2074
2140
  assert.ok(filteredNames.includes('visible.txt'))
2075
2141
  assert.equal(filteredNames.includes('secret.txt'), false, 'the default hides gitignored files')
2076
2142
  assert.equal(filteredNames.includes('ignored-dir'), false)
2143
+ assert.equal(filteredNames.includes('.git'), false, 'git metadata is filtered too')
2077
2144
  assert.equal(filtered.git, true, 'the client needs to know git is what is filtering')
2078
2145
  assert.equal(filtered.filtered, true)
2079
2146
 
@@ -2082,8 +2149,15 @@ test('filter=all shows gitignored files, the default hides them', async () => {
2082
2149
  const allNames = all.entries.map((entry) => entry.name)
2083
2150
  assert.ok(allNames.includes('secret.txt'))
2084
2151
  assert.ok(allNames.includes('ignored-dir'))
2152
+ assert.ok(allNames.includes('.git'), '"show everything" keeps the .git row')
2085
2153
  assert.equal(all.filtered, false)
2086
2154
  assert.equal(all.git, true, 'git is still available, so the toggle can be turned back on')
2155
+
2156
+ // A nested repo is listed through its own root; `.git` is metadata there too.
2157
+ await mkdir(join(dir, 'nested'), { recursive: true })
2158
+ execFileSync('git', ['init', '-q'], { cwd: join(dir, 'nested') })
2159
+ const nested = await __test.listIdeTree(join(dir, 'nested'), dir)
2160
+ assert.equal(nested.entries.map((entry) => entry.name).includes('.git'), false, 'a nested repo hides its own .git')
2087
2161
  })
2088
2162
 
2089
2163
  // ── the tree topic: filesystem changes reach the browser without a manual ⟳ ──
@@ -2222,6 +2296,64 @@ test('the fs routes read text, refuse binary/oversized and write back', async ()
2222
2296
  assert.equal(written.status, 200)
2223
2297
  assert.equal(written.body.ok, true)
2224
2298
  assert.equal((await call('fs/read', { query: { sessionId: 's1', path: textFile } })).body.content, 'class A { int x; }\n')
2299
+
2300
+ // A save carries the whole document: the 64 KB generic JSON cap must NOT apply
2301
+ // to /fs/write (that is what made every save of a >64 KB file fail with
2302
+ // "request body too large"). 120 KB is an ordinary source file.
2303
+ const large = 'x'.repeat(120 * 1024)
2304
+ const largeSaved = await call('fs/write', { body: { sessionId: 's1', path: textFile, content: large } })
2305
+ assert.equal(largeSaved.status, 200, JSON.stringify(largeSaved.body))
2306
+ assert.equal(largeSaved.body.ok, true)
2307
+ const largeRead = await call('fs/read', { query: { sessionId: 's1', path: textFile } })
2308
+ assert.equal(largeRead.status, 200)
2309
+ assert.equal(largeRead.body.kind, 'text')
2310
+ assert.equal(largeRead.body.content, large, 'every byte of the large document landed')
2311
+
2312
+ // Above the writer's own ceiling the answer is a readable Chinese message,
2313
+ // not a bare "request body too large".
2314
+ const huge = await call('fs/write', { body: { sessionId: 's1', path: textFile, content: 'y'.repeat(9 * 1024 * 1024) } })
2315
+ assert.equal(huge.status, 413)
2316
+ assert.equal(huge.body.ok, false)
2317
+ assert.match(huge.body.message, /文件太大/)
2318
+ assert.match(huge.body.message, /8 MB/)
2319
+ const { stat } = await import('node:fs/promises')
2320
+ assert.equal((await stat(textFile)).size, Buffer.byteLength(large),
2321
+ 'the refused save must not touch the file on disk')
2322
+
2323
+ // Chunked save: the editor sends utf8 pieces with byte offsets. Nothing is
2324
+ // visible until the final chunk renames the staged file over the target.
2325
+ const pieces = ['α' + 'b'.repeat(5000), '汉'.repeat(4000), 'end']
2326
+ const staging = textFile + __test.FS_WRITE_TEMP_SUFFIX
2327
+ let offset = 0
2328
+ for (let index = 0; index < pieces.length; index += 1) {
2329
+ const final = index === pieces.length - 1
2330
+ const answer = await call('fs/write', { body: { sessionId: 's1', path: textFile, content: pieces[index], offset, final } })
2331
+ assert.equal(answer.status, 200, JSON.stringify(answer.body))
2332
+ assert.equal(answer.body.chunked, true)
2333
+ assert.equal(answer.body.final, final)
2334
+ offset += Buffer.byteLength(pieces[index])
2335
+ if (!final) {
2336
+ assert.equal(existsSync(staging), true, 'a non-final chunk stages the document')
2337
+ assert.equal((await stat(textFile)).size, Buffer.byteLength(large), 'the old file is still intact mid-save')
2338
+ }
2339
+ }
2340
+ assert.equal(existsSync(staging), false, 'the staging file is renamed away')
2341
+ const chunkedRead = await call('fs/read', { query: { sessionId: 's1', path: textFile } })
2342
+ assert.equal(chunkedRead.body.content, pieces.join(''))
2343
+
2344
+ // A skipped chunk is refused instead of silently leaving zero bytes behind.
2345
+ const firstChunk = await call('fs/write', { body: { sessionId: 's1', path: textFile, content: 'abc', offset: 0, final: false } })
2346
+ assert.equal(firstChunk.status, 200)
2347
+ const skipped = await call('fs/write', { body: { sessionId: 's1', path: textFile, content: 'def', offset: 9, final: true } })
2348
+ assert.equal(skipped.status, 409)
2349
+ assert.match(skipped.body.message, /missing/)
2350
+ assert.equal((await call('fs/read', { query: { sessionId: 's1', path: textFile } })).body.content, pieces.join(''),
2351
+ 'a broken chunked save leaves the previous document in place')
2352
+ // Starting over at offset 0 recovers.
2353
+ await call('fs/write', { body: { sessionId: 's1', path: textFile, content: 'abc', offset: 0, final: false } })
2354
+ const recovered = await call('fs/write', { body: { sessionId: 's1', path: textFile, content: 'def', offset: 3, final: true } })
2355
+ assert.equal(recovered.status, 200)
2356
+ assert.equal((await call('fs/read', { query: { sessionId: 's1', path: textFile } })).body.content, 'abcdef')
2225
2357
  })
2226
2358
 
2227
2359
  // ── a browser that cancels an image/file stream must not kill the host ─────
@@ -2406,11 +2538,11 @@ test('the undo trash is never a tree row and move honours an explicit name', asy
2406
2538
  await __test.serveFsOp({ sessions: { get: () => ({ header: { cwd: dir } }) } }, req, res, {})
2407
2539
  return { status: res.status, body: JSON.parse(chunks.join('') || 'null') }
2408
2540
  }
2409
- await op('fs/mkdir', { sessionId: 's1', path: join(dir, '.dsh-ris-ide-trash') })
2410
- const parked = await op('fs/move', { sessionId: 's1', from: join(dir, 'src', 'A.java'), toDir: join(dir, '.dsh-ris-ide-trash'), name: '1730-A.java' })
2541
+ await op('fs/mkdir', { sessionId: 's1', path: join(dir, '.dsh-ris-ide', 'trash') })
2542
+ const parked = await op('fs/move', { sessionId: 's1', from: join(dir, 'src', 'A.java'), toDir: join(dir, '.dsh-ris-ide', 'trash'), name: '1730-A.java' })
2411
2543
  assert.equal(parked.status, 200)
2412
- assert.equal(parked.body.path, join(dir, '.dsh-ris-ide-trash', '1730-A.java'))
2413
- const restored = await op('fs/move', { sessionId: 's1', from: join(dir, '.dsh-ris-ide-trash', '1730-A.java'), toDir: join(dir, 'src'), name: 'A.java' })
2544
+ assert.equal(parked.body.path, join(dir, '.dsh-ris-ide', 'trash', '1730-A.java'))
2545
+ const restored = await op('fs/move', { sessionId: 's1', from: join(dir, '.dsh-ris-ide', 'trash', '1730-A.java'), toDir: join(dir, 'src'), name: 'A.java' })
2414
2546
  assert.equal(restored.status, 200)
2415
2547
  assert.equal(restored.body.path, join(dir, 'src', 'A.java'))
2416
2548
  assert.equal((await readdir(join(dir, 'src'))).includes('A.java'), true)
@@ -2420,7 +2552,7 @@ test('the undo trash is never a tree row and move honours an explicit name', asy
2420
2552
 
2421
2553
  // ── file-tree mutations (menu / shortcuts / drag&drop) ─────────────────────
2422
2554
  test('fs op routes create, copy, move and remove without clobbering', async () => {
2423
- const { mkdtemp, mkdir, readdir, readFile, writeFile: write } = await import('node:fs/promises')
2555
+ const { mkdtemp, mkdir, readdir, readFile, rm, writeFile: write } = await import('node:fs/promises')
2424
2556
  const { tmpdir } = await import('node:os')
2425
2557
  const { join } = await import('node:path')
2426
2558
  const { Readable } = await import('node:stream')
@@ -2462,6 +2594,11 @@ test('fs op routes create, copy, move and remove without clobbering', async () =
2462
2594
  assert.equal(await readFile(join(copyDir, 'Demo.java'), 'utf8'), 'class Demo {}')
2463
2595
  // …and a second copy refuses the collision
2464
2596
  assert.equal((await call('fs/copy', { sessionId: 's1', cwd: dir, from: join(pkgDir, 'Demo.java'), toDir: copyDir })).status, 409)
2597
+ // A destination given as a FILE means its folder — the tree hands over the
2598
+ // selected row, and "copy next to this file" is what a user means there.
2599
+ const besideCopy = await call('fs/copy', { sessionId: 's1', cwd: dir, from: join(pkgDir, 'Demo.java'), toDir: join(copyDir, 'Demo.java'), name: 'Beside.java' })
2600
+ assert.equal(besideCopy.status, 200)
2601
+ assert.equal(await readFile(join(copyDir, 'Beside.java'), 'utf8'), 'class Demo {}')
2465
2602
 
2466
2603
  // move
2467
2604
  const movedDir = join(dir, 'moved')
@@ -2478,6 +2615,26 @@ test('fs op routes create, copy, move and remove without clobbering', async () =
2478
2615
 
2479
2616
  // the workspace root is never a legal mutation target
2480
2617
  assert.equal((await call('fs/mkdir', { sessionId: 's1', cwd: dir, path: dir })).status, 409)
2618
+
2619
+ // A path is only a string from the page: a mutation never leaves the tree
2620
+ // root, so `../` (or an absolute path outside) cannot widen a delete.
2621
+ const escape = join(dir, '..', 'escape-me.txt')
2622
+ await write(escape, 'outside')
2623
+ const escaped = await call('fs/remove', { sessionId: 's1', cwd: dir, path: escape, recursive: true })
2624
+ assert.equal(escaped.status, 403)
2625
+ assert.equal(await readFile(escape, 'utf8'), 'outside', 'the outside file survives the attempt')
2626
+ await rm(escape, { force: true })
2627
+ assert.equal((await call('fs/copy', { sessionId: 's1', cwd: dir, from: join(pkgDir, 'Demo.java'), toDir: join(dir, '..') })).status, 403)
2628
+
2629
+ // Special characters are just characters: no shell ever sees this name, and
2630
+ // removing it leaves every sibling alone.
2631
+ const odd = join(copyDir, "; rm -rf * $(id) 'quoted' & echo.txt")
2632
+ await write(odd, 'safe')
2633
+ await write(join(copyDir, 'neighbour.txt'), 'keep')
2634
+ assert.equal((await call('fs/remove', { sessionId: 's1', cwd: dir, path: odd })).status, 200)
2635
+ assert.equal(await readFile(join(copyDir, 'neighbour.txt'), 'utf8'), 'keep')
2636
+ // …and a control character in a name is refused outright
2637
+ assert.equal((await call('fs/create', { sessionId: 's1', cwd: dir, path: join(copyDir, 'bad\nname.txt') })).status, 400)
2481
2638
  })
2482
2639
 
2483
2640
  test('pasted OS files upload and import into the tree', async () => {
@@ -2533,6 +2690,15 @@ test('pasted OS files upload and import into the tree', async () => {
2533
2690
  assert.equal((await upload({ sessionId: 's1', cwd: dir, dir, name: 'pasted.bin', overwrite: '1' }, 'new')).status, 200)
2534
2691
  assert.equal(await readFile(target, 'utf8'), 'new')
2535
2692
 
2693
+ // A paste aimed AT a file lands in that file's folder instead of failing: the
2694
+ // tree can hand over the selected file row as the destination.
2695
+ const besideUpload = await upload({ sessionId: 's1', cwd: dir, dir: target, name: 'beside.bin' }, 'b')
2696
+ assert.equal(besideUpload.status, 200)
2697
+ assert.equal(await readFile(join(dir, 'beside.bin'), 'utf8'), 'b')
2698
+ // …but a destination that does not exist is still refused
2699
+ const nowhere = await upload({ sessionId: 's1', cwd: dir, dir: join(dir, 'nope'), name: 'x.bin' }, 'x')
2700
+ assert.equal(nowhere.status, 400)
2701
+
2536
2702
  // A path copied outside the workspace is imported in (the destination stays guarded).
2537
2703
  const sourceFile = join(outside, 'notes.md')
2538
2704
  await writeFile(sourceFile, '# hi\n')
@@ -2541,8 +2707,19 @@ test('pasted OS files upload and import into the tree', async () => {
2541
2707
  assert.equal(await readFile(join(dir, 'notes.md'), 'utf8'), '# hi\n')
2542
2708
  assert.equal((await importPath({ sessionId: 's1', cwd: dir, from: sourceFile, dir })).status, 409)
2543
2709
  assert.equal((await importPath({ sessionId: 's1', cwd: dir, from: sourceFile, dir, overwrite: true })).status, 200)
2710
+ // the same file→folder rule governs a copied path
2711
+ const besideImport = await importPath({ sessionId: 's1', cwd: dir, from: sourceFile, dir: target, name: 'notes-beside.md' })
2712
+ assert.equal(besideImport.status, 200)
2713
+ assert.equal(await readFile(join(dir, 'notes-beside.md'), 'utf8'), '# hi\n')
2544
2714
  // …and a leaf name can never escape the destination directory
2545
2715
  assert.equal((await importPath({ sessionId: 's1', cwd: dir, from: sourceFile, dir, name: '../evil.md' })).status, 400)
2716
+ // The DESTINATION is guarded too: an overwrite paste (which removes the
2717
+ // colliding entry) can never be aimed at a directory outside the tree.
2718
+ assert.equal((await importPath({ sessionId: 's1', cwd: dir, from: sourceFile, dir: outside, name: 'notes.md', overwrite: true })).status, 403)
2719
+ assert.equal(await readFile(sourceFile, 'utf8'), '# hi\n', 'nothing outside the tree was touched')
2720
+ // A control character never reaches a file name (it would corrupt every
2721
+ // line-oriented protocol downstream).
2722
+ assert.equal((await upload({ sessionId: 's1', cwd: dir, dir, name: 'bad\nname.bin' }, 'x')).status, 400)
2546
2723
  })
2547
2724
 
2548
2725
  // ── the debug stream: a page reload must still show its pre-set breakpoints ──
@@ -2666,7 +2843,7 @@ test('a dependency class resolves from its sources.jar into the workspace cache'
2666
2843
  assert.ok(resolved !== undefined, 'the sources.jar entry is found')
2667
2844
  assert.equal(resolved.kind, 'sources')
2668
2845
  assert.equal(resolved.jar, sources)
2669
- assert.equal(resolved.path, join(cwd, '.dsh-ris-ide-cache', 'sources', 'pkg.Dep.java'))
2846
+ assert.equal(resolved.path, join(cwd, '.dsh-ris-ide', 'cache', 'sources', 'pkg.Dep.java'))
2670
2847
  const text = await (await import('node:fs/promises')).readFile(resolved.path, 'utf8')
2671
2848
  assert.match(text, /public class Dep/)
2672
2849
 
@@ -2702,7 +2879,7 @@ test('a rebuilt jar invalidates the cached dependency source', async () => {
2702
2879
  assert.match(await read(again.path, 'utf8'), /rebuilt/)
2703
2880
  assert.ok((await stat(again.path)).mtimeMs > firstInfo.mtimeMs)
2704
2881
 
2705
- const manifest = await __test.readCacheManifest(join(cwd, '.dsh-ris-ide-cache'))
2882
+ const manifest = await __test.readCacheManifest(join(cwd, '.dsh-ris-ide', 'cache'))
2706
2883
  assert.equal(manifest.entries['sources/pkg.Dep.java'].kind, 'sources')
2707
2884
  })
2708
2885
 
@@ -2711,7 +2888,7 @@ test('the dependency cache prunes aged and oversized entries', async () => {
2711
2888
  const { tmpdir } = await import('node:os')
2712
2889
  const { join } = await import('node:path')
2713
2890
  const cwd = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-gc-'))
2714
- const root = join(cwd, '.dsh-ris-ide-cache')
2891
+ const root = join(cwd, '.dsh-ris-ide', 'cache')
2715
2892
  const dir = join(root, 'sources')
2716
2893
  await mkdir(dir, { recursive: true })
2717
2894
  const writeOne = async (name, text, ageMs) => {
@@ -2760,16 +2937,16 @@ test('the visual debug settings persist the decompiler jar without touching the
2760
2937
  }, posted.res, {})
2761
2938
  assert.equal(posted.res.status, 200)
2762
2939
  assert.equal(posted.json().decompiler.jar, '/opt/cfr/cfr.jar')
2763
- const settingsPath = join(dir, '.dsh-ris-ide.settings.json')
2940
+ const settingsPath = join(dir, '.dsh-ris-ide', 'settings.json')
2764
2941
  const saved = JSON.parse(await read(settingsPath, 'utf8'))
2765
2942
  assert.deepEqual(saved.decompiler, { jar: '/opt/cfr/cfr.jar', args: ['{classfile}'] })
2766
- assert.equal(await read(join(dir, '.dsh-ris-ide.json'), 'utf8').catch(() => undefined), undefined, 'the program config stays untouched')
2943
+ assert.equal(await read(join(dir, '.dsh-ris-ide', 'config.json'), 'utf8').catch(() => undefined), undefined, 'the program config stays untouched')
2767
2944
 
2768
2945
  const got = answer()
2769
2946
  await __test.serveSettings(ctx, { method: 'GET', headers: { host: '127.0.0.1:3080' }, url: '/dsh-ris-ide/settings?sessionId=s1' }, got.res, {})
2770
2947
  assert.equal(got.res.status, 200)
2771
2948
  assert.equal(got.json().decompiler.jar, '/opt/cfr/cfr.jar')
2772
- assert.equal(got.json().cacheDir, join(dir, '.dsh-ris-ide-cache'))
2949
+ assert.equal(got.json().cacheDir, join(dir, '.dsh-ris-ide', 'cache'))
2773
2950
 
2774
2951
  // Clearing the field removes the key from the settings file.
2775
2952
  const cleared = answer()
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The standalone IDE window across a `dsh web` restart.
3
+ *
4
+ * The window page is never reloaded by a restart, so it must (a) stay registered
5
+ * with the host without any stored state — its stream IS the registration — and
6
+ * (b) follow the session the workspace is on now, because the id in its URL died
7
+ * with the old host. The DSH page, in turn, must find that window instead of
8
+ * opening a second one. These tests pin the registry contract, the session lookup
9
+ * and the client-side wiring (a real window belongs to the developer's desktop,
10
+ * not to CI).
11
+ */
12
+ import { test } from 'node:test'
13
+ import assert from 'node:assert/strict'
14
+ import { createServer } from 'node:http'
15
+ import { readFile } from 'node:fs/promises'
16
+ import { join } from 'node:path'
17
+
18
+ import { __test } from '../lib/index.js'
19
+
20
+ const {
21
+ WINDOWS_PATH,
22
+ listIdeWindows,
23
+ liveSessionFor,
24
+ ideWindowOpened,
25
+ ideWindowClosed,
26
+ serveWindows,
27
+ } = __test
28
+
29
+ const clientSource = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
30
+ const hostSource = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
31
+ const windowHtml = await readFile(new URL('../lib/standalone/window.html', import.meta.url), 'utf8')
32
+
33
+ function serve(handler) {
34
+ return new Promise((resolve) => {
35
+ const server = createServer((req, res) => { void handler(req, res) })
36
+ server.listen(0, '127.0.0.1', () => resolve(server))
37
+ })
38
+ }
39
+
40
+ function addressOf(server) {
41
+ const info = server.address()
42
+ return `http://127.0.0.1:${info.port}`
43
+ }
44
+
45
+ test('the window route is one GET under the plugin prefix', () => {
46
+ assert.equal(WINDOWS_PATH, '/dsh-ris-ide/windows')
47
+ assert.equal(typeof serveWindows, 'function')
48
+ const source = clientSource
49
+ assert.match(source, /routeUrl\('dsh-ris-ide\/windows'\)/, 'the client asks the host before opening a window')
50
+ })
51
+
52
+ test('a window is alive while its stream is open, and known by its name', () => {
53
+ const name = 'name:test-alive-window'
54
+ ideWindowOpened(name, { name: 'test-alive-window', cwd: '/tmp/test-alive-window', sessionId: 's1' })
55
+ const live = listIdeWindows({ name: 'test-alive-window' })
56
+ assert.equal(live.length, 1)
57
+ assert.equal(live[0].alive, true, 'an open stream means the window is there')
58
+ assert.equal(live[0].sessionId, 's1')
59
+ ideWindowClosed(name)
60
+ const idle = listIdeWindows({ name: 'test-alive-window' })
61
+ assert.equal(idle.length, 1, 'the entry survives a short disconnect (a reload)')
62
+ assert.equal(idle[0].alive, false)
63
+ assert.equal(listIdeWindows({ name: 'no-such-window' }).length, 0)
64
+ })
65
+
66
+ test('two streams of one window count twice, so one close does not end it', () => {
67
+ const name = 'name:test-two-streams'
68
+ ideWindowOpened(name, { name: 'test-two-streams', cwd: '/tmp/test-two-streams', sessionId: 's2' })
69
+ ideWindowOpened(name, { name: 'test-two-streams', cwd: '/tmp/test-two-streams', sessionId: 's2' })
70
+ ideWindowClosed(name)
71
+ assert.equal(listIdeWindows({ name: 'test-two-streams' })[0].alive, true, 'the second stream still holds it')
72
+ ideWindowClosed(name)
73
+ assert.equal(listIdeWindows({ name: 'test-two-streams' })[0].alive, false)
74
+ })
75
+
76
+ test('windows without a name fall back to their workspace as the key', () => {
77
+ const cwd = join('/tmp', 'test-unnamed-window')
78
+ const name = 'cwd:' + cwd
79
+ ideWindowOpened(name, { cwd, sessionId: 's3' })
80
+ const found = listIdeWindows({ cwd })
81
+ assert.equal(found.length, 1)
82
+ assert.equal(found[0].alive, true)
83
+ assert.equal(found[0].name, '')
84
+ ideWindowClosed(name)
85
+ })
86
+
87
+ test('the workspace session is the newest live one in that cwd', () => {
88
+ const cwd = '/tmp/test-session-workspace'
89
+ const ctx = {
90
+ sessions: {
91
+ list: () => [
92
+ { id: 'old', header: { cwd } },
93
+ { id: 'other', header: { cwd: '/tmp/elsewhere' } },
94
+ { id: 'new', header: { cwd } },
95
+ ],
96
+ },
97
+ }
98
+ assert.deepEqual(liveSessionFor(ctx, cwd), { id: 'new' }, 'the newest session wins')
99
+ assert.equal(liveSessionFor(ctx, '/tmp/nothing-here'), null)
100
+ assert.deepEqual(liveSessionFor(ctx, '/tmp/test-session-workspace/sub/program'), { id: 'new' },
101
+ 'the IDE is workspace-level: a window inside a program folder still follows the workspace session')
102
+ assert.deepEqual(liveSessionFor({ sessions: { list: () => [{ id: 'outer', header: { cwd: '/tmp' } }] } }, '/tmp/elsewhere/x'), { id: 'outer' },
103
+ 'an ancestor session is better than nothing')
104
+ assert.equal(liveSessionFor(undefined, cwd), null, 'a host without the service answers nothing')
105
+ assert.equal(liveSessionFor({ sessions: { list: () => { throw new Error('detached') } } }, cwd), null)
106
+ })
107
+
108
+ test('the windows route answers the registry, and rejects a relative cwd', async () => {
109
+ const ctx = {
110
+ sessions: { list: () => [{ id: 'live-1', header: { cwd: '/tmp/test-route-workspace' } }] },
111
+ }
112
+ const server = await serve((req, res) => serveWindows(ctx, req, res))
113
+ try {
114
+ const base = addressOf(server)
115
+ const ok = await fetch(base + WINDOWS_PATH + '?name=name%3Atest-route-window&cwd=' + encodeURIComponent('/tmp/test-route-workspace'))
116
+ assert.equal(ok.status, 200)
117
+ const payload = await ok.json()
118
+ assert.equal(payload.ok, true)
119
+ assert.ok(Array.isArray(payload.windows))
120
+ assert.deepEqual(payload.session, { id: 'live-1' }, 'the route also names the live session of that cwd')
121
+
122
+ const bad = await fetch(base + WINDOWS_PATH + '?cwd=relative%2Fpath')
123
+ assert.equal(bad.status, 400)
124
+ assert.match((await bad.json()).message, /absolute workspace path/)
125
+
126
+ const unnamed = await fetch(base + WINDOWS_PATH)
127
+ assert.equal(unnamed.status, 200)
128
+ assert.equal((await unnamed.json()).session, null, 'no cwd, no session lookup')
129
+ } finally {
130
+ // fetch keeps its socket alive, and a plain close() would wait for it.
131
+ server.closeAllConnections?.()
132
+ server.close()
133
+ }
134
+ })
135
+
136
+ test('the standalone window registers itself and follows the live session', () => {
137
+ assert.match(clientSource, /url\.searchParams\.set\('window', '1'\)/, 'the stream says it is a window')
138
+ assert.match(clientSource, /url\.searchParams\.set\('wname', window\.__dshRisIdeWindowName\)/, 'and which window it is')
139
+ assert.match(clientSource, /window\.__dshRisIdeWindowName = typeof opts\.windowName === 'string' \? opts\.windowName : ''/)
140
+ assert.match(clientSource, /function StandaloneWindow\(props\)/, 'the window root owns the scope')
141
+ assert.match(clientSource, /topics: \['hello'\]/, 'it listens for the host hello frame')
142
+ assert.match(clientSource, /if \(mine !== null && mine\.live === true\) return/, 'a live session id is kept, a dead one is replaced')
143
+ assert.match(clientSource, /setSessionId\(live\)/)
144
+ assert.match(windowHtml, /windowName: params\.get\('wname'\) \|\| ''/, 'the page hands its name to the panel')
145
+ })
146
+
147
+ test('clicking the IDE button closes the old window and opens a fresh one', () => {
148
+ assert.match(clientSource, /async function openStandaloneWindow\(options\)/)
149
+ assert.match(clientSource, /var state = await standaloneWindowState\(windowName, windowCwd\)/, 'the registry is asked before opening')
150
+ // Registration must not depend on which topics the first stream asks for: a
151
+ // window that only listens for `hello` still has to appear in the registry.
152
+ assert.match(hostSource, /const rawWindowCwd = isIdeWindow \? \(url\.searchParams\.get\('cwd'\) \?\? ''\)\.trim\(\) : ''/, 'the window registers from its cwd parameter')
153
+ assert.match(hostSource, /session: helloCwd === undefined \? null : liveSessionFor\(ctx, helloCwd\)/, 'the hello session follows the same cwd')
154
+ // A dropped stream must release its registration from BOTH paths: an aborted
155
+ // connection reports 'error' and 'close', and a window left "alive" forever
156
+ // would make the next IDE-button click wait out a pointless close handshake.
157
+ assert.match(hostSource, /let windowSettled = false/, 'the registration settles exactly once')
158
+ assert.match(hostSource, /const settleWindow = \(\) => \{[\s\S]{0,240}?ideWindowClosed\(windowKey\)/, 'and it is what decrements the stream count')
159
+ assert.match(hostSource, /res\.on\('error', \(\) => \{[\s\S]{0,400}?settleWindow\(\)/, 'an errored stream frees the window too')
160
+ assert.match(clientSource, /if \(state\.exists === true && state\.alive === true\) \{/, 'only a LIVE window is asked to close')
161
+ assert.match(clientSource, /await requestStandaloneWindowClose\(windowName\)/, 'a dead registration cannot block the next open')
162
+ assert.match(clientSource, /channel\.postMessage\(\{ type: 'close' \}\)/, 'the old window is told to close itself')
163
+ assert.match(clientSource, /if \(state\.alive !== true\) \{ release\(\); resolve\(true\); return \}/, 'the handshake waits for the stream to go')
164
+ assert.match(clientSource, /window\.open\(url\.href, windowName, features\)/, 'the new window is opened directly (no blank popup)')
165
+ assert.doesNotMatch(clientSource, /window\.open\('', windowName, features\)/, 'no blank popup that has to be closed again')
166
+ assert.doesNotMatch(clientSource, /settleStandaloneWindow/)
167
+ assert.match(windowHtml, /function closeForOpener\(\)/, 'the window can close itself on request')
168
+ assert.match(windowHtml, /if \(data\.type === 'close'\) \{/, 'the lock holder obeys the close request')
169
+ assert.match(windowHtml, /function takeover\(\)/, 'the blocked window offers "close the old one and open here"')
170
+ assert.match(windowHtml, /关闭旧窗口,在这里打开/)
171
+ // A window that takes the lock over (or sits on the blocked notice) must install
172
+ // the same channel hooks as one that claimed it on load - otherwise the DSH page's
173
+ // close request is never heard and the NEXT click of the IDE button is stuck.
174
+ assert.match(windowHtml, /function startHere\(\) \{\n claim\.blocked = false\n \/\/ The window that ends up running[\s\S]{0,400}?becomeHolder\(\)/, 'every boot route installs the close/focus hooks on the window that ends up running')
175
+ assert.match(windowHtml, /showBlocked\(\)\n becomeHolder\(\)/, 'the blocked notice listens for close as well')
176
+ assert.match(windowHtml, /else if \(data\.type === 'close'\) closeForOpener\(\)/, 'the lock holder obeys the close request')
177
+ assert.match(windowHtml, /if \(data\.type === 'close'\) \{\n\s+\/\/ The DSH page wants a fresh window/, 'the no-Web-Locks fallback obeys it too')
178
+ })
179
+
180
+ test('each workspace gets its own window (and its own close handshake)', () => {
181
+ assert.match(clientSource, /function standaloneWindowName\(cwd\) \{\n return WINDOW_NAME \+ '-' \+ standaloneWindowKey\(cwd\)/, 'the window name is derived from the workspace cwd, not from the session')
182
+ assert.doesNotMatch(clientSource, /standaloneWindowName\(sessionId\)/, 'a session id never names a window')
183
+ assert.match(clientSource, /var windowName = standaloneWindowName\(windowCwd !== undefined \? windowCwd : cwd\)/, 'the window follows the workspace, not the panel\'s subdirectory')
184
+ })
185
+
186
+ test('a restarted host makes every pane drop its stale error and re-read', () => {
187
+ assert.match(clientSource, /var hadFailure = false/, 'a broken stream is remembered')
188
+ assert.match(clientSource, /hadFailure = true/, 'the error handler marks the outage')
189
+ assert.match(clientSource, /if \(recovered === true\) announceRecovery\(\)/, 'the next open is a recovery')
190
+ assert.match(clientSource, /function announceRecovery\(\)/, 'recovery is broadcast once per outage')
191
+ assert.match(clientSource, /hostRecovered: function \(handler\)/, 'panes subscribe to recovery')
192
+ assert.match(clientSource, /function useHostRecovery\(callback\)/, 'one hook for the panes')
193
+ assert.match(clientSource, /useHostRecovery\(function \(\) \{ setError\(undefined\); void recoverTree\(\) \}\)/, 'the tree clears its banner and re-reads')
194
+ assert.match(clientSource, /useHostRecovery\(function \(\) \{ void refresh\(\) \}\)/, 'the log tail re-reads')
195
+ assert.match(clientSource, /useHostRecovery\(function \(\) \{ void refresh\(false\) \}\)/, 'the program console re-reads')
196
+ assert.match(clientSource, /doc\.kind !== 'error'/, 'only documents that failed are retried (edits are kept)')
197
+ assert.match(clientSource, /setError\(undefined\)\n return true/, 'a successful background read also clears the tree banner')
198
+ })