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.
@@ -12,7 +12,8 @@ import { test } from 'node:test'
12
12
  import assert from 'node:assert/strict'
13
13
  import { createServer } from 'node:http'
14
14
  import { createRequire } from 'node:module'
15
- import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
15
+ import { execFileSync } from 'node:child_process'
16
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
16
17
  import { tmpdir } from 'node:os'
17
18
  import { join } from 'node:path'
18
19
  import { fileURLToPath } from 'node:url'
@@ -447,19 +448,22 @@ test('apply adds a Session-header button immediately right of DSH\'s open-in-app
447
448
  }
448
449
  })
449
450
 
450
- test('openStandaloneWindow hands the scope to the plugin\'s own page', () => {
451
+ test('openStandaloneWindow hands the scope to the plugin\'s own page', async () => {
451
452
  const previousWindow = globalThis.window
452
453
  const previousDocument = globalThis.document
454
+ const previousFetch = globalThis.fetch
453
455
  const opened = []
454
456
  globalThis.window = {
455
457
  open: (...args) => { opened.push(args); return { focus() {} } },
456
458
  }
457
459
  globalThis.document = { baseURI: 'http://127.0.0.1:3080/' }
460
+ // No window registered for this workspace yet: the opener creates it.
461
+ globalThis.fetch = async () => ({ ok: false, status: 404, json: async () => ({}) })
458
462
  try {
459
- T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project', programId: 'p1' })
463
+ const handle = await T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project', programId: 'p1' })
460
464
  assert.equal(opened.length, 1)
461
- const [url, name, features] = opened[0]
462
- const parsed = new URL(url)
465
+ const [openedUrl, name, features] = opened[0]
466
+ const parsed = new URL(openedUrl)
463
467
  // Same origin as the DSH page: no new port, cookie auth comes along.
464
468
  assert.equal(parsed.origin, 'http://127.0.0.1:3080')
465
469
  assert.equal(parsed.pathname, '/dsh-ris-ide/window')
@@ -467,6 +471,7 @@ test('openStandaloneWindow hands the scope to the plugin\'s own page', () => {
467
471
  assert.equal(parsed.searchParams.get('cwd'), '/w/project')
468
472
  assert.equal(parsed.searchParams.get('programId'), 'p1')
469
473
  assert.equal(parsed.searchParams.get('debug'), null, 'plain open: no auto-debug')
474
+ assert.notEqual(handle, null, 'the created window is handed back')
470
475
  // One IDE window per workspace: the name is derived from the cwd, so a
471
476
  // second click on the same workspace reuses this window, while another
472
477
  // workspace keeps its own window.
@@ -476,31 +481,144 @@ test('openStandaloneWindow hands the scope to the plugin\'s own page', () => {
476
481
  // A program-subdirectory cwd roots the panel there, but the WINDOW still
477
482
  // follows the workspace (`windowCwd`), so it never opens a second window.
478
483
  globalThis.window.localStorage = { getItem: () => '/w/project' }
479
- T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project/sub', programId: 'p1' })
484
+ await T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project/sub', programId: 'p1' })
480
485
  const scoped = new URL(opened[opened.length - 1][0])
481
486
  assert.equal(scoped.searchParams.get('cwd'), '/w/project/sub', 'the panel keeps its rooted cwd')
482
487
  assert.equal(opened[opened.length - 1][1], T.standaloneWindowName('/w/project'), 'the window name stays workspace-keyed')
483
488
  assert.match(features, /popup=yes/)
484
489
  // The compact panel's 🐞 button: same window, plus "start the JDWP session".
485
- T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project', programId: 'p1', debug: true })
490
+ await T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project', programId: 'p1', debug: true })
486
491
  assert.equal(new URL(opened[opened.length - 1][0]).searchParams.get('debug'), '1')
487
492
  } finally {
488
493
  globalThis.window = previousWindow
489
494
  globalThis.document = previousDocument
495
+ globalThis.fetch = previousFetch
490
496
  }
491
497
  })
492
498
 
493
- test('openStandaloneWindow asks for the whole screen work area (maximized)', () => {
499
+ test('an already-open window is asked to close before a fresh one is opened', async () => {
494
500
  const previousWindow = globalThis.window
495
501
  const previousDocument = globalThis.document
502
+ const previousFetch = globalThis.fetch
503
+ const previousChannel = globalThis.BroadcastChannel
504
+ const opened = []
505
+ const messages = []
506
+ const windowName = T.standaloneWindowName('/w/project')
507
+ let alive = true
508
+ globalThis.window = { open: (...args) => { opened.push(args); return { focus() {} } } }
509
+ globalThis.document = { baseURI: 'http://127.0.0.1:3080/' }
510
+ globalThis.fetch = async () => ({
511
+ ok: true,
512
+ status: 200,
513
+ json: async () => ({ ok: true, windows: [{ name: windowName, cwd: '/w/project', alive, idleMs: 12 }], session: null }),
514
+ })
515
+ globalThis.BroadcastChannel = class {
516
+ constructor(name) { this.name = name; this.onmessage = null }
517
+ postMessage(message) {
518
+ messages.push({ name: this.name, message })
519
+ // The old window obeys: it closes itself, so its stream disappears.
520
+ if (message !== null && message.type === 'close') alive = false
521
+ }
522
+ close() {}
523
+ }
524
+ try {
525
+ const handle = await T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project' })
526
+ assert.notEqual(handle, null, 'the click always ends with a window')
527
+ assert.equal(opened.length, 1, 'exactly one window is opened — after the old one is gone, no twin')
528
+ assert.equal(new URL(opened[0][0]).pathname, '/dsh-ris-ide/window')
529
+ assert.equal(opened[0][1], windowName, 'the window name is workspace-keyed')
530
+ assert.deepEqual(messages, [{ name: windowName, message: { type: 'close' } }], 'the old window is asked to close, not raised')
531
+ } finally {
532
+ globalThis.window = previousWindow
533
+ globalThis.document = previousDocument
534
+ globalThis.fetch = previousFetch
535
+ globalThis.BroadcastChannel = previousChannel
536
+ }
537
+ })
538
+
539
+ test('a window that refuses to close does not block the new one', async () => {
540
+ const previousWindow = globalThis.window
541
+ const previousDocument = globalThis.document
542
+ const previousFetch = globalThis.fetch
543
+ const previousChannel = globalThis.BroadcastChannel
544
+ const opened = []
545
+ const messages = []
546
+ const windowName = T.standaloneWindowName('/w/project')
547
+ globalThis.window = { open: (...args) => { opened.push(args); return { focus() {} } } }
548
+ globalThis.document = { baseURI: 'http://127.0.0.1:3080/' }
549
+ // It stays alive: the old window ignored the close ping (a frozen tab, say).
550
+ globalThis.fetch = async () => ({
551
+ ok: true,
552
+ status: 200,
553
+ json: async () => ({ ok: true, windows: [{ name: windowName, cwd: '/w/project', alive: true, idleMs: 8 }], session: null }),
554
+ })
555
+ globalThis.BroadcastChannel = class {
556
+ constructor(name) { this.name = name; this.onmessage = null }
557
+ postMessage(message) { messages.push({ name: this.name, message }) }
558
+ close() {}
559
+ }
560
+ try {
561
+ const started = Date.now()
562
+ const handle = await T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project' })
563
+ assert.notEqual(handle, null, 'the click still ends with a window')
564
+ assert.equal(opened.length, 1)
565
+ assert.deepEqual(messages.map((entry) => entry.message.type), ['close'], 'the close ping is the only message')
566
+ assert.ok(Date.now() - started >= 1400, 'it waited for the closing handshake before giving up')
567
+ } finally {
568
+ globalThis.window = previousWindow
569
+ globalThis.document = previousDocument
570
+ globalThis.fetch = previousFetch
571
+ globalThis.BroadcastChannel = previousChannel
572
+ }
573
+ })
574
+
575
+ test('a closed window never blocks the next open (dead registrations do not wait)', async () => {
576
+ const previousWindow = globalThis.window
577
+ const previousDocument = globalThis.document
578
+ const previousFetch = globalThis.fetch
579
+ const previousChannel = globalThis.BroadcastChannel
580
+ const opened = []
581
+ const messages = []
582
+ globalThis.window = { open: (...args) => { opened.push(args); return { focus() {} } } }
583
+ globalThis.document = { baseURI: 'http://127.0.0.1:3080/' }
584
+ globalThis.fetch = async () => ({
585
+ ok: true,
586
+ status: 200,
587
+ json: async () => ({ ok: true, windows: [{ name: T.standaloneWindowName('/w/project'), cwd: '/w/project', alive: false, idleMs: 5000 }], session: null }),
588
+ })
589
+ globalThis.BroadcastChannel = class {
590
+ constructor(name) { this.name = name; this.onmessage = null }
591
+ postMessage(message) { messages.push({ name: this.name, message }) }
592
+ close() {}
593
+ }
594
+ try {
595
+ const started = Date.now()
596
+ const handle = await T.openStandaloneWindow({ sessionId: 's1', cwd: '/w/project' })
597
+ assert.notEqual(handle, null, 'a registration whose stream is gone must not block opening')
598
+ assert.equal(opened.length, 1)
599
+ assert.deepEqual(messages, [], 'no close ping: there is nobody to close')
600
+ assert.ok(Date.now() - started < 850, 'no pointless wait for a window that is already gone')
601
+ } finally {
602
+ globalThis.window = previousWindow
603
+ globalThis.document = previousDocument
604
+ globalThis.fetch = previousFetch
605
+ globalThis.BroadcastChannel = previousChannel
606
+ }
607
+ })
608
+
609
+ test('openStandaloneWindow asks for the whole screen work area (maximized)', async () => {
610
+ const previousWindow = globalThis.window
611
+ const previousDocument = globalThis.document
612
+ const previousFetch = globalThis.fetch
496
613
  const opened = []
497
614
  globalThis.window = {
498
615
  screen: { availWidth: 1920, availHeight: 1040 },
499
616
  open: (...args) => { opened.push(args); return { focus() {} } },
500
617
  }
501
618
  globalThis.document = { baseURI: 'http://127.0.0.1:3080/' }
619
+ globalThis.fetch = async () => ({ ok: false, status: 404, json: async () => ({}) })
502
620
  try {
503
- T.openStandaloneWindow({ sessionId: 's1' })
621
+ await T.openStandaloneWindow({ sessionId: 's1' })
504
622
  const features = opened[0][2]
505
623
  assert.match(features, /width=1920/, 'the work area width, not a fixed width')
506
624
  assert.match(features, /height=1040/, 'the work area height, not a fixed height')
@@ -509,24 +627,28 @@ test('openStandaloneWindow asks for the whole screen work area (maximized)', ()
509
627
  assert.match(features, /popup=yes/)
510
628
  // No screen information (odd hosts): keep the old fallback instead of NaN.
511
629
  globalThis.window = { open: (...args) => { opened.push(args); return { focus() {} } } }
512
- T.openStandaloneWindow({ sessionId: 's1' })
630
+ await T.openStandaloneWindow({ sessionId: 's1' })
513
631
  assert.match(opened[1][2], /width=1500/)
514
632
  } finally {
515
633
  globalThis.window = previousWindow
516
634
  globalThis.document = previousDocument
635
+ globalThis.fetch = previousFetch
517
636
  }
518
637
  })
519
638
 
520
- test('openStandaloneWindow reports a blocked popup instead of failing silently', () => {
639
+ test('openStandaloneWindow reports a blocked popup instead of failing silently', async () => {
521
640
  const previousWindow = globalThis.window
522
641
  const previousDocument = globalThis.document
642
+ const previousFetch = globalThis.fetch
523
643
  globalThis.window = { open: () => null }
524
644
  globalThis.document = { baseURI: 'http://127.0.0.1:3080/' }
645
+ globalThis.fetch = async () => ({ ok: false, status: 404, json: async () => ({}) })
525
646
  try {
526
- assert.throws(() => T.openStandaloneWindow({ sessionId: 's1' }), /被拦截/)
647
+ await assert.rejects(T.openStandaloneWindow({ sessionId: 's1' }), /被拦截/)
527
648
  } finally {
528
649
  globalThis.window = previousWindow
529
650
  globalThis.document = previousDocument
651
+ globalThis.fetch = previousFetch
530
652
  }
531
653
  })
532
654
 
@@ -545,11 +667,10 @@ test('mountStandalone renders the IDE panel with no DSH context at all', async (
545
667
  // The panel sits under the error boundary, so one render error cannot blank
546
668
  // the window; the boundary itself is the outermost component.
547
669
  assert.equal(element.type, T.IdeErrorBoundary, 'the panel is wrapped in the error boundary')
548
- const panel = element.props.children
549
- assert.equal(typeof panel.type, 'function', 'the panel component, not a wrapper')
550
- assert.equal(panel.props.sessionId, 's1')
551
- assert.equal(panel.props.cwd, '/w/project')
552
- assert.equal(panel.props.visible, true)
670
+ const windowRoot = element.props.children
671
+ assert.equal(windowRoot.type, T.StandaloneWindow, 'the window root owns the scope it can change')
672
+ assert.equal(windowRoot.props.sessionId, 's1')
673
+ assert.equal(windowRoot.props.cwd, '/w/project')
553
674
  } finally {
554
675
  globalThis.window = previousWindow
555
676
  globalThis.document = previousDocument
@@ -643,7 +764,7 @@ async function withLogServer(run) {
643
764
  res.writeHead(state.disableConfig ? 409 : 200, { 'content-type': 'application/json' })
644
765
  res.end(JSON.stringify(state.disableConfig
645
766
  ? { ok: false, code: 'config-exists', message: 'exists' }
646
- : { ok: true, path: '/w/.dsh-ris-ide.json', count: 3, mode: state.configBody.mode ?? 'generate' }))
767
+ : { ok: true, path: '/w/.dsh-ris-ide/config.json', count: 3, mode: state.configBody.mode ?? 'generate' }))
647
768
  })
648
769
  return
649
770
  }
@@ -919,7 +1040,7 @@ test('generateConfig asks the host to write or update the config', async () => {
919
1040
  const scope = { sessionId: 's1', cwd: '/w' }
920
1041
  const generated = await T.generateConfig(scope)
921
1042
  assert.equal(generated.ok, true)
922
- assert.equal(generated.path, '/w/.dsh-ris-ide.json')
1043
+ assert.equal(generated.path, '/w/.dsh-ris-ide/config.json')
923
1044
  assert.equal(generated.mode, 'generate')
924
1045
  assert.equal(state.configCalls, 1)
925
1046
  assert.deepEqual(state.configBody, { sessionId: 's1', cwd: '/w' })
@@ -1132,6 +1253,45 @@ test('fsWrite posts JSON to our own fs/write route and returns the fresh baselin
1132
1253
  }
1133
1254
  })
1134
1255
 
1256
+ test('fsWrite sends an oversized document in utf8 chained chunks', async () => {
1257
+ const calls = []
1258
+ const original = globalThis.fetch
1259
+ globalThis.fetch = async (url, init) => {
1260
+ calls.push(JSON.parse(init.body))
1261
+ return { ok: true, status: 200, json: async () => ({ ok: true, mtimeMs: 777, chunked: true }) }
1262
+ }
1263
+ try {
1264
+ // 1.6 MB of 3-byte code points: the 512 KB cuts land INSIDE characters, so a
1265
+ // naive byte split would corrupt them. The client must cut at code points and
1266
+ // the host must reassemble the identical document.
1267
+ const text = '汉'.repeat(Math.floor(1.6 * 1024 * 1024 / 3))
1268
+ const written = await T.fsWrite({ sessionId: 's1', cwd: '/w' }, '/w/big.java', text)
1269
+ assert.equal(written.mtimeMs, 777)
1270
+ assert.ok(calls.length >= 3, `expected several chunks, got ${calls.length}`)
1271
+ assert.deepEqual(calls.map((body) => body.offset).slice(1), calls.slice(1).map((body) => body.offset),
1272
+ 'offsets are ascending byte positions')
1273
+ assert.equal(calls[0].offset, 0)
1274
+ assert.equal(calls[calls.length - 1].final, true, 'only the last chunk is final')
1275
+ assert.ok(calls.slice(0, -1).every((body) => body.final === false))
1276
+ assert.equal(calls.map((body) => body.content).join(''), text, 'the pieces rebuild the document exactly')
1277
+ const byteTotal = new TextEncoder().encode(text).length
1278
+ const last = calls[calls.length - 1]
1279
+ assert.equal(last.offset + new TextEncoder().encode(last.content).length, byteTotal, 'the last offset lands on the exact size')
1280
+ assert.ok(calls.every((body) => new TextEncoder().encode(body.content).length <= 512 * 1024))
1281
+
1282
+ // A failed chunk surfaces the host's message and stops the loop.
1283
+ calls.length = 0
1284
+ globalThis.fetch = async (url, init) => {
1285
+ calls.push(JSON.parse(init.body))
1286
+ return { ok: false, status: 409, json: async () => ({ ok: false, message: 'chunk is missing; save again' }) }
1287
+ }
1288
+ await assert.rejects(T.fsWrite({ sessionId: 's1' }, '/w/big.java', text), /save again/)
1289
+ assert.equal(calls.length, 1)
1290
+ } finally {
1291
+ globalThis.fetch = original
1292
+ }
1293
+ })
1294
+
1135
1295
  test('undo back to the saved text is not dirty any more', () => {
1136
1296
  assert.equal(T.docDirty({ kind: 'text', text: 'a', saved: 'a' }, { dirty: true }), false, 'mirrored text wins over the stale toolbar flag')
1137
1297
  assert.equal(T.docDirty({ kind: 'text', text: 'a', saved: 'b' }, undefined), true)
@@ -1304,12 +1464,40 @@ test('Ctrl+C copies the selected rows without the context menu', async () => {
1304
1464
  assert.doesNotMatch(source, /The tree is single-selection, so 全选 has nothing to expand into/)
1305
1465
  })
1306
1466
 
1467
+ test('a drag inside the tree confirms before it moves anything', async () => {
1468
+ const { readFile } = await import('node:fs/promises')
1469
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1470
+ // A drop only ASKS: the move itself waits in `pendingMove`.
1471
+ assert.match(source, /var \[pendingMove, setPendingMove\] = useState\(null\)/)
1472
+ assert.match(source, /function movablePaths\(paths, dirPath\) \{/, 'self / same-parent / own-subtree drops are filtered out first')
1473
+ assert.match(source, /function requestMove\(paths, dirPath\) \{/)
1474
+ assert.match(source, /setPendingMove\(\{ paths: movable, dir: dirPath \}\)/)
1475
+ // Both drop surfaces (a row and the blank area) go through the confirmation.
1476
+ assert.match(source, /if \(paths\.length > 0\) requestMove\(paths, dropDir\)/)
1477
+ assert.match(source, /if \(paths\.length > 0\) requestMove\(paths, rootDir\)/)
1478
+ assert.doesNotMatch(source, /void moveEntriesInto\(paths, dropDir\)/, 'a drop never moves without asking')
1479
+ // The card says what moves where, 取消 owns focus, Esc cancels, 移动 runs it.
1480
+ assert.match(source, /function renderTreeMoveConfirm\(\) \{/)
1481
+ assert.match(source, /'data-tree-move-confirm': '1'/)
1482
+ assert.match(source, /'data-tree-move-cancel': '1'/)
1483
+ assert.match(source, /'data-tree-move-ok': '1'/)
1484
+ assert.match(source, /var moveCancelRef = useRef\(null\)/)
1485
+ assert.match(source, /移动到:' \+ dir/)
1486
+ assert.match(source, /if \(pending !== null\) void moveEntriesInto\(pending\.paths, pending\.dir\)/)
1487
+ assert.match(source, /move\{0,1\}CancelRef|cancel\.focus\(\)/, '取消 takes focus so Esc/Enter are predictable')
1488
+ assert.match(source, /setPendingMove\(null\)\n\s+\}\n\s+document\.addEventListener\('keydown', onKey, true\)/,
1489
+ 'Esc closes the confirmation')
1490
+ // While the card is open the tree must not run its own Del / Ctrl+C / Ctrl+V.
1491
+ assert.match(source, /if \(prompt !== null \|\| pendingDelete !== null \|\| pendingMove !== null\) return/)
1492
+ assert.match(source, /var anyDialogOpen = prompt !== null \|\| pendingDelete !== null \|\| batchConflict !== null \|\| pendingMove !== null/)
1493
+ })
1494
+
1307
1495
  test('a file row is a drop target for the directory it lives in', async () => {
1308
1496
  const { readFile } = await import('node:fs/promises')
1309
1497
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1310
1498
  assert.match(source, /var dropDir = entry\.isDir === true \? entry\.path : parentOf\(entry\.path\)/)
1311
1499
  assert.match(source, /var isDropTarget = dropTarget === entry\.path/, 'file rows highlight too')
1312
- assert.match(source, /void moveEntriesInto\(paths, dropDir\)/, 'dropping on a file moves into its parent')
1500
+ assert.match(source, /if \(paths\.length > 0\) requestMove\(paths, dropDir\)/, 'dropping on a file asks first, then moves into its parent')
1313
1501
  assert.match(source, /setData\('application\/x-dsh-ris-ide-paths', JSON\.stringify\(dragged\)\)/, 'a drag carries the whole selection')
1314
1502
  assert.match(source, /function dragPaths\(transfer\)/, 'drops read the path list back')
1315
1503
  assert.match(source, /void importExternal\(dropDir, external, \[\]\)/)
@@ -1319,6 +1507,105 @@ test('a file row is a drop target for the directory it lives in', async () => {
1319
1507
  assert.doesNotMatch(source, /onDragOver: entry\.isDir === true \?/)
1320
1508
  })
1321
1509
 
1510
+ // 1.7.1: 从系统桌面复制多个文件到文件树、目标目录里已有同名文件时,1.7.0 的
1511
+ // importExternal 在第一个同名冲突处 `break`,后面的文件被静默丢弃(用户看到「只复制了
1512
+ // 一个」)。批量导入现在先落地其余文件,把同名的收集进同一张「覆盖 / 生成副本」卡片;
1513
+ // 只有单个文件时才保留「粘贴为」改名卡。files 与 text/uri-list 也必须一起读——有些
1514
+ // 桌面只投递文本,只读 files 会再次丢文件。
1515
+ test('pasting several OS files never stops at the first existing name', async () => {
1516
+ const { readFile } = await import('node:fs/promises')
1517
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1518
+ // The batch loop no longer abandons the rest of the paste on a collision.
1519
+ assert.doesNotMatch(source, /if \(created === undefined\) break/,
1520
+ 'a 同名 collision must not drop every file after it')
1521
+ assert.match(source, /async function importOne\(source, dir, name, overwrite\)/)
1522
+ assert.match(source, /async function importOneWithCopyName\(source, dir\)/)
1523
+ assert.match(source, /var name = attempt === 0 \? source\.name : collisionCopyName\(source\.name, false, attempt\)/,
1524
+ '生成副本 reuses the batch suffix rule')
1525
+ // ONE file keeps the 粘贴为 card; MANY collect the collisions into the batch card.
1526
+ assert.match(source, /if \(sources\.length === 1\) \{\n\s+\/\/ A single pasted file: the collision is a choice, not a batch\.\n\s+parkPasteName\(source, trimmedDir, source\.name\)/)
1527
+ assert.match(source, /items: conflicts, created: created,\n\s+origins: \[\], touched: \[trimmedDir\], external: true,/,
1528
+ 'the external collisions park the same 覆盖 / 生成副本 card')
1529
+ assert.match(source, /if \(pending\.external === true\) \{/, 'the batch card knows how to place a pasted blob/path')
1530
+ assert.match(source, /created\.push\(await importOne\(item, pending\.dir, item\.name, true\)\)/, '覆盖 re-sends the pasted bytes')
1531
+ assert.match(source, /var placedExternal = await importOneWithCopyName\(item, pending\.dir\)/, '生成副本 re-sends under a suffixed name')
1532
+ // files AND the URI list are read together; a name delivered as both is imported once.
1533
+ assert.match(source, /if \(files\.length > 0 \|\| paths\.length > 0\) \{/,
1534
+ 'a payload with files or paths goes through the tree paste path')
1535
+ assert.match(source, /void pasteFromOsClipboard\(text\)/,
1536
+ 'an empty payload asks the Host what the OS clipboard holds')
1537
+ assert.match(source, /void importExternal\(pasteTargetDir\(\), files, paths\)/)
1538
+ assert.match(source, /if \(fileName === '' \|\| seen\[fileName\] === true\) continue/)
1539
+ assert.match(source, /if \(leaf === '' \|\| seen\[leaf\] === true\) continue/)
1540
+ })
1541
+
1542
+ // 1.7.1: 树里按 Ctrl+C(内部剪贴板非空)之后,在资源管理器复制别的文件、再回树里
1543
+ // Ctrl+V —— keydown 曾经直接 preventDefault + pasteInto(内部剪贴板),浏览器根本不发
1544
+ // paste 事件,粘出来的是「之前复制出去的那批文件」(源文件已删就报不存在)。现在 OS
1545
+ // 剪贴板优先:keydown 只兜底,paste 事件先到先按外部内容导入;只有同名同数量的那批
1546
+ // 才是回头的自家剪贴板,仍走树内语义(剪切 = 移动)。
1547
+ test('an OS clipboard paste wins over a stale tree clipboard', async () => {
1548
+ const { readFile } = await import('node:fs/promises')
1549
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1550
+ // The keydown no longer claims the gesture when our own clipboard is non-empty…
1551
+ assert.match(source, /if \(clipboard === null\) return\n\s+\/\/ A text field owns Ctrl\+V/,
1552
+ 'the tree clipboard no longer swallows Ctrl+V outright')
1553
+ assert.match(source, /if \(isTextEntry\(event\.target\)\) return/, 'an editor keeps its native paste')
1554
+ // …it waits one beat, so an empty OS clipboard still pastes the tree clipboard.
1555
+ assert.match(source, /var askedAt = Date\.now\(\)/)
1556
+ assert.match(source, /if \(pasteAtRef\.current >= askedAt\) return/)
1557
+ // The paste handler decides: our own copy keeps the tree semantics, anything else imports.
1558
+ assert.match(source, /pasteAtRef\.current = Date\.now\(\)/, 'the paste event stands the fallback down')
1559
+ assert.match(source, /if \(clipboard !== null && isTreeClipboardCopy\(files, paths\)\) \{/,
1560
+ 'our own copy is confirmed against the Host before it takes the tree path')
1561
+ assert.match(source, /function isTreeClipboardCopy\(files, paths\) \{/)
1562
+ assert.match(source, /function isTextEntry\(node\) \{/)
1563
+ assert.match(source, /if \(own\.length === 0 \|\| seen\.length !== own\.length\) return false/,
1564
+ 'a different file set is external content, not the tree clipboard')
1565
+ })
1566
+
1567
+ // 谁新谁赢:`beginCopy` 会把同一批写进系统剪贴板,所以粘贴负载与树内那批不同 ⇒
1568
+ // 系统剪贴板是后来复制的东西,树里的旧剪贴板作废(丢弃),绝不复活旧条目。
1569
+ test('a newer OS clipboard discards the older tree clipboard', async () => {
1570
+ const { readFile } = await import('node:fs/promises')
1571
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1572
+ assert.match(source, /\/\/ Different files than the tree copied[\s\S]{0,300}if \(clipboard !== null\) setClipboard\(null\)\n\s+void importExternal\(pasteTargetDir\(\), files, paths\)/)
1573
+ assert.match(source, /已清空文件树里的旧复制/)
1574
+ assert.match(source, /var newer = text\.trim\(\) !== '' \|\| \(host !== null && host\.text\.trim\(\) !== ''\)/)
1575
+ assert.match(source, /\/\/ No paste payload at all and nothing readable[\s\S]{0,200}void pasteInto\(pasteTargetDir\(\)\)/)
1576
+ })
1577
+
1578
+ // 桌面 → 文件树(WSL):Explorer 里的文件复制根本进不了 Chromium(WSLg 不桥接
1579
+ // Windows 的 CF_HDROP),paste 事件是空负载;此时由宿主读系统剪贴板,拿真实文件
1580
+ // 列表走 /fs/import。宿主的读数同时用来判断树里那份旧剪贴板是否还有效。
1581
+ test('a desktop copy reaches the tree through the Host clipboard', async () => {
1582
+ const { readFile } = await import('node:fs/promises')
1583
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1584
+ assert.match(source, /void pasteFromOsClipboard\(text\)/, 'an empty payload asks the Host')
1585
+ assert.match(source, /async function fsClipboardState\(scope\) \{[\s\S]{0,400}'dsh-ris-ide\/clipboard\/read'/)
1586
+ assert.match(source, /var host = await readHostClipboard\(\)/)
1587
+ assert.match(source, /if \(clipboard !== null && samePathList\(host\.files, clipboardItems\(\)\)\) \{/,
1588
+ 'our own copy stays on the tree path')
1589
+ assert.match(source, /void importExternal\(pasteTargetDir\(\), \[\], host\.files\)/,
1590
+ 'files the page cannot see are imported from the Host list')
1591
+ assert.match(source, /function samePathList\(files, items\) \{/)
1592
+ assert.match(source, /function trimTrailingSeparator\(path\) \{/)
1593
+ })
1594
+
1595
+ // 系统剪贴板只投递 `text/uri-list`(没有 File blob)时走 `/fs/import`:宿主读的是
1596
+ // `from` = 源文件、`dir` = 目标目录。两个调用点曾把两者写反(from=目标目录、
1597
+ // dir=源文件),于是粘贴报「粘贴目标不是目录」,文件一个都落不下来。
1598
+ test('a path paste sends the source as `from` and the folder as `dir`', async () => {
1599
+ const { readFile } = await import('node:fs/promises')
1600
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1601
+ assert.match(source, /async function fsImportPath\(scope, sourcePath, dir, name, overwrite\)/)
1602
+ assert.match(source, /\{ from: sourcePath, dir: dir, name: name, overwrite: overwrite === true \}/)
1603
+ assert.match(source, /await fsImportPath\(scope, source\.path, trimmedDir, name, overwrite === true\)/)
1604
+ assert.match(source, /await fsImportPath\(scope, source\.path, dir, name, replace\)/)
1605
+ assert.doesNotMatch(source, /fsImportPath\(scope, dir, source\.path/)
1606
+ assert.doesNotMatch(source, /fsImportPath\(scope, trimmedDir, source\.path/)
1607
+ })
1608
+
1322
1609
  test('a forced tree read asks the host for a fresh listing', async () => {
1323
1610
  const { readFile } = await import('node:fs/promises')
1324
1611
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
@@ -1524,9 +1811,9 @@ test('the tree watch only reloads loaded directories and keeps a short cache', (
1524
1811
  })
1525
1812
 
1526
1813
  test('deletes park in the undo trash under a unique, recognisable name', () => {
1527
- assert.equal(T.TREE_TRASH_DIR, '.dsh-ris-ide-trash')
1528
- assert.equal(T.trashDirFor('/w/ris'), '/w/ris/.dsh-ris-ide-trash')
1529
- assert.equal(T.trashDirFor('/w/ris/'), '/w/ris/.dsh-ris-ide-trash')
1814
+ assert.equal(T.TREE_TRASH_DIR, '.dsh-ris-ide/trash')
1815
+ assert.equal(T.trashDirFor('/w/ris'), '/w/ris/.dsh-ris-ide/trash')
1816
+ assert.equal(T.trashDirFor('/w/ris/'), '/w/ris/.dsh-ris-ide/trash')
1530
1817
  assert.equal(T.trashNameFor('/w/ris/src/ModelHelper.java', 1730), '1730-ModelHelper.java')
1531
1818
  assert.equal(T.trashNameFor('/w/ris/src', 1730), '1730-src')
1532
1819
  })
@@ -1923,7 +2210,7 @@ test('a whole workbench console row picks the program, name and blank alike', as
1923
2210
  // pressing ■ on another program does not also switch this pane's log.
1924
2211
  assert.match(source, /onClick: function \(\) \{ selectProgram\(program\) \}/, 'row picks the program')
1925
2212
  assert.match(source, /button\('▶', function \(event\) \{ event\.stopPropagation\(\); void consoleStart\(program\) \}/)
1926
- assert.match(source, /button\('■', function \(event\) \{ event\.stopPropagation\(\); void consoleStop\(program\) \}/)
2213
+ assert.match(source, /button\(stopGlyph\(11\), function \(event\) \{ event\.stopPropagation\(\); void consoleStop\(program\) \}/)
1927
2214
  assert.match(source, /button\('⟳', function \(event\) \{ event\.stopPropagation\(\); void consoleRestart\(program\) \}/)
1928
2215
  assert.match(source, /button\(ideBadgeIcon\('bug', 'play', 13\), function \(event\) \{ event\.stopPropagation\(\); void consoleDebug\(program\) \}/)
1929
2216
  })
@@ -1940,6 +2227,41 @@ test('sidebar start/stop/restart stay silent, and ⟳ is green like ▶', async
1940
2227
  assert.match(source, /width: 25, start: true, action: 'console-restart'/, 'workbench ⟳ is green')
1941
2228
  })
1942
2229
 
2230
+ test('the stop mark is a drawn square, and the sidebar batch bar keeps the row tones', async () => {
2231
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
2232
+ // The ■ character's ink is about half its advance width: inside a 20px sidebar
2233
+ // button (or a 25px workbench one) it read as a dot. Every stop control draws a
2234
+ // fixed square instead, so both consoles agree on the size.
2235
+ // Module scope, not inside ProgramWorkbench: the sidebar ProgramsPanel draws it too,
2236
+ // and a nested declaration makes the whole sidebar tab throw "stopGlyph is not defined".
2237
+ assert.match(source, /^ {4}function stopGlyph\(size\) \{/m, 'stopGlyph is declared at module scope')
2238
+ assert.match(source, /width: side, height: side, flex: '0 0 auto'/, 'the square has a real box')
2239
+ assert.match(
2240
+ source,
2241
+ /display: 'inline-block', verticalAlign: 'middle'/,
2242
+ 'the square keeps the text line box, so the border matches the neighbouring buttons',
2243
+ )
2244
+ assert.match(source, /S\.paneIconOff : S\.stopIcon, 'data-action': 'batch-stop'/, 'sidebar batch ■ is red like the row ■')
2245
+ assert.match(source, /S\.paneIconOff : S\.startIcon, 'data-action': 'batch-start'/, 'sidebar batch ▶ is green like the row ▶')
2246
+ assert.match(source, /width: 25, stop: true, action: 'batch-stop'/, 'workbench batch ■ keeps its red tone')
2247
+ const glyphUses = source.match(/stopGlyph\(/g) || []
2248
+ assert.ok(glyphUses.length >= 4, 'both consoles (row + batch) draw the square')
2249
+ })
2250
+
2251
+ test('copying in the tree also publishes the files to the OS clipboard', async () => {
2252
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
2253
+ // The internal clipboard alone only feeds the tree's own Ctrl+V. Putting the
2254
+ // SAME list on the system clipboard is what lets Explorer / a desktop paste it;
2255
+ // the page cannot do that itself, so the Host route does it — and when the Host
2256
+ // has no backend the paths still land as text instead of the copy failing.
2257
+ assert.match(source, /dsh-ris-ide\/clipboard\/files/, 'the copy asks the host clipboard route')
2258
+ assert.match(source, /await fsClipboardFiles\(scope, items, mode === 'cut'\)/, 'cut keeps its MOVE intent')
2259
+ assert.match(source, /function clipboardQuery\(scope\) \{/, 'the host needs the workspace to stage a copy')
2260
+ assert.match(source, /await fsClipboardFiles\(scope, items, mode === 'cut'\)[\s\S]{0,40}/)
2261
+ assert.match(source, /await navigator\.clipboard\.writeText\(items\.map/, 'without a backend the paths still land as text')
2262
+ assert.match(source, /void publishSystemClipboard\(items, mode\)/, 'beginCopy publishes right after it sets the internal clipboard')
2263
+ })
2264
+
1943
2265
  test('console program rows keep one horizontal inset when a row is picked', async () => {
1944
2266
  const S = T.stylesFor(1)
1945
2267
  assert.equal(S.consoleRow.padding, '1px 6px', 'unpicked rows have a left/right inset')
@@ -1987,7 +2309,7 @@ test('the help panel data covers tree, editor and debug shortcuts', () => {
1987
2309
  const logKeys = sections.find((section) => section.title === '日志').rows.map((row) => row.keys).join(' ')
1988
2310
  assert.match(logKeys, /Ctrl\+F/, 'log find is documented')
1989
2311
  const configKeys = sections.find((section) => section.title === '配置').rows.map((row) => row.keys).join(' ')
1990
- assert.match(configKeys, /\.dsh-ris-ide\.json/, 'the hidden config file is documented')
2312
+ assert.match(configKeys, /\.dsh-ris-ide\/config\.json/, 'the config file (inside the state folder) is documented')
1991
2313
  // The help panel must not promise an editor back/forward that does not exist.
1992
2314
  assert.doesNotMatch(generalKeys, /Alt\+\u2190/, 'no fake editor back/forward row')
1993
2315
  })
@@ -2309,6 +2631,57 @@ test('childEntryFor follows the RENDERED rows, so a folded chain still locates',
2309
2631
  assert.equal(T.childEntryFor([null, 'x', { path: '/w/ris', isDir: false }], file), undefined)
2310
2632
  })
2311
2633
 
2634
+ test('pathWithin decides whether the locate walk can start at the tree root', () => {
2635
+ assert.equal(T.pathWithin('/w', '/w/a/B.java'), true)
2636
+ assert.equal(T.pathWithin('/w', '/w'), true, 'a root contains itself')
2637
+ assert.equal(T.pathWithin('/w/', '/w/a/B.java'), true, 'a trailing slash is ignored')
2638
+ assert.equal(T.pathWithin('/w\\a', '/w/a/B.java'), true, 'windows separators compare equal')
2639
+ assert.equal(T.pathWithin('/w/ris', '/w/AGENTS.md'), false, 'a re-rooted tree cannot reach a sibling file')
2640
+ assert.equal(T.pathWithin('/w/ris', '/w/ris2/A.java'), false, 'a shared prefix is not a parent')
2641
+ assert.equal(T.pathWithin('/', '/w/A.java'), true, 'the filesystem root contains everything')
2642
+ assert.equal(T.pathWithin('', '/w/A.java'), false)
2643
+ assert.equal(T.pathWithin(undefined, '/w/A.java'), false)
2644
+ assert.equal(T.pathWithin('/w', undefined), false)
2645
+ })
2646
+
2647
+ test('locate expands EVERY ancestor in one update and re-roots when the file is outside the tree', async () => {
2648
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
2649
+ const tree = source.slice(source.indexOf('function IdeTree('), source.indexOf('function IdeEditor('))
2650
+
2651
+ // One commit for the whole chain, keyed from the frozen array: a `setExpanded`
2652
+ // updater runs LATER, so a key read from the loop variable made the top
2653
+ // ancestors expand with a deeper path — the "locate does nothing" race.
2654
+ const locate = tree.slice(tree.indexOf('async function locate(target) {'), tree.indexOf('function revealRow(path) {'))
2655
+ assert.match(locate, /var chain = \[\]/, 'the walk collects the chain first')
2656
+ assert.match(locate, /chain\.push\(descend\)/, 'each level appends the RENDERED row path')
2657
+ assert.match(locate, /setExpanded\(function \(prev\) \{\n\s*var state = Object\.assign\(\{\}, prev\)\n\s*for \(var index = 0; index < chain\.length; index \+= 1\) state\[chain\[index\]\] = true/, 'one update opens the whole chain')
2658
+ assert.doesNotMatch(locate, /state\[descend\] = true/, 'the loop variable is no longer captured by the deferred updater')
2659
+ // A re-rooted tree walks from its own root; a file outside it is only reachable
2660
+ // from the workspace root, so the walk falls back there (and re-roots the tree).
2661
+ assert.match(locate, /if \(!pathWithin\(startRoot, filePath\) && pathWithin\(workspaceRoot, filePath\)\) \{/)
2662
+ assert.match(locate, /startRoot = workspaceRoot\n\s*setRootTrail\(\[\]\)/, 'the tree follows the locate')
2663
+ assert.match(locate, /var startRoot = absolutePath\(cwd, activeRoot\)/)
2664
+ // The file is still opened, and its row scrolled into view, whatever happened.
2665
+ assert.match(locate, /props\.onOpen\(filePath\)\n\s*revealRow\(filePath\)/)
2666
+ })
2667
+
2668
+ test('the tree highlight follows the editor, not the last locate', async () => {
2669
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
2670
+ const tree = source.slice(source.indexOf('function IdeTree('), source.indexOf('function IdeEditor('))
2671
+
2672
+ // A locate paints nothing of its own: `reveal` exists to SCROLL the row into
2673
+ // view, and a locate row used to stay lit until the next locate.
2674
+ assert.doesNotMatch(tree, /isRevealed/, 'the locate highlight is gone')
2675
+ assert.doesNotMatch(source, /'data-tree-revealed'/, 'and so is its attribute')
2676
+ // The strong tint means "the file the editor is showing" (or the directory an
2677
+ // operation targets); a merely-selected file row wears the softer multi tint.
2678
+ assert.match(tree, /var isCurrent = isActive \|\| \(isSelected && entry\.isDir === true\)/)
2679
+ assert.match(tree, /isCurrent \? S\.treeRowOn : \(isMulti \|\| isSelected \? S\.treeRowMulti : S\.treeRow\)/)
2680
+ assert.match(tree, /'data-tree-current': isCurrent \? '1' : undefined/)
2681
+ // Selecting another tab moves the highlight with it.
2682
+ assert.match(tree, /if \(selectedPath === active\) return\n\s*selectOne\(active\)/)
2683
+ })
2684
+
2312
2685
  test('the locate walk against a real single-child package chain reaches the file parent', async () => {
2313
2686
  const { mkdtemp, mkdir, writeFile, rm } = await import('node:fs/promises')
2314
2687
  const { execFile } = await import('node:child_process')
@@ -2505,6 +2878,36 @@ test('the search toolbar does not clip its results dropdown', () => {
2505
2878
  }
2506
2879
  })
2507
2880
 
2881
+ test('a pre-1.7.3 host without the stream routes still answers from the batch route', async () => {
2882
+ const original = globalThis.fetch
2883
+ const calls = []
2884
+ try {
2885
+ globalThis.fetch = async (href) => {
2886
+ const url = new URL(String(href))
2887
+ calls.push(url.pathname)
2888
+ if (url.pathname.endsWith('/dsh-ris-ide/search/stream')) return { ok: false, status: 404, headers: new Headers() }
2889
+ return { ok: true, status: 200, json: async () => ({ ok: true, matches: ['/w/ris/a.java'], dirs: {} }) }
2890
+ }
2891
+ const pages = []
2892
+ const done = await T.fsSearchStream({ sessionId: 's1', cwd: '/w' }, 'a.java', { onPage: (items) => pages.push(items) })
2893
+ assert.deepEqual(pages, [['/w/ris/a.java']], 'the batch answer arrives as one page')
2894
+ assert.deepEqual(done, { matches: 1, files: 0, truncated: false })
2895
+ assert.equal(calls.length, 2)
2896
+ assert.equal(calls[1].endsWith('/dsh-ris-ide/search'), true, 'the fallback is the batch search route')
2897
+
2898
+ globalThis.fetch = async (href) => {
2899
+ const url = new URL(String(href))
2900
+ if (url.pathname.endsWith('/dsh-ris-ide/search-content/stream')) return { ok: false, status: 404, headers: new Headers() }
2901
+ return { ok: true, status: 200, json: async () => ({ ok: true, hits: [{ path: '/w/a.txt', line: 3, text: 'needle' }] }) }
2902
+ }
2903
+ const contentPages = []
2904
+ await T.fsSearchContentStream({ sessionId: 's1', cwd: '/w' }, 'needle', { onPage: (items) => contentPages.push(items) })
2905
+ assert.deepEqual(contentPages, [[{ path: '/w/a.txt', line: 3, text: 'needle' }]])
2906
+ } finally {
2907
+ globalThis.fetch = original
2908
+ }
2909
+ })
2910
+
2508
2911
  test('search replies become dropdown payloads without crashing on `dirs`', () => {
2509
2912
  // The host /search route answers files only: `dirs` is an empty OBJECT. Treating
2510
2913
  // it as an array (`dirs.forEach`) threw and made every filename search look dead.
@@ -2524,6 +2927,102 @@ test('search replies become dropdown payloads without crashing on `dirs`', () =>
2524
2927
  assert.deepEqual(T.searchHitPayload(undefined, '/w'), { matches: [], dirs: {} })
2525
2928
  })
2526
2929
 
2930
+ test('streamed search answers are read page by page, not after the whole body', async () => {
2931
+ const encoder = new TextEncoder()
2932
+ const frames = [
2933
+ { type: 'start', root: '/w', repoCount: 2 },
2934
+ { type: 'page', items: ['/w/ris/a/A.java'] },
2935
+ { type: 'page', items: ['/w/ris/b/B.java', '/w/ris/b/C.java'] },
2936
+ { type: 'done', files: 900, matches: 3, truncated: false },
2937
+ ]
2938
+ const text = frames.map((frame) => `${JSON.stringify(frame)}\n`).join('')
2939
+ // Split mid-frame and mid-line: the reader must hold the partial NDJSON line.
2940
+ const cut = text.indexOf('\n') + 12
2941
+ const body = new ReadableStream({
2942
+ start(controller) {
2943
+ controller.enqueue(encoder.encode(text.slice(0, cut)))
2944
+ controller.enqueue(encoder.encode(text.slice(cut)))
2945
+ controller.close()
2946
+ },
2947
+ })
2948
+ const pages = []
2949
+ const done = await T.readSearchStream(new Response(body), (items) => pages.push(items))
2950
+ assert.deepEqual(pages, [['/w/ris/a/A.java'], ['/w/ris/b/B.java', '/w/ris/b/C.java']])
2951
+ assert.deepEqual(done, { matches: 3, files: 900, truncated: false })
2952
+
2953
+ // A connection that ends without `done` is incomplete: throw, never pretend.
2954
+ const truncated = new ReadableStream({
2955
+ start(controller) {
2956
+ controller.enqueue(encoder.encode(`${JSON.stringify({ type: 'page', items: ['x'] })}\n`))
2957
+ controller.close()
2958
+ },
2959
+ })
2960
+ await assert.rejects(() => T.readSearchStream(new Response(truncated), () => {}), /检索连接中断/)
2961
+
2962
+ // An `error` frame surfaces the host's message instead of swallowing it.
2963
+ const failed = new ReadableStream({
2964
+ start(controller) {
2965
+ controller.enqueue(encoder.encode(`${JSON.stringify({ type: 'error', code: 'bad-request', message: 'q is required' })}\n`))
2966
+ controller.close()
2967
+ },
2968
+ })
2969
+ await assert.rejects(() => T.readSearchStream(new Response(failed), () => {}), /q is required/)
2970
+
2971
+ // No readable stream (an old WebView): a clear error, not a silent hang.
2972
+ await assert.rejects(() => T.readSearchStream({}, () => {}), /不支持流式读取/)
2973
+ })
2974
+
2975
+ test('fsSearchStream paints page by page from the REAL streamed host route', async () => {
2976
+ // End-to-end through the host half's own handler and a real listener: the
2977
+ // NDJSON is chunked over HTTP, so this proves the client parser and the host
2978
+ // framing agree — a unit fixture with a hand-made Response cannot.
2979
+ const cwd = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-stream-'))
2980
+ const seen = []
2981
+ try {
2982
+ for (const repo of ['aa-repo', 'bb-repo']) {
2983
+ const dir = join(cwd, repo)
2984
+ await mkdir(dir, { recursive: true })
2985
+ await writeFile(join(dir, 'agent-one.txt'), 'agent\n')
2986
+ await writeFile(join(dir, 'other.txt'), 'other\n')
2987
+ execFileSync('git', ['init', '-q'], { cwd: dir })
2988
+ execFileSync('git', ['add', '.'], { cwd: dir })
2989
+ }
2990
+ const ctx = { sessions: { get: (id) => (id === 's1' ? { header: { cwd } } : undefined) } }
2991
+ const options = { maxBytes: 1024 * 1024, restrictToCwd: false, stopGraceMs: 5000, minFreeMemoryBytes: 1 }
2992
+ const server = createServer((req, res) => hostTest.handleRequest(ctx, req, res, options))
2993
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
2994
+ const previousDocument = globalThis.document
2995
+ globalThis.document = { baseURI: `http://127.0.0.1:${server.address().port}/` }
2996
+ try {
2997
+ const done = await T.fsSearchStream({ sessionId: 's1', cwd }, 'agent', {
2998
+ onPage: (items) => { seen.push(items) },
2999
+ })
3000
+ const relative = seen.map((items) => items.map((item) => item.slice(cwd.length + 1)))
3001
+ assert.deepEqual(relative, [['aa-repo/agent-one.txt'], ['bb-repo/agent-one.txt']],
3002
+ 'pages arrive in tree order, one per root page, already absolute')
3003
+ assert.equal(done.matches, 2)
3004
+ assert.equal(done.truncated, false)
3005
+ } finally {
3006
+ globalThis.document = previousDocument
3007
+ server.closeAllConnections?.()
3008
+ await new Promise((resolve) => server.close(resolve))
3009
+ }
3010
+ } finally {
3011
+ await rm(cwd, { recursive: true, force: true })
3012
+ }
3013
+ })
3014
+
3015
+ test('the search effects stream their pages and abort a query the user moved past', async () => {
3016
+ const source = await readFile(join(ROOT, 'lib', 'client.js'), 'utf8')
3017
+ assert.match(source, /fsSearchStream\(scopeRef\.current, text, \{/, 'the filename search streams')
3018
+ assert.match(source, /fsSearchContentStream\(scopeRef\.current, text, \{/, 'the content search streams')
3019
+ assert.match(source, /onPage: function \(page\) \{/, 'every page is painted as it lands')
3020
+ assert.match(source, /if \(controller !== null\) controller\.abort\(\)/, 'a changed query aborts the previous stream')
3021
+ assert.match(source, /var SEARCH_STREAM_PAGE_SIZE = 40/)
3022
+ assert.match(source, /pageSize', String\(SEARCH_STREAM_PAGE_SIZE\)\)/)
3023
+ assert.match(source, /if \(cancelled \|\| isAbortError\(problem\)\) return/, 'an aborted stream is not an error line')
3024
+ })
3025
+
2527
3026
  test('the search dropdown renders hits, empty state and errors', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, () => {
2528
3027
  const { renderToStaticMarkup } = require(`${REACT_ROOT}/react-dom/server`)
2529
3028
  const render = (hits) => renderToStaticMarkup(React.createElement(T.SearchResults, { hits, fontRatio: 1 }))
@@ -2901,7 +3400,7 @@ test('the IDE top bar hosts the workspace search and only shows config buttons w
2901
3400
  // the programs listed underneath (the sidebar console keeps 打开配置/更新配置
2902
3401
  // in the same place), so they no longer ride on the source pane toolbar.
2903
3402
  const consoleHead = consoleHeadOf(markup)
2904
- assert.match(consoleHead, /title="打开配置文件/, 'the console offers 📄 for .dsh-ris-ide.json')
3403
+ assert.match(consoleHead, /title="打开配置文件/, 'the console offers 📄 for .dsh-ris-ide/config.json')
2905
3404
  for (const action of ['config-open', 'config-generate']) {
2906
3405
  const tag = consoleHead.match(new RegExp(`<button[^>]*data-action="${action}"[^>]*>`))
2907
3406
  assert.ok(tag !== null, `missing ${action} in the console title bar`)
@@ -3443,7 +3942,17 @@ test('one IDE window per workspace: the window name is keyed by the workspace cw
3443
3942
  assert.match(source, /var windowCwd = typeof opts\.windowCwd === 'string'/)
3444
3943
  assert.match(source, /var windowName = standaloneWindowName\(windowCwd !== undefined \? windowCwd : cwd\)/)
3445
3944
  assert.match(source, /url\.searchParams\.set\('wname', windowName\)/)
3446
- assert.match(source, /window\.open\(url\.href, windowName, features\)/)
3945
+ // A workspace owns ONE window: ask the host registry first, and only create a
3946
+ // window when the registry says there is none (no blank popup that is closed
3947
+ // again, which both flashes and still fails to raise the window).
3948
+ assert.match(source, /async function openStandaloneWindow\(options\) \{/)
3949
+ assert.match(source, /if \(state\.exists === true && state\.alive === true\) \{/)
3950
+ assert.doesNotMatch(source, /focusStandaloneWindow/, 'raising a foreign window is not attempted any more')
3951
+ assert.match(source, /await requestStandaloneWindowClose\(windowName\)/, 'present: ask the old window to close, then open one')
3952
+ assert.doesNotMatch(source, /focus-ack/, 'no focus handshake: the browser forbids it')
3953
+ assert.match(source, /window\.open\(url\.href, windowName, features\)/, 'absent: create it straight on the IDE url')
3954
+ assert.doesNotMatch(source, /window\.open\('', windowName, features\)/, 'never a blank window to close again')
3955
+ assert.doesNotMatch(source, /settleStandaloneWindow/)
3447
3956
  })
3448
3957
 
3449
3958
  test('the standalone window claims a single-instance lock before booting the IDE', async () => {
@@ -3458,7 +3967,11 @@ test('the standalone window claims a single-instance lock before booting the IDE
3458
3967
  assert.match(claim, /BroadcastChannel/, 'fallback channel exists')
3459
3968
  assert.match(claim, /params\.get\('wname'\)/, 'the opener hands the workspace window name over')
3460
3969
  assert.match(claim, /var key = windowName/, 'the lock key IS the window name')
3461
- assert.match(claim, /type: 'focus'/, 'the surviving window is nudged forward')
3970
+ assert.match(claim, /data\.type === 'focus'/, 'the surviving window is nudged forward')
3971
+ assert.match(claim, /data\.type === 'close'/, 'the opener can ask the old window to close itself')
3972
+ assert.match(claim, /function closeForOpener\(\)/, 'closing is the window\'s own decision')
3973
+ assert.match(claim, /function takeover\(\)/, 'the blocked window can wait for the old lock and boot here')
3974
+ assert.match(claim, /关闭旧窗口,在这里打开/, 'the duplicate offers to replace the old window')
3462
3975
  // A reused window (same name, e.g. after a dsh restart) can still see the old
3463
3976
  // document's lock for a moment: retry before believing there is a real second
3464
3977
  // window, and NEVER close this one (that made it flash and vanish).
@@ -3468,7 +3981,7 @@ test('the standalone window claims a single-instance lock before booting the IDE
3468
3981
  // offers an explicit "close this window" action instead — and only that button
3469
3982
  // may close it (never an automatic close at boot).
3470
3983
  assert.match(claim, /关闭这个窗口/, 'the duplicate window can be closed on demand')
3471
- assert.equal((claim.match(/window\.close\(\)/g) || []).length, 1, 'closing happens only from the button')
3984
+ assert.equal((claim.match(/window\.close\(\)/g) || []).length, 2, 'closing happens only from the two explicit user actions')
3472
3985
  // Booting waits for the claim, so the notice cannot be raced by a mounted panel.
3473
3986
  assert.match(html, /window\.__risIdeClaimReady/)
3474
3987
  assert.match(html, /window\.__risIdeBootPanel = bootPanel/)
@@ -3585,7 +4098,7 @@ test('a render failure inside the panel shows a retry banner instead of taking d
3585
4098
 
3586
4099
  // BOTH mount points are wrapped (the dsh sidebar tab and the standalone window).
3587
4100
  assert.match(source, /function IdePanelBoundary\(props\) \{ return h\(IdeErrorBoundary, null, h\(ProgramsPanel, Object\.assign\(\{\}, props, \{ clientCtx: ctx \}\)\)\) \}/)
3588
- assert.match(source, /root\.render\(h\(IdeErrorBoundary, null, h\(ProgramsPanel, \{ sessionId: sessionId, cwd: cwd, visible: true, compact: false \}\)\)\)/)
4101
+ assert.match(source, /root\.render\(h\(IdeErrorBoundary, null, h\(StandaloneWindow, \{ sessionId: sessionId, cwd: cwd \}\)\)\)/)
3589
4102
  })
3590
4103
 
3591
4104
  test('a start switches to that program log before waiting for the spawn', async () => {
@@ -3613,7 +4126,7 @@ test('the debug pane has a visual settings dialog for dependency sources', { ski
3613
4126
  assert.match(source, /fsDependencySource\(scopeRef\.current, cleaned/, 'a missing workspace source asks the host for the jar source')
3614
4127
  assert.match(source, /dsh-ris-ide\/debug\/source/)
3615
4128
  assert.match(source, /-sources\.jar/)
3616
- assert.match(source, /\.dsh-ris-ide-cache/)
4129
+ assert.match(source, /\.dsh-ris-ide\/cache/)
3617
4130
  })
3618
4131
 
3619
4132
  test('the IDE console masks a program row while it starts, stops or debugs, and the compact note expires', async () => {
@@ -3821,9 +4334,10 @@ test('only the standalone IDE window claims browser shortcuts; a DSH page keeps
3821
4334
  // Ownership is the standalone window, FULL STOP: a DSH page never claims keys.
3822
4335
  assert.match(source, /function ownsKeyTarget\(target\) \{[\s\S]{0,500}?return inStandaloneIdeWindow\(\)/)
3823
4336
  assert.ok(!source.includes('if (inStandaloneIdeWindow()) return true'), 'no page-vs-panel split any more')
3824
- // Ctrl+W, the find chord and the debug keys still check ownership first.
4337
+ // Ctrl+W, the find chords (Ctrl+R / Ctrl+F) and the debug keys still check
4338
+ // ownership first.
3825
4339
  const guards = source.split('if (!ownsKeyTarget(event.target)) return').length - 1
3826
- assert.equal(guards, 3, 'Ctrl+W, the find chord and debug keys all bail out on foreign targets')
4340
+ assert.equal(guards, 4, 'Ctrl+W, the find chords, Ctrl+F and debug keys all bail out on foreign targets')
3827
4341
  // The panel net only works in the IDE window and only claims the reload chord:
3828
4342
  // the host's other chords (Ctrl+N/O/K/...) are released everywhere.
3829
4343
  assert.match(source, /if \(!inStandaloneIdeWindow\(\)\) return\n\s*if \(isBrowserReloadChord\(event\)\)/)
@@ -3875,6 +4389,42 @@ test('Ctrl+F searches what the editor, log or fallback editor has highlighted',
3875
4389
  assert.doesNotMatch(logHandler, /setTreeQuery/)
3876
4390
  })
3877
4391
 
4392
+ test('Ctrl+F with the search panel ALREADY open puts the caret back in the find field', async () => {
4393
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4394
+ const chunkSource = await readFile(new URL('../src/chunks/codemirror.js', import.meta.url), 'utf8')
4395
+ const chunk = await readFile(new URL('../lib/client-codemirror.js', import.meta.url), 'utf8')
4396
+
4397
+ // @codemirror/search finds the find field through `[main-field]`; without it a
4398
+ // second Ctrl+F with the panel open had no input to focus and did nothing.
4399
+ assert.match(chunkSource, /searchInput\.setAttribute\('main-field', 'true'\)/)
4400
+ assert.match(chunk, /searchInput\.setAttribute\("main-field", "true"\)/)
4401
+ // The keymap only sees keys pressed in the document, so the panel listens for
4402
+ // Ctrl+F itself: focus may sit in the replace box or on a toggle button.
4403
+ assert.match(chunkSource, /dom\.addEventListener\('keydown', \(event\) => \{\n\s*if \(\(event\.ctrlKey === true \|\| event\.metaKey === true\)/)
4404
+ assert.match(chunkSource, /event\.preventDefault\(\)\n\s*focusInput\(\)/)
4405
+ assert.match(chunk, /dom\.addEventListener\("keydown", \(event\) => \{/)
4406
+
4407
+ // The log pane and the plain-text fallback editor have the same promise, and
4408
+ // both used to rely on a mount/effect that does not re-run for an open bar.
4409
+ assert.match(source, /var findInputRef = useRef\(null\)/)
4410
+ assert.match(source, /findInputRef\.current\.focus\(\)/)
4411
+ // The fallback editor's input is ref'd and its Ctrl+F pulls focus there.
4412
+ const editorStart = source.indexOf('function IdeEditor(props) {')
4413
+ const editorSource = source.slice(editorStart, editorStart + 6000)
4414
+ assert.match(editorSource, /ref: findInputRef, style: S\.findInput/)
4415
+ assert.match(editorSource, /var findInput = findInputRef\.current\n\s*if \(findInput !== null && findInput !== undefined\) \{\n\s*findInput\.focus\(\)/)
4416
+
4417
+ // Keys pressed OUTSIDE the document (tabs bar, tree, workspace search box) never
4418
+ // reach CodeMirror's keymap, so the browser's own find bar opened instead. The
4419
+ // workbench claims the chord in the standalone window and hands it to the open
4420
+ // file's editor handle, which opens/focuses the panel.
4421
+ assert.match(chunkSource, /find\(\) \{\n\s*openSearchPanel\(view\)\n\s*\},/)
4422
+ assert.match(chunk, /find\(\) \{\s*openSearchPanel\(view\);\s*\}/)
4423
+ assert.match(source, /function onFindKey\(event\) \{\n\s*if \(event\.defaultPrevented === true\) return/)
4424
+ assert.match(source, /if \(!ownsKeyTarget\(event\.target\)\) return[\s\S]{0,900}?typeof controls\.find === 'function'/)
4425
+ assert.match(source, /window\.addEventListener\('keydown', onFindKey\)/)
4426
+ })
4427
+
3878
4428
  test('an oversized text file opens a read-only windowed preview', async () => {
3879
4429
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
3880
4430
  assert.match(source, /function fsWindowRead\(scope, path, offset, length\)/)
@@ -4115,6 +4665,12 @@ test('the editor find panel matches the IDE chrome', async () => {
4115
4665
  assert.match(css, /background:color-mix\(in srgb, currentColor 6%, transparent\) !important/)
4116
4666
  assert.match(css, /background-image:none !important/, 'CM gradient buttons are neutralised')
4117
4667
  assert.match(css, /\.cm-searchMatch-selected\{background:rgba\(255,150,40,0\.42\)/)
4668
+ // The panel must NOT out-stack the pane's header row: the workspace-search
4669
+ // dropdown is anchored there (`editorPaneHead`, z-index 30) and drops down over
4670
+ // the editor's top edge — CodeMirror's baseTheme `z-index:300` painted the find
4671
+ // panel over the whole dropdown ("文件检索框的结果下拉框被编辑器的搜索面板遮挡").
4672
+ assert.match(css, /\.cm-panels\{[^}]*z-index:20 !important\}/, 'find panel stays under the search dropdown')
4673
+ assert.match(source, /editorPaneHead: \{\n[\s\S]{0,400}?zIndex: 30,/, 'the header row that anchors the dropdown')
4118
4674
  // The panel itself is the IDE's own (chunk-side), not CodeMirror's built-in one.
4119
4675
  const chunkSource = await readFile(new URL('../src/chunks/codemirror.js', import.meta.url), 'utf8')
4120
4676
  const chunkBuilt = await readFile(new URL('../lib/client-codemirror.js', import.meta.url), 'utf8')