dsh-ris-ide 1.7.1 → 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'
@@ -1252,6 +1253,45 @@ test('fsWrite posts JSON to our own fs/write route and returns the fresh baselin
1252
1253
  }
1253
1254
  })
1254
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
+
1255
1295
  test('undo back to the saved text is not dirty any more', () => {
1256
1296
  assert.equal(T.docDirty({ kind: 'text', text: 'a', saved: 'a' }, { dirty: true }), false, 'mirrored text wins over the stale toolbar flag')
1257
1297
  assert.equal(T.docDirty({ kind: 'text', text: 'a', saved: 'b' }, undefined), true)
@@ -1424,12 +1464,40 @@ test('Ctrl+C copies the selected rows without the context menu', async () => {
1424
1464
  assert.doesNotMatch(source, /The tree is single-selection, so 全选 has nothing to expand into/)
1425
1465
  })
1426
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
+
1427
1495
  test('a file row is a drop target for the directory it lives in', async () => {
1428
1496
  const { readFile } = await import('node:fs/promises')
1429
1497
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1430
1498
  assert.match(source, /var dropDir = entry\.isDir === true \? entry\.path : parentOf\(entry\.path\)/)
1431
1499
  assert.match(source, /var isDropTarget = dropTarget === entry\.path/, 'file rows highlight too')
1432
- 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')
1433
1501
  assert.match(source, /setData\('application\/x-dsh-ris-ide-paths', JSON\.stringify\(dragged\)\)/, 'a drag carries the whole selection')
1434
1502
  assert.match(source, /function dragPaths\(transfer\)/, 'drops read the path list back')
1435
1503
  assert.match(source, /void importExternal\(dropDir, external, \[\]\)/)
@@ -2563,6 +2631,57 @@ test('childEntryFor follows the RENDERED rows, so a folded chain still locates',
2563
2631
  assert.equal(T.childEntryFor([null, 'x', { path: '/w/ris', isDir: false }], file), undefined)
2564
2632
  })
2565
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
+
2566
2685
  test('the locate walk against a real single-child package chain reaches the file parent', async () => {
2567
2686
  const { mkdtemp, mkdir, writeFile, rm } = await import('node:fs/promises')
2568
2687
  const { execFile } = await import('node:child_process')
@@ -2759,6 +2878,36 @@ test('the search toolbar does not clip its results dropdown', () => {
2759
2878
  }
2760
2879
  })
2761
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
+
2762
2911
  test('search replies become dropdown payloads without crashing on `dirs`', () => {
2763
2912
  // The host /search route answers files only: `dirs` is an empty OBJECT. Treating
2764
2913
  // it as an array (`dirs.forEach`) threw and made every filename search look dead.
@@ -2778,6 +2927,102 @@ test('search replies become dropdown payloads without crashing on `dirs`', () =>
2778
2927
  assert.deepEqual(T.searchHitPayload(undefined, '/w'), { matches: [], dirs: {} })
2779
2928
  })
2780
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
+
2781
3026
  test('the search dropdown renders hits, empty state and errors', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, () => {
2782
3027
  const { renderToStaticMarkup } = require(`${REACT_ROOT}/react-dom/server`)
2783
3028
  const render = (hits) => renderToStaticMarkup(React.createElement(T.SearchResults, { hits, fontRatio: 1 }))
@@ -4089,9 +4334,10 @@ test('only the standalone IDE window claims browser shortcuts; a DSH page keeps
4089
4334
  // Ownership is the standalone window, FULL STOP: a DSH page never claims keys.
4090
4335
  assert.match(source, /function ownsKeyTarget\(target\) \{[\s\S]{0,500}?return inStandaloneIdeWindow\(\)/)
4091
4336
  assert.ok(!source.includes('if (inStandaloneIdeWindow()) return true'), 'no page-vs-panel split any more')
4092
- // 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.
4093
4339
  const guards = source.split('if (!ownsKeyTarget(event.target)) return').length - 1
4094
- 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')
4095
4341
  // The panel net only works in the IDE window and only claims the reload chord:
4096
4342
  // the host's other chords (Ctrl+N/O/K/...) are released everywhere.
4097
4343
  assert.match(source, /if \(!inStandaloneIdeWindow\(\)\) return\n\s*if \(isBrowserReloadChord\(event\)\)/)
@@ -4143,6 +4389,42 @@ test('Ctrl+F searches what the editor, log or fallback editor has highlighted',
4143
4389
  assert.doesNotMatch(logHandler, /setTreeQuery/)
4144
4390
  })
4145
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
+
4146
4428
  test('an oversized text file opens a read-only windowed preview', async () => {
4147
4429
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4148
4430
  assert.match(source, /function fsWindowRead\(scope, path, offset, length\)/)
@@ -4383,6 +4665,12 @@ test('the editor find panel matches the IDE chrome', async () => {
4383
4665
  assert.match(css, /background:color-mix\(in srgb, currentColor 6%, transparent\) !important/)
4384
4666
  assert.match(css, /background-image:none !important/, 'CM gradient buttons are neutralised')
4385
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')
4386
4674
  // The panel itself is the IDE's own (chunk-side), not CodeMirror's built-in one.
4387
4675
  const chunkSource = await readFile(new URL('../src/chunks/codemirror.js', import.meta.url), 'utf8')
4388
4676
  const chunkBuilt = await readFile(new URL('../lib/client-codemirror.js', import.meta.url), 'utf8')
@@ -22,7 +22,8 @@ import { __test } from '../lib/index.js'
22
22
 
23
23
  const {
24
24
  handleRequest, searchWorkspaceContent,
25
- CONTENT_SEARCH_PATH, RUN_TEST_PATH, START_PATH, STOP_PATH, PROGRAMS_PATH,
25
+ CONTENT_SEARCH_PATH, SEARCH_STREAM_PATH, CONTENT_SEARCH_STREAM_PATH,
26
+ RUN_TEST_PATH, START_PATH, STOP_PATH, PROGRAMS_PATH,
26
27
  runTestOutput, RUN_TEST_HEAD_CHARS, RUN_TEST_TAIL_CHARS, RUN_TEST_MAX_RECORDS,
27
28
  HARD_MAX_BYTES, PID_SUFFIX, IS_WINDOWS,
28
29
  } = __test
@@ -157,6 +158,129 @@ test('GET /search-content serves hits and rejects a missing q or the wrong metho
157
158
  }, root)
158
159
  })
159
160
 
161
+ // ── Streamed search routes (async paging) ──────────────────────────────────
162
+
163
+ /** Read one NDJSON search answer into its frames, in arrival order. */
164
+ async function readNdjson(response) {
165
+ const frames = []
166
+ const reader = response.body.getReader()
167
+ const decoder = new TextDecoder()
168
+ let buffer = ''
169
+ for (;;) {
170
+ const { done, value } = await reader.read()
171
+ if (done) break
172
+ buffer += decoder.decode(value, { stream: true })
173
+ let index = buffer.indexOf('\n')
174
+ while (index !== -1) {
175
+ const line = buffer.slice(0, index).trim()
176
+ buffer = buffer.slice(index + 1)
177
+ if (line !== '') frames.push(JSON.parse(line))
178
+ index = buffer.indexOf('\n')
179
+ }
180
+ }
181
+ return frames
182
+ }
183
+
184
+ /** Two nested repo roots (`aa-repo`, `bb-repo`), each holding one matching file. */
185
+ async function makeTwoRootFixture(label) {
186
+ const root = await mkdtemp(join(scratch, `${label}-`))
187
+ for (const name of ['aa-repo', 'bb-repo']) {
188
+ const dir = join(root, name)
189
+ await mkdir(dir, { recursive: true })
190
+ await writeFile(join(dir, 'agent-one.txt'), 'needle one\nsecond needle\n')
191
+ await writeFile(join(dir, 'other.txt'), 'nothing here\n')
192
+ execFileSync('git', ['init', '-q'], { cwd: dir })
193
+ execFileSync('git', ['add', '-A'], { cwd: dir })
194
+ }
195
+ return root
196
+ }
197
+
198
+ test('createOrderedPages spends the row budget in root order, not arrival order', () => {
199
+ // Roots answer concurrently: rows of a LATER root must never consume the budget
200
+ // before an earlier root has been emitted, or the streamed prefix would differ
201
+ // from the (sequential) batch answer. Roots 2 and 1 fill their buffers first.
202
+ const pages = []
203
+ let full = 0
204
+ const emitter = __test.createOrderedPages(3, 2, (page) => pages.push(page), { maxItems: 3, onFull: () => { full += 1 } })
205
+ emitter.push(2, ['c1', 'c2', 'c3'])
206
+ emitter.push(1, ['b1', 'b2', 'b3'])
207
+ assert.deepEqual(pages, [], 'a non-head root only buffers, whatever arrives first')
208
+ emitter.push(0, ['a1', 'a2', 'a3'])
209
+ assert.deepEqual(pages, [['a1', 'a2']], 'the head root pages as it fills')
210
+ emitter.finish(0)
211
+ assert.deepEqual(pages, [['a1', 'a2'], ['a3']], 'its remainder goes out as a short page')
212
+ assert.equal(full, 1, 'the third row spends the budget and closes the emitter')
213
+ assert.equal(emitter.total(), 3)
214
+ assert.equal(emitter.isClosed(), true)
215
+ // Nothing leaks in after the budget is spent, and later roots cannot emit.
216
+ emitter.push(2, ['c4'])
217
+ emitter.finish(1)
218
+ emitter.finish(2)
219
+ assert.deepEqual(pages, [['a1', 'a2'], ['a3']])
220
+ })
221
+
222
+ test('GET /search/stream pages the filename matches in tree order and ends with done', async () => {
223
+ const root = await makeTwoRootFixture('stream-name')
224
+ await withServer(async ({ base }) => {
225
+ const response = await fetch(`${base}${SEARCH_STREAM_PATH}?sessionId=s1&q=agent&pageSize=1&limit=10`)
226
+ assert.equal(response.status, 200)
227
+ assert.match(String(response.headers.get('content-type')), /application\/x-ndjson/)
228
+ const frames = await readNdjson(response)
229
+ assert.equal(frames[0].type, 'start')
230
+ assert.equal(frames[0].root, root)
231
+ assert.equal(frames[0].repoCount, 2, 'two nested repo roots are searched')
232
+ const pages = frames.filter((frame) => frame.type === 'page')
233
+ assert.equal(pages.length, 2, 'pageSize=1 ⇒ one page per matching root')
234
+ assert.deepEqual(pages.map((page) => page.items), [
235
+ [join(root, 'aa-repo', 'agent-one.txt')],
236
+ [join(root, 'bb-repo', 'agent-one.txt')],
237
+ ], 'pages follow the repo-root order, never the completion order')
238
+ const done = frames.at(-1)
239
+ assert.equal(done.type, 'done')
240
+ assert.equal(done.matches, 2)
241
+ assert.equal(done.files, 4)
242
+ assert.equal(done.truncated, false)
243
+ }, root)
244
+ })
245
+
246
+ test('GET /search-content/stream pages grep hits and keeps the batch validation', async () => {
247
+ const root = await makeTwoRootFixture('stream-content')
248
+ await withServer(async ({ base }) => {
249
+ const response = await fetch(`${base}${CONTENT_SEARCH_STREAM_PATH}?sessionId=s1&q=needle&pageSize=1&limit=10`)
250
+ assert.equal(response.status, 200)
251
+ const frames = await readNdjson(response)
252
+ const hits = frames.filter((frame) => frame.type === 'page').flatMap((frame) => frame.items)
253
+ assert.deepEqual(hits.map((hit) => `${hit.path.slice(root.length + 1)}:${hit.line}`), [
254
+ 'aa-repo/agent-one.txt:1',
255
+ 'aa-repo/agent-one.txt:2',
256
+ 'bb-repo/agent-one.txt:1',
257
+ 'bb-repo/agent-one.txt:2',
258
+ ])
259
+ assert.deepEqual(frames.at(-1), { type: 'done', files: 2, matches: 4, truncated: false })
260
+
261
+ // A content search still needs a query, and the stream routes stay GET-only.
262
+ const missingQ = await fetch(`${base}${CONTENT_SEARCH_STREAM_PATH}?sessionId=s1`)
263
+ assert.equal(missingQ.status, 400)
264
+ assert.equal((await missingQ.json()).code, 'bad-request')
265
+ const wrongMethod = await postJson(base, SEARCH_STREAM_PATH, { sessionId: 's1', q: 'needle' })
266
+ assert.equal(wrongMethod.status, 405)
267
+ const noSession = await fetch(`${base}${SEARCH_STREAM_PATH}?q=needle`)
268
+ assert.equal(noSession.status, 400)
269
+ }, root)
270
+ })
271
+
272
+ test('GET /search/stream stops early at limit and reports truncated', async () => {
273
+ const root = await makeTwoRootFixture('stream-limit')
274
+ await withServer(async ({ base }) => {
275
+ const response = await fetch(`${base}${SEARCH_STREAM_PATH}?sessionId=s1&q=agent&pageSize=2&limit=1`)
276
+ const frames = await readNdjson(response)
277
+ const items = frames.filter((frame) => frame.type === 'page').flatMap((frame) => frame.items)
278
+ assert.equal(items.length, 1)
279
+ assert.equal(frames.at(-1).type, 'done')
280
+ assert.equal(frames.at(-1).truncated, true, 'limit=1 is reached before the second root answers')
281
+ }, root)
282
+ })
283
+
160
284
  // ── Run-test route: validation ──────────────────────────────────────────────
161
285
 
162
286
  /** A cwd holding one real Maven module (`mod/pom.xml`). */
@@ -1773,11 +1773,15 @@ test('listIdeTree hides ignored files and folds package chains only under java',
1773
1773
  // A single-child folder chain OUTSIDE java must stay as separate rows.
1774
1774
  await mkdir(join(root, 'docs', 'guide'), { recursive: true })
1775
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')
1776
1779
 
1777
1780
  const level = await __test.listIdeTree(root, root)
1778
1781
  const labels = level.entries.map((entry) => entry.label)
1779
1782
  assert.ok(labels.includes('a.java'), 'a tracked/untracked-but-not-ignored file shows')
1780
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')
1781
1785
  assert.equal(labels.includes('ignored'), false, 'an ignored directory disappears')
1782
1786
  // src -> main -> java is a single-child chain, but it is NOT a package tail.
1783
1787
  assert.equal(labels.includes('src'), true, 'src/main/java is not compacted into one row')
@@ -2292,6 +2296,64 @@ test('the fs routes read text, refuse binary/oversized and write back', async ()
2292
2296
  assert.equal(written.status, 200)
2293
2297
  assert.equal(written.body.ok, true)
2294
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')
2295
2357
  })
2296
2358
 
2297
2359
  // ── a browser that cancels an image/file stream must not kill the host ─────