dsh-ris-ide 1.7.1 → 1.7.3

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,9 @@ 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'
17
+ import { readFileSync as readSync } from 'node:fs'
16
18
  import { tmpdir } from 'node:os'
17
19
  import { join } from 'node:path'
18
20
  import { fileURLToPath } from 'node:url'
@@ -182,6 +184,72 @@ test('double-clicking a title-bar control does not maximise the pane', () => {
182
184
  assert.equal(T.headerDoubleClickIsTitle(input), false)
183
185
  })
184
186
 
187
+ test('the dialog marks exactly one of start/stop as the live action', async () => {
188
+ const { readFile } = await import('node:fs/promises')
189
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
190
+ // `S.buttonOff` is the DISABLED skin, so painting an enabled action with it made
191
+ // 启动/停止 look equally dead. One shared factory fixes the box, and only the
192
+ // actionable button is filled.
193
+ assert.ok(source.includes('function dialogButton(spec)'), 'start/stop/save must share one button shape')
194
+ assert.ok(source.includes('minWidth: 84, height: 28'), 'all three must share one box so the row lines up')
195
+ assert.ok(source.includes('var filled = spec.primary === true && spec.disabled !== true'),
196
+ 'grey is reserved for "nothing to do here"')
197
+ assert.ok(source.includes("primary: !running,"), '启动 is the filled one while stopped')
198
+ assert.ok(source.includes("primary: running,"), '停止 is the filled one while running')
199
+ assert.ok(source.includes("'data-proxy-action': spec.action"), 'the three actions stay addressable')
200
+ // Enabled controls must not borrow the disabled skin.
201
+ assert.equal(source.includes("style: S.buttonOff, 'data-proxy-add'"), false, '+ 添加规则 is enabled, not inert')
202
+ assert.equal(source.includes("style: S.buttonOff, 'data-proxy-close'"), false, 'the close ✕ is enabled, not inert')
203
+ })
204
+
205
+ test('one proxy control governs engine, interception and git together', async () => {
206
+ const { readFile } = await import('node:fs/promises')
207
+ const client = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
208
+ const host = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
209
+ // No separate git buttons: git follows the tunnel it belongs to.
210
+ assert.equal(client.includes('data-proxy-git-on'), false, 'the git-on button is gone')
211
+ assert.equal(client.includes('data-proxy-git-off'), false, 'the git-off button is gone')
212
+ assert.ok(client.includes('启动同时写入 git 代理,停止同时清除'), 'the footer has to say what start/stop do')
213
+ // Start/stop drive all three layers, and so does the host exit hook.
214
+ assert.ok(host.includes('const redirector = await startRedirectors()'), 'start brings the interception up')
215
+ assert.ok(host.includes('syncGitProxy({ cwd, host: gitHost, enabled: true })'), 'start writes the git entry')
216
+ assert.ok(host.includes('syncGitProxy({ cwd, host: gitHost, enabled: false })'), 'stop clears the git entry')
217
+ assert.ok(host.includes('const redirector = await stopRedirector()'), 'stop brings the interception down')
218
+ assert.ok(host.includes('clearGitProxySync()'), 'the exit hook undoes the git entry too')
219
+ // The route reports each layer's outcome so a dismissed UAC prompt is visible.
220
+ assert.ok(client.includes("' · 系统层拦截已启动('"), 'the note reports the interception start')
221
+ assert.ok(client.includes("' · git 代理已写入 '"), 'the note reports the git entry')
222
+ })
223
+
224
+ test('the console follows the live sidebar session, not the one it opened in', async () => {
225
+ const { readFile } = await import('node:fs/promises')
226
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
227
+ // `keepMounted` keeps the body alive across Session switches, so the session id
228
+ // it was opened with goes stale — the panel has to read the sidebar's live one.
229
+ assert.ok(source.includes('data-sidebar-right-session'), 'the live marker must be read')
230
+ assert.ok(source.includes("attributeFilter: ['data-sidebar-right-session', 'data-sidebar-right-panel', 'hidden']"),
231
+ 'switch must be observed, including retained wrappers being shown')
232
+ assert.ok(source.includes('data-sidebar-right-panel'), 'the panel element outranks a retained SessionView wrapper')
233
+ assert.ok(source.includes("node.closest('[hidden]') !== null"), 'a wrapper inside a hidden tree must not win')
234
+ assert.ok(source.includes('getClientRects().length === 0'), 'an unrendered wrapper must not win')
235
+ assert.ok(source.includes('if (nearestId !== undefined && shown(nearest)) return nearestId'),
236
+ 'the nearest marker only wins while it is on screen')
237
+ assert.ok(source.includes('setInterval(sync, 1500)'), 'a repaint-only switch still needs a fallback')
238
+ assert.ok(source.includes("window.addEventListener('focus', sync)"), 'returning to the window re-checks the session')
239
+ assert.ok(source.includes("if (typeof liveSessionId === 'string' && liveSessionId !== '') sessionId = liveSessionId"),
240
+ 'the live id must win over the injected one')
241
+ assert.ok(source.includes('}, [sessionIdentity])'), 'another workspace must drop the followed program')
242
+ // Both console shapes share one dialog, so it must not inherit either font.
243
+ assert.ok(source.includes("fontFamily: CHROME_FAMILY, fontSize: DEFAULT_FONT_SIZE + 'px'"),
244
+ 'the proxy dialog pins the IDE chrome font so the narrow console does not wrap rows')
245
+ assert.ok(source.includes("'Microsoft YaHei', sans-serif)"),
246
+ 'the chrome stack must match what the IDE theme resolves to, not a mono list')
247
+ // Form controls do not inherit the page font: the dialog has to say so, twice.
248
+ assert.ok(source.includes("fontFamily: 'inherit'"), 'the field style must inherit the dialog font')
249
+ assert.ok(source.includes('[data-proxy-dialog] input, [data-proxy-dialog] button, [data-proxy-dialog] select, [data-proxy-dialog] textarea { font-family: inherit; font-size: inherit; }'),
250
+ 'every control inside the dialog must inherit the card font')
251
+ })
252
+
185
253
  test('only invisible outcomes and failures raise a toast', async () => {
186
254
  const { readFile } = await import('node:fs/promises')
187
255
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
@@ -447,6 +515,32 @@ test('apply adds a Session-header button immediately right of DSH\'s open-in-app
447
515
  }
448
516
  })
449
517
 
518
+ test('the header button opens THIS session\'s workspace, not the remembered one', async () => {
519
+ // The slot hands every entry the session store (`useSessions`) and the
520
+ // session id, so the window's cwd comes from the session itself. Passing only
521
+ // the id let the window fall back to `dsh-ris-ide:last-cwd` — the workspace of
522
+ // the previous session, which is what the button then reopened.
523
+ assert.equal(T.sessionWorkspaceCwd(undefined, 's1'), undefined, 'no store hook: the caller keeps its own fallback')
524
+ assert.equal(T.sessionWorkspaceCwd(() => undefined, ''), undefined, 'no session id: nothing to look up')
525
+ const store = (state) => (selector) => selector(state)
526
+ assert.equal(T.sessionWorkspaceCwd(store({ byId: { s1: { cwd: '/w/current' } } }), 's1'), '/w/current')
527
+ assert.equal(T.sessionWorkspaceCwd(store({ byId: { s1: {} } }), 's1'), undefined, 'a session row without a cwd')
528
+ assert.equal(T.sessionWorkspaceCwd(store({ byId: { s1: { cwd: '' } } }), 's1'), undefined, 'an empty cwd is not a workspace')
529
+ assert.equal(T.sessionWorkspaceCwd(store({}), 's1'), undefined, 'a store that has not listed the session yet')
530
+ assert.equal(T.sessionWorkspaceCwd(store(undefined), 's1'), undefined, 'a missing store snapshot')
531
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
532
+ assert.match(
533
+ source,
534
+ /var sessionCwd = sessionWorkspaceCwd\(props !== null && props !== undefined \? props\.useSessions : undefined, sessionId\)/,
535
+ 'the button reads the session store',
536
+ )
537
+ assert.match(
538
+ source,
539
+ /openStandaloneWindow\(\{ sessionId: sessionId, cwd: sessionCwd, windowCwd: sessionCwd \}\)/,
540
+ 'both the panel cwd and the single-window name follow the session workspace',
541
+ )
542
+ })
543
+
450
544
  test('openStandaloneWindow hands the scope to the plugin\'s own page', async () => {
451
545
  const previousWindow = globalThis.window
452
546
  const previousDocument = globalThis.document
@@ -1252,6 +1346,45 @@ test('fsWrite posts JSON to our own fs/write route and returns the fresh baselin
1252
1346
  }
1253
1347
  })
1254
1348
 
1349
+ test('fsWrite sends an oversized document in utf8 chained chunks', async () => {
1350
+ const calls = []
1351
+ const original = globalThis.fetch
1352
+ globalThis.fetch = async (url, init) => {
1353
+ calls.push(JSON.parse(init.body))
1354
+ return { ok: true, status: 200, json: async () => ({ ok: true, mtimeMs: 777, chunked: true }) }
1355
+ }
1356
+ try {
1357
+ // 1.6 MB of 3-byte code points: the 512 KB cuts land INSIDE characters, so a
1358
+ // naive byte split would corrupt them. The client must cut at code points and
1359
+ // the host must reassemble the identical document.
1360
+ const text = '汉'.repeat(Math.floor(1.6 * 1024 * 1024 / 3))
1361
+ const written = await T.fsWrite({ sessionId: 's1', cwd: '/w' }, '/w/big.java', text)
1362
+ assert.equal(written.mtimeMs, 777)
1363
+ assert.ok(calls.length >= 3, `expected several chunks, got ${calls.length}`)
1364
+ assert.deepEqual(calls.map((body) => body.offset).slice(1), calls.slice(1).map((body) => body.offset),
1365
+ 'offsets are ascending byte positions')
1366
+ assert.equal(calls[0].offset, 0)
1367
+ assert.equal(calls[calls.length - 1].final, true, 'only the last chunk is final')
1368
+ assert.ok(calls.slice(0, -1).every((body) => body.final === false))
1369
+ assert.equal(calls.map((body) => body.content).join(''), text, 'the pieces rebuild the document exactly')
1370
+ const byteTotal = new TextEncoder().encode(text).length
1371
+ const last = calls[calls.length - 1]
1372
+ assert.equal(last.offset + new TextEncoder().encode(last.content).length, byteTotal, 'the last offset lands on the exact size')
1373
+ assert.ok(calls.every((body) => new TextEncoder().encode(body.content).length <= 512 * 1024))
1374
+
1375
+ // A failed chunk surfaces the host's message and stops the loop.
1376
+ calls.length = 0
1377
+ globalThis.fetch = async (url, init) => {
1378
+ calls.push(JSON.parse(init.body))
1379
+ return { ok: false, status: 409, json: async () => ({ ok: false, message: 'chunk is missing; save again' }) }
1380
+ }
1381
+ await assert.rejects(T.fsWrite({ sessionId: 's1' }, '/w/big.java', text), /save again/)
1382
+ assert.equal(calls.length, 1)
1383
+ } finally {
1384
+ globalThis.fetch = original
1385
+ }
1386
+ })
1387
+
1255
1388
  test('undo back to the saved text is not dirty any more', () => {
1256
1389
  assert.equal(T.docDirty({ kind: 'text', text: 'a', saved: 'a' }, { dirty: true }), false, 'mirrored text wins over the stale toolbar flag')
1257
1390
  assert.equal(T.docDirty({ kind: 'text', text: 'a', saved: 'b' }, undefined), true)
@@ -1424,12 +1557,40 @@ test('Ctrl+C copies the selected rows without the context menu', async () => {
1424
1557
  assert.doesNotMatch(source, /The tree is single-selection, so 全选 has nothing to expand into/)
1425
1558
  })
1426
1559
 
1560
+ test('a drag inside the tree confirms before it moves anything', async () => {
1561
+ const { readFile } = await import('node:fs/promises')
1562
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1563
+ // A drop only ASKS: the move itself waits in `pendingMove`.
1564
+ assert.match(source, /var \[pendingMove, setPendingMove\] = useState\(null\)/)
1565
+ assert.match(source, /function movablePaths\(paths, dirPath\) \{/, 'self / same-parent / own-subtree drops are filtered out first')
1566
+ assert.match(source, /function requestMove\(paths, dirPath\) \{/)
1567
+ assert.match(source, /setPendingMove\(\{ paths: movable, dir: dirPath \}\)/)
1568
+ // Both drop surfaces (a row and the blank area) go through the confirmation.
1569
+ assert.match(source, /if \(paths\.length > 0\) requestMove\(paths, dropDir\)/)
1570
+ assert.match(source, /if \(paths\.length > 0\) requestMove\(paths, rootDir\)/)
1571
+ assert.doesNotMatch(source, /void moveEntriesInto\(paths, dropDir\)/, 'a drop never moves without asking')
1572
+ // The card says what moves where, 取消 owns focus, Esc cancels, 移动 runs it.
1573
+ assert.match(source, /function renderTreeMoveConfirm\(\) \{/)
1574
+ assert.match(source, /'data-tree-move-confirm': '1'/)
1575
+ assert.match(source, /'data-tree-move-cancel': '1'/)
1576
+ assert.match(source, /'data-tree-move-ok': '1'/)
1577
+ assert.match(source, /var moveCancelRef = useRef\(null\)/)
1578
+ assert.match(source, /移动到:' \+ dir/)
1579
+ assert.match(source, /if \(pending !== null\) void moveEntriesInto\(pending\.paths, pending\.dir\)/)
1580
+ assert.match(source, /move\{0,1\}CancelRef|cancel\.focus\(\)/, '取消 takes focus so Esc/Enter are predictable')
1581
+ assert.match(source, /setPendingMove\(null\)\n\s+\}\n\s+document\.addEventListener\('keydown', onKey, true\)/,
1582
+ 'Esc closes the confirmation')
1583
+ // While the card is open the tree must not run its own Del / Ctrl+C / Ctrl+V.
1584
+ assert.match(source, /if \(prompt !== null \|\| pendingDelete !== null \|\| pendingMove !== null\) return/)
1585
+ assert.match(source, /var anyDialogOpen = prompt !== null \|\| pendingDelete !== null \|\| batchConflict !== null \|\| pendingMove !== null/)
1586
+ })
1587
+
1427
1588
  test('a file row is a drop target for the directory it lives in', async () => {
1428
1589
  const { readFile } = await import('node:fs/promises')
1429
1590
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
1430
1591
  assert.match(source, /var dropDir = entry\.isDir === true \? entry\.path : parentOf\(entry\.path\)/)
1431
1592
  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')
1593
+ assert.match(source, /if \(paths\.length > 0\) requestMove\(paths, dropDir\)/, 'dropping on a file asks first, then moves into its parent')
1433
1594
  assert.match(source, /setData\('application\/x-dsh-ris-ide-paths', JSON\.stringify\(dragged\)\)/, 'a drag carries the whole selection')
1434
1595
  assert.match(source, /function dragPaths\(transfer\)/, 'drops read the path list back')
1435
1596
  assert.match(source, /void importExternal\(dropDir, external, \[\]\)/)
@@ -2027,7 +2188,9 @@ test('the title-bar controls share one 20px row height', { skip: !reactIsReal ?
2027
2188
  const sourceTags = buttonsOf(sourceHead)
2028
2189
  const consoleTags = buttonsOf(consoleHead)
2029
2190
  assert.ok(sourceTags.length >= 3, 'the source toolbar carries the font scale, the theme switch and reset')
2030
- assert.equal(consoleTags.length, 2, 'the console title bar carries 📄 open-config and ⚙ config-generate')
2191
+ const consoleActions = consoleTags.map((tag) => /data-action="([^"]+)"/.exec(tag)[1])
2192
+ assert.deepEqual(consoleActions, ['config-open', 'config-generate', 'proxy-open'],
2193
+ 'the console title bar carries 📄 open-config, ⚙ config-generate and 🌐 proxy')
2031
2194
  for (const tag of sourceTags.concat(consoleTags)) {
2032
2195
  const action = /data-action="([^"]+)"/.exec(tag)[1]
2033
2196
  assert.match(tag, /height:20px/, `${action} must sit on the shared 20px row`)
@@ -2563,6 +2726,57 @@ test('childEntryFor follows the RENDERED rows, so a folded chain still locates',
2563
2726
  assert.equal(T.childEntryFor([null, 'x', { path: '/w/ris', isDir: false }], file), undefined)
2564
2727
  })
2565
2728
 
2729
+ test('pathWithin decides whether the locate walk can start at the tree root', () => {
2730
+ assert.equal(T.pathWithin('/w', '/w/a/B.java'), true)
2731
+ assert.equal(T.pathWithin('/w', '/w'), true, 'a root contains itself')
2732
+ assert.equal(T.pathWithin('/w/', '/w/a/B.java'), true, 'a trailing slash is ignored')
2733
+ assert.equal(T.pathWithin('/w\\a', '/w/a/B.java'), true, 'windows separators compare equal')
2734
+ assert.equal(T.pathWithin('/w/ris', '/w/AGENTS.md'), false, 'a re-rooted tree cannot reach a sibling file')
2735
+ assert.equal(T.pathWithin('/w/ris', '/w/ris2/A.java'), false, 'a shared prefix is not a parent')
2736
+ assert.equal(T.pathWithin('/', '/w/A.java'), true, 'the filesystem root contains everything')
2737
+ assert.equal(T.pathWithin('', '/w/A.java'), false)
2738
+ assert.equal(T.pathWithin(undefined, '/w/A.java'), false)
2739
+ assert.equal(T.pathWithin('/w', undefined), false)
2740
+ })
2741
+
2742
+ test('locate expands EVERY ancestor in one update and re-roots when the file is outside the tree', async () => {
2743
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
2744
+ const tree = source.slice(source.indexOf('function IdeTree('), source.indexOf('function IdeEditor('))
2745
+
2746
+ // One commit for the whole chain, keyed from the frozen array: a `setExpanded`
2747
+ // updater runs LATER, so a key read from the loop variable made the top
2748
+ // ancestors expand with a deeper path — the "locate does nothing" race.
2749
+ const locate = tree.slice(tree.indexOf('async function locate(target) {'), tree.indexOf('function revealRow(path) {'))
2750
+ assert.match(locate, /var chain = \[\]/, 'the walk collects the chain first')
2751
+ assert.match(locate, /chain\.push\(descend\)/, 'each level appends the RENDERED row path')
2752
+ 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')
2753
+ assert.doesNotMatch(locate, /state\[descend\] = true/, 'the loop variable is no longer captured by the deferred updater')
2754
+ // A re-rooted tree walks from its own root; a file outside it is only reachable
2755
+ // from the workspace root, so the walk falls back there (and re-roots the tree).
2756
+ assert.match(locate, /if \(!pathWithin\(startRoot, filePath\) && pathWithin\(workspaceRoot, filePath\)\) \{/)
2757
+ assert.match(locate, /startRoot = workspaceRoot\n\s*setRootTrail\(\[\]\)/, 'the tree follows the locate')
2758
+ assert.match(locate, /var startRoot = absolutePath\(cwd, activeRoot\)/)
2759
+ // The file is still opened, and its row scrolled into view, whatever happened.
2760
+ assert.match(locate, /props\.onOpen\(filePath\)\n\s*revealRow\(filePath\)/)
2761
+ })
2762
+
2763
+ test('the tree highlight follows the editor, not the last locate', async () => {
2764
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
2765
+ const tree = source.slice(source.indexOf('function IdeTree('), source.indexOf('function IdeEditor('))
2766
+
2767
+ // A locate paints nothing of its own: `reveal` exists to SCROLL the row into
2768
+ // view, and a locate row used to stay lit until the next locate.
2769
+ assert.doesNotMatch(tree, /isRevealed/, 'the locate highlight is gone')
2770
+ assert.doesNotMatch(source, /'data-tree-revealed'/, 'and so is its attribute')
2771
+ // The strong tint means "the file the editor is showing" (or the directory an
2772
+ // operation targets); a merely-selected file row wears the softer multi tint.
2773
+ assert.match(tree, /var isCurrent = isActive \|\| \(isSelected && entry\.isDir === true\)/)
2774
+ assert.match(tree, /isCurrent \? S\.treeRowOn : \(isMulti \|\| isSelected \? S\.treeRowMulti : S\.treeRow\)/)
2775
+ assert.match(tree, /'data-tree-current': isCurrent \? '1' : undefined/)
2776
+ // Selecting another tab moves the highlight with it.
2777
+ assert.match(tree, /if \(selectedPath === active\) return\n\s*selectOne\(active\)/)
2778
+ })
2779
+
2566
2780
  test('the locate walk against a real single-child package chain reaches the file parent', async () => {
2567
2781
  const { mkdtemp, mkdir, writeFile, rm } = await import('node:fs/promises')
2568
2782
  const { execFile } = await import('node:child_process')
@@ -2759,6 +2973,36 @@ test('the search toolbar does not clip its results dropdown', () => {
2759
2973
  }
2760
2974
  })
2761
2975
 
2976
+ test('a pre-1.7.3 host without the stream routes still answers from the batch route', async () => {
2977
+ const original = globalThis.fetch
2978
+ const calls = []
2979
+ try {
2980
+ globalThis.fetch = async (href) => {
2981
+ const url = new URL(String(href))
2982
+ calls.push(url.pathname)
2983
+ if (url.pathname.endsWith('/dsh-ris-ide/search/stream')) return { ok: false, status: 404, headers: new Headers() }
2984
+ return { ok: true, status: 200, json: async () => ({ ok: true, matches: ['/w/ris/a.java'], dirs: {} }) }
2985
+ }
2986
+ const pages = []
2987
+ const done = await T.fsSearchStream({ sessionId: 's1', cwd: '/w' }, 'a.java', { onPage: (items) => pages.push(items) })
2988
+ assert.deepEqual(pages, [['/w/ris/a.java']], 'the batch answer arrives as one page')
2989
+ assert.deepEqual(done, { matches: 1, files: 0, truncated: false })
2990
+ assert.equal(calls.length, 2)
2991
+ assert.equal(calls[1].endsWith('/dsh-ris-ide/search'), true, 'the fallback is the batch search route')
2992
+
2993
+ globalThis.fetch = async (href) => {
2994
+ const url = new URL(String(href))
2995
+ if (url.pathname.endsWith('/dsh-ris-ide/search-content/stream')) return { ok: false, status: 404, headers: new Headers() }
2996
+ return { ok: true, status: 200, json: async () => ({ ok: true, hits: [{ path: '/w/a.txt', line: 3, text: 'needle' }] }) }
2997
+ }
2998
+ const contentPages = []
2999
+ await T.fsSearchContentStream({ sessionId: 's1', cwd: '/w' }, 'needle', { onPage: (items) => contentPages.push(items) })
3000
+ assert.deepEqual(contentPages, [[{ path: '/w/a.txt', line: 3, text: 'needle' }]])
3001
+ } finally {
3002
+ globalThis.fetch = original
3003
+ }
3004
+ })
3005
+
2762
3006
  test('search replies become dropdown payloads without crashing on `dirs`', () => {
2763
3007
  // The host /search route answers files only: `dirs` is an empty OBJECT. Treating
2764
3008
  // it as an array (`dirs.forEach`) threw and made every filename search look dead.
@@ -2778,6 +3022,102 @@ test('search replies become dropdown payloads without crashing on `dirs`', () =>
2778
3022
  assert.deepEqual(T.searchHitPayload(undefined, '/w'), { matches: [], dirs: {} })
2779
3023
  })
2780
3024
 
3025
+ test('streamed search answers are read page by page, not after the whole body', async () => {
3026
+ const encoder = new TextEncoder()
3027
+ const frames = [
3028
+ { type: 'start', root: '/w', repoCount: 2 },
3029
+ { type: 'page', items: ['/w/ris/a/A.java'] },
3030
+ { type: 'page', items: ['/w/ris/b/B.java', '/w/ris/b/C.java'] },
3031
+ { type: 'done', files: 900, matches: 3, truncated: false },
3032
+ ]
3033
+ const text = frames.map((frame) => `${JSON.stringify(frame)}\n`).join('')
3034
+ // Split mid-frame and mid-line: the reader must hold the partial NDJSON line.
3035
+ const cut = text.indexOf('\n') + 12
3036
+ const body = new ReadableStream({
3037
+ start(controller) {
3038
+ controller.enqueue(encoder.encode(text.slice(0, cut)))
3039
+ controller.enqueue(encoder.encode(text.slice(cut)))
3040
+ controller.close()
3041
+ },
3042
+ })
3043
+ const pages = []
3044
+ const done = await T.readSearchStream(new Response(body), (items) => pages.push(items))
3045
+ assert.deepEqual(pages, [['/w/ris/a/A.java'], ['/w/ris/b/B.java', '/w/ris/b/C.java']])
3046
+ assert.deepEqual(done, { matches: 3, files: 900, truncated: false })
3047
+
3048
+ // A connection that ends without `done` is incomplete: throw, never pretend.
3049
+ const truncated = new ReadableStream({
3050
+ start(controller) {
3051
+ controller.enqueue(encoder.encode(`${JSON.stringify({ type: 'page', items: ['x'] })}\n`))
3052
+ controller.close()
3053
+ },
3054
+ })
3055
+ await assert.rejects(() => T.readSearchStream(new Response(truncated), () => {}), /检索连接中断/)
3056
+
3057
+ // An `error` frame surfaces the host's message instead of swallowing it.
3058
+ const failed = new ReadableStream({
3059
+ start(controller) {
3060
+ controller.enqueue(encoder.encode(`${JSON.stringify({ type: 'error', code: 'bad-request', message: 'q is required' })}\n`))
3061
+ controller.close()
3062
+ },
3063
+ })
3064
+ await assert.rejects(() => T.readSearchStream(new Response(failed), () => {}), /q is required/)
3065
+
3066
+ // No readable stream (an old WebView): a clear error, not a silent hang.
3067
+ await assert.rejects(() => T.readSearchStream({}, () => {}), /不支持流式读取/)
3068
+ })
3069
+
3070
+ test('fsSearchStream paints page by page from the REAL streamed host route', async () => {
3071
+ // End-to-end through the host half's own handler and a real listener: the
3072
+ // NDJSON is chunked over HTTP, so this proves the client parser and the host
3073
+ // framing agree — a unit fixture with a hand-made Response cannot.
3074
+ const cwd = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-stream-'))
3075
+ const seen = []
3076
+ try {
3077
+ for (const repo of ['aa-repo', 'bb-repo']) {
3078
+ const dir = join(cwd, repo)
3079
+ await mkdir(dir, { recursive: true })
3080
+ await writeFile(join(dir, 'agent-one.txt'), 'agent\n')
3081
+ await writeFile(join(dir, 'other.txt'), 'other\n')
3082
+ execFileSync('git', ['init', '-q'], { cwd: dir })
3083
+ execFileSync('git', ['add', '.'], { cwd: dir })
3084
+ }
3085
+ const ctx = { sessions: { get: (id) => (id === 's1' ? { header: { cwd } } : undefined) } }
3086
+ const options = { maxBytes: 1024 * 1024, restrictToCwd: false, stopGraceMs: 5000, minFreeMemoryBytes: 1 }
3087
+ const server = createServer((req, res) => hostTest.handleRequest(ctx, req, res, options))
3088
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
3089
+ const previousDocument = globalThis.document
3090
+ globalThis.document = { baseURI: `http://127.0.0.1:${server.address().port}/` }
3091
+ try {
3092
+ const done = await T.fsSearchStream({ sessionId: 's1', cwd }, 'agent', {
3093
+ onPage: (items) => { seen.push(items) },
3094
+ })
3095
+ const relative = seen.map((items) => items.map((item) => item.slice(cwd.length + 1)))
3096
+ assert.deepEqual(relative, [['aa-repo/agent-one.txt'], ['bb-repo/agent-one.txt']],
3097
+ 'pages arrive in tree order, one per root page, already absolute')
3098
+ assert.equal(done.matches, 2)
3099
+ assert.equal(done.truncated, false)
3100
+ } finally {
3101
+ globalThis.document = previousDocument
3102
+ server.closeAllConnections?.()
3103
+ await new Promise((resolve) => server.close(resolve))
3104
+ }
3105
+ } finally {
3106
+ await rm(cwd, { recursive: true, force: true })
3107
+ }
3108
+ })
3109
+
3110
+ test('the search effects stream their pages and abort a query the user moved past', async () => {
3111
+ const source = await readFile(join(ROOT, 'lib', 'client.js'), 'utf8')
3112
+ assert.match(source, /fsSearchStream\(scopeRef\.current, text, \{/, 'the filename search streams')
3113
+ assert.match(source, /fsSearchContentStream\(scopeRef\.current, text, \{/, 'the content search streams')
3114
+ assert.match(source, /onPage: function \(page\) \{/, 'every page is painted as it lands')
3115
+ assert.match(source, /if \(controller !== null\) controller\.abort\(\)/, 'a changed query aborts the previous stream')
3116
+ assert.match(source, /var SEARCH_STREAM_PAGE_SIZE = 40/)
3117
+ assert.match(source, /pageSize', String\(SEARCH_STREAM_PAGE_SIZE\)\)/)
3118
+ assert.match(source, /if \(cancelled \|\| isAbortError\(problem\)\) return/, 'an aborted stream is not an error line')
3119
+ })
3120
+
2781
3121
  test('the search dropdown renders hits, empty state and errors', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, () => {
2782
3122
  const { renderToStaticMarkup } = require(`${REACT_ROOT}/react-dom/server`)
2783
3123
  const render = (hits) => renderToStaticMarkup(React.createElement(T.SearchResults, { hits, fontRatio: 1 }))
@@ -4089,9 +4429,10 @@ test('only the standalone IDE window claims browser shortcuts; a DSH page keeps
4089
4429
  // Ownership is the standalone window, FULL STOP: a DSH page never claims keys.
4090
4430
  assert.match(source, /function ownsKeyTarget\(target\) \{[\s\S]{0,500}?return inStandaloneIdeWindow\(\)/)
4091
4431
  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.
4432
+ // Ctrl+W, the find chords (Ctrl+R / Ctrl+F) and the debug keys still check
4433
+ // ownership first.
4093
4434
  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')
4435
+ assert.equal(guards, 4, 'Ctrl+W, the find chords, Ctrl+F and debug keys all bail out on foreign targets')
4095
4436
  // The panel net only works in the IDE window and only claims the reload chord:
4096
4437
  // the host's other chords (Ctrl+N/O/K/...) are released everywhere.
4097
4438
  assert.match(source, /if \(!inStandaloneIdeWindow\(\)\) return\n\s*if \(isBrowserReloadChord\(event\)\)/)
@@ -4125,7 +4466,7 @@ test('Ctrl+F searches what the editor, log or fallback editor has highlighted',
4125
4466
  // next one after a caret parked deep in the document.
4126
4467
  assert.match(chunkSource, /function findFirstFromStart\(view\) \{\n\s*view\.dispatch\(\{ selection: \{ anchor: 0 \} \}\)\n\s*findNext\(view\)/)
4127
4468
  assert.match(chunkSource, /if \(jump\) findFirstFromStart\(view\)/)
4128
- assert.match(chunkSource, /const seeded = searchSelectedText\(instance\); openSearchPanel\(instance\); if \(seeded\) findFirstFromStart\(instance\)/)
4469
+ assert.match(chunkSource, /const seeded = searchSelectedText\(instance\); openSearchPanel\(instance\); if \(seeded\) findFirstFromStart\(instance\); caretToEndOfFindField\(instance\)/)
4129
4470
  assert.match(chunk, /function findFirstFromStart\(view\)/)
4130
4471
  assert.match(chunk, /if \(jump\) findFirstFromStart\(view\)/)
4131
4472
  // A handed-over hit still starts at ITS line (that is the point of clicking it).
@@ -4143,6 +4484,95 @@ test('Ctrl+F searches what the editor, log or fallback editor has highlighted',
4143
4484
  assert.doesNotMatch(logHandler, /setTreeQuery/)
4144
4485
  })
4145
4486
 
4487
+ test('Ctrl+F with the search panel ALREADY open puts the caret back in the find field', async () => {
4488
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4489
+ const chunkSource = await readFile(new URL('../src/chunks/codemirror.js', import.meta.url), 'utf8')
4490
+ const chunk = await readFile(new URL('../lib/client-codemirror.js', import.meta.url), 'utf8')
4491
+
4492
+ // @codemirror/search finds the find field through `[main-field]`; without it a
4493
+ // second Ctrl+F with the panel open had no input to focus and did nothing.
4494
+ assert.match(chunkSource, /searchInput\.setAttribute\('main-field', 'true'\)/)
4495
+ assert.match(chunk, /searchInput\.setAttribute\("main-field", "true"\)/)
4496
+ // The keymap only sees keys pressed in the document, so the panel listens for
4497
+ // Ctrl+F itself: focus may sit in the replace box or on a toggle button.
4498
+ assert.match(chunkSource, /dom\.addEventListener\('keydown', \(event\) => \{\n\s*if \(\(event\.ctrlKey === true \|\| event\.metaKey === true\)/)
4499
+ assert.match(chunkSource, /event\.preventDefault\(\)\n\s*focusInput\(\)/)
4500
+ assert.match(chunk, /dom\.addEventListener\("keydown", \(event\) => \{/)
4501
+
4502
+ // The log pane and the plain-text fallback editor have the same promise, and
4503
+ // both used to rely on a mount/effect that does not re-run for an open bar.
4504
+ assert.match(source, /var findInputRef = useRef\(null\)/)
4505
+ assert.match(source, /findInputRef\.current\.focus\(\)/)
4506
+ // The fallback editor's input is ref'd and its Ctrl+F pulls focus there.
4507
+ const editorStart = source.indexOf('function IdeEditor(props) {')
4508
+ const editorSource = source.slice(editorStart, editorStart + 6000)
4509
+ assert.match(editorSource, /ref: findInputRef, style: S\.findInput/)
4510
+ assert.match(editorSource, /var findInput = findInputRef\.current\n\s*if \(findInput !== null && findInput !== undefined\) \{\n\s*findInput\.focus\(\)/)
4511
+
4512
+ // Keys pressed OUTSIDE the document (tabs bar, tree, workspace search box) never
4513
+ // reach CodeMirror's keymap, so the browser's own find bar opened instead. The
4514
+ // workbench claims the chord in the standalone window and hands it to the open
4515
+ // file's editor handle, which opens/focuses the panel.
4516
+ assert.match(chunkSource, /find\(\) \{\n\s*openSearchPanel\(view\)[\s\S]{0,400}?caretToEndOfFindField\(view\)\n\s*\},/)
4517
+ assert.match(chunk, /find\(\) \{\s*openSearchPanel\(view\);[\s\S]{0,400}?caretToEndOfFindField\(view\);\s*\}/)
4518
+ assert.match(source, /function onFindKey\(event\) \{\n\s*if \(event\.defaultPrevented === true\) return/)
4519
+ assert.match(source, /if \(!ownsKeyTarget\(event\.target\)\) return[\s\S]{0,900}?typeof controls\.find === 'function'/)
4520
+ assert.match(source, /window\.addEventListener\('keydown', onFindKey\)/)
4521
+ })
4522
+
4523
+ test('the find box accepts more than one character while it has matches', async () => {
4524
+ const chunkSource = await readFile(new URL('../src/chunks/codemirror.js', import.meta.url), 'utf8')
4525
+ const chunk = await readFile(new URL('../lib/client-codemirror.js', import.meta.url), 'utf8')
4526
+
4527
+ // Root cause: @codemirror/search's `selectSearchInput` selects the whole query
4528
+ // when the panel's [main-field] has focus, so the second keystroke replaced the
4529
+ // first and a term could never exceed one character (only once there was a hit:
4530
+ // with no match `findNext` returns before selecting).
4531
+ assert.match(chunkSource, /const end = searchInput\.value\.length\n\s*searchInput\.setSelectionRange\(end, end\)/)
4532
+ assert.ok(!chunkSource.includes('searchInput.select()'), 'focusing the field must never select the query')
4533
+ // Every path that runs findNext/findPrevious from the box restores the caret.
4534
+ assert.match(chunkSource, /const restoreSearchCaret = \(range\) => \{[\s\S]{0,600}?searchInput\.setSelectionRange\(start, stop\)/)
4535
+ assert.match(chunkSource, /const caret = \{ start: searchInput\.selectionStart, end: searchInput\.selectionEnd \}\n\s*apply\(\{ search: searchInput\.value \}, true\)\n\s*restoreSearchCaret\(caret\)/)
4536
+ assert.match(chunkSource, /restoreSearchCaret\(caret\)\n\s*sync\(\)/)
4537
+ // Programmatic opens (Ctrl+F keymap, editor handle, content-search hand-off) too.
4538
+ assert.match(chunkSource, /function caretToEndOfFindField\(view\) \{/)
4539
+ assert.match(chunkSource, /caretToEndOfFindField\(view\)\n\s*return true/)
4540
+ assert.match(chunkSource, /findNext\(view\)\n\s*caretToEndOfFindField\(view\)/)
4541
+ // The built chunk carries all of it (the runtime loads this file, not the source).
4542
+ assert.match(chunk, /function caretToEndOfFindField\(view\)/)
4543
+ assert.match(chunk, /restoreSearchCaret = \(range\) => \{/)
4544
+ assert.match(chunk, /setSelectionRange\(end, end\)/)
4545
+ })
4546
+
4547
+ test('Ctrl+R re-reads the workspace instead of replaying the search cache', async () => {
4548
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4549
+
4550
+ // The cache is keyed by the query TEXT only, so an explicit re-search must drop
4551
+ // the entries and make both streaming effects run again.
4552
+ assert.match(source, /var \[searchReload, setSearchReload\] = useState\(0\)/)
4553
+ assert.match(source, /function reloadWorkspaceSearch\(text\) \{/)
4554
+ assert.match(source, /searchCacheRef\.current\.delete\('content:' \+ query\)/)
4555
+ assert.match(source, /searchCacheRef\.current\.delete\('name:' \+ query\)/)
4556
+ const effects = source.split("var cached = searchCacheRef.current.get('name:' + text)")
4557
+ assert.equal(effects.length, 2)
4558
+ const contentStart = effects[1].indexOf("var cached = searchCacheRef.current.get('content:' + text)")
4559
+ assert.ok(contentStart !== -1)
4560
+ assert.match(effects[1].slice(contentStart, contentStart + 5000), /\}, \[treeQuery, cwd, searchReload\]\)/)
4561
+
4562
+ // Ctrl+R (Ctrl+Shift+R / F3) in the standalone window focuses the box through the
4563
+ // nonce effect; that same effect is where the stale cache is thrown away.
4564
+ const nonceGuard = "if (searchFocusPendingRef.current !== true) return"
4565
+ const nonceStart = source.indexOf(nonceGuard)
4566
+ assert.ok(nonceStart !== -1)
4567
+ const nonceEffect = source.slice(nonceStart, nonceStart + 1200)
4568
+ assert.match(nonceEffect, /input\.select\(\)\n\s*reloadWorkspaceSearch\(treeQuery\)/)
4569
+
4570
+ // Saving a file changes what `git grep` would return, so it invalidates too.
4571
+ const writeStart = source.indexOf('return fsWrite(scopeRef.current, path, docTextForDisk(doc)).then(function () {')
4572
+ assert.ok(writeStart !== -1)
4573
+ assert.match(source.slice(writeStart, writeStart + 500), /reloadWorkspaceSearch\(treeQuery\)/)
4574
+ })
4575
+
4146
4576
  test('an oversized text file opens a read-only windowed preview', async () => {
4147
4577
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4148
4578
  assert.match(source, /function fsWindowRead\(scope, path, offset, length\)/)
@@ -4294,6 +4724,19 @@ test('the sidebar console opens the config as a sidebar file resource', async ()
4294
4724
  assert.match(source, /已在右侧栏打开 /, 'the console reports where the config went')
4295
4725
  })
4296
4726
 
4727
+ test('the config note names the file without a helper nested in another component', async () => {
4728
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4729
+ // `shortName` used to be declared INSIDE ProgramWorkbench. The SIDEBAR
4730
+ // ProgramsPanel is a sibling component, so its openConfig threw
4731
+ // "shortName is not defined" right after the config file had already opened:
4732
+ // the file appeared, but the note showed 打开配置失败 instead. The basename
4733
+ // helper is module scope (like the stop square), so both halves share it.
4734
+ assert.doesNotMatch(source, /function shortName\(/, 'no basename helper nested in one component')
4735
+ assert.match(source, /^ {4}function fileBaseName\(path\) \{/m, 'the basename helper is declared at module scope')
4736
+ assert.match(source, /'已在右侧栏打开 ' \+ fileBaseName\(path\)/, 'the sidebar config note names the file through it')
4737
+ assert.match(source, /pendingBulk\.dirty\.slice\(0, 2\)\.map\(fileBaseName\)/, 'the workbench prompt uses the same helper')
4738
+ })
4739
+
4297
4740
  test('the mask names the action and a window opened on a program auto-debugs it', async () => {
4298
4741
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4299
4742
 
@@ -4383,6 +4826,12 @@ test('the editor find panel matches the IDE chrome', async () => {
4383
4826
  assert.match(css, /background:color-mix\(in srgb, currentColor 6%, transparent\) !important/)
4384
4827
  assert.match(css, /background-image:none !important/, 'CM gradient buttons are neutralised')
4385
4828
  assert.match(css, /\.cm-searchMatch-selected\{background:rgba\(255,150,40,0\.42\)/)
4829
+ // The panel must NOT out-stack the pane's header row: the workspace-search
4830
+ // dropdown is anchored there (`editorPaneHead`, z-index 30) and drops down over
4831
+ // the editor's top edge — CodeMirror's baseTheme `z-index:300` painted the find
4832
+ // panel over the whole dropdown ("文件检索框的结果下拉框被编辑器的搜索面板遮挡").
4833
+ assert.match(css, /\.cm-panels\{[^}]*z-index:20 !important\}/, 'find panel stays under the search dropdown')
4834
+ assert.match(source, /editorPaneHead: \{\n[\s\S]{0,400}?zIndex: 30,/, 'the header row that anchors the dropdown')
4386
4835
  // The panel itself is the IDE's own (chunk-side), not CodeMirror's built-in one.
4387
4836
  const chunkSource = await readFile(new URL('../src/chunks/codemirror.js', import.meta.url), 'utf8')
4388
4837
  const chunkBuilt = await readFile(new URL('../lib/client-codemirror.js', import.meta.url), 'utf8')
@@ -4455,6 +4904,19 @@ test('content hits render in the same dropdown, with line numbers and the conten
4455
4904
  assert.match(markup, /data-search-hit-icon="content"/, 'content rows have their own icon')
4456
4905
  })
4457
4906
 
4907
+ test('editing the query ends the dropdown state Escape left behind', async () => {
4908
+ const { readFile } = await import('node:fs/promises')
4909
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4910
+ const box = source.slice(source.indexOf("'data-action': 'tree-search'"), source.indexOf('// The dropdown belongs to FOCUS'))
4911
+ assert.match(box, /onChange: function \(event\) \{\n\s*var value = event\.target\.value\n\s*setTreeQuery\(value\)/, 'the edit is still applied verbatim')
4912
+ assert.match(box, /if \(value\.trim\(\) !== ''\) setSearchFocused\(true\)/, 'a non-empty edit re-opens the dropdown')
4913
+ // Escape is "leave the box", not "throw my query away": it blurs, and the focus
4914
+ // handler hides the dropdown while the query (and its cached hits) stay.
4915
+ const escape = box.slice(box.indexOf("if (event.key === 'Escape')"), box.indexOf('// Whichever dropdown is open'))
4916
+ assert.match(escape, /searchInputRef\.current\.blur\(\)/, 'Escape gives the caret back')
4917
+ assert.doesNotMatch(escape, /setTreeQuery\(''\)/, 'Escape no longer clears the query')
4918
+ })
4919
+
4458
4920
  test('a dialog keeps the anchor it opened at when the pointer moves or clicks again', async () => {
4459
4921
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4460
4922
  // The point is frozen on open, not read live on every render: a second
@@ -4487,3 +4949,157 @@ test('a folder row only expands; the context menu\'s 进入 re-roots with an 上
4487
4949
  assert.match(region, /if \(locateRequest\.kind === 'dir'\) openDirRoot\(locateRequest\.path\)/, 'picking a folder search hit re-roots too')
4488
4950
  assert.match(region, /walk\(activeRoot, 0, \{\}\)/, 'Ctrl+A walks the active root')
4489
4951
  })
4952
+
4953
+ // ── proxy dialog: both consoles offer it, and it renders standalone ──────────
4954
+ test('the console title bar carries the proxy button', { skip: !reactIsReal }, () => {
4955
+ const { renderToStaticMarkup } = require(`${REACT_ROOT}/react-dom/server`)
4956
+ const markup = renderToStaticMarkup(React.createElement(T.ProgramsPanel, { sessionId: 's1', cwd: '/w/project', visible: true, compact: true }))
4957
+ assert.match(markup, /data-action="compact-proxy"/, 'the sidebar console opens the proxy dialog')
4958
+ })
4959
+
4960
+ test('the proxy dialog mounts with its address section and actions', { skip: !reactIsReal }, () => {
4961
+ const { renderToStaticMarkup } = require(`${REACT_ROOT}/react-dom/server`)
4962
+ const markup = renderToStaticMarkup(React.createElement(T.ProxyDialog, { scope: { sessionId: 's1', cwd: '/w/project' }, onClose: () => {} }))
4963
+ assert.match(markup, /data-proxy-dialog="1"/, 'the overlay is rendered')
4964
+ assert.match(markup, /data-proxy-close="1"/)
4965
+ // SSR runs no effect, so the form is still loading — the shell must exist anyway.
4966
+ assert.match(markup, /读取中/)
4967
+ })
4968
+
4969
+ test('the proxy dialog has no per-row launch or mapping switch', async () => {
4970
+ const { readFile } = await import('node:fs/promises')
4971
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4972
+ // Launching programs from the dialog was dropped: ProxyBridge intercepts by
4973
+ // process name, so a program started anywhere is covered and a ▶ button only
4974
+ // ever covered the one instance we spawned.
4975
+ assert.equal(source.includes('data-proxy-run'), false, 'no row-level start button')
4976
+ assert.equal(source.includes('runButton('), false, 'the button builder is gone')
4977
+ // The mapping is decided by the program's capabilities, not by a checkbox: the
4978
+ // row reports the outcome instead.
4979
+ assert.equal(source.includes('checked: rule.shadow'), false, 'no mapping checkbox bound to the rule')
4980
+ assert.ok(source.includes("'data-proxy-map'"), 'the row still reports the mapping')
4981
+ assert.ok(source.includes("? '127.0.0.1' + portSuffix(rule)"), 'and names where it landed')
4982
+ // The state is machine-wide, so the row label is provenance, not a boundary.
4983
+ assert.ok(source.includes("'来源 '"))
4984
+ assert.ok(source.includes('data-proxy-redirector'), 'ProxyBridge block exists in the dialog')
4985
+ })
4986
+
4987
+ test('an adopted leftover engine is reported with a stop action', async () => {
4988
+ const { readFile } = await import('node:fs/promises')
4989
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
4990
+ const region = source.slice(source.indexOf('function ProxyDialog('), source.indexOf('function viewerFontCss('))
4991
+ // A previous dsh left its engine behind (the pre-fix Ctrl+C leak). The host adopts
4992
+ // it so the tunnel keeps working, and the dialog must say who started it instead
4993
+ // of pretending this session did — plus a stop that does not touch the rule table.
4994
+ assert.match(region, /view\.inherited === true/, 'the banner is driven by the host flag')
4995
+ assert.match(region, /'data-proxy-inherited': '1'/, 'the banner is addressable in the DOM')
4996
+ assert.match(region, /原 dsh pid/, 'it names the dsh that started the engine')
4997
+ assert.match(region, /action: 'stop-inherited',/, 'it offers its own action id')
4998
+ assert.match(region, /onClick: function \(\) \{ act\('stop'\) \}/, 'the stop goes through the normal action path')
4999
+ })
5000
+
5001
+ test('auto-save is versioned, flushed before it can be lost, and the host decides "applies"', () => {
5002
+ const source = readSync(new URL('../lib/client.js', import.meta.url), 'utf8')
5003
+ // C-M1: the whole table is posted, so the payload names the table it came from.
5004
+ // Without that, two windows save and the loser's row disappears without an error.
5005
+ assert.ok(source.includes('revision: revisionRef.current'), 'the save names its base table')
5006
+ assert.ok(source.includes("answer.status === 409 && payload.conflict === true"), 'a stale save is detected')
5007
+ assert.ok(source.includes('规则表已在别处被修改,已重新载入(本次改动未写入)'), 'and reported in words')
5008
+ // C-M2: a 700 ms debounce is a window in which an edit exists only in memory; both
5009
+ // paths that reload the view must write it out first.
5010
+ assert.ok(source.includes('function flushSave()'), 'there is a flush')
5011
+ assert.ok(source.includes('flushSave().catch(function () {}).then(function () { actNow(action, ruleId, side) })'),
5012
+ 'start/stop writes the pending edit first')
5013
+ assert.ok(source.includes('flushSave().catch(function () {}).then(function () { onClose() })'),
5014
+ 'closing the dialog writes the pending edit first')
5015
+ // C-M3: local parsing is a preview; once the host has seen the exact row, its
5016
+ // verdict wins, so the form cannot claim a row applies when the engine skipped it.
5017
+ assert.ok(source.includes('function hostVerdictFor(rule)'), 'the host verdict is looked up')
5018
+ assert.ok(source.includes('var hostRow = hostVerdictFor(rule)'), 'and used by the row')
5019
+ // P2: the placeholder used to promise the opposite of what the engine does.
5020
+ assert.equal(source.includes('(空=不限)'), false, 'no placeholder advertises the old meaning')
5021
+ assert.ok(source.includes('(全部写 *;空=本行不生效)'))
5022
+ })
5023
+
5024
+ test('the program cell is typed, and the picker offers three tabs and one tree', () => {
5025
+ const source = readSync(new URL('../lib/client.js', import.meta.url), 'utf8')
5026
+ // Typing `java` (any path) or `D:\…\java.exe` (exact) is the primary way to set a
5027
+ // rule; the picker is a helper, not the only door.
5028
+ assert.ok(source.includes("'data-proxy-program': rule.id"))
5029
+ assert.ok(source.includes("placeholder: '程序名或路径:java / D:\\\\…\\\\java.exe'"))
5030
+ assert.ok(source.includes("'data-proxy-pick': rule.id"))
5031
+ // Exactly two tabs: running processes, and ONE file tree. On WSL the Windows
5032
+ // disks are ordinary folders under /mnt, so a separate "Windows 文件" tab would
5033
+ // be the same tree with another spelling.
5034
+ assert.ok(source.includes("tabButton('running', '运行中的程序')"))
5035
+ assert.ok(source.includes("tabButton('local', '选择文件')"))
5036
+ assert.equal(source.includes("tabButton('windows'"), false, 'one file tree, not two')
5037
+ // `/` is prepended client-side too: the roots list comes from the host half,
5038
+ // which only reloads with dsh web, and a refresh must not drop the entry that
5039
+ // reaches every path.
5040
+ assert.ok(source.includes('function withFilesystemRoot(roots, posix)'))
5041
+ assert.ok(source.includes('withFilesystemRoot(tree.roots, hostIsPosix)'))
5042
+ // …and the shortcuts in front of it are dropped, so the first thing the user sees
5043
+ // is the start of the filesystem, not a pile of convenience roots.
5044
+ assert.ok(source.includes("root.path === '/' || /^\\/mnt\\/[A-Za-z](\\/|$)/.test(root.path)"))
5045
+ // A pick under /mnt is written as a Windows path: that is the spelling the
5046
+ // program's own OS uses, and what a Windows-side interceptor matches.
5047
+ assert.ok(source.includes('function pickedPath(value)'))
5048
+ assert.ok(source.includes('program: pickedPath(value)'))
5049
+ assert.ok(source.includes("url.searchParams.set('side', side)"))
5050
+ // The picker is a dialog of its own, opened from the row: a two-root tree does
5051
+ // not fit in a rule row.
5052
+ assert.ok(source.includes("'data-proxy-picker-dialog': '1'"), 'the picker renders as a nested dialog')
5053
+ assert.ok(source.includes('void loadPrograms()'), 'the process list is fetched when the picker opens')
5054
+ // Expanding a folder must grow the tree IN PLACE — no "enter directory" stepping,
5055
+ // no breadcrumb, and no re-reading what is already on screen.
5056
+ assert.ok(source.includes('data-proxy-tree-dir'), 'folders are rows in the tree')
5057
+ assert.ok(source.includes('data-proxy-tree-file'), 'files are rows in the tree')
5058
+ assert.ok(source.includes('function toggleDir(dir)'), 'a folder toggles instead of navigating')
5059
+ assert.ok(source.includes("if (open !== true && tree.nodes[key] === undefined) void loadTreeDir(key)"),
5060
+ 'a folder is read the first time it is expanded')
5061
+ assert.equal(source.includes("'data-proxy-browse-up'"), false, 'the stepwise browser is gone')
5062
+ // The program cell is typed, the picker is a helper: choosing a file must call
5063
+ // the chooser that belongs to the dialog (passing it into the tree, not closing
5064
+ // over a name that is not in scope).
5065
+ assert.ok(source.includes('function dirRow(dir, depth, chooser)'), 'the tree rows take the chooser')
5066
+ assert.ok(source.includes('rows = rows.concat(treeRows(dir.path, depth + 1, chooser))'))
5067
+ assert.ok(source.includes('rows = rows.concat(dirRow(dir, depth, chooser))'))
5068
+ // A file is not a folder: it gets no caret in that slot (only a placeholder span),
5069
+ // otherwise the arrow reads as "expand me" on something that cannot expand.
5070
+ assert.equal(source.includes("'▶ ' + file.name"), false, 'no caret in front of files')
5071
+ assert.ok(source.includes("h('span', null, '📄 ' + file.name)"))
5072
+ // A folder whose listing came back empty is a leaf: caret becomes `·`, no click.
5073
+ assert.ok(source.includes("'data-proxy-tree-leaf': leaf ? '1' : '0'"))
5074
+ assert.ok(source.includes("leaf ? '·' : open ? '▾' : '▸'"))
5075
+ // The old "choose from list only" button is gone.
5076
+ assert.equal(source.includes("rule.program === '' ? '选择程序…'"), false)
5077
+ })
5078
+
5079
+ test('edits save themselves, and adding a row adds a row', () => {
5080
+ const source = readSync(new URL('../lib/client.js', import.meta.url), 'utf8')
5081
+ // No 保存 button: every edit is written 700ms after the last keystroke, so a
5082
+ // half-typed IP never becomes a half-written rule on disk.
5083
+ assert.equal(source.includes("action: 'save'"), false, 'the save button is gone')
5084
+ assert.ok(source.includes('function draftSignature(draft)'))
5085
+ assert.ok(source.includes('savedSignature.current = draftSignature(draft)'),
5086
+ 'what the host confirmed is remembered, so a reload is not an edit')
5087
+ // The timer lives in a ref so a button press or a close can flush it first.
5088
+ assert.ok(source.includes('saveTimer.current = setTimeout(function () { saveTimer.current = null; void save() }, 700)'))
5089
+ assert.ok(source.includes('data-proxy-autosave'))
5090
+ // Half-typed rows are not written: auto-save fires mid-typing, and a rule with no
5091
+ // program/ip/port would come back as a row that silently does nothing.
5092
+ assert.ok(source.includes('function storableRule(rule)'))
5093
+ assert.ok(source.includes('var mode = writeMode(rule)'))
5094
+ assert.ok(source.includes("if (storable.length === 0 && skipped > 0)"),
5095
+ 'never blank the file while every row is still being typed')
5096
+ // A row that is already on disk must not silently keep its OLD content when it is
5097
+ // edited into an incomplete state: it is written as disabled instead.
5098
+ assert.ok(source.includes('function writeMode(rule)'))
5099
+ assert.ok(source.includes("return savedIds.current[rule.id] === true ? 'disable' : 'skip'"))
5100
+ assert.ok(source.includes("storable.push(Object.assign({}, rule, { enabled: false }))"))
5101
+ assert.ok(source.includes('savedIds.current = ids'))
5102
+ // "+ 添加规则" appends an empty row and does NOT pop the picker over the table.
5103
+ const addRule = source.slice(source.indexOf('function addRule()'), source.indexOf('function addRule()') + 900)
5104
+ assert.equal(addRule.includes('pickFor'), false, 'adding a row must not open the picker')
5105
+ })