dsh-ris-ide 1.8.3 → 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.
package/lib/client.js CHANGED
@@ -269,10 +269,17 @@ window.__ModuleLoader__.load({
269
269
  * `sessionId` can go stale and the host then answers every route with 400.
270
270
  * The host accepts an absolute `cwd` from the client, which is enough to keep
271
271
  * the panel working across a session switch or a `dsh web` restart.
272
+ *
273
+ * ONLY the DSH page writes this slot. The standalone window and the IDE inside
274
+ * the risd-ui tab are separate surfaces with their own workspace in the URL:
275
+ * letting them overwrite the slot made the DSH console open the workspace the
276
+ * embedded IDE happened to switch to (m00173-3). They keep using their own
277
+ * (session, cwd) scope and the per-session keys.
272
278
  * @param {string} value - absolute workspace path.
273
279
  */
274
280
  function rememberWorkspaceCwd(value) {
275
281
  if (typeof value !== 'string' || value === '' || value[0] !== '/') return
282
+ if (typeof window !== 'undefined' && window.__dshRisIdeWindow === true) return
276
283
  try { window.localStorage.setItem(WORKSPACE_CWD_KEY, value) } catch { /* private mode */ }
277
284
  }
278
285
 
@@ -486,16 +493,27 @@ window.__ModuleLoader__.load({
486
493
  * event (same origin, fires in every other window) carries the selected log
487
494
  * path, so starting a program from the console also moves the IDE window's log
488
495
  * pane immediately instead of only when the debug session attaches ~40s later.
496
+ *
497
+ * The broadcast is SCOPED by (sessionId, cwd): two views of two different
498
+ * workspaces must stay independent — a start made in workspace B never moves
499
+ * the console that is showing workspace A (m00173-3).
489
500
  */
490
501
  var LOG_FOCUS_KEY = 'dsh-ris-ide:log-focus'
491
502
 
492
503
  /**
493
504
  * @param {string} logPath - the log the user should now be watching.
505
+ * @param {string} [sessionId] - the session the log belongs to.
506
+ * @param {string} [cwd] - the workspace the log belongs to.
494
507
  */
495
- function broadcastLogFocus(logPath) {
508
+ function broadcastLogFocus(logPath, sessionId, cwd) {
496
509
  if (typeof logPath !== 'string' || logPath === '') return
497
510
  try {
498
- window.localStorage.setItem(LOG_FOCUS_KEY, JSON.stringify({ path: logPath, at: Date.now() }))
511
+ window.localStorage.setItem(LOG_FOCUS_KEY, JSON.stringify({
512
+ path: logPath,
513
+ sessionId: typeof sessionId === 'string' ? sessionId : '',
514
+ cwd: typeof cwd === 'string' ? cwd : '',
515
+ at: Date.now(),
516
+ }))
499
517
  } catch { /* private mode / quota: the broadcast is best-effort */ }
500
518
  }
501
519
 
@@ -558,6 +576,48 @@ window.__ModuleLoader__.load({
558
576
  return true
559
577
  }
560
578
 
579
+ /** Normalised workspace path, for comparing two panels' scopes. */
580
+ function risScopeCwd(value) {
581
+ if (typeof value !== 'string' || value === '') return ''
582
+ return value.replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase()
583
+ }
584
+
585
+ /**
586
+ * Does this subscriber belong to the (Session, workspace) the socket carries?
587
+ *
588
+ * ONE socket has ONE scope, but DSH keeps a `keepMounted` panel body alive
589
+ * across Session switches, so the subscriber set can hold panels from several
590
+ * workspaces at once. The scope used to be picked from whichever panel
591
+ * subscribed first, and every frame was then handed to every subscriber of the
592
+ * topic: the console of workspace A painted B's rows (and after a few switches
593
+ * "内容窜"), because `programs` frames carry a `root` that the handler stored
594
+ * unexamined. Frames for another scope are NOT delivered here — that panel
595
+ * falls back to polling its own scope.
596
+ *
597
+ * A subscriber that names neither a session nor a workspace (the `opens` /
598
+ * `debugs` watchers) is connection-wide and matches every socket.
599
+ *
600
+ * @param {object} sub - the subscription.
601
+ * @param {string} sessionId - session the socket was opened for.
602
+ * @param {string} cwd - workspace the socket was opened for.
603
+ * @returns {boolean} whether the sub may receive this socket's frames.
604
+ */
605
+ function risScopeMatches(sub, sessionId, cwd) {
606
+ var subSession = typeof sub.sessionId === 'string' ? sub.sessionId : ''
607
+ var subCwd = risScopeCwd(sub.cwd)
608
+ var socketSession = typeof sessionId === 'string' ? sessionId : ''
609
+ var socketCwd = risScopeCwd(cwd)
610
+ if (subSession !== '' && socketSession !== '' && subSession !== socketSession) return false
611
+ if (subCwd !== '' && socketCwd !== '' && subCwd !== socketCwd) return false
612
+ return true
613
+ }
614
+
615
+ /** The session the right sidebar is showing RIGHT NOW (document-wide, visible marker only). */
616
+ function liveSidebarSessionOfDocument() {
617
+ var live = liveSidebarSessionId()
618
+ return typeof live === 'string' && live !== '' ? live : ''
619
+ }
620
+
561
621
  /** Subscribe an object `{topics, sessionId?, cwd?, handlers, onOpen?}` to the hub. */
562
622
  function risStreamHub() {
563
623
  if (RIS_STREAM_HUB !== null) return RIS_STREAM_HUB
@@ -566,6 +626,9 @@ window.__ModuleLoader__.load({
566
626
  var signature = ''
567
627
  /** The tail path the CURRENT connection carries ('' when none). */
568
628
  var servedTail = ''
629
+ /** The scope the CURRENT connection carries ('' = unknown / connection-wide). */
630
+ var servedSession = ''
631
+ var servedCwd = ''
569
632
  var rebuildTimer = null
570
633
  var retryTimer = null
571
634
  var retryDelay = 3000
@@ -611,20 +674,33 @@ window.__ModuleLoader__.load({
611
674
  return
612
675
  }
613
676
  var topics = []
614
- var sessionId
615
- var cwd
616
677
  var tail
617
678
  var tailBytes
618
679
  var debugPath
680
+ var firstSession
681
+ var firstCwd
682
+ var activeSession
683
+ var activeCwd
619
684
  subscribers.forEach(function (sub) {
620
685
  ;(sub.topics || []).forEach(function (topic) { if (topics.indexOf(topic) === -1) topics.push(topic) })
621
- if (sessionId === undefined && typeof sub.sessionId === 'string' && sub.sessionId !== '') sessionId = sub.sessionId
622
- if (cwd === undefined && typeof sub.cwd === 'string' && sub.cwd !== '') cwd = sub.cwd
623
- if (cwd === undefined) cwd = knownWorkspaceCwd()
686
+ var subSession = typeof sub.sessionId === 'string' ? sub.sessionId : ''
687
+ var subCwd = typeof sub.cwd === 'string' ? sub.cwd : ''
688
+ if (firstSession === undefined && subSession !== '') firstSession = subSession
689
+ if (firstCwd === undefined && subCwd !== '') firstCwd = subCwd
690
+ // The panel the user is looking at owns the socket. A kept-mounted panel
691
+ // from a previous Session just holds its subscription and polls instead
692
+ // of dragging the connection (and every other panel) to its own scope.
693
+ if (sub.active === true) {
694
+ if (activeSession === undefined && subSession !== '') activeSession = subSession
695
+ if (activeCwd === undefined && subCwd !== '') activeCwd = subCwd
696
+ }
624
697
  if (tail === undefined && typeof sub.tail === 'string' && sub.tail !== '') tail = sub.tail
625
698
  if (tailBytes === undefined && typeof sub.tailBytes === 'number' && sub.tailBytes > 0) tailBytes = sub.tailBytes
626
699
  if (debugPath === undefined && typeof sub.debugPath === 'string' && sub.debugPath !== '') debugPath = sub.debugPath
627
700
  })
701
+ var sessionId = activeSession !== undefined ? activeSession : firstSession
702
+ var cwd = activeCwd !== undefined ? activeCwd : firstCwd
703
+ if (cwd === undefined) cwd = knownWorkspaceCwd()
628
704
  topics.sort()
629
705
  var next = topics.join(',') + '|' + [sessionId || '', cwd || '', tail || '', tailBytes || '', debugPath || ''].join('|')
630
706
  if (source !== null && next === signature) {
@@ -638,6 +714,8 @@ window.__ModuleLoader__.load({
638
714
  closeSource()
639
715
  signature = next
640
716
  servedTail = tail || ''
717
+ servedSession = typeof sessionId === 'string' ? sessionId : ''
718
+ servedCwd = typeof cwd === 'string' ? cwd : ''
641
719
  var url = routeUrl('dsh-ris-ide/stream')
642
720
  url.searchParams.set('topics', topics.join(','))
643
721
  if (sessionId !== undefined) url.searchParams.set('sessionId', sessionId)
@@ -690,6 +768,11 @@ window.__ModuleLoader__.load({
690
768
  var payload
691
769
  try { payload = JSON.parse(event.data) } catch { return }
692
770
  subscribers.forEach(function (sub) {
771
+ // Frames belong to the socket's ONE scope. `stream-error` is a
772
+ // connection-wide report, everything else must match the subscriber's
773
+ // own (session, workspace) — a kept-mounted panel from another Session
774
+ // polls its scope instead of painting this one's rows.
775
+ if (topic !== 'stream-error' && !risScopeMatches(sub, servedSession, servedCwd)) return
693
776
  // A frame does not always belong to its own topic (tail bytes arrive
694
777
  // as `append`): risFrameWanted owns that mapping.
695
778
  if (!risFrameWanted(sub.topics, topic, sub.tail, servedTail)) return
@@ -699,10 +782,17 @@ window.__ModuleLoader__.load({
699
782
  })
700
783
  })
701
784
  }
702
- /** Tell subscribers the connection is up, and WHICH tail it carries. */
785
+ /** Tell subscribers the connection is up, WHICH tail it carries and WHICH scope. */
703
786
  function notifyOpen() {
704
787
  subscribers.forEach(function (sub) {
705
- if (typeof sub.onOpen === 'function') sub.onOpen({ tail: servedTail })
788
+ if (typeof sub.onOpen !== 'function') return
789
+ sub.onOpen({
790
+ tail: servedTail,
791
+ sessionId: servedSession,
792
+ cwd: servedCwd,
793
+ // This panel's scope is not the one on the wire: it must poll, not wait.
794
+ scopeMismatch: !risScopeMatches(sub, servedSession, servedCwd),
795
+ })
706
796
  })
707
797
  }
708
798
  function scheduleRetry() {
@@ -2441,11 +2531,14 @@ window.__ModuleLoader__.load({
2441
2531
  onOpen: function (info) {
2442
2532
  failures = 0
2443
2533
  // The panel shares ONE streaming socket and that socket carries ONE
2444
- // tail path. When the host bound it to another file (another log viewer
2445
- // mounted first), this pane would never see its own file on the stream
2446
- // — poll `/tail` for it instead of waiting forever.
2534
+ // tail path AND one (Session, workspace). When the host bound it to
2535
+ // another file or another workspace (another pane mounted first, or a
2536
+ // kept panel from an older Session still holds the connection), this
2537
+ // pane would never see its own file on the stream — poll `/tail` for it
2538
+ // instead of waiting forever.
2447
2539
  var served = info !== null && info !== undefined && typeof info.tail === 'string' ? info.tail : ''
2448
- setStreamOk(served === '' || served === path)
2540
+ var mismatch = info !== null && info !== undefined && info.scopeMismatch === true
2541
+ setStreamOk(mismatch !== true && (served === '' || served === path))
2449
2542
  },
2450
2543
  onError: function (readyState) {
2451
2544
  failures += 1
@@ -7582,6 +7675,14 @@ window.__ModuleLoader__.load({
7582
7675
  var openProgram = props !== null && props !== undefined && props.openProgram !== null && typeof props.openProgram === 'object' ? props.openProgram : null
7583
7676
  var openLogPath = openProgram !== null && typeof openProgram.logPath === 'string' ? openProgram.logPath : ''
7584
7677
  var visible = props ? props.visible !== false : true
7678
+ /**
7679
+ * The console's 🌐 button. The URL/token work lives in the OWNING panel
7680
+ * (`ProgramsPanel.openSite`) because this component never scans: it only
7681
+ * knows the `programs` array it is handed (m04354/m03945).
7682
+ */
7683
+ var onOpenSite = typeof props.onOpenSite === 'function' ? props.onOpenSite : null
7684
+ var siteBusyId = typeof props.siteBusyId === 'string' ? props.siteBusyId : undefined
7685
+ var ydsProject = props.ydsProject === true
7585
7686
  /** The workspace search box (Ctrl+Alt+F / F3 target outside the editor). */
7586
7687
  var searchInputRef = useRef(null)
7587
7688
  /** The panel root: the boundary of "inside the IDE" for the shortcut shield. */
@@ -7989,6 +8090,14 @@ var [ui, setUi] = useState(function () {
7989
8090
  if (event.key !== LOG_FOCUS_KEY || typeof event.newValue !== 'string' || event.newValue === '') return
7990
8091
  var parsed
7991
8092
  try { parsed = JSON.parse(event.newValue) } catch (error) { return }
8093
+ // The broadcast is scoped: a start made in another workspace must not
8094
+ // move THIS window's log pane (two surfaces, two Sessions — m00173-3).
8095
+ var mineSession = typeof sessionId === 'string' ? sessionId : ''
8096
+ var mineCwd = risScopeCwd(typeof cwd === 'string' ? cwd : '')
8097
+ var theirSession = parsed !== null && typeof parsed.sessionId === 'string' ? parsed.sessionId : ''
8098
+ var theirCwd = risScopeCwd(parsed !== null && typeof parsed.cwd === 'string' ? parsed.cwd : '')
8099
+ if (mineSession !== '' && theirSession !== '' && mineSession !== theirSession) return
8100
+ if (mineCwd !== '' && theirCwd !== '' && mineCwd !== theirCwd) return
7992
8101
  var path = parsed !== null && typeof parsed.path === 'string' ? parsed.path : ''
7993
8102
  if (path === '') return
7994
8103
  var found
@@ -8831,7 +8940,7 @@ var [ui, setUi] = useState(function () {
8831
8940
  // Watch this program's log while it starts: mvn compile is quiet, so the
8832
8941
  // view has to switch at click time, not after the spawn settles.
8833
8942
  selectProgram(program)
8834
- broadcastLogFocus(program.logPath)
8943
+ broadcastLogFocus(program.logPath, sessionId, cwd)
8835
8944
  var logPath = typeof program.logPath === 'string' ? program.logPath : ''
8836
8945
  // Same first-output watch as the debug path. Without it the pane can sit on
8837
8946
  // the wrapper's marker/command line forever: a start's output arrives as
@@ -8874,7 +8983,7 @@ var [ui, setUi] = useState(function () {
8874
8983
  /** Restart one program: the host stops it (pidfile released) then starts it. */
8875
8984
  async function consoleRestart(program) {
8876
8985
  selectProgram(program)
8877
- broadcastLogFocus(program.logPath)
8986
+ broadcastLogFocus(program.logPath, sessionId, cwd)
8878
8987
  var logPath = typeof program.logPath === 'string' ? program.logPath : ''
8879
8988
  var baseline = logPath === '' ? undefined : await logSizeOf(logPath)
8880
8989
  statusNote('正在重启 ' + program.name + '…', 0)
@@ -8928,7 +9037,7 @@ var [ui, setUi] = useState(function () {
8928
9037
  setConsoleBusyKind(kind)
8929
9038
  if (kind === 'start') {
8930
9039
  selectProgram(targets[index])
8931
- broadcastLogFocus(targets[index].logPath)
9040
+ broadcastLogFocus(targets[index].logPath, sessionId, cwd)
8932
9041
  }
8933
9042
  try {
8934
9043
  var result = kind === 'start'
@@ -8952,7 +9061,7 @@ var [ui, setUi] = useState(function () {
8952
9061
  }
8953
9062
  async function consoleDebug(program) {
8954
9063
  selectProgram(program)
8955
- broadcastLogFocus(program.logPath)
9064
+ broadcastLogFocus(program.logPath, sessionId, cwd)
8956
9065
  sourcePathRef.current = {}
8957
9066
  setDbg(function () { return { attached: false, port: null, suspended: false, suspendedThreads: [], currentThreadId: null, seq: 0, events: [], breakpoints: globalBreakpointsSnapshot(), threads: [], frames: [], variables: [], missingSource: null, lastError: null } })
8958
9067
  setUi(function (prev) { return Object.assign({}, prev, { busy: true, note: '正在以调试模式重启 ' + program.name + '(Spring 约 40–55s)…' }) })
@@ -9230,7 +9339,7 @@ var [ui, setUi] = useState(function () {
9230
9339
  setActivePath(logPath)
9231
9340
  activePathRef.current = logPath
9232
9341
  }
9233
- broadcastLogFocus(logPath)
9342
+ broadcastLogFocus(logPath, sessionId, cwd)
9234
9343
  }
9235
9344
  var baseline = logPath === '' ? undefined : await logSizeOf(logPath)
9236
9345
  setUi(function (prev) { return Object.assign({}, prev, { busy: true, note: '正在以调试模式重启(Spring 约 40–55s)…' }) })
@@ -10741,6 +10850,19 @@ var [ui, setUi] = useState(function () {
10741
10850
  alive ? button(stopGlyph(11), function (event) { event.stopPropagation(); void consoleStop(program) }, { icon: true, width: 25, stop: true, action: 'console-stop', title: '停止 ' + program.name }) : null,
10742
10851
  // ⟳ shares ▶'s green: both (re)start the program, only ■ is red.
10743
10852
  startable ? button('⟳', function (event) { event.stopPropagation(); void consoleRestart(program) }, { icon: true, width: 25, start: true, action: 'console-restart', title: '重启 ' + program.name }) : null,
10853
+ // The IDE console has the same 🌐 as the sidebar console (m03945):
10854
+ // only a frontend serves a page, and only the owning panel can ask
10855
+ // the host where that page is (m04354).
10856
+ program.kind === 'frontend'
10857
+ ? button(siteBusyId === program.id ? '…' : '🌐', function (event) {
10858
+ event.stopPropagation()
10859
+ if (onOpenSite !== null) onOpenSite(program)
10860
+ }, {
10861
+ icon: true, width: 25, off: true, disabled: siteBusyId === program.id, action: 'console-open-site',
10862
+ title: '在系统浏览器打开 ' + program.name + ' 的页面'
10863
+ + (ydsProject ? '(yds 项目:请求自动带上登录 token,免登录)' : ''),
10864
+ })
10865
+ : null,
10744
10866
  program.kind === 'spring' ? button(ideBadgeIcon('bug', 'play', 13), function (event) { event.stopPropagation(); void consoleDebug(program) }, { icon: true, width: 25, debug: true, off: ui.busy, action: 'console-debug', title: '调试 ' + program.name }) : null,
10745
10867
  busy
10746
10868
  ? h('div', {
@@ -14141,21 +14263,12 @@ var [ui, setUi] = useState(function () {
14141
14263
  return { loading: true, programs: [], root: undefined, dir: undefined, config: undefined, error: undefined, note: prev.note }
14142
14264
  })
14143
14265
  }, [sessionIdentity, cwd])
14144
- // A workspace switch opens a blank DSH session, and a sidebar layout is stored
14145
- // per session — so the blank one has no IDE tab and the panel would sit on an
14146
- // empty pane. Put the tab back on the new session. Capability-checked: hosts
14147
- // without the right-Sidebar service keep working (nothing happens).
14148
- useEffect(function () {
14149
- if (sessionIdentity === '' || props.compact !== true) return
14150
- var sidebar = props.clientCtx !== null && props.clientCtx !== undefined ? props.clientCtx.sidebarRight : undefined
14151
- if (sidebar === undefined || sidebar === null || typeof sidebar.openTab !== 'function') return
14152
- try {
14153
- sidebar.openTab(IDE_TAB_KIND)
14154
- } catch (error) {
14155
- // A host that refuses the tab kind must not break the switch itself.
14156
- void error
14157
- }
14158
- }, [sessionIdentity])
14266
+ // NOTE: this panel must NOT open its own sidebar tab. `openTab()` expands the
14267
+ // sidebar column (a session starts collapsed and empty by design), so doing
14268
+ // it on every session change is what made the console pop open by itself at
14269
+ // the start of a session. The tab is opened by user actions only
14270
+ // (`openIdeTab` from the header/⧉/log routes); a session with no layout yet
14271
+ // simply keeps the panel closed until the user asks for it.
14159
14272
  /** Warm the compact ⧉'s address; a fresh cache makes the click synchronous. */
14160
14273
  function warmCompactRisd() {
14161
14274
  if (typeof sessionId !== 'string' || sessionId === '') return
@@ -14324,9 +14437,17 @@ var [ui, setUi] = useState(function () {
14324
14437
  topics: ['programs'],
14325
14438
  sessionId: sessionId,
14326
14439
  cwd: typeof cwd === 'string' ? cwd : undefined,
14327
- onOpen: function () {
14440
+ // The shared socket serves ONE scope: the console the user is looking at.
14441
+ // A kept-mounted body of another Session stays subscribed but must not
14442
+ // pull the connection (and every panel) to its own workspace.
14443
+ active: typeof sessionId === 'string' && sessionId !== '' && sessionId === liveSidebarSessionOfDocument(),
14444
+ onOpen: function (info) {
14328
14445
  failures = 0
14329
- setStreamOk(true)
14446
+ // The socket carries another panel's scope: poll our own instead of
14447
+ // sitting on rows that will never arrive.
14448
+ var mismatch = info !== null && info !== undefined && info.scopeMismatch === true
14449
+ setStreamOk(mismatch !== true)
14450
+ if (mismatch === true) void refresh(false)
14330
14451
  },
14331
14452
  onError: function (readyState) {
14332
14453
  failures += 1
@@ -14334,6 +14455,15 @@ var [ui, setUi] = useState(function () {
14334
14455
  },
14335
14456
  handlers: {
14336
14457
  programs: function (payload) {
14458
+ // Defence in depth: a frame naming another workspace must never paint
14459
+ // this session's console (the hub already filters by scope, but this
14460
+ // handler is where the rows and the tree root are stored).
14461
+ if (cwdKnown === true && typeof cwd === 'string' && cwd !== '' &&
14462
+ payload !== null && payload !== undefined && typeof payload.root === 'string' && payload.root !== '' &&
14463
+ risScopeCwd(payload.root) !== risScopeCwd(cwd)) {
14464
+ void refresh(false)
14465
+ return
14466
+ }
14337
14467
  setState(function (prev) {
14338
14468
  return {
14339
14469
  loading: false,
@@ -14401,7 +14531,7 @@ var [ui, setUi] = useState(function () {
14401
14531
  setBusyKind(kind)
14402
14532
  if (kind === 'start') {
14403
14533
  setActive(targets[index])
14404
- broadcastLogFocus(targets[index].logPath)
14534
+ broadcastLogFocus(targets[index].logPath, sessionId, cwd)
14405
14535
  }
14406
14536
  var scopeArg = { sessionId: sessionId, cwd: cwd }
14407
14537
  var result
@@ -14438,7 +14568,7 @@ var [ui, setUi] = useState(function () {
14438
14568
  // Show this program's log from the first moment: the start call waits for
14439
14569
  // a pidfile (up to START_WAIT_MS), and Maven compile is silent. The same
14440
14570
  // event moves the standalone IDE window's log pane right away.
14441
- if (boots) { setActive(program); broadcastLogFocus(program.logPath); setCompactLogNonce(function (value) { return value + 1 }) }
14571
+ if (boots) { setActive(program); broadcastLogFocus(program.logPath, sessionId, cwd); setCompactLogNonce(function (value) { return value + 1 }) }
14442
14572
  var scopeArg = { sessionId: sessionId, cwd: cwd }
14443
14573
  var task = kind === 'stop'
14444
14574
  ? requestStop(program.logPath, scopeArg)
@@ -15067,6 +15197,12 @@ var [ui, setUi] = useState(function () {
15067
15197
  // The row the window was opened on (sidebar 🐞): seeds the log pane and
15068
15198
  // turns on auto-debug. `null` = plain workspace window.
15069
15199
  openProgram: active !== null && active !== undefined && typeof active === 'object' ? active : null,
15200
+ // The IDE console renders the same 🌐 as the sidebar rows: the URL/token
15201
+ // resolution and the "one tab at a time" guard stay HERE (this panel owns
15202
+ // the fetch and the note bar), the workbench only draws the button.
15203
+ onOpenSite: openSite,
15204
+ siteBusyId: busySiteId,
15205
+ ydsProject: ydsProject,
15070
15206
  tab: {
15071
15207
  id: PROGRAM_TAB_ID,
15072
15208
  type: PROGRAM_TAB_ID,
package/lib/index.js CHANGED
@@ -3969,9 +3969,11 @@ function describe(error) {
3969
3969
  /**
3970
3970
  * Resolve the URL "open in browser" should use for one program.
3971
3971
  *
3972
- * Two sources, in this order: the dev-server URL the program printed into its own
3973
- * log (webpack/vite always do), then dsh-ris-yds' injecting proxy — which is only
3974
- * used when that plugin answers, so ris-ide keeps working without it.
3972
+ * The dev-server URL the program printed into its own log (webpack/vite always do)
3973
+ * is the answer. dsh-ris-yds may then wrap it — but ONLY when the program is one of
3974
+ * the yds front-ends the workspace declares, and it is told which one (m00555);
3975
+ * otherwise the page opens directly (m00462). A missing/failing yds plugin never
3976
+ * blocks the button: ris-ide keeps working without it.
3975
3977
  */
3976
3978
  async function serveOpenTarget(ctx, req, res, options) {
3977
3979
  try {
@@ -3994,19 +3996,20 @@ async function serveOpenTarget(ctx, req, res, options) {
3994
3996
  })
3995
3997
  return
3996
3998
  }
3997
- // Preferred path for a yds project: yds starts its private debugging browser
3998
- // (extension preloaded, CDP on). The page there carries rdbga, so its requests
3999
- // reach the local backend; the old loopback proxy only rewrites the bundles.
4000
- const debug = await askYdsToWrap(req, cwd, devUrl, { mode: 'debug' })
4001
- if (debug !== null && debug.ok === true && debug.mode === 'debug') {
4002
- writeJson(res, 200, debug)
4003
- return
4004
- }
4005
- const wrapped = await askYdsToWrap(req, cwd, devUrl)
4006
- if (wrapped !== null) {
4007
- if (wrapped.ok === true) writeJson(res, 200, wrapped)
4008
- else writeJson(res, 200, { ok: false, code: wrapped.code ?? 'yds', message: wrapped.reason ?? 'dsh-ris-yds 无法代理这个地址' })
4009
- return
3999
+ // The 🌐 button opens the dev-server page the program printed. That page is
4000
+ // enough on its own; dsh-ris-yds is asked ONLY for a program that IS a yds
4001
+ // frontend, and it is told WHICH frontend: `yds.webConfig` declares one entry
4002
+ // per front-end project with its own port, and injecting another entry's rules
4003
+ // opens a page that talks to the wrong dev server (m00555). A plain npm app, a
4004
+ // spring program, or an unlisted frontend opens directly — no proxy, no
4005
+ // private browser (m00462), and a yds refusal is not an error.
4006
+ const frontend = program.kind === 'frontend' ? await ydsFrontendOf(req, cwd, program) : null
4007
+ if (frontend !== null) {
4008
+ const wrapped = await askYdsToWrap(req, cwd, devUrl, frontend)
4009
+ if (wrapped !== null && wrapped.ok === true && typeof wrapped.url === 'string') {
4010
+ writeJson(res, 200, { ...wrapped, source: 'yds' })
4011
+ return
4012
+ }
4010
4013
  }
4011
4014
  writeJson(res, 200, { ok: true, url: devUrl, source: 'dev-server' })
4012
4015
  } catch (error) {
@@ -4027,10 +4030,62 @@ async function findProgramById(cwd, logsDir, ref) {
4027
4030
  }
4028
4031
 
4029
4032
  /**
4030
- * Ask dsh-ris-yds to serve this URL through its injecting proxy.
4033
+ * The yds front-end project identity of one program, or null when it is not one.
4034
+ *
4035
+ * `yds.webConfig` is keyed by the front-end project's directory name, and the
4036
+ * program's own directory basename is that project. Asking the probe first keeps
4037
+ * the rule honest: a plain npm app, the backend module, or a frontend the
4038
+ * workspace never declared as a yds frontend must NOT be proxied at all.
4039
+ * @returns {Promise<{code: string, name: string, relDir: string}|null>}
4040
+ */
4041
+ async function ydsFrontendOf(req, cwd, program) {
4042
+ const dir = typeof program.dir === 'string' ? program.dir : ''
4043
+ if (dir === '') return null
4044
+ const code = basename(dir)
4045
+ if (code === '') return null
4046
+ const probe = await askYdsProbe(req, cwd)
4047
+ if (probe === null || probe.yds !== true) return null
4048
+ const frontends = Array.isArray(probe.frontends) ? probe.frontends : []
4049
+ if (frontends.indexOf(code) === -1) return null
4050
+ return {
4051
+ code,
4052
+ name: typeof program.name === 'string' && program.name !== '' ? program.name : code,
4053
+ relDir: typeof program.relDir === 'string' ? program.relDir : '',
4054
+ }
4055
+ }
4056
+
4057
+ /** One short JSON answer from a sibling plugin route, or null when it is not there. */
4058
+ async function askPluginJson(req, path, timeoutMs) {
4059
+ const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4060
+ if (host === '') return null
4061
+ const controller = new AbortController()
4062
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
4063
+ try {
4064
+ const response = await fetch(`http://${host}${path}`, {
4065
+ headers: { accept: 'application/json' },
4066
+ signal: controller.signal,
4067
+ })
4068
+ if (response.status === 404) return null
4069
+ const parsed = await response.json().catch(() => null)
4070
+ return parsed === null || typeof parsed !== 'object' ? null : parsed
4071
+ } catch {
4072
+ return null
4073
+ } finally {
4074
+ clearTimeout(timer)
4075
+ }
4076
+ }
4077
+
4078
+ /** Ask dsh-ris-yds which front-ends this workspace declares (`null` = plugin absent). */
4079
+ async function askYdsProbe(req, cwd) {
4080
+ return askPluginJson(req, `/dsh-ris-yds/probe?workspace=${encodeURIComponent(cwd)}`, 5000)
4081
+ }
4082
+
4083
+ /**
4084
+ * Ask dsh-ris-yds to serve this URL through its injecting proxy for ONE frontend.
4085
+ * @param {object} frontend - `{code, name, relDir}` of the yds front-end program.
4031
4086
  * @returns {Promise<object|null>} the yds answer, or null when the plugin is absent.
4032
4087
  */
4033
- async function askYdsToWrap(req, cwd, devUrl, options = {}) {
4088
+ async function askYdsToWrap(req, cwd, devUrl, frontend) {
4034
4089
  const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4035
4090
  if (host === '') return null
4036
4091
  const controller = new AbortController()
@@ -4039,7 +4094,7 @@ async function askYdsToWrap(req, cwd, devUrl, options = {}) {
4039
4094
  const response = await fetch(`http://${host}/dsh-ris-yds/open`, {
4040
4095
  method: 'POST',
4041
4096
  headers: { 'content-type': 'application/json' },
4042
- body: JSON.stringify({ workspace: cwd, devUrl, ...(options.mode === 'debug' ? { mode: 'debug' } : {}) }),
4097
+ body: JSON.stringify({ workspace: cwd, devUrl, frontend }),
4043
4098
  signal: controller.signal,
4044
4099
  })
4045
4100
  if (response.status === 404) return null
@@ -118,9 +118,18 @@ function dshSidebarRows(sidebar, windows, origin) {
118
118
  const window = remembered.get(cwd)
119
119
  if (window !== undefined) remembered.delete(cwd)
120
120
  const title = typeof entry.title === 'string' ? entry.title : ''
121
- const sessionId = typeof entry.sessionId === 'string' && entry.sessionId !== ''
122
- ? entry.sessionId
123
- : (window === undefined ? '' : window.sessionId)
121
+ // Which Session should the IDE bind to? The sidebar mirror names the session
122
+ // DSH associates with the workspace, but a remembered window row names the
123
+ // session that actually refreshed this workspace LAST — validated by the
124
+ // plugin (its header.cwd === row.cwd, else the row is dropped). Preferring
125
+ // the live window session keeps the row's sessionId stable while the page is
126
+ // open: mixing the two ids across `/v1/dsh` polls made the maintenance page
127
+ // rewrite the iframe URL (cwd|sessionId signature) and reload the IDE — the
128
+ // "切换工作区加载错误 / 内容窜" symptom (m00001-2). The sidebar value stays as
129
+ // the fallback for a workspace nobody opened yet.
130
+ const sessionId = window !== undefined && typeof window.sessionId === 'string' && window.sessionId !== ''
131
+ ? window.sessionId
132
+ : (typeof entry.sessionId === 'string' ? entry.sessionId : '')
124
133
  rows.push({
125
134
  cwd,
126
135
  title: title !== '' ? title : (window === undefined ? '' : window.title),
@@ -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.3",
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": [
@@ -3516,6 +3516,54 @@ test('only a FRONTEND row offers the browser button, and only a yds project prom
3516
3516
  assert.doesNotMatch(source, /yds 项目会自动注入 YYCToken/, 'the old unconditional yds wording is gone')
3517
3517
  })
3518
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
+
3519
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 }, () => {
3520
3568
  const markup = renderWorkbenchWithFile('/w/README.md')
3521
3569
  const tag = (markup.match(/<button[^>]*data-action="reload-file"[^>]*>/) || [''])[0]
@@ -4553,9 +4601,9 @@ test('a start switches to that program log before waiting for the spawn', async
4553
4601
  // block for START_WAIT_MS, and Maven compile prints nothing for tens of seconds.
4554
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\)/)
4555
4603
  // The sidebar rows do the same before awaiting requestStart.
4556
- 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/)
4557
4605
  // …and every window watching another log is moved by the same broadcast.
4558
- assert.match(source, /function broadcastLogFocus\(logPath\)/)
4606
+ assert.match(source, /function broadcastLogFocus\(logPath, sessionId, cwd\)/)
4559
4607
  })
4560
4608
 
4561
4609
  test('the debug pane has a visual settings dialog for dependency sources', { skip: !reactIsReal ? 'React unavailable for SSR' : false }, async () => {
@@ -4614,7 +4662,7 @@ test('debug start switches the log pane first, and the variable caret is borderl
4614
4662
  assert.match(slice, /setLogNonce\(function \(value\) \{ return value \+ 1 \}\)/)
4615
4663
  // The switch follows the user into other windows, and the tail is re-read the
4616
4664
  // moment the restarted service prints its first byte (Maven is quiet).
4617
- assert.match(slice, /broadcastLogFocus\(logPath\)/)
4665
+ assert.match(slice, /broadcastLogFocus\(logPath, sessionId, cwd\)/)
4618
4666
  assert.match(slice, /watchLogOutput\(logPath, baseline\)/)
4619
4667
  // Tree caret: glyph only, no bordered button box.
4620
4668
  assert.match(source, /var caretStyle = \{[\s\S]{0,400}?border: 'none'/)
@@ -5006,7 +5054,7 @@ test('the editor scrollbars are visible and a start re-reads its log', async ()
5006
5054
  assert.match(source, /SELECTION_CSS \+ SCROLLBAR_CSS \+ SEARCH_PANEL_CSS \+ TOAST_CSS/, 'injected with the panel styles')
5007
5055
  assert.doesNotMatch(source, /SCROLLBAR_CSS[\s\S]{0,800}?scrollbar-gutter/, 'no empty gutter on files that do not overflow')
5008
5056
  // BUG6: a start records a size baseline and watches for its first new byte …
5009
- 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')
5010
5058
  assert.match(source, /async function consoleStart\(program\) \{[\s\S]{0,2400}?watchLogOutput\(logPath, baseline\)/, 'and watches the first new byte')
5011
5059
  // … a pane mounting on an already-open socket reads its tail once …
5012
5060
  assert.match(source, /if \(typeof EventSource !== 'function'\) return\n\s*void refresh\(\)/, 'first paint reads the tail')
@@ -5014,7 +5062,7 @@ test('the editor scrollbars are visible and a start re-reads its log', async ()
5014
5062
  // polls instead of waiting on someone else's stream.
5015
5063
  assert.match(source, /var servedTail = ''/, 'the connection remembers its tail path')
5016
5064
  assert.match(source, /notifyOpen\(\)/)
5017
- 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')
5018
5066
  assert.match(source, /setCompactLogNonce\(function \(value\) \{ return value \+ 1 \}\)/, 'the sidebar pane re-reads after start/stop')
5019
5067
  // … and the host never drops a delta without re-snapshotting.
5020
5068
  const host = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
@@ -409,6 +409,28 @@ test('/v1/dsh drops unusable `at` values and counts them (review A3-P2-6)', asyn
409
409
  assert.equal(body.dropped, 3, 'every unusable timestamp is reported, not silently pruned')
410
410
  })
411
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
+
412
434
  test('/v1/dsh probes a live host when no usable snapshot exists (m00186)', async (t) => {
413
435
  // The daemon cannot read dsh's own API (its launch token lives in dsh's memory), so
414
436
  // the plugin advertises one `instances/dsh-<pid>.json` per running host. When the