dsh-ris-ide 1.8.2 → 1.8.4

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.
@@ -175,6 +175,16 @@
175
175
  else if (data.type === 'close') closeForOpener()
176
176
  }
177
177
  }
178
+ // INSIDE an iframe (the maintenance page's IDE tab) the one-window rule is
179
+ // already enforced by the single reused <iframe>: it navigates THIS document
180
+ // away instead of stacking a second one. Claiming the lock there only races
181
+ // the previous document's release — the fresh document failed its claim and
182
+ // painted "RIS-IDE 已在另一个窗口打开" instead of the IDE, which is what made
183
+ // a workspace switch in risd-ui look like a load error (m00001-2). Embedded
184
+ // windows boot directly; standalone popups keep the lock.
185
+ var embeddedBoot = false
186
+ try { embeddedBoot = window.self !== window.top } catch (error) { embeddedBoot = false }
187
+ if (embeddedBoot) { becomeHolder(); resolveClaim(true); return }
178
188
  var locks = typeof navigator !== 'undefined' ? navigator.locks : undefined
179
189
  if (locks && typeof locks.request === 'function') {
180
190
  var attempt = 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ris-ide",
3
- "version": "1.8.2",
3
+ "version": "1.8.4",
4
4
  "license": "MIT",
5
5
  "description": "RIS-IDE local dev panel for the DSH web GUI: live log tail, one-click start/stop of workspace programs, JDWP debugging, file tree + editor, and a standalone IDE window that carries no session history. · DSH 右侧栏本地开发面板:日志实时跟随、一键启停本地程序、Java 断点调试、文件树与编辑器、独立 IDE 窗口。",
6
6
  "keywords": [
@@ -387,6 +387,51 @@ test('the compact panel is console rows plus a resizable 240px log pane', () =>
387
387
  }
388
388
  })
389
389
 
390
+ test('each session remembers ITS workspace; the origin-wide slot stays separate (m04873)', () => {
391
+ // One slot shared by every document on the origin made the sidebar console and
392
+ // the IDE console drag each other to whichever workspace was remembered last.
393
+ const map = new Map()
394
+ const previous = globalThis.window.localStorage
395
+ globalThis.window.localStorage = {
396
+ getItem: (key) => (map.has(key) ? map.get(key) : null),
397
+ setItem: (key, value) => { map.set(key, value) },
398
+ }
399
+ try {
400
+ T.rememberSessionCwd('/work/a', 'session-a')
401
+ T.rememberSessionCwd('/work/b', 'session-b')
402
+ assert.equal(T.knownSessionCwd('session-a'), '/work/a')
403
+ assert.equal(T.knownSessionCwd('session-b'), '/work/b')
404
+ assert.equal(map.get(T.SESSION_CWD_PREFIX + 'session-a'), '/work/a', 'keyed by session')
405
+ // The origin-wide slot is written by the panels too, but reading it as a
406
+ // SESSION's workspace is exactly the cross-talk this fixes.
407
+ T.rememberWorkspaceCwd('/work/b')
408
+ assert.equal(T.knownWorkspaceCwd(), '/work/b')
409
+ assert.equal(T.knownSessionCwd('session-a'), '/work/a', 'a session keeps its own answer')
410
+ // Garbage never lands: relative paths and missing session ids are ignored.
411
+ T.rememberSessionCwd('relative/path', 'session-a')
412
+ T.rememberSessionCwd('/work/c', '')
413
+ assert.equal(T.knownSessionCwd('session-a'), '/work/a')
414
+ assert.equal(T.knownSessionCwd(''), undefined)
415
+ assert.equal(T.knownSessionCwd(undefined), undefined)
416
+ } finally {
417
+ globalThis.window.localStorage = previous
418
+ }
419
+ })
420
+
421
+ test('a panel never steers the host with a GUESSED workspace (m04873)', () => {
422
+ const source = readSync(new URL('../lib/client.js', import.meta.url), 'utf8')
423
+ // The console resolves its workspace from the session store or from what the host
424
+ // answered for THIS session; the origin-wide last-cwd slot is not an input.
425
+ assert.match(source, /var sessionCwd = knownSessionCwd\(sessionId\)/)
426
+ assert.match(source, /if \(cwdKnown === true && typeof cwd === 'string' && cwd !== ''\) url\.searchParams\.set\('cwd', cwd\)/)
427
+ assert.match(source, /rememberSessionCwd\(payload\.root, sessionId\)/)
428
+ // The standalone IDE window is pinned to the workspace in its URL, so a hello
429
+ // that resolved to another workspace cannot move its console.
430
+ assert.match(source, /payload\.root !== props\.cwd\) return/)
431
+ // A log pane follows its own scope, never the origin-wide slot.
432
+ assert.match(source, /var scopedCwd = knownSessionCwd\(sessionId\)/)
433
+ })
434
+
390
435
  test('the compact panel does NOT remember which section was maximized (m00584)', () => {
391
436
  // A persisted ⤢ used to hide the other section on every reopen, with nothing on
392
437
  // screen explaining where it went, so the maximize mode became view state only.
@@ -3447,6 +3492,78 @@ test('every advisory strip carries a ✕ to close it', { skip: !reactIsReal ? 'R
3447
3492
  assert.match(workbench, /data-notice-close="config-note"/, 'the config note is closable')
3448
3493
  })
3449
3494
 
3495
+ test('only a FRONTEND row offers the browser button, and only a yds project promises a token (m03945/m04354)', async () => {
3496
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
3497
+ // Two renderers (sidebar compact row + full panel) both carry the button, but a
3498
+ // backend (spring) program serves no page to open — m04354: no button there.
3499
+ const hits = source.split("'data-action': 'open-site'").length - 1
3500
+ assert.equal(hits, 2, 'the 🌐 button is rendered by both program rows')
3501
+ assert.match(source, /startable && program\.kind === 'frontend'/, 'the sidebar row gates on kind')
3502
+ assert.match(source, /program\.kind === 'frontend'\s*\n\s*\? h\('button', \{/, 'the full row gates on kind')
3503
+ assert.match(source, /async function requestOpenTarget\(program, scope\)/)
3504
+ assert.match(source, /dsh-ris-ide\/open-target\?/)
3505
+ assert.match(source, /function openSite\(program\)/)
3506
+ // The row click picks the program for the log pane: the button must not steal or
3507
+ // pass that click through.
3508
+ assert.match(source, /event\.stopPropagation\(\); openSite\(program\)/)
3509
+ // Errors are told in the panel's note bar, never swallowed.
3510
+ assert.match(source, /还没有可打开的地址|这个程序还没有\.\.\./)
3511
+ // The token sentence may only appear behind the yds flag: a plain workspace must
3512
+ // never read "yds" (m04354).
3513
+ assert.match(source, /async function requestYdsProject\(scope\)/)
3514
+ assert.match(source, /dsh-ris-yds\/probe\?/)
3515
+ assert.match(source, /ydsProject \? '(yds 项目:请求自动带上登录 token,免登录)' : ''/)
3516
+ assert.doesNotMatch(source, /yds 项目会自动注入 YYCToken/, 'the old unconditional yds wording is gone')
3517
+ })
3518
+
3519
+ test('the IDE console is wired to the owning panel\'s openSite (m00982)', async () => {
3520
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
3521
+ // The button RESOLVES nothing itself: ProgramsPanel owns the fetch and the
3522
+ // one-tab guard, and hands both down (m04354: a backend has no page to open).
3523
+ assert.match(source, /onOpenSite: openSite,/)
3524
+ assert.match(source, /siteBusyId: busySiteId,/)
3525
+ assert.match(source, /ydsProject: ydsProject,/)
3526
+ // `button()` turns `action` into `data-action` in the DOM.
3527
+ assert.match(source, /action: 'console-open-site'/)
3528
+ assert.match(source, /var onOpenSite = typeof props\.onOpenSite === 'function' \? props\.onOpenSite : null/)
3529
+ assert.match(source, /if \(onOpenSite !== null\) onOpenSite\(program\)/)
3530
+ })
3531
+
3532
+ test('the IDE console opens a frontend page with the same 🌐 as the sidebar (m00982)', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, () => {
3533
+ const markup = renderWorkbench({
3534
+ programs: [
3535
+ { id: 'frontend:ui#dev', name: 'ris-ui-3', kind: 'frontend', logPath: '/w/logs/ui.log', running: { alive: true } },
3536
+ { id: 'spring:a#A', name: 'a-biz', kind: 'spring', logPath: '/w/logs/a.log', running: { alive: true } },
3537
+ ],
3538
+ })
3539
+ assert.equal((markup.match(/data-action="console-open-site"/g) || []).length, 1, 'frontend rows only: the spring row has no page')
3540
+ const buttonTag = ((markup.match(/<button[^>]*>/g) || []).filter((tag) => tag.includes('data-action="console-open-site"'))[0]) || ''
3541
+ assert.match(buttonTag, /width:25px/, 'same fixed width as the other console icons')
3542
+ assert.match(buttonTag, /在系统浏览器打开 ris-ui-3 的页面/)
3543
+
3544
+ // No frontend → no button at all (a workspace of backends must not show one).
3545
+ const springOnly = renderWorkbench({
3546
+ programs: [{ id: 'spring:a#A', name: 'a-biz', kind: 'spring', logPath: '/w/logs/a.log', running: { alive: false } }],
3547
+ })
3548
+ assert.doesNotMatch(springOnly, /console-open-site/, 'backend-only workspaces get no browser button')
3549
+
3550
+ // In flight: the row shows progress and cannot launch a second tab.
3551
+ const busy = renderWorkbench({
3552
+ siteBusyId: 'frontend:ui#dev',
3553
+ programs: [{ id: 'frontend:ui#dev', name: 'ris-ui-3', kind: 'frontend', logPath: '/w/logs/ui.log', running: { alive: true } }],
3554
+ })
3555
+ const busyTag = ((busy.match(/<button[^>]*>/g) || []).filter((tag) => tag.includes('data-action="console-open-site"'))[0]) || ''
3556
+ assert.match(busyTag, /disabled=""/)
3557
+ assert.match(busy, /…<\/button>/)
3558
+
3559
+ // The token sentence only appears for a yds workspace (m04354).
3560
+ const yds = renderWorkbench({
3561
+ ydsProject: true,
3562
+ programs: [{ id: 'frontend:ui#dev', name: 'ris-ui-3', kind: 'frontend', logPath: '/w/logs/ui.log', running: { alive: true } }],
3563
+ })
3564
+ assert.match(yds, /yds 项目:请求自动带上登录 token,免登录/)
3565
+ })
3566
+
3450
3567
  test('the tab strip shows ⟳ while the buffer is clean and ± once it is dirty (m00388/m00808)', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, () => {
3451
3568
  const markup = renderWorkbenchWithFile('/w/README.md')
3452
3569
  const tag = (markup.match(/<button[^>]*data-action="reload-file"[^>]*>/) || [''])[0]
@@ -3476,6 +3593,19 @@ test('closing a notice sticks for EVERY mounted copy of the panel (m00388)', ()
3476
3593
  assert.equal(T.noticeIsOpen('config-updated', 'updated'), true, 'reset restores the initial state')
3477
3594
  })
3478
3595
 
3596
+ test('the automatic config sync is silent: nothing renders a sync notice (m03291)', async () => {
3597
+ // The host rewrites .dsh-ris-ide/config.json whenever the scan drifts, and the
3598
+ // panel used to answer with a row per sync ("配置已与工作区同步…") that was noise
3599
+ // after every workspace switch — and could not be dismissed while two copies of
3600
+ // the pane were mounted. The text is gone; the actionable drift notice stays.
3601
+ const { readFile } = await import('node:fs/promises')
3602
+ const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
3603
+ assert.doesNotMatch(source, /配置已与工作区同步/, 'the auto-sync notice text is gone')
3604
+ assert.doesNotMatch(source, /'config-updated'/, 'nothing renders that kind any more')
3605
+ assert.match(source, /kind: 'drift'/, 'the actionable drift notice stays')
3606
+ assert.match(source, /kind: 'config-generated'/, 'the one-off "config created" note stays')
3607
+ })
3608
+
3479
3609
  test('the source tab strip offers 重新加载, and a dirty tab asks before dropping it (m00388)', async () => {
3480
3610
  const { readFile } = await import('node:fs/promises')
3481
3611
  const source = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
@@ -4471,9 +4601,9 @@ test('a start switches to that program log before waiting for the spawn', async
4471
4601
  // block for START_WAIT_MS, and Maven compile prints nothing for tens of seconds.
4472
4602
  assert.match(source, /async function consoleStart\(program\) \{\n\s*\/\/[\s\S]*?\n\s*selectProgram\(program\)[\s\S]*?setConsoleBusy\(program\.id\)[\s\S]*?requestStart\(program\.id, scopeRef\.current\)/)
4473
4603
  // The sidebar rows do the same before awaiting requestStart.
4474
- assert.match(source, /if \(boots\) \{ setActive\(program\); broadcastLogFocus\(program\.logPath\); setCompactLogNonce/)
4604
+ assert.match(source, /if \(boots\) \{ setActive\(program\); broadcastLogFocus\(program\.logPath, sessionId, cwd\); setCompactLogNonce/)
4475
4605
  // …and every window watching another log is moved by the same broadcast.
4476
- assert.match(source, /function broadcastLogFocus\(logPath\)/)
4606
+ assert.match(source, /function broadcastLogFocus\(logPath, sessionId, cwd\)/)
4477
4607
  })
4478
4608
 
4479
4609
  test('the debug pane has a visual settings dialog for dependency sources', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, async () => {
@@ -4532,7 +4662,7 @@ test('debug start switches the log pane first, and the variable caret is borderl
4532
4662
  assert.match(slice, /setLogNonce\(function \(value\) \{ return value \+ 1 \}\)/)
4533
4663
  // The switch follows the user into other windows, and the tail is re-read the
4534
4664
  // moment the restarted service prints its first byte (Maven is quiet).
4535
- assert.match(slice, /broadcastLogFocus\(logPath\)/)
4665
+ assert.match(slice, /broadcastLogFocus\(logPath, sessionId, cwd\)/)
4536
4666
  assert.match(slice, /watchLogOutput\(logPath, baseline\)/)
4537
4667
  // Tree caret: glyph only, no bordered button box.
4538
4668
  assert.match(source, /var caretStyle = \{[\s\S]{0,400}?border: 'none'/)
@@ -4924,7 +5054,7 @@ test('the editor scrollbars are visible and a start re-reads its log', async ()
4924
5054
  assert.match(source, /SELECTION_CSS \+ SCROLLBAR_CSS \+ SEARCH_PANEL_CSS \+ TOAST_CSS/, 'injected with the panel styles')
4925
5055
  assert.doesNotMatch(source, /SCROLLBAR_CSS[\s\S]{0,800}?scrollbar-gutter/, 'no empty gutter on files that do not overflow')
4926
5056
  // BUG6: a start records a size baseline and watches for its first new byte …
4927
- assert.match(source, /async function consoleStart\(program\) \{[\s\S]{0,700}?await logSizeOf\(logPath\)/, 'the start records a size baseline')
5057
+ assert.match(source, /async function consoleStart\(program\) \{[\s\S]{0,900}?await logSizeOf\(logPath\)/, 'the start records a size baseline')
4928
5058
  assert.match(source, /async function consoleStart\(program\) \{[\s\S]{0,2400}?watchLogOutput\(logPath, baseline\)/, 'and watches the first new byte')
4929
5059
  // … a pane mounting on an already-open socket reads its tail once …
4930
5060
  assert.match(source, /if \(typeof EventSource !== 'function'\) return\n\s*void refresh\(\)/, 'first paint reads the tail')
@@ -4932,7 +5062,7 @@ test('the editor scrollbars are visible and a start re-reads its log', async ()
4932
5062
  // polls instead of waiting on someone else's stream.
4933
5063
  assert.match(source, /var servedTail = ''/, 'the connection remembers its tail path')
4934
5064
  assert.match(source, /notifyOpen\(\)/)
4935
- assert.match(source, /setStreamOk\(served === '' \|\| served === path\)/, 'a pane the socket does not carry falls back to polling')
5065
+ assert.match(source, /setStreamOk\(mismatch !== true && \(served === '' \|\| served === path\)\)/, 'a pane the socket does not carry (or another scope) falls back to polling')
4936
5066
  assert.match(source, /setCompactLogNonce\(function \(value\) \{ return value \+ 1 \}\)/, 'the sidebar pane re-reads after start/stop')
4937
5067
  // … and the host never drops a delta without re-snapshotting.
4938
5068
  const host = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
@@ -33,7 +33,7 @@ const {
33
33
  startProgram, stopLogPath, processGroupLeader, groupMembers, jsonSafe,
34
34
  SKILL_NAME, PKG_VERSION, bundledSkillPath, findProjectRoot, skillRootFor, skillFileState, installSkill,
35
35
  skillRootsFor, syncInstalledSkills,
36
- TAIL_PATH, STOP_PATH, INSTANCES_PATH, PROGRAMS_PATH, START_PATH, CONFIG_PATH, OPENS_PATH, DEBUG_PATH,
36
+ TAIL_PATH, STOP_PATH, INSTANCES_PATH, PROGRAMS_PATH, OPEN_TARGET_PATH, START_PATH, CONFIG_PATH, OPENS_PATH, DEBUG_PATH,
37
37
  DEFAULT_BYTES, HARD_MAX_BYTES, MIN_BYTES, PID_SUFFIX,
38
38
  } = __test
39
39
  const WRAPPER = fileURLToPath(new URL('../bin/run-with-log.sh', import.meta.url))
@@ -669,6 +669,47 @@ test('the programs route scans over HTTP and the start route refuses bad input',
669
669
  }, undefined, root)
670
670
  })
671
671
 
672
+ test('the open-target route resolves a program by id and never invents a URL (m03945)', async () => {
673
+ const { root } = await makeProgramFixture()
674
+ await withServer(async ({ base }) => {
675
+ const listing = await (await fetch(`${base}${PROGRAMS_PATH}?sessionId=s1&refresh=1`)).json()
676
+ const program = listing.programs.find((entry) => entry.kind === 'frontend')
677
+ assert.ok(program !== undefined, 'the fixture frontend program is discovered')
678
+
679
+ // A program that never printed a dev-server line has no address: say so instead
680
+ // of opening about:blank (the panel turns `message` into its note bar).
681
+ const noUrl = await (await fetch(`${base}${OPEN_TARGET_PATH}?sessionId=s1&id=${encodeURIComponent(program.id)}`)).json()
682
+ assert.equal(noUrl.ok, false)
683
+ assert.equal(noUrl.code, 'no-url')
684
+ assert.match(noUrl.message, /Local: http:\/\/localhost/)
685
+
686
+ const unknown = await fetch(`${base}${OPEN_TARGET_PATH}?sessionId=s1&id=${encodeURIComponent('frontend:missing#dev')}`)
687
+ assert.equal(unknown.status, 404)
688
+ assert.equal((await unknown.json()).ok, false)
689
+ assert.equal((await fetch(`${base}${OPEN_TARGET_PATH}`)).status, 400, 'sessionId is required')
690
+ assert.equal((await fetch(`${base}${OPEN_TARGET_PATH}?sessionId=s1`, { method: 'POST' })).status, 405)
691
+ }, undefined, root)
692
+ })
693
+
694
+ test('a dev-server URL is read from local hosts, placeholders and ANSI logs (m03945)', async () => {
695
+ // What scaffolds actually print: webpack/vite use localhost, MDF prints
696
+ // `Node服务地址:http://<HOST地址>:3003`, and colour codes wrap both the label
697
+ // and the URL. A gateway URL on the next line must never win.
698
+ const cases = [
699
+ ['Local: http://localhost:5173/\n', 'http://localhost:5173/'],
700
+ ['Node服务地址:http://<HOST地址>:3003 当前环境:daily\n', 'http://127.0.0.1:3003'],
701
+ ['\u001b[32m - Local: \u001b[36mhttp://0.0.0.0:8080/\u001b[39m\n', 'http://127.0.0.1:8080/'],
702
+ ['http://[::]:9000/\n', 'http://127.0.0.1:9000/'],
703
+ ['Java服务地址:https://srmdev.hanslaser.com/c-ass-kk-hans\n', undefined],
704
+ ]
705
+ const dir = await mkdtemp(join(tmpdir(), 'ris-logurl-'))
706
+ const logPath = join(dir, 'prog.log')
707
+ for (const [line, want] of cases) {
708
+ await writeFile(logPath, line, 'utf8')
709
+ assert.equal(await __test.logUrl(logPath), want, `log line: ${JSON.stringify(line)}`)
710
+ }
711
+ })
712
+
672
713
  test('the start route launches a program through run-with-log.sh and stop terminates it', { skip: skipWithout(HAS_BASH, 'bash') }, async () => {
673
714
  const { root } = await makeStartableFixture()
674
715
  await withServer(async ({ base }) => {
@@ -3150,6 +3191,35 @@ test('fs/window pages a large file and never splits a multi-byte character', asy
3150
3191
  assert.equal(__test.utf8CompleteLength(Buffer.alloc(0)), 0)
3151
3192
  })
3152
3193
 
3194
+ test('a git spawn failed by a deleted cwd does not disable git for the process (m03193)', { skip: skipWithout(HAS_GIT, 'git') }, () => {
3195
+ // `spawn('git', …, { cwd })` reports a missing binary and a deleted cwd the same
3196
+ // way (ENOENT, error.path 'git'), and the plugin runs git inside tree folders. A
3197
+ // single folder deleted mid-command used to latch "no git" for the whole process:
3198
+ // every tree then answered git:false (no .gitignore filter, greyed toggle) until
3199
+ // dsh restarted. The verdict is now a short quarantine, confirmed by a probe.
3200
+ const { gitUnavailable, noteGitSpawnFailure, noteGitSuccess } = __test
3201
+ noteGitSuccess()
3202
+ assert.equal(gitUnavailable(), false, 'git is trusted to begin with')
3203
+
3204
+ // The failure that used to poison it: git exists, only the cwd was gone.
3205
+ noteGitSpawnFailure()
3206
+ assert.equal(gitUnavailable(), false, 'a bad cwd must not be held against git')
3207
+
3208
+ // A probe from a cwd that always exists still has to be able to say "gone".
3209
+ const savedPath = process.env.PATH
3210
+ process.env.PATH = '/definitely/not/here'
3211
+ try {
3212
+ noteGitSpawnFailure()
3213
+ assert.equal(gitUnavailable(), true, 'an empty PATH confirms the binary is absent')
3214
+ } finally {
3215
+ process.env.PATH = savedPath
3216
+ }
3217
+
3218
+ // …and one good answer brings git back without restarting dsh.
3219
+ noteGitSuccess()
3220
+ assert.equal(gitUnavailable(), false, 'a successful git command clears the verdict')
3221
+ })
3222
+
3153
3223
  test('a same-named row of another kind is not taken over by an update', () => {
3154
3224
  // A yds project: the launcher row is `spring`, the discovered frontend row carries
3155
3225
  // the package.json name — an update must not move the launcher's startCommand onto
@@ -622,26 +622,43 @@ test('SOCKS5: a split domain reply is never accepted before it is complete', asy
622
622
  Buffer.from([0x00, 80]),
623
623
  ])
624
624
  let fragmentSent = false
625
+ // Read the promise state at the exact instant the tail is written: four bytes
626
+ // are a header fragment, not a reply. The old `length < 4` guard (and the NaN
627
+ // successor that replaced it) resolved right there and leaked the remaining
628
+ // handshake bytes into the tunnel as garbage.
629
+ //
630
+ // Deliberately NOT a sleep-then-assert: that version compared the state 25 ms
631
+ // after the fragment against a timer writing the tail 80 ms later, so on a
632
+ // throttled CI pod the loop stalled past both deadlines and the tail landed
633
+ // before the assertion — it reported `resolved` where it expected `pending`
634
+ // (m05789) with a correct parser, because the check raced the very delay it
635
+ // relied on. Reading the state inside the timer callback cannot race: microtasks
636
+ // drain before the next timer, so a settlement caused by the fragment (or by
637
+ // anything else that already arrived) has run by the time this line executes.
638
+ let whenTailSent = null
639
+ let settledWith = 'pending'
625
640
  const socks = await scriptedSocks((client) => {
626
641
  socksHandshake(client, () => {
627
642
  client.write(reply.subarray(0, 4))
628
643
  fragmentSent = true
629
- setTimeout(() => client.write(reply.subarray(4)), 80)
644
+ setTimeout(() => {
645
+ whenTailSent = settledWith
646
+ if (!client.destroyed) client.write(reply.subarray(4))
647
+ }, 80)
630
648
  })
631
649
  })
632
650
  let upstream = null
633
651
  try {
634
- let settledWith = 'pending'
635
652
  const pending = connectSocks({ host: '127.0.0.1', port: socks.port }, 'example.com', 80)
636
653
  pending.then((socket) => { upstream = socket; settledWith = 'resolved' }, () => { settledWith = 'rejected' })
637
- for (let attempt = 0; attempt < 100 && fragmentSent !== true; attempt += 1) await sleep(5)
638
- await sleep(25)
639
- // Four bytes are a header fragment, not a reply. The old `length < 4` guard
640
- // (and the NaN successor that replaced it) resolved right here and leaked
641
- // the remaining handshake bytes into the tunnel as garbage.
642
- assert.equal(settledWith, 'pending')
643
- await pending
644
- assert.equal(settledWith, 'resolved')
654
+ for (let attempt = 0; attempt < 200 && fragmentSent !== true; attempt += 1) await sleep(5)
655
+ assert.equal(fragmentSent, true, 'the scripted server never saw the CONNECT request')
656
+ const settled = await Promise.race([
657
+ pending.then(() => 'resolved', () => 'rejected'),
658
+ sleep(2000).then(() => 'timed-out'),
659
+ ])
660
+ assert.equal(whenTailSent, 'pending', 'the four-byte fragment must not settle the promise')
661
+ assert.equal(settled, 'resolved')
645
662
  } finally {
646
663
  upstream?.destroy()
647
664
  await socks.close()
@@ -959,3 +959,33 @@ test('readElevationState treats options.home as the PROXY home (server.js contra
959
959
  rmSync(home, { recursive: true, force: true })
960
960
  }
961
961
  })
962
+
963
+ test('the sudo probe is cached between background attempts (m03761)', { skip: process.platform === 'win32' ? 'no sudo on Windows' : false }, () => {
964
+ // A real `sudo -n true` writes a journal line on every call — including the
965
+ // failures. The reconciler retries a background start every minute, so on a box
966
+ // without passwordless sudo that used to be one audit line per minute. Pinned
967
+ // here with a fake `sudo` on PATH that records each invocation.
968
+ const bin = mkdtempSync(join(tmpdir(), 'ris-sudo-'))
969
+ const calls = join(bin, 'calls.log')
970
+ // `printf`, not `echo "$@"`: the args start with `-n`, which echo takes as
971
+ // "no trailing newline" — the invocations would then concatenate into one line
972
+ // and the counter would never move.
973
+ writeFileSync(join(bin, 'sudo'), `#!/bin/sh\nprintf '[%s]\\n' "$*" >> "${calls}"\nexit 1\n`, { mode: 0o755 })
974
+ chmodSync(join(bin, 'sudo'), 0o755)
975
+ const previousPath = process.env.PATH
976
+ const count = () => (existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n').filter((line) => line !== '').length : 0)
977
+ process.env.PATH = bin
978
+ try {
979
+ __test.resetSudoProbe()
980
+ assert.equal(__test.sudoPasswordless(), false, 'the fake sudo never succeeds')
981
+ assert.equal(count(), 1)
982
+ assert.equal(__test.sudoPasswordless(), false, 'the cached answer is reused')
983
+ assert.equal(count(), 1, 'a background retry must not spawn sudo again')
984
+ __test.sudoPasswordless({ interactive: true })
985
+ assert.equal(count(), 2, 'a user-initiated start asks fresh (NOPASSWD may be new)')
986
+ } finally {
987
+ process.env.PATH = previousPath
988
+ __test.resetSudoProbe()
989
+ rmSync(bin, { recursive: true, force: true })
990
+ }
991
+ })
@@ -324,7 +324,8 @@ test('config reports the decided policy and only accepts a lifecycle body', asyn
324
324
  assert.equal(body.idleExitMs, 600000)
325
325
  // The daemon has no restart supervisor; advertising one was a lie (review A-P2-3).
326
326
  assert.equal(body.engineRestart, undefined)
327
- assert.equal(body.lifecycle.daemon.followDsh, true)
327
+ assert.equal(body.lifecycle.daemon.stopWithDsh, true)
328
+ assert.equal(body.lifecycle.daemon.startWithDsh, true, 'the daemon start half is forced on')
328
329
 
329
330
  // POST exists for the lifecycle settings only: no body = bad request, and the
330
331
  // response says what is missing instead of pretending to be read-only.
@@ -408,6 +409,28 @@ test('/v1/dsh drops unusable `at` values and counts them (review A3-P2-6)', asyn
408
409
  assert.equal(body.dropped, 3, 'every unusable timestamp is reported, not silently pruned')
409
410
  })
410
411
 
412
+ test('/v1/dsh names a workspace by the Session that refreshed its window row (m00001-2)', async (t) => {
413
+ // The sidebar mirror names the session DSH associates with each workspace; the
414
+ // remembered window row names the session that most recently opened that
415
+ // workspace. They can differ, and mixing them per poll made the maintenance page
416
+ // rewrite (and reload) the IDE iframe every few seconds. The live window row wins.
417
+ const { home, state } = await startFixture(t)
418
+ const now = new Date().toISOString()
419
+ writeFileSync(join(home, 'dsh-window.json'), `${JSON.stringify({
420
+ windows: [{ url: 'http://127.0.0.1:3080', sessionId: 'win-session', cwd: '/tmp/ws-window', title: 'window', at: now }],
421
+ workspaces: [
422
+ { cwd: '/tmp/ws-window', title: 'window', sessionId: 'sidebar-session', active: true },
423
+ { cwd: '/tmp/ws-sidebar', title: 'sidebar', sessionId: 'sidebar-only', active: true },
424
+ ],
425
+ at: now,
426
+ })}\n`)
427
+ const body = await (await call(state, '/v1/dsh')).json()
428
+ assert.equal(body.available, true)
429
+ const rows = new Map(body.windows.map((row) => [row.cwd, row]))
430
+ assert.equal(rows.get('/tmp/ws-window').sessionId, 'win-session', 'the window row session wins')
431
+ assert.equal(rows.get('/tmp/ws-sidebar').sessionId, 'sidebar-only', 'a workspace nobody opened keeps the sidebar session')
432
+ })
433
+
411
434
  test('/v1/dsh probes a live host when no usable snapshot exists (m00186)', async (t) => {
412
435
  // The daemon cannot read dsh's own API (its launch token lives in dsh's memory), so
413
436
  // the plugin advertises one `instances/dsh-<pid>.json` per running host. When the
@@ -13,8 +13,47 @@ import { tmpdir } from 'node:os'
13
13
  import { join } from 'node:path'
14
14
  import { spawn } from 'node:child_process'
15
15
  import test from 'node:test'
16
+ import { setTimeout as sleep } from 'node:timers/promises'
16
17
  import { readRisdState } from '../lib/risd/state.js'
17
18
 
19
+ /**
20
+ * SIGTERM, wait until the process is really gone, then remove the temp trees.
21
+ *
22
+ * Deleting straight after `kill` raced the daemon: it kept writing its heartbeat
23
+ * and pid files into `home` while the collector walked the tree, and CI failed in
24
+ * the `after` hook with `EACCES: Directory not empty` (m05845). Waiting for the
25
+ * exit removes the writer; the bounded retry absorbs a last flush already queued.
26
+ * @param {import('node:child_process').ChildProcess} child the daemon we started.
27
+ * @param {string[]} dirs temp trees to delete.
28
+ */
29
+ async function stopAndClean(child, dirs) {
30
+ const gone = () => child.exitCode === null && child.signalCode === null
31
+ if (gone()) {
32
+ const exited = new Promise((resolve) => child.once('exit', resolve))
33
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
34
+ await Promise.race([exited, sleep(5000)])
35
+ }
36
+ if (gone()) {
37
+ const exited = new Promise((resolve) => child.once('exit', resolve))
38
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
39
+ await Promise.race([exited, sleep(2000)])
40
+ }
41
+ for (const dir of dirs) {
42
+ let lastError = null
43
+ for (let attempt = 0; attempt < 20; attempt += 1) {
44
+ try {
45
+ rmSync(dir, { recursive: true, force: true, maxRetries: 2, retryDelay: 50 })
46
+ lastError = null
47
+ break
48
+ } catch (error) {
49
+ lastError = error
50
+ await sleep(50)
51
+ }
52
+ }
53
+ if (lastError !== null) throw lastError
54
+ }
55
+ }
56
+
18
57
  const CLI = new URL('../bin/risd.mjs', import.meta.url).pathname
19
58
 
20
59
  test('a CLI run without --home resolves the machine home from the environment', async (t) => {
@@ -25,10 +64,8 @@ test('a CLI run without --home resolves the machine home from the environment',
25
64
  env: Object.assign({}, process.env, { DSH_RIS_IDE_PROXY_HOME: home, DSH_RISD_PORT: '0' }),
26
65
  stdio: ['ignore', 'pipe', 'pipe'],
27
66
  })
28
- t.after(() => {
29
- child.kill('SIGTERM')
30
- rmSync(home, { recursive: true, force: true })
31
- rmSync(cwd, { recursive: true, force: true })
67
+ t.after(async () => {
68
+ await stopAndClean(child, [home, cwd])
32
69
  })
33
70
  let stderr = ''
34
71
  child.stderr.setEncoding('utf8')
@@ -1,6 +1,7 @@
1
1
  // 「代理引擎跟随 dsh」 has two halves on ONE signal: the lease. The daemon starts the
2
- // engine when the first lease arrives and tears it down when the last one leaves, so
3
- // the two sides read the same lifecycle.proxy.followDsh and cannot disagree (m13950).
2
+ // engine when the first lease arrives (proxy.startWithDsh) and tears it down when the
3
+ // last one leaves (proxy.stopWithDsh) — two switches, one signal, so the two sides
4
+ // still cannot disagree (m13950 / m03397).
4
5
  // The automatic path must stay non-interactive: a password dialog cannot be a side
5
6
  // effect of dsh starting (m13910) — only a click may ask.
6
7
  import assert from 'node:assert/strict'
@@ -41,8 +42,8 @@ test('a lease never starts an engine when the policy is off or no rule is action
41
42
  await sleep(400)
42
43
  assert.equal(await engine(), 'stopped', 'an empty table is not a reason to spawn an engine')
43
44
 
44
- // Turning the lifecycle off must also turn the start half off.
45
- assert.equal((await save({ lifecycle: { proxy: { followDsh: false } } })).status, 200)
45
+ // Turning the start half off must stop the lease from spawning anything.
46
+ assert.equal((await save({ lifecycle: { proxy: { startWithDsh: false } } })).status, 200)
46
47
  assert.equal((await lease(home)).status, 200)
47
48
  await sleep(400)
48
49
  assert.equal(await engine(), 'stopped', 'a policy that does not follow dsh cannot start it')
@@ -58,7 +59,7 @@ test('the start half rides the lease, not a separate route or plugin call', () =
58
59
  const leaseAt = server.indexOf("if (path === '/v1/leases')")
59
60
  assert.ok(leaseAt > 0)
60
61
  const leaseBlock = server.slice(leaseAt, server.indexOf("const leaseMatch", leaseAt))
61
- assert.match(leaseBlock, /lifecycle\.proxy\.followDsh === true/, 'the same policy the teardown reads')
62
+ assert.match(leaseBlock, /lifecycle\.proxy\.startWithDsh === true/, 'the start half the policy exposes')
62
63
  assert.match(leaseBlock, /followStartForLease\(lease\.cwd\)/, 'the lease is the start signal')
63
64
 
64
65
  const start = server.indexOf('function followStartForLease(')
@@ -78,9 +79,9 @@ test('the start half rides the lease, not a separate route or plugin call', () =
78
79
  assert.match(teardownBlock, /followStarting === null\) return/, 'a pending start must not suppress the teardown schedule')
79
80
  assert.doesNotMatch(server, /'\/v1\/follow-start'/, 'there is no second entry point to keep in sync')
80
81
 
81
- // Teardown reads the same key, so "start follows dsh" and "stop follows dsh" are
82
- // two directions of one policy rather than two switches.
83
- assert.match(server, /if \(lifecycle\.proxy\.followDsh === true\) \{\n\s+await teardownNetwork\(cwd\)/)
82
+ // Teardown reads the other half of the same resource, so "start follows dsh" and
83
+ // "stop follows dsh" cannot disagree about which resource they describe.
84
+ assert.match(server, /if \(lifecycle\.proxy\.stopWithDsh === true\) \{\n\s+await teardownNetwork\(cwd\)/)
84
85
 
85
86
  assert.doesNotMatch(read('lib/risd-client.js'), /followStartRisd/, 'the plugin does not need a call')
86
87
  assert.doesNotMatch(read('lib/index.js'), /followStartRisd/, 'the lease acquired by attachBridgeState is the signal')