ui.html 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039
  1. <!doctype html>
  2. <html data-theme="dark">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>sm121</title>
  7. <style>
  8. :root[data-theme="dark"] {
  9. --bg: #0d1117; --panel: #161b22; --fg: #e6edf3; --muted: #8b949e;
  10. --border: #30363d; --accent: #58a6ff; --shade: rgba(0,0,0,.55);
  11. /* monospace content (raw/logs/jobs/node names) — the Alacritty font (~/.alacritty.toml) */
  12. --mono: "DMMono Nerd Font", Menlo, ui-monospace, SFMono-Regular, monospace;
  13. --led-on: #3fb950; --led-off: #f85149; --led-busy: #d29922; --led-free: #30363d;
  14. --glow-on: 0 0 8px 2px rgba(63,185,80,.55); --glow-busy: 0 0 8px 2px rgba(210,153,34,.55);
  15. --btn: #21262d; --btn-hover: #30363d;
  16. }
  17. :root[data-theme="light"] {
  18. --bg: #f6f8fa; --panel: #ffffff; --fg: #1f2328; --muted: #656d76;
  19. --border: #d0d7de; --accent: #0969da; --shade: rgba(31,35,40,.20);
  20. --mono: "DMMono Nerd Font", Menlo, ui-monospace, SFMono-Regular, monospace;
  21. --led-on: #1a7f37; --led-off: #cf222e; --led-busy: #9a6700; --led-free: #8c959f;
  22. --glow-on: 0 0 8px 2px rgba(26,127,55,.35); --glow-busy: 0 0 8px 2px rgba(154,103,0,.35);
  23. --btn: #f6f8fa; --btn-hover: #eaeef2;
  24. }
  25. * { box-sizing: border-box; }
  26. html, body { height: 100%; }
  27. body {
  28. margin: 0; background: var(--bg); color: var(--fg);
  29. font: 14px/1.45 ui-sans-serif, system-ui, "SF Pro", sans-serif;
  30. display: flex; flex-direction: column;
  31. transition: background .25s, color .25s;
  32. }
  33. header {
  34. display: flex; align-items: center; gap: 12px;
  35. padding: 10px 16px; border-bottom: 1px solid var(--border);
  36. background: var(--panel); position: sticky; top: 0; z-index: 5;
  37. }
  38. header h1 { font-size: 15px; margin: 0; font-weight: 650; letter-spacing: .3px; }
  39. header .spacer { flex: 1; }
  40. .ssec { font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
  41. .ssec .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--led-off); }
  42. .ssec.ok .dot { background: var(--led-on); }
  43. .ssec.re .dot { animation: pulse 1s infinite; }
  44. button.tbtn {
  45. background: var(--btn); color: var(--fg); border: 1px solid var(--border);
  46. border-radius: 6px; padding: 4px 10px; cursor: pointer; font: inherit; font-size: 13px;
  47. }
  48. button.tbtn:hover { background: var(--btn-hover); }
  49. /* --- window manager ------------------------------------------------------ */
  50. #winlayer { position: relative; flex: 1; overflow: hidden; }
  51. .win {
  52. position: absolute; background: var(--panel); border: 1px solid var(--border);
  53. border-radius: 10px; display: flex; flex-direction: column;
  54. box-shadow: 0 6px 24px rgba(0,0,0,.35); animation: winIn .3s ease both;
  55. }
  56. /* maximized: the frame disappears and the window IS the layer; its title
  57. moves into the header (with a restore button) */
  58. .win.max { border: 0; border-radius: 0; box-shadow: none; }
  59. .win.max .win-bar, .win.max .win-resize { display: none; }
  60. /* `display: flex` would override the `hidden` attribute (whose UA rule is
  61. just `display: none`) — guard it, like .dlg-back does */
  62. #maxinfo { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--muted); }
  63. #maxinfo[hidden] { display: none; }
  64. #maxinfo .maxtitle { color: var(--fg); font-weight: 600; }
  65. #maxinfo .wbtn { width: 22px; height: 20px; font-size: 12px; }
  66. .win-bar {
  67. display: flex; align-items: center; gap: 6px; padding: 7px 10px;
  68. border-bottom: 1px solid var(--border); cursor: grab; user-select: none;
  69. font-size: 12px; text-transform: uppercase; letter-spacing: .6px; color: var(--muted);
  70. flex-shrink: 0;
  71. }
  72. .win-bar:active { cursor: grabbing; }
  73. .win-bar .wtitle { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  74. .wbtn {
  75. background: none; border: 1px solid transparent; color: var(--muted);
  76. border-radius: 5px; width: 20px; height: 18px; cursor: pointer; font: inherit; font-size: 12px;
  77. line-height: 1; padding: 0;
  78. }
  79. .wbtn:hover { background: var(--btn-hover); color: var(--fg); }
  80. .win-body { flex: 1; overflow: auto; padding: 12px 14px; }
  81. .win-resize {
  82. position: absolute; right: 0; bottom: 0; width: 14px; height: 14px; cursor: nwse-resize;
  83. background: linear-gradient(135deg, transparent 50%, var(--border) 50%);
  84. }
  85. #dock {
  86. display: flex; gap: 6px; align-items: center; padding: 6px 12px;
  87. border-top: 1px solid var(--border); background: var(--panel); min-height: 34px; flex-shrink: 0;
  88. }
  89. #dock:empty { display: none; }
  90. .dock-chip {
  91. background: var(--btn); color: var(--muted); border: 1px solid var(--border);
  92. border-radius: 999px; padding: 2px 10px; font-size: 12px; cursor: pointer; font: inherit;
  93. }
  94. .dock-chip:hover { color: var(--fg); border-color: var(--accent); }
  95. /* --- cluster board ------------------------------------------------------- */
  96. .cluster.anim { animation: winIn .35s ease both; }
  97. .cluster { margin-bottom: 14px; }
  98. .cluster-head { display: flex; align-items: baseline; gap: 8px; margin-bottom: 6px; }
  99. .cluster-head b { font-size: 13px; }
  100. .cluster-head .free { color: var(--muted); font-size: 12px; }
  101. .cluster-head .down { color: var(--led-off); font-size: 12px; }
  102. .cluster-head .soft { color: var(--led-busy); font-size: 12px; }
  103. .node {
  104. display: flex; align-items: center; gap: 10px; padding: 5px 0;
  105. border-bottom: 1px solid var(--border); cursor: pointer;
  106. }
  107. .node:hover { background: var(--btn); }
  108. .node:last-child { border-bottom: none; }
  109. .led {
  110. width: 11px; height: 11px; border-radius: 50%; background: var(--led-off);
  111. transition: background .4s, box-shadow .4s; flex-shrink: 0;
  112. }
  113. .led.on { background: var(--led-on); box-shadow: var(--glow-on); }
  114. .led.b { background: var(--led-busy); box-shadow: var(--glow-busy); }
  115. .led.off { background: var(--led-off); }
  116. .led.flip { animation: flip .45s ease; }
  117. .nname { width: 64px; font-family: var(--mono); font-size: 12.5px; }
  118. .nmeta { color: var(--muted); font-size: 12px; flex: 1; overflow: hidden; text-overflow: ellipsis; }
  119. .containers { width: 100%; margin-top: 2px; }
  120. .crow { display: flex; align-items: center; gap: 8px; padding: 2px 0 2px 21px; font-size: 12px; color: var(--muted); }
  121. .cled { width: 7px; height: 7px; border-radius: 50%; background: var(--led-busy); box-shadow: var(--glow-busy); flex-shrink: 0; }
  122. .cname { font-family: var(--mono); color: var(--fg); }
  123. .actions { display: flex; gap: 8px; align-items: center; margin: 6px 0 0 21px; flex-wrap: wrap; }
  124. .actions select { font: inherit; }
  125. .actions input[type=checkbox] {
  126. appearance: none; -webkit-appearance: none;
  127. width: 15px; height: 15px; margin: 0; flex-shrink: 0;
  128. border: 1.5px solid var(--border); border-radius: 4px; background: var(--btn);
  129. cursor: pointer; position: relative; transition: background .15s, border-color .15s;
  130. }
  131. .actions input[type=checkbox]:hover { border-color: var(--accent); }
  132. .actions input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
  133. .actions input[type=checkbox]:checked::after {
  134. content: ""; position: absolute; left: 3.5px; top: 0;
  135. width: 4px; height: 8px; border: solid #fff; border-width: 0 2px 2px 0;
  136. transform: rotate(45deg);
  137. }
  138. .actions select {
  139. background: var(--btn); color: var(--fg); border: 1px solid var(--border);
  140. border-radius: 6px; padding: 2px 6px; font-size: 12.5px; max-width: 260px; height: 26px;
  141. }
  142. .actions label { font-size: 12px; color: var(--muted); display: inline-flex; align-items: center; gap: 4px; height: 26px; }
  143. .actions label input { margin: 0; }
  144. .strip { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--border); }
  145. .chip {
  146. display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none;
  147. border: 1px solid var(--border); border-radius: 999px; padding: 3px 10px; font-size: 12px;
  148. color: var(--muted); background: var(--btn); transition: border-color .15s, color .15s;
  149. }
  150. .chip .m { opacity: .7; }
  151. .chip.active { color: var(--fg); border-color: var(--accent); }
  152. .abtn {
  153. background: var(--btn); color: var(--fg); border: 1px solid var(--border);
  154. border-radius: 6px; padding: 0 12px; cursor: pointer; font: inherit; font-size: 12.5px;
  155. height: 26px; transition: background .15s;
  156. }
  157. .abtn:hover:not(:disabled) { background: var(--btn-hover); }
  158. .abtn:disabled { opacity: .45; cursor: default; }
  159. .abtn.danger { color: var(--led-off); }
  160. .jobs { font-family: var(--mono); font-size: 12px; }
  161. .job { display: flex; gap: 8px; align-items: baseline; padding: 4px 0; border-bottom: 1px solid var(--border); }
  162. .job.new { animation: winIn .3s ease both; }
  163. .job:last-child { border-bottom: none; }
  164. .jdot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex-shrink: 0; align-self: center; }
  165. .job.ok .jdot { background: var(--led-on); }
  166. .job.failed .jdot { background: var(--led-off); }
  167. .jkind { width: 48px; color: var(--muted); }
  168. .jmsg { color: var(--muted); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  169. .jjob .jmsg { color: var(--fg); }
  170. .jobs-empty { color: var(--muted); font-size: 12.5px; padding: 6px 0; }
  171. /* --- log windows ---------------------------------------------------------- */
  172. .logwin .win-body { display: flex; flex-direction: column; padding: 0; }
  173. .logbar {
  174. display: flex; gap: 8px; align-items: center; padding: 8px 10px;
  175. border-bottom: 1px solid var(--border); flex-shrink: 0; flex-wrap: wrap;
  176. }
  177. .logbar select {
  178. background: var(--btn); color: var(--fg); border: 1px solid var(--border);
  179. border-radius: 6px; padding: 2px 6px; font-size: 12px; max-width: 300px; height: 26px;
  180. }
  181. .logbar label { font-size: 12px; color: var(--muted); display: inline-flex; gap: 4px; align-items: center; }
  182. .logbar input[type=checkbox] {
  183. appearance: none; -webkit-appearance: none; width: 15px; height: 15px; margin: 0;
  184. border: 1.5px solid var(--border); border-radius: 4px; background: var(--btn);
  185. cursor: pointer; position: relative;
  186. }
  187. .logbar input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
  188. .logbar input[type=checkbox]:checked::after {
  189. content: ""; position: absolute; left: 3.5px; top: 0;
  190. width: 4px; height: 8px; border: solid #fff; border-width: 0 2px 2px 0;
  191. transform: rotate(45deg);
  192. }
  193. .lognote { font-size: 12px; color: var(--muted); flex: 1; }
  194. .lognote.dead { color: var(--led-busy); }
  195. .logpre {
  196. flex: 1; margin: 0; padding: 10px 12px; overflow: auto;
  197. font: 11.5px/1.5 var(--mono); white-space: pre-wrap;
  198. word-break: break-word; color: var(--fg);
  199. }
  200. /* --- raw content windows --------------------------------------------------- */
  201. .rawwin .win-body { display: flex; flex-direction: column; padding: 0; }
  202. .recwin .win-body { padding: 0; }
  203. .recwin iframe { width: 100%; height: 100%; border: 0; display: block; background: var(--panel); }
  204. /* the embedded report page resolves `color-scheme: light dark` from this
  205. element, so it follows the dashboard theme instead of the OS one */
  206. :root[data-theme="dark"] .recwin iframe { color-scheme: dark; }
  207. :root[data-theme="light"] .recwin iframe { color-scheme: light; }
  208. .rawbar {
  209. display: flex; gap: 8px; align-items: center; padding: 8px 10px;
  210. border-bottom: 1px solid var(--border); flex-shrink: 0;
  211. }
  212. .rawbar select {
  213. background: var(--btn); color: var(--fg); border: 1px solid var(--border);
  214. border-radius: 6px; padding: 2px 6px; font-size: 12px; max-width: 320px; height: 26px;
  215. }
  216. .rawbar .abtn { height: 26px; }
  217. .rawnote { font-size: 12px; color: var(--muted); flex: 1; }
  218. /* --- polish: skeleton + attention ------------------------------------------ */
  219. .skeleton { height: 14px; border-radius: 6px; margin: 10px 0;
  220. background: linear-gradient(90deg, var(--btn) 25%, var(--btn-hover) 50%, var(--btn) 75%);
  221. background-size: 200% 100%; animation: shimmer 1.2s infinite; }
  222. @keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
  223. .cled.exited { background: var(--led-off); box-shadow: 0 0 8px 2px rgba(248,81,73,.5); animation: pulse 1.2s infinite; }
  224. .abtn:disabled { animation: pulse 1.2s infinite; }
  225. .job.jjob .jdot { animation: pulse 1.2s infinite; }
  226. /* --- serve flags (CLI parity) + node logs button + dock menu ---------------- */
  227. .fnode {
  228. background: var(--btn); color: var(--muted); border: 1px solid var(--border);
  229. border-radius: 6px; padding: 2px 6px; font-size: 12px; height: 26px; max-width: 140px;
  230. }
  231. .flags summary {
  232. cursor: pointer; font-size: 12px; color: var(--muted); height: 26px;
  233. display: inline-flex; align-items: center; padding: 0 8px;
  234. border: 1px dashed var(--border); border-radius: 6px; user-select: none;
  235. }
  236. .flags summary:hover { color: var(--fg); border-color: var(--accent); }
  237. .flags-in {
  238. display: flex; gap: 10px; flex-wrap: wrap; margin-top: 8px;
  239. padding: 8px; background: var(--btn); border-radius: 6px;
  240. }
  241. .flags-in label { font-size: 12px; color: var(--muted); display: inline-flex; align-items: center; gap: 4px; }
  242. .flags-in input[type=checkbox] {
  243. appearance: none; -webkit-appearance: none; width: 14px; height: 14px; margin: 0;
  244. border: 1.5px solid var(--border); border-radius: 4px; background: var(--bg);
  245. cursor: pointer; position: relative;
  246. }
  247. .flags-in input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
  248. .flags-in input[type=checkbox]:checked::after {
  249. content: ""; position: absolute; left: 3px; top: 0; width: 3.5px; height: 7px;
  250. border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg);
  251. }
  252. .flags-in input[type=text] {
  253. background: var(--bg); color: var(--fg); border: 1px solid var(--border);
  254. border-radius: 5px; padding: 1px 5px; font: inherit; font-size: 12px; height: 22px;
  255. }
  256. .logsbtn { margin-left: auto; height: 20px; font-size: 11px; padding: 0 8px; flex-shrink: 0; }
  257. .win.flash { outline: 2px solid var(--accent); outline-offset: -1px; }
  258. .dockmenu {
  259. position: fixed; bottom: 44px; right: 12px; display: flex; flex-direction: column; gap: 4px;
  260. background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 8px;
  261. box-shadow: 0 12px 40px rgba(0,0,0,.5); z-index: 300; animation: winIn .15s ease both;
  262. }
  263. /* window switcher menu (header): same look, anchored below the header */
  264. .winmenu { position: fixed; top: 42px; right: 12px; bottom: auto;
  265. display: flex; flex-direction: column; gap: 2px;
  266. background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 8px;
  267. box-shadow: 0 12px 40px rgba(0,0,0,.5); z-index: 300; animation: winIn .15s ease both; }
  268. .winmenu .dock-chip { text-align: left; }
  269. .winmenu .wmax-on { font-weight: 600; }
  270. /* --- confirm dialog ------------------------------------------------------- */
  271. .dlg-back[hidden] { display: none; }
  272. .dlg-back {
  273. position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 400;
  274. display: flex; align-items: center; justify-content: center; animation: fadeIn .15s ease;
  275. }
  276. .dlg {
  277. background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
  278. padding: 18px; width: min(460px, 92vw); max-height: 80vh; overflow: auto;
  279. box-shadow: 0 12px 40px rgba(0,0,0,.5); animation: winIn .2s ease both;
  280. }
  281. .dlg h3 { margin: 0 0 10px; font-size: 14px; }
  282. .dlg .body { font-size: 13px; color: var(--fg); margin-bottom: 12px; }
  283. .dlg .body code { font-family: var(--mono); font-size: 12px; background: var(--btn); padding: 1px 5px; border-radius: 4px; }
  284. .dlg .cbox { font-family: var(--mono); font-size: 12px; color: var(--muted); margin: 8px 0 0; padding: 8px; background: var(--btn); border-radius: 6px; }
  285. .dlg .cbox li { margin: 2px 0; }
  286. .dlg input {
  287. width: 100%; background: var(--btn); color: var(--fg); border: 1px solid var(--border);
  288. border-radius: 6px; padding: 6px 8px; font: inherit; margin: 8px 0;
  289. }
  290. .dlg .row { display: flex; justify-content: flex-end; gap: 8px; }
  291. @keyframes flip { 0% { transform: scale(1); } 40% { transform: scale(1.5); } 100% { transform: scale(1); } }
  292. @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .35; } }
  293. @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
  294. @keyframes winIn { from { opacity: 0; transform: translateY(-4px) scale(.985); } to { opacity: 1; transform: none; } }
  295. @media (prefers-reduced-motion: reduce) {
  296. *, .led, .led.flip, .ssec.re .dot, .cluster, .job, .dlg, .win, .skeleton, .cled.exited, .abtn:disabled { animation: none !important; }
  297. }
  298. /* --- topology map ------------------------------------------------------- */
  299. #topo { height: 100%; overflow: hidden; }
  300. #topo svg { width: 100%; height: 100%; display: block; }
  301. #topo .topo-empty { height: 100%; display: grid; place-items: center; color: var(--muted); }
  302. #topo text { font: 12px/1.25 ui-sans-serif, system-ui; fill: var(--fg); }
  303. #topo .sub { fill: var(--muted); font-size: 10px; }
  304. #topo .dev { transition: opacity .5s, filter .5s; }
  305. #topo .dev.unpowered { opacity: .7; filter: grayscale(1); }
  306. #topo .dev.unpowered .body { fill: var(--bg); stroke-dasharray: 4 3; filter: none; }
  307. #topo .dev .body { fill: color-mix(in srgb, var(--fg) 5%, var(--panel)); stroke: color-mix(in srgb, var(--fg) 55%, transparent); stroke-width: 1.4; filter: drop-shadow(0 1px 2px var(--shade)); }
  308. #topo .dev .top { fill: color-mix(in srgb, var(--fg) 12%, transparent); }
  309. #topo .dev .vent { fill: color-mix(in srgb, var(--fg) 32%, transparent); }
  310. #topo .dev .plate { fill: color-mix(in srgb, var(--fg) 10%, var(--panel)); }
  311. #topo .dev .nm { font-size: 12.5px; font-weight: 600; }
  312. #topo .dev .ip { font-size: 10px; fill: var(--muted); font-family: var(--mono); }
  313. #topo .dev .ctr { fill: color-mix(in srgb, var(--muted) 22%, transparent); stroke: color-mix(in srgb, var(--muted) 60%, transparent); }
  314. #topo .dev .ctr.hot { fill: color-mix(in srgb, var(--led-busy) 35%, transparent); }
  315. #topo .dev .ctrt { font-size: 8.5px; fill: var(--muted); }
  316. #topo .dev.planned .body { stroke-dasharray: 4 4; opacity: .5; }
  317. .pled { fill: var(--led-free); }
  318. .pled.on { fill: var(--led-on); filter: drop-shadow(0 0 3px var(--led-on)); }
  319. .pled.b { fill: var(--led-busy); filter: drop-shadow(0 0 3px var(--led-busy)); animation: pulse 1.6s infinite; }
  320. .pled.off { fill: var(--led-off); }
  321. #topo .cable { fill: none; stroke-linecap: round; stroke-linejoin: round; }
  322. #topo .c-200g { stroke: color-mix(in srgb, var(--accent) 78%, transparent); stroke-width: 2.6; }
  323. #topo .c-dac { stroke: color-mix(in srgb, #a371f7 78%, transparent); stroke-width: 2.6; }
  324. #topo .c-10g { stroke: color-mix(in srgb, var(--muted) 68%, transparent); stroke-width: 1.5; }
  325. #topo .flow { opacity: 0; transition: opacity .6s; }
  326. #topo .flow.live { opacity: .9; }
  327. #topo .flow.c-200g { stroke: var(--accent); stroke-dasharray: 4 10; animation: flow 1.1s linear infinite; }
  328. #topo .flow.c-dac { stroke: #a371f7; stroke-dasharray: 4 10; animation: flow 1.1s linear infinite; }
  329. #topo .flow.c-10g { stroke: color-mix(in srgb, var(--fg) 50%, transparent); stroke-width: 1.5; stroke-dasharray: 3 9; animation: flow 1.6s linear infinite; }
  330. /* bus-mode crossings: the 10g run hops over the 200g lane */
  331. #topo .bridge { fill: none; stroke: color-mix(in srgb, var(--fg) 70%, transparent); stroke-width: 1.5; }
  332. #topo .cablemode { cursor: pointer; fill: var(--muted); font-size: 11px; }
  333. #topo .cablemode:hover { fill: var(--fg); text-decoration: underline; }
  334. @keyframes flow { to { stroke-dashoffset: -14; } }
  335. #topo .port { fill: var(--led-free); }
  336. #topo .port.on { fill: var(--led-on); }
  337. #topo .swbox { fill: color-mix(in srgb, var(--fg) 5%, var(--panel)); stroke: color-mix(in srgb, var(--fg) 55%, transparent); stroke-width: 1.4; }
  338. #topo .sw .swbox { transition: stroke .4s; }
  339. #topo .sw.ib.on .swbox { stroke: color-mix(in srgb, var(--led-on) 65%, transparent); filter: drop-shadow(0 0 5px color-mix(in srgb, var(--led-on) 35%, transparent)); }
  340. #topo .sw.ib.off .swbox { stroke: color-mix(in srgb, var(--led-off) 75%, transparent); }
  341. #topo .sw.ib.unk .swbox { stroke: color-mix(in srgb, var(--led-busy) 60%, transparent); }
  342. #topo .fan .fbody { fill: color-mix(in srgb, var(--fg) 5%, var(--panel)); stroke: color-mix(in srgb, var(--fg) 55%, transparent); stroke-width: 1.4; }
  343. #topo .fan .blade { fill: color-mix(in srgb, var(--fg) 34%, transparent); }
  344. #topo .fan .hub { fill: color-mix(in srgb, var(--fg) 50%, transparent); }
  345. #topo .fan .blades { transform-origin: 770px 318px; animation: spin 1.4s linear infinite; }
  346. #topo .fan.off .blades { animation: none; opacity: .4; }
  347. #topo .fan.unk .blades { animation: spin 4s linear infinite; opacity: .55; }
  348. @keyframes spin { to { transform: rotate(1turn); } }
  349. #topo .cluster-frame { cursor: pointer; }
  350. #topo .cluster-frame:hover .frame { stroke-width: 2.2; }
  351. #topo .fchip { cursor: pointer; }
  352. #topo .fchip:hover rect { stroke-width: 2; }
  353. #topo .fchip.down { filter: saturate(.5); }
  354. #topo .frame { stroke-width: 1.5; transition: opacity .4s; }
  355. #topo .cluster-frame.down .frame { stroke-dasharray: 5 4; opacity: .5; }
  356. #topo .fchip rect { fill: var(--panel); stroke-width: 1.2; }
  357. #topo .fchip text { font-size: 10.5px; letter-spacing: .3px; font-weight: 600; }
  358. #topo .fchip .cdot { fill: var(--led-off); }
  359. #topo .fchip .cdot.on { fill: var(--led-on); }
  360. #topo .legend text { font-size: 10.5px; fill: var(--muted); }
  361. </style>
  362. </head>
  363. <body>
  364. <header>
  365. <h1>sm121</h1>
  366. <div id="maxinfo" hidden><span>⛶</span><span class="maxtitle" id="max-title"></span>
  367. <button class="wbtn" id="max-restore" title="restore window size">❐</button>
  368. <button class="wbtn" id="max-min" title="minimize">–</button>
  369. <button class="wbtn" id="max-close" title="close">×</button></div>
  370. <div class="spacer"></div>
  371. <button class="tbtn" id="winmenu" title="all open windows (switch without losing maximize state)">▦</button>
  372. <div class="ssec" id="sse"><span class="dot"></span><span id="sse-t">connecting…</span></div>
  373. <button class="tbtn" id="theme">◐</button>
  374. </header>
  375. <div id="winlayer"></div>
  376. <div id="dock"></div>
  377. <div class="dlg-back" id="dlg" hidden>
  378. <div class="dlg">
  379. <h3 id="dlg-title"></h3>
  380. <div class="body" id="dlg-body"></div>
  381. <div class="row">
  382. <button class="tbtn" id="dlg-cancel">Cancel</button>
  383. <button class="abtn" id="dlg-ok">Confirm</button>
  384. </div>
  385. </div>
  386. </div>
  387. <script>
  388. "use strict";
  389. // Auth: the server may gate data endpoints with `--token` (required off
  390. // loopback). The token travels as `?token=...` (SSE EventSource cannot set
  391. // headers) — a one-shot URL param is promoted to localStorage, and every
  392. // data URL is wrapped with auth(). The /recipes iframe is same-origin, so
  393. // the embedded report page reads the same localStorage.
  394. const TOKEN = (() => {
  395. const q = new URLSearchParams(location.search).get("token");
  396. if (q) localStorage.setItem("sm121token", q);
  397. return localStorage.getItem("sm121token") || "";
  398. })();
  399. const auth = (p) => TOKEN ? p + (p.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(TOKEN) : p;
  400. function showTokenPrompt() {
  401. const d = document.createElement("div");
  402. d.style.cssText = "position:fixed;inset:0;z-index:100;background:var(--shade);display:flex;align-items:center;justify-content:center";
  403. const card = document.createElement("div");
  404. card.style.cssText = "background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:24px;max-width:360px";
  405. card.innerHTML = "<h3 style='margin:0 0 8px'>Dashboard token</h3>" +
  406. "<p style='color:var(--muted);font-size:13px'>Data endpoints require the token passed to <code>sm121 web --token</code>. It is kept in this browser only (localStorage).</p>" +
  407. "<input id='tok' type='password' placeholder='token' autocomplete='off' style='width:100%;box-sizing:border-box;padding:8px;background:var(--bg);color:var(--fg);border:1px solid var(--border);border-radius:6px'>";
  408. const btn = document.createElement("button");
  409. btn.textContent = "Connect";
  410. btn.style.cssText = "margin-top:10px;padding:8px 16px;background:var(--accent);color:#fff;border:0;border-radius:6px;cursor:pointer";
  411. const apply = () => { const v = document.getElementById("tok").value.trim(); if (v) { localStorage.setItem("sm121token", v); location.reload(); } };
  412. btn.onclick = apply;
  413. card.querySelector("input").addEventListener("keydown", (e) => { if (e.key === "Enter") apply(); });
  414. card.appendChild(btn);
  415. d.appendChild(card);
  416. document.body.appendChild(d);
  417. document.getElementById("tok").focus();
  418. }
  419. const $ = (s) => document.querySelector(s);
  420. const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
  421. const state = { snap: null, jobs: new Map(), recipes: [], active: localStorage.getItem("sm121-active") || "", panel: null, shown: new Set(), flags: {} };
  422. /*FLAGS-LT:START*/
  423. // Pure: build the POST /api/serve body from cluster + recipe + dry + the
  424. // per-cluster flags state. Absent keys are omitted (server defaults win):
  425. // fit "" = bare --fit (whole cluster), mirror "" = bare --mirror (default
  426. // path); a non-empty path wins over the bare checkbox.
  427. function serveBody(cluster, recipe, dry, f) {
  428. const body = { cluster, recipe, dry_run: !!dry };
  429. if (f.node) body.node = f.node;
  430. if (f.solo) body.solo = true;
  431. if (f.force) body.force = true;
  432. if (f.clear) body.clear = true;
  433. if (f.keep) body.keep = true;
  434. const fit = String(f.fit || "").trim();
  435. if (fit) body.fit = fit;
  436. else if (f.fitAll) body.fit = "";
  437. const mir = String(f.mirror || "").trim();
  438. if (mir) body.mirror = mir;
  439. else if (f.mirrorAll) body.mirror = "";
  440. return body;
  441. }
  442. function flagsOf(cluster) {
  443. return (state.flags[cluster] = state.flags[cluster] || { node: "", solo: false, force: false, clear: false, keep: false, fit: "", fitAll: false, mirror: "", mirrorAll: false });
  444. }
  445. /*FLAGS-LT:END*/
  446. /*SNAP-LT:START*/
  447. // Pure: same fleet + jobs? (`ts` changes on every probe, so it is
  448. // excluded). Used to skip DOM rebuilds when nothing changed — no blink.
  449. // (log-attaches are intentionally excluded: they change out-of-band and are
  450. // tracked in their own windows, not the cluster board)
  451. function sameSnapshot(a, b) {
  452. return JSON.stringify({ c: a.clusters, j: a.jobs }) === JSON.stringify({ c: b.clusters, j: b.jobs });
  453. }
  454. /*SNAP-LT:END*/
  455. // --- theme ---------------------------------------------------------------
  456. const root = document.documentElement;
  457. root.dataset.theme = localStorage.getItem("sm121-theme") || (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
  458. $("#max-restore").onclick = () => maxedHandle?.unmaximize();
  459. $("#max-min").onclick = () => maxedHandle?.minimize();
  460. $("#max-close").onclick = () => maxedHandle?.close();
  461. $("#theme").onclick = () => {
  462. root.dataset.theme = root.dataset.theme === "dark" ? "light" : "dark";
  463. localStorage.setItem("sm121-theme", root.dataset.theme);
  464. };
  465. // --- window manager ------------------------------------------------------
  466. // Vanilla win manager: absolute windows, drag by titlebar, corner resize,
  467. // minimize/close to the dock (chip to restore), click-to-front z-order.
  468. let ztop = 20;
  469. const wins = {}; // named windows: { topo, state, jobs }
  470. // every window ever created (named, logs, raw, recipes) — the dock lists
  471. // minimized ones from here, so a window can't be minimized into nowhere
  472. const winRegistry = new Set();
  473. const logWins = new Map(); // attach_id -> { win, pre, buf, paused, ... }
  474. const front = (el) => { el.style.zIndex = ++ztop; };
  475. // Multiple windows can be maximized at once — each keeps its own state —
  476. // but only one is shown: the rest stay maximized and merely hidden, and
  477. // the header switcher (▦) moves between them without losing anything.
  478. let maxedHandle = null; // the maximized window currently on screen
  479. function showMaxTitle(h) {
  480. if (maxedHandle && maxedHandle !== h) maxedHandle.win.style.display = "none";
  481. maxedHandle = h;
  482. h.win.style.display = "";
  483. front(h.win);
  484. $("#max-title").textContent = h.title;
  485. $("#maxinfo").hidden = false;
  486. }
  487. function hideMaxTitle(h) {
  488. if (maxedHandle !== h) return;
  489. maxedHandle = null;
  490. // a still-maximized window behind this one comes to the front of the
  491. // maximized stack — the layer never goes back to bare
  492. const others = [...winRegistry].filter(
  493. (x) => x !== h && x.isMaximized() && !x.isClosed() && x.win.isConnected,
  494. );
  495. if (others.length) showMaxTitle(others[others.length - 1]);
  496. else $("#maxinfo").hidden = true;
  497. }
  498. // Bring any open window forward: un-minimize if needed, and if it is
  499. // maximized, make it the one shown (hiding the other maximized ones).
  500. function activateWindow(h) {
  501. if (h.isMinimized()) h.restore();
  502. if (h.isMaximized()) {
  503. for (const o of winRegistry)
  504. if (o !== h && o.isMaximized() && !o.isClosed() && o.win.isConnected) o.win.style.display = "none";
  505. h.win.style.display = "";
  506. showMaxTitle(h);
  507. } else front(h.win);
  508. saveWinState();
  509. }
  510. let winMenuEl = null;
  511. function toggleWinMenu() {
  512. if (winMenuEl) { winMenuEl.remove(); winMenuEl = null; return; }
  513. const m = document.createElement("div");
  514. m.className = "winmenu";
  515. const open = [...winRegistry].filter((h) => !h.isClosed() && h.win.isConnected);
  516. const glyph = (h) => (h.isMaximized() ? "⛶ " : h.isMinimized() ? "– " : "▪ ");
  517. for (const h of open) {
  518. const b = document.createElement("button");
  519. b.className = "dock-chip" + (h === maxedHandle ? " wmax-on" : "");
  520. b.textContent = glyph(h) + h.label;
  521. b.title = (h.isMaximized() ? "maximized" : h.isMinimized() ? "minimized" : "floating") + " — click to show";
  522. b.onclick = () => { winMenuEl.remove(); winMenuEl = null; activateWindow(h); };
  523. m.appendChild(b);
  524. }
  525. document.body.appendChild(m);
  526. winMenuEl = m;
  527. setTimeout(() => addEventListener("click", () => { m.remove(); winMenuEl = null; }, { once: true }), 0);
  528. }
  529. $("#winmenu").onclick = (e) => { e.stopPropagation(); toggleWinMenu(); };
  530. // --- window layout persistence -------------------------------------------
  531. // The dashboard has no session: geometry, minimized/closed/maximized and
  532. // which optional windows are open are kept in localStorage and restored on
  533. // load (log windows come back from the server's attach registry instead).
  534. const WS_KEY = "sm121-wins";
  535. let restoring = false; // don't write half-restored state back
  536. function readWinState() {
  537. try { return JSON.parse(localStorage.getItem(WS_KEY) || "{}"); } catch { return {}; }
  538. }
  539. function saveWinState() {
  540. if (restoring) return;
  541. const st = {};
  542. const put = (k, h) => {
  543. st[k] = { ...h.geometry(), min: h.isMinimized(), closed: h.isClosed(), max: h.isMaximized() };
  544. };
  545. for (const [k, h] of Object.entries(wins)) put(k, h);
  546. if (recipesWin) put("recipes", recipesWin);
  547. if (rawWin) put("raw", rawWin);
  548. try { localStorage.setItem(WS_KEY, JSON.stringify(st)); } catch { /* private mode */ }
  549. }
  550. // Re-open an optional window (recipes/raw) exactly as it was left.
  551. function restoreWindow(key, open) {
  552. const st = readWinState()[key];
  553. if (!st || st.closed) return;
  554. Promise.resolve(open(st)).then((h) => {
  555. if (st.max) h.maximize();
  556. else if (st.min) h.minimize();
  557. });
  558. }
  559. // Windows keep px geometry, so a shrinking layer (dock appears, browser
  560. // resize) would push their bottom edge out of view — clamp them back in.
  561. function fitToLayer() {
  562. const layer = $("#winlayer");
  563. const W = layer.clientWidth, H = layer.clientHeight;
  564. for (const h of winRegistry) {
  565. const w = h.win;
  566. if (!w.isConnected || w.classList.contains("max")) continue;
  567. const left = parseFloat(w.style.left) || 0, top = parseFloat(w.style.top) || 0;
  568. if (left + w.offsetWidth > W) w.style.width = Math.max(240, W - left) + "px";
  569. if (top + w.offsetHeight > H) {
  570. if (top > H - 120) w.style.top = Math.max(0, H - 200) + "px";
  571. w.style.height = Math.max(140, H - (parseFloat(w.style.top) || 0)) + "px";
  572. }
  573. }
  574. }
  575. function makeWin({ id, title, short, x, y, w, h, bodyHtml, onClosed, extraCls, removeOnClose }) {
  576. const win = document.createElement("section");
  577. win.className = "win" + (extraCls ? " " + extraCls : "");
  578. if (id) win.id = id;
  579. win.style.cssText = `left:${x}px;top:${y}px;width:${w}px;height:${h}px;z-index:${++ztop}`;
  580. const bar = document.createElement("div");
  581. bar.className = "win-bar";
  582. bar.innerHTML = `<span class="wtitle">${esc(title)}</span>
  583. <button class="wbtn" data-act="max" title="maximize">▢</button>
  584. <button class="wbtn" data-act="min" title="minimize">–</button>
  585. <button class="wbtn" data-act="close" title="close">×</button>`;
  586. const body = document.createElement("div");
  587. body.className = "win-body";
  588. body.innerHTML = bodyHtml;
  589. const rz = document.createElement("div");
  590. rz.className = "win-resize";
  591. win.append(bar, body, rz);
  592. $("#winlayer").appendChild(win);
  593. const closed = { value: false };
  594. const doMin = () => {
  595. // minimize keeps the maximize state: a maximized window minimized goes
  596. // to the maximized stack (▦ switcher) and comes back full-screen
  597. win.style.display = "none";
  598. if (maxedHandle === handle) hideMaxTitle(handle);
  599. renderDock();
  600. saveWinState();
  601. };
  602. bar.querySelector('[data-act="min"]').onclick = doMin;
  603. // maximize = drop the frame and fill the window layer (the dock is a
  604. // sibling below it, so it stays usable); the title moves to the header
  605. const maxBtn = bar.querySelector('[data-act="max"]');
  606. let geom = null;
  607. const unmax = () => {
  608. if (!geom) return;
  609. win.classList.remove("max");
  610. Object.assign(win.style, geom);
  611. geom = null;
  612. maxBtn.textContent = "▢";
  613. maxBtn.title = "maximize";
  614. hideMaxTitle(handle);
  615. saveWinState();
  616. };
  617. maxBtn.onclick = () => {
  618. front(win);
  619. if (geom) { unmax(); return; }
  620. geom = { left: win.style.left, top: win.style.top, width: win.style.width, height: win.style.height };
  621. win.classList.add("max");
  622. win.style.left = "0px";
  623. win.style.top = "0px";
  624. win.style.width = "100%";
  625. win.style.height = "100%";
  626. maxBtn.textContent = "❐";
  627. maxBtn.title = "restore size";
  628. showMaxTitle(handle);
  629. saveWinState();
  630. };
  631. const doClose = () => {
  632. closed.value = true;
  633. hideMaxTitle(handle);
  634. if (removeOnClose) {
  635. // log/recipes/raw: gone for good (reopened from the + menu)
  636. win.remove();
  637. winRegistry.delete(handle);
  638. } else {
  639. // named windows stay addressable: the dock offers a + chip
  640. win.style.display = "none";
  641. }
  642. renderDock();
  643. saveWinState();
  644. if (onClosed) onClosed();
  645. };
  646. bar.querySelector('[data-act="close"]').onclick = doClose;
  647. bar.addEventListener("pointerdown", (e) => {
  648. if (e.target.closest(".wbtn") || win.classList.contains("max")) return;
  649. front(win);
  650. const ox = win.offsetLeft, oy = win.offsetTop; // baseline — read ONCE
  651. drag(
  652. e.clientX,
  653. e.clientY,
  654. (dx, dy) => {
  655. win.style.left = Math.max(0, ox + dx) + "px";
  656. win.style.top = Math.max(0, oy + dy) + "px";
  657. },
  658. saveWinState,
  659. );
  660. });
  661. rz.addEventListener("pointerdown", (e) => {
  662. e.stopPropagation();
  663. front(win);
  664. const ow = win.offsetWidth, oh = win.offsetHeight; // baseline — read ONCE
  665. drag(
  666. e.clientX,
  667. e.clientY,
  668. (dx, dy) => {
  669. win.style.width = Math.max(240, ow + dx) + "px";
  670. win.style.height = Math.max(140, oh + dy) + "px";
  671. },
  672. saveWinState,
  673. );
  674. });
  675. win.addEventListener("pointerdown", () => front(win));
  676. const handle = {
  677. win, body, title,
  678. label: short || title,
  679. unmaximize: unmax,
  680. minimize: doMin,
  681. close: doClose,
  682. maximize: () => maxBtn.onclick(),
  683. isMaximized: () => !!geom,
  684. setGeometry(g) {
  685. if (!g) return;
  686. const px = (v, d) => (Number.isFinite(parseFloat(v)) ? parseFloat(v) : d);
  687. win.style.left = Math.max(0, px(g.left, 0)) + "px";
  688. win.style.top = Math.max(0, px(g.top, 0)) + "px";
  689. win.style.width = Math.max(240, px(g.width, 600)) + "px";
  690. win.style.height = Math.max(140, px(g.height, 400)) + "px";
  691. },
  692. // the normal (un-maximized) rect — that is what gets persisted
  693. geometry: () => {
  694. const g = geom || { left: win.style.left, top: win.style.top, width: win.style.width, height: win.style.height };
  695. return { left: g.left, top: g.top, width: g.width, height: g.height };
  696. },
  697. restore() { win.style.display = ""; closed.value = false; front(win); renderDock(); },
  698. // a hidden maximized window is display:none but NOT minimized — it
  699. // waits in the maximized stack, reachable from the ▦ switcher
  700. isMinimized: () => win.style.display === "none" && !geom,
  701. isClosed: () => closed.value,
  702. };
  703. winRegistry.add(handle);
  704. return handle;
  705. }
  706. function drag(sx, sy, move, done) {
  707. const st = { x: sx, y: sy };
  708. const mv = (e) => move(e.clientX - st.x, e.clientY - st.y);
  709. const up = () => {
  710. removeEventListener("pointermove", mv);
  711. removeEventListener("pointerup", up);
  712. if (done) done();
  713. };
  714. addEventListener("pointermove", mv);
  715. addEventListener("pointerup", up);
  716. }
  717. function renderDock() {
  718. const dock = $("#dock");
  719. dock.innerHTML = "";
  720. const chip = (label, fn) => {
  721. const b = document.createElement("button");
  722. b.className = "dock-chip";
  723. b.textContent = label;
  724. b.onclick = fn;
  725. dock.appendChild(b);
  726. };
  727. const min = [...winRegistry].filter((h) => h.isMinimized() && h.win.isConnected);
  728. // "– " = minimized (still open), "+ " = closed (bring it back)
  729. for (const h of min) chip((h.isClosed() ? "+ " : "– ") + h.label, h.restore);
  730. if (!min.length && !rawWin) chip("+ raw config / recipe / effective", openRaw);
  731. // New-window menu (plan): State / Logs / Jobs / Raw.
  732. const plus = document.createElement("button");
  733. plus.className = "dock-chip plus";
  734. plus.textContent = "+";
  735. plus.title = "new window";
  736. plus.onclick = (e) => { e.stopPropagation(); toggleDockMenu(); };
  737. dock.appendChild(plus);
  738. fitToLayer(); // the dock just appeared/disappeared → the layer resized
  739. }
  740. let dockMenuEl = null;
  741. function closeDockMenu() { if (dockMenuEl) { dockMenuEl.remove(); dockMenuEl = null; } }
  742. function toggleDockMenu() {
  743. if (dockMenuEl) { closeDockMenu(); return; }
  744. const m = document.createElement("div");
  745. m.className = "dockmenu";
  746. const item = (label, fn) => {
  747. const b = document.createElement("button");
  748. b.className = "dock-chip";
  749. b.textContent = label;
  750. b.onclick = () => { closeDockMenu(); fn(); };
  751. m.appendChild(b);
  752. };
  753. item("topo", () => activateWindow(wins.topo));
  754. item("state", () => activateWindow(wins.state));
  755. item("jobs", () => activateWindow(wins.jobs));
  756. item("recipes", openRecipes);
  757. item("logs…", openLogsPicker);
  758. item("raw", openRaw);
  759. document.body.appendChild(m);
  760. dockMenuEl = m;
  761. setTimeout(() => addEventListener("click", closeDockMenu, { once: true }), 0);
  762. }
  763. // Open a logs window from the dock: pick a node (★ = running containers).
  764. function openLogsPicker() {
  765. const snap = state.snap;
  766. const body = document.createElement("div");
  767. body.className = "body";
  768. const sel = document.createElement("select");
  769. sel.style.cssText = "width:100%;margin:8px 0;padding:6px;background:var(--btn);color:var(--fg);border:1px solid var(--border);border-radius:6px;";
  770. if (snap) for (const c of snap.clusters) for (const n of c.nodes) {
  771. const o = document.createElement("option");
  772. o.value = c.name + "|" + n.name;
  773. o.textContent = (n.containers.length ? "★ " : "") + c.name + " / " + n.name + (n.containers.length ? " (" + n.containers.length + ")" : "");
  774. sel.appendChild(o);
  775. }
  776. body.innerHTML = `Open a logs window for a node (★ = has sm121 containers).`;
  777. body.appendChild(sel);
  778. openDialogHtml("open logs", body, () => {
  779. const i = sel.value.indexOf("|");
  780. openLog(sel.value.slice(0, i), sel.value.slice(i + 1));
  781. });
  782. }
  783. // --- SSE -------------------------------------------------------------------
  784. function sse(cls, txt) { $("#sse").className = "ssec " + cls; $("#sse-t").textContent = txt; }
  785. /*SSE-LT:START*/
  786. function connectSSE() {
  787. // the fleet polls every 30s, so a working stream is never silent for
  788. // long (plus 15s server keepalive comments). If it IS silent, the chip
  789. // is lying — rebuild the stream instead of trusting "open".
  790. const POLL_MS = 30000, STALE_MS = 3 * POLL_MS + 5000;
  791. let es = null, last = Date.now();
  792. const bounce = (txt) => {
  793. if (es) es.close();
  794. sse("re", txt);
  795. es = new EventSource(auth("/events"));
  796. // connection is up and a snapshot is already on its way — don't sit on
  797. // "connecting…" for a whole poll interval
  798. es.onopen = () => { last = Date.now(); sse("ok", "live"); };
  799. es.onmessage = (e) => {
  800. last = Date.now();
  801. sse("ok", "live");
  802. let ev;
  803. try { ev = JSON.parse(e.data); } catch { return; }
  804. if (ev.type === "state") onState(ev.snapshot);
  805. else if (ev.type === "job") onJob(ev);
  806. else if (ev.type === "log") onLog(ev);
  807. };
  808. es.onerror = () => {
  809. sse("re", "reconnecting…");
  810. // readyState CLOSED = EventSource gave up for good — only a fresh
  811. // object reconnects (the server replays the snapshot, so it heals
  812. // without a manual page reload)
  813. if (es.readyState === 2) setTimeout(() => bounce("reconnecting…"), 1000);
  814. };
  815. };
  816. bounce("connecting…");
  817. setInterval(() => {
  818. if (document.visibilityState === "visible" && Date.now() - last > STALE_MS) bounce("resyncing…");
  819. }, POLL_MS);
  820. // back from a frozen/sleeping tab or a network hop: check immediately
  821. document.addEventListener("visibilitychange", () => {
  822. if (document.visibilityState === "visible" && Date.now() - last > 40000) bounce("resyncing…");
  823. });
  824. addEventListener("online", () => bounce("reconnecting…"));
  825. }
  826. /*SSE-LT:END*/
  827. // --- state render ------------------------------------------------------------
  828. function ledState(n) { return n.reachable ? (n.occupied ? "b" : "on") : "off"; }
  829. function meta(n, c) {
  830. if (!n.reachable) return "offline";
  831. if (!c.up) return "online — cluster offline";
  832. if (n.occupied) return n.containers.map((x) => x.status).join(", ");
  833. return "free";
  834. }
  835. function clusterReason(c) {
  836. let r = "";
  837. if (c.up) r = "";
  838. else if (c.switch_off) r = "switch off";
  839. else {
  840. const off = c.nodes.filter((n) => !n.reachable).map((n) => n.name);
  841. r = off.length + " node" + (off.length === 1 ? "" : "s") + " offline" + (off.length ? " (" + off.join(", ") + ")" : "");
  842. }
  843. if (c.soft_off && c.soft_off.length) r = (r ? r + " · " : "") + "⚙ " + c.soft_off.join(", ") + " off";
  844. return r;
  845. }
  846. function renderCluster(c, prev, animate) {
  847. const el = document.createElement("div");
  848. el.className = "cluster" + (animate ? " anim" : "");
  849. const head = document.createElement("div");
  850. head.className = "cluster-head";
  851. if (c.up) {
  852. const soft = c.soft_off && c.soft_off.length ? `<span class="soft" title="non-blocking entity off">⚙ ${esc(c.soft_off.join(", "))} off</span>` : "";
  853. head.innerHTML = `<b>${esc(c.name)}</b><span class="free">${c.free} free</span>${soft}`;
  854. } else {
  855. head.innerHTML = `<b>${esc(c.name)}</b><span class="down">⏻ offline — ${esc(clusterReason(c))}</span>`;
  856. }
  857. el.appendChild(head);
  858. const prevNodes = prev ? Object.fromEntries(prev.nodes.map((n) => [n.name, n])) : {};
  859. for (const n of c.nodes) {
  860. const row = document.createElement("div");
  861. row.className = "node";
  862. row.title = "open logs for " + n.name;
  863. const cls = ledState(n);
  864. const flip = prevNodes[n.name] && ledState(prevNodes[n.name]) !== cls ? " flip" : "";
  865. row.innerHTML = `<span class="led ${cls}${flip}"></span>
  866. <span class="nname">${esc(n.name)}</span>
  867. <span class="nmeta" title="${esc(n.ssh_ip)}">${esc(meta(n, c))}</span>
  868. <button class="abtn logsbtn" title="open logs for ${esc(n.name)}">▤ logs</button>`;
  869. row.querySelector(".logsbtn").onclick = (e) => { e.stopPropagation(); openLog(c.name, n.name); };
  870. row.onclick = () => openLog(c.name, n.name);
  871. el.appendChild(row);
  872. if (n.occupied && n.containers.length) {
  873. const box = document.createElement("div");
  874. box.className = "containers";
  875. for (const x of n.containers) {
  876. const crow = document.createElement("div");
  877. crow.className = "crow";
  878. const dead = /exited|dead/i.test(x.status);
  879. crow.innerHTML = `<span class="cled${dead ? " exited" : ""}"></span><span class="cname">${esc(x.name)}</span><span>${esc(x.recipe)} · ${esc(x.status)}</span>`;
  880. box.appendChild(crow);
  881. }
  882. el.appendChild(box);
  883. }
  884. }
  885. el.appendChild(actionBar(c, prevNodes));
  886. return el;
  887. }
  888. function actionBar(c, prevNodes) {
  889. const bar = document.createElement("div");
  890. bar.className = "actions";
  891. if (!c.up) {
  892. // Down cluster: serve/stop are meaningless — only power actions apply.
  893. bar.appendChild(abtn("power-" + c.name, "power on", () => doPower("on", c.name), ""));
  894. bar.appendChild(abtn("pwswitch-" + c.name, "switch", () => doPower("switch", c.name), ""));
  895. return bar;
  896. }
  897. const sel = document.createElement("select");
  898. sel.id = "recipe-" + c.name;
  899. if (!state.recipes.length) {
  900. sel.innerHTML = "<option value=''></option>";
  901. } else {
  902. for (const r of state.recipes) {
  903. const o = document.createElement("option");
  904. o.value = r.name;
  905. o.textContent = r.name + (r.deploy === "tmux" ? " (tmux)" : "");
  906. sel.appendChild(o);
  907. }
  908. }
  909. bar.appendChild(sel);
  910. const dry = document.createElement("label");
  911. dry.innerHTML = `<input type="checkbox" id="dry-${esc(c.name)}"> dry-run`;
  912. bar.appendChild(dry);
  913. // Serve flags (CLI parity): solo / force / clear / keep / fit / mirror / node.
  914. // Values persist in state.flags across re-renders.
  915. const f = flagsOf(c.name);
  916. const nodeSel = document.createElement("select");
  917. nodeSel.className = "fnode";
  918. nodeSel.title = "target node (default: cluster selection)";
  919. nodeSel.innerHTML = `<option value=''>node: auto</option>` + c.nodes.map((n) => `<option value='${esc(n.name)}'>${esc(n.name)}</option>`).join("");
  920. nodeSel.value = f.node || "";
  921. nodeSel.onchange = () => { f.node = nodeSel.value; };
  922. const det = document.createElement("details");
  923. det.className = "flags";
  924. det.innerHTML = `<summary title="solo · force · fit · clear · mirror · keep (keep containers after stop)">⚙ flags</summary>
  925. <div class="flags-in">
  926. <label><input type="checkbox" id="fsolo-${esc(c.name)}"> solo</label>
  927. <label><input type="checkbox" id="fforce-${esc(c.name)}"> force</label>
  928. <label><input type="checkbox" id="fclear-${esc(c.name)}" title="clear cgroup memory limits (sudo) on launch nodes"> clear</label>
  929. <label><input type="checkbox" id="fkeep-${esc(c.name)}" title="keep containers after stop"> keep</label>
  930. <label title="scale TP to N nodes / whole cluster">fit <input type="checkbox" id="ffitb-${esc(c.name)}" title="bare --fit: whole cluster">all <input type="text" id="ffit-${esc(c.name)}" placeholder="N" size="3"></label>
  931. <label title="per-node HF mirror">mirror <input type="checkbox" id="fmirr-${esc(c.name)}" title="bare --mirror: ~/.cache/hf-models">~ <input type="text" id="fmirror-${esc(c.name)}" placeholder="~/.cache/hf-models" size="18"></label>
  932. </div>`;
  933. const wire = (id, key, isText) => {
  934. const el = det.querySelector("#" + id);
  935. if (isText) { el.value = f[key] || ""; el.oninput = () => { f[key] = el.value; }; }
  936. else { el.checked = !!f[key]; el.onchange = () => { f[key] = el.checked; }; }
  937. };
  938. wire("fsolo-" + c.name, "solo");
  939. wire("fforce-" + c.name, "force");
  940. wire("fclear-" + c.name, "clear");
  941. wire("fkeep-" + c.name, "keep");
  942. wire("ffitb-" + c.name, "fitAll");
  943. wire("ffit-" + c.name, "fit", true);
  944. wire("fmirr-" + c.name, "mirrorAll");
  945. wire("fmirror-" + c.name, "mirror", true);
  946. bar.appendChild(det);
  947. bar.appendChild(nodeSel);
  948. bar.appendChild(abtn("serve-" + c.name, "serve", () => doServe(c.name)));
  949. bar.appendChild(abtn("stop-" + c.name, "stop", () => doStop(c.name), "danger"));
  950. bar.appendChild(abtn("power-" + c.name, "power off", () => doPower("off", c.name), "danger"));
  951. bar.appendChild(abtn("pwswitch-" + c.name, "switch", () => doPower("switch", c.name), ""));
  952. return bar;
  953. }
  954. function abtn(id, label, fn, cls) {
  955. const b = document.createElement("button");
  956. b.className = "abtn " + (cls || "");
  957. b.id = id;
  958. b.textContent = label;
  959. b.onclick = fn;
  960. return b;
  961. }
  962. function onState(snap, force) {
  963. const prev = state.snap;
  964. updateLogNotes(snap); // runs even on no-churn ticks (attaches change out-of-band)
  965. if (!force && prev && sameSnapshot(prev, snap)) {
  966. state.snap = snap; // adopt the fresh attaches state; no DOM churn
  967. return; // nothing else changed — no rebuild
  968. }
  969. state.snap = snap;
  970. state.jobs = new Map(snap.jobs.map((j) => [j.id, j]));
  971. renderTopo(snap);
  972. if (!snap.clusters.find((c) => c.name === state.active)) {
  973. state.active = snap.clusters[0] ? snap.clusters[0].name : "";
  974. }
  975. // control state must survive the rebuild (recipe pick, dry-run tick)
  976. const activeName = state.active;
  977. const keepRecipe = recipeOf(activeName);
  978. const keepDry = dryOf(activeName);
  979. const animate = state.panel !== activeName; // first paint or cluster switch
  980. state.panel = activeName;
  981. const box = $("#clusters");
  982. box.innerHTML = "";
  983. const active = snap.clusters.find((c) => c.name === activeName);
  984. if (active) {
  985. box.appendChild(renderCluster(active, prev ? prev.clusters.find((p) => p.name === activeName) : null, animate));
  986. }
  987. restoreControls(activeName, keepRecipe, keepDry);
  988. // compact fleet strip: one chip per cluster, click to make it active
  989. const strip = document.createElement("div");
  990. strip.className = "strip";
  991. for (const c of snap.clusters) {
  992. const chip = document.createElement("div");
  993. chip.className = "chip" + (c.name === state.active ? " active" : "");
  994. const dot = c.up ? (c.free > 0 ? "on" : "b") : "off";
  995. const m = c.up ? c.free + " free" : "⏻ OFF";
  996. chip.title = clusterReason(c);
  997. chip.innerHTML = `<span class="led ${dot}"></span>${esc(c.name)}<span class="m">${m}</span>`;
  998. chip.onclick = () => { state.active = c.name; localStorage.setItem("sm121-active", c.name); onState(state.snap, true); };
  999. strip.appendChild(chip);
  1000. }
  1001. box.appendChild(strip);
  1002. renderJobs();
  1003. }
  1004. function restoreControls(name, recipe, dry) {
  1005. if (!name) return;
  1006. const d = document.getElementById("dry-" + name);
  1007. if (d && dry) d.checked = true;
  1008. const sel = document.getElementById("recipe-" + name);
  1009. if (sel && recipe) {
  1010. for (const o of sel.options) if (o.value === recipe) { sel.value = recipe; break; }
  1011. }
  1012. }
  1013. // --- topology map -------------------------------------------------------------
  1014. // The physical layer behind the windows: 8 GX10 boxes on a 2×4 grid, the
  1015. // 200G fabric switch and the passive 10G switch in the middle corridor,
  1016. // DAC direct links, HA glyphs (fan) and cluster frames. The structure is
  1017. // rebuilt only when the topo signature changes (config edit); state ticks
  1018. // just flip classes so flow/pulse/spin animations keep running.
  1019. const TG_W = 1060, TG_H = 540;
  1020. const tgPos = (i) => {
  1021. const cx = 20 + (i % 4) * 255;
  1022. return { x: cx + 37, y: i < 4 ? 74 : 386, w: 180, h: 104, dcx: cx + 127 };
  1023. };
  1024. const tgSlot = (n) => {
  1025. const m = String(n).match(/\d+/);
  1026. return m ? +m[0] : 999;
  1027. };
  1028. const tgIdx = (t, name) => t.nodes.findIndex((n) => n === name);
  1029. // cluster identity colors — green/red stay reserved for up/down state
  1030. const TG_HUES = ["#58a6ff", "#a371f7", "#f778ba", "#f0883e", "#39c5cf", "#e3b341", "#ff7b72", "#79c0ff", "#d2a8ff", "#ffa657"];
  1031. const hueOf = (name) => {
  1032. let h = 0;
  1033. for (const c of String(name)) h = (h * 31 + c.charCodeAt(0)) >>> 0;
  1034. return TG_HUES[h % TG_HUES.length];
  1035. };
  1036. function topoSig(t) {
  1037. return t.nodes.join(",") + "|" + t.links.map((l) => l.kind + l.a + ">" + l.b).join(",")
  1038. + "|" + t.switches.map((s) => s.entity).join(",");
  1039. }
  1040. function tgCablePath(l, t) {
  1041. const bi = tgIdx(t, l.b);
  1042. if (bi < 0) return "";
  1043. const b = tgPos(bi);
  1044. if (l.kind === "10g") {
  1045. const px = 396 + bi * 38;
  1046. if (bi < 4) { // row0: device bottom → 10G switch top
  1047. const ex = b.dcx + 40, ey = b.y + b.h;
  1048. return `M ${ex} ${ey} C ${ex} ${ey + 26} ${px} ${ey + 6} ${px} 210`;
  1049. }
  1050. return `M ${b.dcx} ${b.y} C ${b.dcx} ${b.y - 50} ${px} ${b.y - 80} ${px} 266`;
  1051. }
  1052. if (l.kind === "200g") {
  1053. const fi = t.links.filter((x) => x.kind === "200g").findIndex((x) => x.b === l.b);
  1054. const px = 396 + (fi % 4) * 80;
  1055. if (bi < 4) { // row0: device bottom → fabric switch top
  1056. const ex = b.dcx - 40, ey = b.y + b.h;
  1057. return `M ${ex} ${ey} C ${ex} ${ey + 76} ${px} ${ey + 66} ${px} 290`;
  1058. }
  1059. // row1: device top → fabric switch bottom — an S-curve inside the 40px
  1060. // corridor (switch bottom 346 .. device top 386) so the last approach
  1061. // to the port is vertical, not a slide in from the side
  1062. const ex = b.dcx - 40, ey = b.y;
  1063. return `M ${ex} ${ey} C ${ex} 363 ${px} 363 ${px} 346`;
  1064. }
  1065. // dac: arc between adjacent device tops
  1066. const ai = tgIdx(t, l.a);
  1067. if (ai < 0) return "";
  1068. const a = tgPos(ai);
  1069. const mx = (a.x + a.w + b.x) / 2;
  1070. return `M ${a.x + a.w - 4} ${a.y + 14} C ${mx} ${a.y - 22} ${mx} ${a.y - 22} ${b.x + 4} ${b.y + 14}`;
  1071. }
  1072. function devSvg(name, i) {
  1073. const d = tgPos(i);
  1074. return `<g class="dev" data-dev="${esc(name)}" transform="translate(${d.x},${d.y})">
  1075. <title>${esc(name)}</title>
  1076. <rect class="body" width="${d.w}" height="${d.h}" rx="10"/>
  1077. <rect class="top" x="4" y="3" width="${d.w - 8}" height="7" rx="3.5"/>
  1078. <rect class="vent" x="14" y="24" width="5" height="24" rx="2.5"/>
  1079. <rect class="vent" x="23" y="24" width="5" height="24" rx="2.5"/>
  1080. <rect class="vent" x="32" y="24" width="5" height="24" rx="2.5"/>
  1081. <rect class="ctr" x="122" y="18" width="52" height="15" rx="7.5"/>
  1082. <text class="ctrt" x="148" y="29" text-anchor="middle">…</text>
  1083. <rect class="plate" x="1" y="62" width="${d.w - 2}" height="41" rx="8"/>
  1084. <text class="nm" x="12" y="79">${esc(name)}</text>
  1085. <text class="ip" x="12" y="94">…</text>
  1086. <circle class="pled" cx="166" cy="74" r="4"/>
  1087. </g>`;
  1088. }
  1089. function swSvg(sw, entries) {
  1090. const label = sw.kind === "lan" ? "10G switch"
  1091. : sw.entity.includes(".") ? sw.entity.split(".")[1] : sw.entity;
  1092. const ib = sw.kind === "ib";
  1093. const y = ib ? 290 : 210;
  1094. const sub = ib ? "200G fabric · HA" : "passive · no HA";
  1095. const step = ib ? 80 : 38;
  1096. // ib ports sit 4+4 across two edges (the box fits 4 per edge at step 80);
  1097. // lan ports keep the continuous index (step 38 fits 8 across 2 rows)
  1098. const rows = entries.map((p) => { const col = ib ? p.i % 4 : p.i; return `<rect class="port" data-${ib ? "fab" : "lan"}port="${esc(p.name)}"
  1099. x="${396 + col * step - 7}" y="${p.top ? y + 2 : y + 49}" width="14" height="7" rx="2"/>`; }).join("");
  1100. return `<g class="sw ${sw.kind}" data-sw="${esc(sw.entity)}" transform="translate(0,0)">
  1101. <title>${esc(sw.entity)}</title>
  1102. <rect class="swbox" x="370" y="${y}" width="320" height="56" rx="8"/>
  1103. ${rows}
  1104. <text x="386" y="${y + 32}">${esc(label)}</text>
  1105. <text class="sub" x="386" y="${y + 46}">${sub}</text>
  1106. ${ib ? '<circle class="pled swled" cx="672" cy="' + (y + 40) + '" r="4"/>' : ""}
  1107. </g>`;
  1108. }
  1109. function fanSvg(sw) {
  1110. return `<g class="fan" data-sw="${esc(sw.entity)}">
  1111. <title>${esc(sw.entity)}</title>
  1112. <circle class="fbody" cx="770" cy="318" r="26"/>
  1113. <g class="blades">
  1114. <path class="blade" d="M770 294 C 781 298 783 310 775 316 L 770 318 Z"/>
  1115. <path class="blade" d="M770 294 C 781 298 783 310 775 316 L 770 318 Z" transform="rotate(120 770 318)"/>
  1116. <path class="blade" d="M770 294 C 781 298 783 310 775 316 L 770 318 Z" transform="rotate(240 770 318)"/>
  1117. <circle class="hub" cx="770" cy="318" r="5"/>
  1118. </g>
  1119. <text class="sub" x="770" y="362" text-anchor="middle">${esc(sw.entity.split(".")[1] || sw.entity)}</text>
  1120. </g>`;
  1121. }
  1122. function topoFrames(snap) {
  1123. const t = snap.topo;
  1124. // clusters with identical node sets share one frame (several chips on
  1125. // it) — no doubled rectangles, no mutual-containment depth inflation
  1126. const seen = new Map();
  1127. const groups = [];
  1128. for (const c of snap.clusters) {
  1129. const key = c.nodes.map((n) => n.name).sort().join("|");
  1130. if (seen.has(key)) seen.get(key).clusters.push(c);
  1131. else {
  1132. const g = { clusters: [c], nodes: c.nodes.map((n) => n.name) };
  1133. seen.set(key, g);
  1134. groups.push(g);
  1135. }
  1136. }
  1137. const contains = (a, b) => b.nodes.every((n) => a.nodes.includes(n));
  1138. const depthOf = (x) => groups.filter((o) => o !== x && contains(o, x)).length;
  1139. // pads grow with cluster rank in its region: the outermost (most
  1140. // containing) cluster sits furthest out on BOTH edges, so label chips
  1141. // land on separate "floors" and frame edges never stack into one line;
  1142. // inner frames hug their nodes
  1143. const pad = (g) => {
  1144. const d = depthOf(g);
  1145. const region = groups.filter((o) => o.nodes.some((n) => g.nodes.includes(n)));
  1146. const rmax = Math.max(...region.map(depthOf));
  1147. return { x: 14 + 10 * (rmax - d), top: 12 + 18 * (rmax - d), bottom: 12 + 5 * (rmax - d) };
  1148. };
  1149. const rects = [];
  1150. for (const g of groups) {
  1151. const ps = g.nodes.map((n) => tgPos(tgIdx(t, n))).filter(Boolean);
  1152. if (!ps.length) continue;
  1153. const p = pad(g);
  1154. const x = Math.min(...ps.map((q) => q.x)) - p.x;
  1155. const y = Math.min(...ps.map((q) => q.y)) - p.top;
  1156. const w = Math.max(...ps.map((q) => q.x + q.w)) + p.x - x;
  1157. const h = Math.max(...ps.map((q) => q.y + q.h)) + p.bottom - y;
  1158. rects.push({ g, x, y, w, h, area: w * h });
  1159. }
  1160. rects.sort((a, b) => b.area - a.area); // big frames behind, nested on top
  1161. // a chip never shares its hue with a frame that contains its frame
  1162. // (containers sort first — bigger area — so their hues are final)
  1163. for (const r of rects) {
  1164. const containers = rects.filter((o) => o !== r && o.x <= r.x && o.y <= r.y
  1165. && o.x + o.w >= r.x + r.w && o.y + o.h >= r.y + r.h);
  1166. for (const c of r.g.clusters) {
  1167. let hue = hueOf(c.name);
  1168. while (containers.some((o) => o.hue === hue)) {
  1169. hue = TG_HUES[(TG_HUES.indexOf(hue) + 1) % TG_HUES.length];
  1170. }
  1171. c._hue = hue;
  1172. }
  1173. r.hue = r.g.clusters[0]._hue;
  1174. }
  1175. // chip bands: chips sharing a frame-top floor get x-staggered so labels
  1176. // never overlap (merged frames put several chips on one frame)
  1177. const bands = new Map();
  1178. for (const r of rects) {
  1179. for (const c of r.g.clusters) (bands.get(r.y) ?? bands.set(r.y, []).get(r.y)).push({ r, c });
  1180. }
  1181. for (const band of bands.values()) {
  1182. band.sort((a, b) => a.r.x - b.r.x || a.c.name.localeCompare(b.c.name));
  1183. let cursor = -1e9;
  1184. for (const chip of band) {
  1185. chip.cw = chip.c.name.length * 6.6 + 30;
  1186. chip.x = Math.max(chip.r.x + 12, cursor);
  1187. cursor = chip.x + chip.cw + 6;
  1188. }
  1189. }
  1190. state.topoGroupTitles = {};
  1191. for (const r of rects) {
  1192. state.topoGroupTitles[r.g.clusters[0].name] = r.g.clusters.map((c) => c.name).join(" · ");
  1193. }
  1194. // two layers: frame rects (below cables/devices) and chips (topmost —
  1195. // opaque badges, nothing shows through, always clickable)
  1196. let frames = "", chips = "";
  1197. for (const r of rects) {
  1198. frames += `<g class="cluster-frame" data-cluster="${esc(r.g.clusters[0].name)}">
  1199. <title>${esc(r.g.clusters.map((c) => c.name).join(" · "))}</title>
  1200. <rect class="frame" style="stroke:${r.hue};fill:color-mix(in srgb, ${r.hue} 6%, transparent)"
  1201. x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" rx="14"/>
  1202. </g>`;
  1203. }
  1204. for (const r of rects) {
  1205. for (const c of r.g.clusters) {
  1206. const chip = bands.get(r.y).find((x) => x.c === c);
  1207. chips += `<g class="fchip" data-cluster="${esc(c.name)}" transform="translate(${chip.x},${r.y - 8})">
  1208. <title>${esc(c.name)}</title>
  1209. <rect width="${chip.cw}" height="16" rx="8" style="stroke:${c._hue}"/>
  1210. <circle class="cdot" cx="10" cy="8" r="3.5"/>
  1211. <text x="18" y="12" style="fill:${c._hue}">${esc(c.name)}</text>
  1212. </g>`;
  1213. }
  1214. }
  1215. return { frames, chips };
  1216. }
  1217. function cablesSvg(t, bus) {
  1218. let out = "";
  1219. for (const l of t.links) {
  1220. const p = bus ? tgCablePathBus(l, t) : tgCablePath(l, t);
  1221. if (!p) continue;
  1222. const key = `${l.kind}|${l.a}|${l.b}`;
  1223. out += `<path class="cable c-${l.kind}" d="${p}"/>`;
  1224. out += `<path class="cable c-${l.kind} flow" data-flow="${esc(key)}" d="${p}"/>`;
  1225. }
  1226. if (bus) out += bridgesSvg(t);
  1227. return out;
  1228. }
  1229. // Bus mode: row-1 (bottom) cables route as right-angle runs along two
  1230. // shared lanes — 200g at y=366 (in the 40px corridor under the fabric
  1231. // switch), 10g at y=278 (the 24px gap between the two switches). A 10g
  1232. // cable whose vertical would cut the fabric switch detours around its
  1233. // nearer side. Where a 10g run crosses the 200g lane it hops over it on
  1234. // a bridge arc, so crossings read as intentional.
  1235. function tgCablePathBus(l, t) {
  1236. const bi = tgIdx(t, l.b);
  1237. if (bi < 0 || bi < 4) return tgCablePath(l, t); // row 0 and DAC unchanged
  1238. const b = tgPos(bi);
  1239. if (l.kind === "200g") {
  1240. const ex = b.dcx - 40;
  1241. const fi = t.links.filter((x) => x.kind === "200g").findIndex((x) => x.b === l.b);
  1242. const px = 396 + (fi % 4) * 80;
  1243. return `M ${ex} 386 L ${ex} 366 L ${px} 366 L ${px} 346`;
  1244. }
  1245. // 10g: up the device side, across the inter-switch gap, down to the port
  1246. const px = 396 + bi * 38;
  1247. const x = b.dcx;
  1248. if (x < 370 || x > 690) return `M ${x} 386 L ${x} 278 L ${px} 278 L ${px} 266`;
  1249. const side = x < 530 ? 350 : 710; // nearest clearance past the fabric box
  1250. return `M ${x} 386 L ${x} 366 L ${side} 366 L ${side} 278 L ${px} 278 L ${px} 266`;
  1251. }
  1252. // Small semicircle hops where a 10g row-1 vertical crosses the 200g lane.
  1253. function bridgesSvg(t) {
  1254. const lane = t.links
  1255. .filter((l) => l.kind === "200g")
  1256. .map((l) => {
  1257. const bi = tgIdx(t, l.b);
  1258. if (bi < 4) return null;
  1259. const b = tgPos(bi);
  1260. const ex = b.dcx - 40;
  1261. const fi = t.links.filter((x) => x.kind === "200g").findIndex((x) => x.b === l.b);
  1262. const px = 396 + (fi % 4) * 80;
  1263. return { y: 366, x1: Math.min(ex, px), x2: Math.max(ex, px) };
  1264. })
  1265. .filter(Boolean);
  1266. let out = "";
  1267. for (const l of t.links.filter((l) => l.kind === "10g")) {
  1268. const bi = tgIdx(t, l.b);
  1269. if (bi < 4) continue;
  1270. const x = tgPos(bi).dcx;
  1271. // detour devices turn ON the lane (a T-junction) — only a vertical that
  1272. // spans the lane (outer devices, x outside the fabric box) gets a hop
  1273. if (x >= 370 && x <= 690) continue;
  1274. for (const h of lane)
  1275. if (x > h.x1 + 2 && x < h.x2 - 2)
  1276. out += `<path class="bridge b-10g" d="M ${x - 5} ${h.y} A 5 5 0 0 1 ${x + 5} ${h.y}"/>`;
  1277. }
  1278. return out;
  1279. }
  1280. function switchesSvg(t) {
  1281. const fi = {};
  1282. const fabEntries = t.links.filter((l) => l.kind === "200g").map((l) => ({
  1283. name: l.b, i: (fi[l.b] = fi[l.b] ?? Object.keys(fi).length), top: fi[l.b] < 4,
  1284. }));
  1285. const lanEntries = t.nodes.map((n, i) => ({ name: n, i, top: i < 4 }));
  1286. const glyphs = t.switches.map((s) => s.kind === "aux" ? fanSvg(s) : swSvg(s, fabEntries)).join("");
  1287. // the passive 10G switch has no HA entity — the UI draws it explicitly
  1288. return glyphs + swSvg({ entity: "lan", kind: "lan" }, lanEntries);
  1289. }
  1290. const devsSvg = (t) => t.nodes.map((n, i) => devSvg(n, i)).join("");
  1291. function legendSvg(bus) {
  1292. return `<g class="legend" transform="translate(20,526)">
  1293. <line x1="0" y1="0" x2="26" y2="0" class="cable c-200g"/><text x="32" y="4">200G fabric</text>
  1294. <line x1="120" y1="0" x2="146" y2="0" class="cable c-dac"/><text x="152" y="4">DAC direct</text>
  1295. <line x1="240" y1="0" x2="266" y2="0" class="cable c-10g"/><text x="272" y="4">10G mgmt</text>
  1296. <circle cx="352" cy="0" r="4" class="pled on"/><text x="362" y="4">plug on</text>
  1297. <circle cx="428" cy="0" r="4" class="pled off"/><text x="438" y="4">plug off / HA?</text>
  1298. <text x="560" y="4" class="cablemode" data-topobus="1">cables: ${bus ? "bus + bridges" : "direct"} ▸</text>
  1299. </g>`;
  1300. }
  1301. // Per-tick state update: flip LED/port/frame/flow classes in place —
  1302. // the SVG skeleton survives, so CSS animations keep running.
  1303. // Power policy for fabric ports and their cable flows: a port is green only
  1304. // when its switch reports ON (unknown is tolerated) AND the node is
  1305. // occupied — an HA-OFF switch cannot carry traffic, so all of its ports
  1306. // stay gray even if a node still reports a running container.
  1307. /*TOPOPORT:START*/
  1308. function fabPortOn(swOn, occupied) {
  1309. return swOn !== false && !!occupied;
  1310. }
  1311. /*TOPOPORT:END*/
  1312. function topoTick(snap) {
  1313. const t = snap.topo;
  1314. const ns = {};
  1315. for (const c of snap.clusters) for (const n of c.nodes) {
  1316. const s = (ns[n.name] ||= { reachable: false, occupied: false, ha: undefined, containers: [] });
  1317. s.reachable ||= n.reachable;
  1318. s.occupied ||= n.occupied;
  1319. if (!s.ip) s.ip = n.ssh_ip;
  1320. if (n.ha !== null) s.ha = n.ha;
  1321. for (const ct of n.containers) if (!s.containers.some((x) => x.name === ct.name)) s.containers.push(ct);
  1322. }
  1323. for (const name of t.nodes) {
  1324. const g = document.querySelector(`#topo g[data-dev="${CSS.escape(name)}"]`);
  1325. const s = ns[name];
  1326. if (!g || !s) continue;
  1327. const led = g.querySelector(".pled");
  1328. if (led) led.setAttribute("class", "pled " + (s.reachable ? (s.occupied ? "b" : "on") : "off"));
  1329. g.classList.toggle("unpowered", s.ha === false);
  1330. const ip = g.querySelector(".ip");
  1331. if (ip) ip.textContent = s.ip || "";
  1332. const ctr = g.querySelector(".ctrt"), chip = g.querySelector(".ctr");
  1333. const recipes = [...new Set(s.containers.map((x) => x.recipe))];
  1334. if (ctr) ctr.textContent = s.containers.length ? `${s.containers.length}·${recipes[0].slice(0, 7)}` : "idle";
  1335. if (chip) chip.classList.toggle("hot", s.containers.length > 0);
  1336. const tt = g.querySelector("title");
  1337. if (tt) tt.textContent = `${name} · ${s.ip || ""} · ${s.reachable ? (s.occupied ? "serving" : "free") : "down"}`
  1338. + (s.ha === false ? " · plug OFF" : "")
  1339. + (s.containers.length ? " · " + s.containers.map((x) => x.name).join(", ") : "");
  1340. }
  1341. const swStateOf = (ent) => t.states.find((x) => x.entity === ent)?.on;
  1342. for (const l of t.links) {
  1343. const fl = document.querySelector(`#topo path[data-flow="${CSS.escape(l.kind + "|" + l.a + "|" + l.b)}"]`);
  1344. if (!fl) continue;
  1345. const B = ns[l.b], A = l.kind === "dac" ? ns[l.a] : null;
  1346. fl.classList.toggle("live", l.kind === "10g" ? !!B?.reachable
  1347. : l.kind === "200g" ? fabPortOn(swStateOf(l.a), B?.occupied)
  1348. : !!(B?.occupied && A?.occupied));
  1349. }
  1350. for (const name of t.nodes) {
  1351. const lp = document.querySelector(`#topo rect[data-lanport="${CSS.escape(name)}"]`);
  1352. if (lp) lp.classList.toggle("on", !!ns[name]?.reachable);
  1353. const fp = document.querySelector(`#topo rect[data-fabport="${CSS.escape(name)}"]`);
  1354. if (fp) {
  1355. const swEnt = fp.closest("[data-sw]")?.dataset?.sw;
  1356. fp.classList.toggle("on", fabPortOn(swStateOf(swEnt), ns[name]?.occupied));
  1357. }
  1358. }
  1359. for (const sw of t.switches) {
  1360. const st = t.states.find((x) => x.entity === sw.entity);
  1361. const g = document.querySelector(`#topo [data-sw="${CSS.escape(sw.entity)}"]`);
  1362. if (!g) continue;
  1363. const cls = st?.on === true ? "on" : st?.on === false ? "off" : "unk";
  1364. g.classList.remove("on", "off", "unk");
  1365. g.classList.add(cls);
  1366. const led = g.querySelector(".swled");
  1367. if (led) led.setAttribute("class", "pled swled " + (st?.on === true ? "on" : st?.on === false ? "off" : ""));
  1368. const tt = g.querySelector("title");
  1369. if (tt) tt.textContent = `${sw.entity} · ${st?.on === true ? "on" : st?.on === false ? "OFF" : "state unknown"}`;
  1370. }
  1371. for (const c of snap.clusters) {
  1372. const st = `${c.up ? `up · ${c.free} free` : "down"}${c.switch_off ? " · HA switch off" : ""}`;
  1373. for (const g of document.querySelectorAll(`#topo [data-cluster="${CSS.escape(c.name)}"]`)) {
  1374. g.classList.toggle("down", !c.up);
  1375. const dot = g.querySelector(".cdot");
  1376. if (dot) dot.setAttribute("class", "cdot " + (c.up ? "on" : "off"));
  1377. const tt = g.querySelector("title");
  1378. if (tt) tt.textContent = `${(state.topoGroupTitles || {})[c.name] || c.name} · ${st}`;
  1379. }
  1380. }
  1381. }
  1382. function renderTopo(snap) {
  1383. const host = document.getElementById("topo");
  1384. const t = snap.topo;
  1385. if (!host || !t) return;
  1386. if (state.topoBus === undefined) state.topoBus = localStorage.getItem("sm121-topobus") === "1";
  1387. const sig = topoSig(t) + (state.topoBus ? ":bus" : ":direct");
  1388. if (state.topoSig !== sig) {
  1389. state.topoSig = sig;
  1390. const tf = topoFrames(snap);
  1391. host.innerHTML = `<svg viewBox="0 0 ${TG_W} ${TG_H}" preserveAspectRatio="xMidYMid meet">
  1392. ${tf.frames}${cablesSvg(t, state.topoBus)}${switchesSvg(t)}${devsSvg(t)}${legendSvg(state.topoBus)}${tf.chips}
  1393. </svg>`;
  1394. for (const g of host.querySelectorAll("[data-cluster]")) {
  1395. g.onclick = () => {
  1396. state.active = g.dataset.cluster;
  1397. localStorage.setItem("sm121-active", state.active);
  1398. if (wins.state) wins.state.isMinimized() ? wins.state.restore() : front(wins.state.win);
  1399. onState(state.snap, true);
  1400. };
  1401. }
  1402. // cable-mode toggle (legend): direct bezier runs ↔ bus + bridge arcs
  1403. const cm = host.querySelector("[data-topobus]");
  1404. if (cm)
  1405. cm.onclick = () => {
  1406. state.topoBus = !state.topoBus;
  1407. localStorage.setItem("sm121-topobus", state.topoBus ? "1" : "0");
  1408. state.topoSig = ""; // force a re-render with the other mode
  1409. renderTopo(state.snap || snap);
  1410. };
  1411. }
  1412. topoTick(snap);
  1413. }
  1414. // --- jobs ---------------------------------------------------------------------
  1415. // "Running" entries come from the docker labels (sm121.recipe / sm121.cluster)
  1416. // on live containers — jobs don't need to have started from this dashboard.
  1417. // One row per launcher job, NOT per node×cluster: a container is visible on
  1418. // every cluster sharing its node, so the board used to look entirely busy.
  1419. /*JOBS-LT:START*/
  1420. function runningFromLabels() {
  1421. const m = new Map();
  1422. if (!state.snap) return [];
  1423. for (const c of state.snap.clusters) {
  1424. if (!c.up) continue; // down clusters report no containers
  1425. for (const n of c.nodes) {
  1426. for (const x of n.containers) {
  1427. const key = x.cluster + "|" + x.recipe;
  1428. let r = m.get(key);
  1429. if (!r) m.set(key, (r = { cluster: x.cluster, recipe: x.recipe, nodes: [], statuses: new Set() }));
  1430. if (!r.nodes.includes(n.name)) r.nodes.push(n.name);
  1431. r.statuses.add(x.status);
  1432. }
  1433. }
  1434. }
  1435. const nat = (a, b) => a.localeCompare(b, undefined, { numeric: true });
  1436. return [...m.values()].map((r) => ({ ...r, nodes: r.nodes.sort(nat), statuses: [...r.statuses].sort(nat) }));
  1437. }
  1438. /*JOBS-LT:END*/
  1439. function renderJobs() {
  1440. const box = $("#jobs");
  1441. box.innerHTML = "";
  1442. const prevShown = state.shown;
  1443. state.shown = new Set();
  1444. const row = (key, cls, html) => {
  1445. const el = document.createElement("div");
  1446. el.className = "job " + cls + (prevShown.has(key) ? "" : " new");
  1447. el.innerHTML = html;
  1448. box.appendChild(el);
  1449. state.shown.add(key);
  1450. return el;
  1451. };
  1452. const run = runningFromLabels();
  1453. if (run.length) {
  1454. const h = document.createElement("div");
  1455. h.className = "jobs-empty"; h.textContent = "running (docker labels)";
  1456. box.appendChild(h);
  1457. for (const r of run) {
  1458. const many = r.nodes.length > 1;
  1459. row("c:" + r.cluster + ":" + r.recipe, "jjob",
  1460. `<span class="jdot"></span><span class="jkind">serve</span>
  1461. <span class="jmsg">${esc(r.cluster)}:${esc(r.recipe || "?")} — ${r.nodes.length} node${many ? "s" : ""} (${esc(r.nodes.join(", "))}) · ${esc(r.statuses.join(", "))}</span>`);
  1462. }
  1463. }
  1464. const js = [...state.jobs.values()].sort((a, b) => b.started - a.started);
  1465. if (!run.length && !js.length) { box.innerHTML = '<div class="jobs-empty">no sm121 containers running, no actions yet — serve / stop / power started from this dashboard appear here</div>'; return; }
  1466. if (run.length) {
  1467. const sep = document.createElement("div");
  1468. sep.className = "jobs-empty"; sep.textContent = "actions";
  1469. box.appendChild(sep);
  1470. }
  1471. for (const j of js) {
  1472. const cls = j.status === "ok" ? "ok" : j.status === "failed" ? "failed" : "jjob";
  1473. const when = new Date(j.started * 1000).toLocaleTimeString();
  1474. row("j:" + j.id, cls, `<span class="jdot"></span><span class="jkind">${esc(j.kind)}</span>
  1475. <span class="jmsg">${esc(j.cluster)}${j.recipe ? ":" + esc(j.recipe) : ""} — ${esc(j.message)} <span>(${when})</span></span>`);
  1476. setBtnBusy(j, j.status === "running");
  1477. }
  1478. }
  1479. function setBtnBusy(j, busy) {
  1480. // power jobs disable both the off and switch buttons (the job event
  1481. // doesn't carry the action)
  1482. const keys = j.kind === "power" ? ["power", "pwswitch"] : [j.kind];
  1483. for (const k of keys) {
  1484. const el = document.getElementById(k + "-" + j.cluster);
  1485. if (el) el.disabled = busy;
  1486. }
  1487. }
  1488. // --- job events ------------------------------------------------------------------
  1489. function onJob(ev) {
  1490. if (ev.event === "started") {
  1491. state.jobs.set(ev.id, { id: ev.id, kind: ev.kind, cluster: ev.cluster, recipe: ev.recipe, status: "running", message: ev.message, started: Date.now() / 1000 });
  1492. }
  1493. const j = state.jobs.get(ev.id);
  1494. if (j && ev.event !== "started") {
  1495. j.message = ev.message;
  1496. j.status = ev.event === "ok" ? "ok" : "failed";
  1497. }
  1498. renderJobs();
  1499. }
  1500. // Stream-end notes: the snapshot carries attaches[].done; surface a
  1501. // re-attach hint in each log window whose stream died.
  1502. function updateLogNotes(snap) {
  1503. for (const w of logWins.values()) {
  1504. if (!w.attach || !snap.attaches) continue;
  1505. const a = snap.attaches.find((x) => x.id === w.attach);
  1506. const note = w.win.querySelector(".lognote");
  1507. if (!note) continue;
  1508. if (a && a.done && !note.classList.contains("dead")) {
  1509. note.textContent = "stream ended — click ↻ to re-attach";
  1510. note.classList.add("dead");
  1511. }
  1512. }
  1513. }
  1514. function attachDone(attachId) {
  1515. if (!attachId) return true;
  1516. const a = state.snap && state.snap.attaches ? state.snap.attaches.find((x) => x.id === attachId) : null;
  1517. return a ? a.done : false;
  1518. }
  1519. function flashWin(win) {
  1520. win.classList.add("flash");
  1521. setTimeout(() => win.classList.remove("flash"), 700);
  1522. }
  1523. // --- log windows -------------------------------------------------------------------
  1524. const MAX_PRE_LINES = 1000;
  1525. // ponytail: trimPre re-splits the whole text per line (O(n)); fine at log
  1526. // rates — ring it (line array) if a busy container makes this visible.
  1527. function trimPre(pre) {
  1528. const t = pre.textContent;
  1529. if (t.split("\n").length > MAX_PRE_LINES + 1) {
  1530. pre.textContent = t.split("\n").slice(-MAX_PRE_LINES).join("\n");
  1531. }
  1532. }
  1533. function appendLogLine(w, line) {
  1534. if (w.paused) { w.buf += line + "\n"; return; }
  1535. preSet(w, w.pre.textContent + line + "\n");
  1536. }
  1537. function preSet(w, text) {
  1538. w.pre.textContent = text;
  1539. trimPre(w.pre);
  1540. if (!w.paused) w.pre.scrollTop = w.pre.scrollHeight;
  1541. }
  1542. function onLog(ev) {
  1543. const w = logWins.get(ev.attach);
  1544. if (!w) return; // window closed (or from another tab) — nothing to show
  1545. appendLogLine(w, ev.line);
  1546. }
  1547. async function openLog(cluster, node, recipe) {
  1548. const snap = state.snap;
  1549. const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
  1550. const n = c ? c.nodes.find((x) => x.name === node) : null;
  1551. if (!n) return;
  1552. // A window for this node is already open and no specific recipe asked for
  1553. // → front it with feedback; if its stream died, re-attach (fresh history).
  1554. if (!recipe) {
  1555. for (const w of logWins.values()) if (w.cluster === cluster && w.node === node) {
  1556. front(w.win);
  1557. flashWin(w.win);
  1558. if (w.attach && attachDone(w.attach)) reattachLog(w); // dead stream → fresh
  1559. return;
  1560. }
  1561. }
  1562. recipe = recipe || (n.containers[0] ? n.containers[0].recipe : "");
  1563. const win = makeWin({
  1564. title: "logs: " + node + (recipe ? " · " + recipe : ""),
  1565. short: "logs: " + node,
  1566. x: 20 + (logWins.size * 26) % 240, y: 20 + (logWins.size * 26) % 160,
  1567. w: Math.min(620, innerWidth - 40), h: Math.min(420, innerHeight * 0.6),
  1568. bodyHtml: `<div class="logbar">
  1569. <select title="container on ${esc(node)}"></select>
  1570. <label><input type="checkbox" class="logpause"> pause</label>
  1571. <button class="abtn logcopy">copy</button>
  1572. <button class="abtn logrefresh" title="re-attach (fresh history + stream)">↻</button>
  1573. <span class="lognote"></span>
  1574. </div><pre class="logpre"></pre>`,
  1575. extraCls: "logwin",
  1576. removeOnClose: true,
  1577. onClosed: () => {
  1578. const w = [...logWins.entries()].find(([, x]) => x.node === node && x.cluster === cluster && x.win === win.win);
  1579. if (w) detachLog(w[0]);
  1580. },
  1581. });
  1582. const w = { cluster, node, recipe, rank: n.rank, win: win.win, pre: win.body.querySelector(".logpre"), buf: "", paused: false };
  1583. win.body.querySelector(".logcopy").onclick = async () => {
  1584. try { await navigator.clipboard.writeText(w.pre.textContent); } catch {}
  1585. };
  1586. win.body.querySelector(".logrefresh").onclick = () => { if (w.attach) reattachLog(w); };
  1587. const pauseCb = win.body.querySelector(".logpause");
  1588. pauseCb.onchange = () => {
  1589. w.paused = pauseCb.checked;
  1590. if (!w.paused && w.buf) { preSet(w, w.pre.textContent + w.buf); w.buf = ""; }
  1591. };
  1592. const sel = win.body.querySelector("select");
  1593. for (const x of n.containers) {
  1594. const o = document.createElement("option");
  1595. o.value = x.recipe;
  1596. o.textContent = x.name + " · " + x.recipe;
  1597. sel.appendChild(o);
  1598. }
  1599. if (n.containers.length) sel.value = recipe;
  1600. sel.onchange = async () => {
  1601. if (!sel.value) return;
  1602. const cur = [...logWins.entries()].find(([, x]) => x.win === win.win);
  1603. if (cur) detachLog(cur[0], false); // drop the old stream, keep this window
  1604. await attachLog(w, sel.value);
  1605. };
  1606. const note = win.body.querySelector(".lognote");
  1607. // No containers AND no explicit recipe → nothing to attach; just the note.
  1608. // An explicit recipe attaches anyway (the snapshot may lag the fleet —
  1609. // the container can be running but not yet probed).
  1610. if (!n.containers.length && !recipe) {
  1611. note.textContent = "no sm121 containers on " + node + " — nothing to stream";
  1612. note.classList.add("dead");
  1613. logWins.set("noop:" + cluster + ":" + node, { ...w, attach: null });
  1614. return;
  1615. }
  1616. await attachLog(w, recipe || (n.containers[0] ? n.containers[0].recipe : ""));
  1617. }
  1618. async function attachLog(w, recipe) {
  1619. w.recipe = recipe;
  1620. w.win.querySelector(".wtitle").textContent = "logs: " + w.node + " · " + recipe;
  1621. const post = await api("/api/logs", { cluster: w.cluster, node: w.node, recipe, rank: w.rank });
  1622. w.attach = post.attach_id;
  1623. preSet(w, (post.history || []).join("\n"));
  1624. // Re-key: a select-change swap detached the old entry under its old id.
  1625. for (const [k] of [...logWins.entries()]) {
  1626. if (logWins.get(k).win === w.win && logWins.get(k).attach !== post.attach_id) logWins.delete(k);
  1627. }
  1628. logWins.set(post.attach_id, w);
  1629. const note = w.win.querySelector(".lognote");
  1630. note.textContent = "";
  1631. note.classList.remove("dead");
  1632. }
  1633. function detachLog(attachId, hide = true) {
  1634. const w = logWins.get(attachId);
  1635. if (!w) return;
  1636. logWins.delete(attachId);
  1637. if (w.attach) fetch(auth("/api/logs"), { method: "DELETE", headers: { "content-type": "application/json" }, body: JSON.stringify({ attach_id: w.attach }) }).catch(() => {});
  1638. if (hide && w.win && w.win.isConnected) { w.win.style.display = "none"; renderDock(); }
  1639. }
  1640. // Re-attach an existing window: drop the old stream (window stays) and
  1641. // start a fresh one (new 200-line history + follow).
  1642. async function reattachLog(w) {
  1643. const recipe = w.recipe;
  1644. if (w.attach) detachLog(w.attach, false);
  1645. await attachLog(w, recipe);
  1646. }
  1647. // --- raw content windows ---------------------------------------------------------
  1648. // One window, a kind selector: config / effective / recipe:<name>. Content is
  1649. // verbatim from the server (effective is pretty JSON); copy grabs the text.
  1650. let rawWin = null;
  1651. let recipesWin = null;
  1652. // The recipes panel IS the `sm121 report --serve` page, nested by the
  1653. // server at /recipes and embedded as-is: table, grouping, stars, the /r/
  1654. // viewer and live updates stay one implementation (paths prefix-rewritten
  1655. // server-side, theme inherited through the iframe's color-scheme).
  1656. function openRecipes(g) {
  1657. if (recipesWin) { activateWindow(recipesWin); return recipesWin; } // shows a minimized/hidden-max one too
  1658. const r = (k, d) => (g && Number.isFinite(parseFloat(g[k])) ? parseFloat(g[k]) : d);
  1659. recipesWin = makeWin({
  1660. id: "win-recipes", title: "Recipes", x: r("left", 24), y: r("top", 24),
  1661. w: r("width", Math.min(1180, innerWidth - 48)), h: r("height", Math.min(760, innerHeight - 80)),
  1662. bodyHtml: `<iframe src="${auth("/recipes")}" title="recipes report"></iframe>`,
  1663. extraCls: "recwin",
  1664. removeOnClose: true,
  1665. onClosed: () => { recipesWin = null; },
  1666. });
  1667. saveWinState();
  1668. return recipesWin;
  1669. }
  1670. async function openRaw(g) {
  1671. if (rawWin) { activateWindow(rawWin); return rawWin; }
  1672. const r = (k, d) => (g && Number.isFinite(parseFloat(g[k])) ? parseFloat(g[k]) : d);
  1673. const handle = makeWin({
  1674. title: "raw", x: r("left", 20), y: r("top", 20),
  1675. w: r("width", Math.min(680, innerWidth - 40)), h: r("height", Math.min(460, innerHeight * 0.65)),
  1676. bodyHtml: `<div class="rawbar">
  1677. <select></select>
  1678. <button class="abtn rawcopy">copy</button>
  1679. <span class="rawnote"></span>
  1680. </div><pre class="logpre rawpre"></pre>`,
  1681. extraCls: "rawwin",
  1682. removeOnClose: true,
  1683. onClosed: () => { rawWin = null; },
  1684. });
  1685. rawWin = handle;
  1686. const sel = handle.body.querySelector("select");
  1687. const pre = handle.body.querySelector(".rawpre");
  1688. const note = handle.body.querySelector(".rawnote");
  1689. handle.body.querySelector(".rawcopy").onclick = async () => {
  1690. try { await navigator.clipboard.writeText(pre.textContent); } catch {}
  1691. };
  1692. const fill = () => {
  1693. // rebuild only when the recipe set changed (works with zero recipes:
  1694. // config/effective are always selectable; recipe data may live in an
  1695. // external workspace).
  1696. const sig = state.recipes.map((r) => r.name).join(",");
  1697. if (sel.dataset.sig === sig && sel.options.length) return;
  1698. sel.dataset.sig = sig;
  1699. const cur = sel.value;
  1700. sel.innerHTML = "";
  1701. for (const kind of ["config", "effective", "recipe:", ...state.recipes.map((r) => "recipe:" + r.name)]) {
  1702. const o = document.createElement("option");
  1703. o.value = kind === "recipe:" ? "" : kind;
  1704. o.textContent = kind === "effective" ? "effective (merged config)" : kind;
  1705. if (kind === "recipe:") { o.disabled = true; o.textContent = "— recipes —"; }
  1706. sel.appendChild(o);
  1707. }
  1708. sel.value = cur || "config";
  1709. load();
  1710. };
  1711. let seq = 0;
  1712. async function load() {
  1713. const kind = sel.value;
  1714. const mine = ++seq; // responses can land out of order — last one wins
  1715. note.textContent = "";
  1716. if (!kind) return;
  1717. const path = kind === "config" ? "/api/raw/config" : kind === "effective" ? "/api/raw/effective" : "/api/raw/recipe/" + encodeURIComponent(kind.slice("recipe:".length));
  1718. try {
  1719. const res = await fetch(auth(path));
  1720. const text = await res.text();
  1721. if (mine !== seq) return; // a newer selection already answered
  1722. if (!res.ok) { note.textContent = "error: " + text; return; }
  1723. if (kind === "effective") {
  1724. try { pre.textContent = JSON.stringify(JSON.parse(text), null, 2); } catch { pre.textContent = text; }
  1725. } else pre.textContent = text;
  1726. } catch (e) { if (mine === seq) note.textContent = "error: " + e.message; }
  1727. }
  1728. sel.onchange = load;
  1729. fill(); // config/effective are always available; recipes fill in later
  1730. state.onRecipesReady = fill; // recipes may arrive after the first open
  1731. saveWinState();
  1732. return handle;
  1733. }
  1734. // --- actions -----------------------------------------------------------------------
  1735. const cur = () => state.snap;
  1736. function recipeOf(cluster) {
  1737. const sel = document.getElementById("recipe-" + cluster);
  1738. return sel ? sel.value : "";
  1739. }
  1740. function dryOf(cluster) {
  1741. const d = document.getElementById("dry-" + cluster);
  1742. return d ? d.checked : false;
  1743. }
  1744. async function api(path, body) {
  1745. const res = await fetch(auth(path), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
  1746. if (!res.ok) {
  1747. if (res.status === 401) { showTokenPrompt(); throw new Error("unauthorized"); }
  1748. let m = res.status;
  1749. try { m = (await res.json()).error || m; } catch {}
  1750. throw new Error(m);
  1751. }
  1752. return res.json();
  1753. }
  1754. function doServe(cluster) {
  1755. const recipe = recipeOf(cluster);
  1756. if (!recipe) { alert("pick a recipe first"); return; }
  1757. const body = serveBody(cluster, recipe, dryOf(cluster), flagsOf(cluster));
  1758. if (body.dry_run) {
  1759. api("/api/serve", body).then((r) => openDialog("dry-run: " + r.job, "started (watch the jobs window)", () => {}));
  1760. return;
  1761. }
  1762. openDialog(`serve ${recipe} on ${cluster}`, `Launches <code>${esc(recipe)}</code> on cluster <code>${esc(cluster)}</code>.`, () => {
  1763. api("/api/serve", body).catch((e) => openDialog("serve failed", esc(e.message), () => {}, true));
  1764. });
  1765. }
  1766. function doStop(cluster) {
  1767. const snap = cur();
  1768. const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
  1769. const containers = (c ? c.nodes : []).flatMap((n) => n.containers.map((x) => ({ ...x, node: n.name })));
  1770. // stop what is actually running here — never the whole recipe catalogue
  1771. const running = [...new Set(containers.map((x) => x.recipe).filter(Boolean))];
  1772. if (!running.length) {
  1773. // up but nothing detected: fall back to the serve-form pick (a stale
  1774. // serve the probe missed is still worth stopping)
  1775. const recipe = recipeOf(cluster);
  1776. if (!recipe) { alert(`nothing is running on ${cluster}`); return; }
  1777. stopDialog(cluster, recipe, containers);
  1778. return;
  1779. }
  1780. if (running.length === 1) { stopDialog(cluster, running[0], containers); return; }
  1781. const body = document.createElement("div");
  1782. body.className = "body";
  1783. body.innerHTML = `Several recipes are running on <code>${esc(cluster)}</code> — pick the one to stop:`;
  1784. const sel = document.createElement("select");
  1785. sel.style.cssText = "width:100%;margin:8px 0;padding:6px;background:var(--btn);color:var(--fg);border:1px solid var(--border);border-radius:6px;";
  1786. for (const r of running) {
  1787. const o = document.createElement("option");
  1788. o.value = r; o.textContent = r;
  1789. sel.appendChild(o);
  1790. }
  1791. body.appendChild(sel);
  1792. openDialogHtml(`stop ${cluster}`, body, () => stopDialog(cluster, sel.value, containers));
  1793. }
  1794. function stopDialog(cluster, recipe, containers) {
  1795. const snap = cur();
  1796. const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
  1797. const body = document.createElement("div");
  1798. body.className = "body";
  1799. const nodeSel = document.createElement("select");
  1800. nodeSel.id = "stopnode";
  1801. nodeSel.title = "stop on one node instead of all";
  1802. nodeSel.innerHTML = `<option value=''>all nodes</option>` + (c ? c.nodes.map((n) => `<option value='${esc(n.name)}'>${esc(n.name)}</option>`).join("") : "");
  1803. const list = containers.length
  1804. ? `<ul class="cbox">${containers.map((x) => `<li><b>${esc(x.name)}</b> — ${esc(x.status)} <span class="dim">on ${esc(x.node)}</span></li>`).join("")}</ul>`
  1805. : `<div class="cbox">no containers detected on ${esc(cluster)} (recipe may not be running here)</div>`;
  1806. body.innerHTML = `Will run <code>sm121 stop</code> for <code>${esc(recipe)}</code> on <code>${esc(cluster)}</code>. Node: <span data-stopnode></span>. Currently running:${list}`;
  1807. body.querySelector("[data-stopnode]").replaceWith(nodeSel);
  1808. openDialogHtml(`stop ${recipe}`, body, () => {
  1809. api("/api/stop", { cluster, recipe, node: nodeSel.value || undefined }).catch((e) => openDialog("stop failed", esc(e.message), () => {}, true));
  1810. });
  1811. }
  1812. function doPower(action, cluster) {
  1813. if (action === "off") {
  1814. const snap = cur();
  1815. const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
  1816. const busy = c ? c.nodes.filter((n) => n.occupied) : [];
  1817. if (busy.length) {
  1818. openDialog(`power off ${cluster} blocked`,
  1819. `Cluster has ${busy.length} occupied node(s): <code>${esc(busy.map((n) => n.name).join(", "))}</code>. Stop its workloads first.`,
  1820. () => {}, true);
  1821. return;
  1822. }
  1823. twoStep(`power off ${cluster}`,
  1824. `Shuts down <b>all nodes</b> of <code>${esc(cluster)}</code> (SSH then Home Assistant). This can kill live traffic.`,
  1825. cluster, () => {
  1826. api("/api/power", { action: "off", cluster }).catch((e) => openDialog("power failed", esc(e.message), () => {}, true));
  1827. });
  1828. return;
  1829. }
  1830. if (action === "switch") {
  1831. const snap = cur();
  1832. const names = snap ? snap.clusters.map((c) => c.name) : [];
  1833. const body = document.createElement("div");
  1834. body.className = "body";
  1835. let inner = `Power <code>${esc(cluster)}</code> off and bring up another cluster instead.`;
  1836. const sel = document.createElement("select");
  1837. sel.style.cssText = "width:100%;margin:8px 0;padding:6px;background:var(--btn);color:var(--fg);border:1px solid var(--border);border-radius:6px;";
  1838. for (const n of names.filter((n) => n !== cluster)) {
  1839. const o = document.createElement("option");
  1840. o.value = n; o.textContent = n;
  1841. sel.appendChild(o);
  1842. }
  1843. body.innerHTML = inner;
  1844. body.appendChild(sel);
  1845. openDialogHtml(`power switch from ${cluster}`, body, () => {
  1846. const to = sel.value;
  1847. api("/api/power", { action: "switch", cluster, to }).catch((e) => openDialog("power failed", esc(e.message), () => {}, true));
  1848. });
  1849. return;
  1850. }
  1851. twoStep(`power on ${cluster}`, `Turns on <code>${esc(cluster)}</code> via Home Assistant (SSH is not used).`, cluster, () => {
  1852. api("/api/power", { action: "on", cluster }).catch((e) => openDialog("power failed", esc(e.message), () => {}, true));
  1853. });
  1854. }
  1855. function twoStep(title, bodyHtml, nameToType, go) {
  1856. openDialogHtml(title, (() => { const d = document.createElement("div"); d.className = "body"; d.innerHTML = bodyHtml; return d; })(),
  1857. () => {}, { twoStep: nameToType, go });
  1858. }
  1859. // --- dialog -----------------------------------------------------------------------
  1860. let dlg = { ok: null, twoStep: null };
  1861. function openDialog(title, bodyHtml, go, danger) {
  1862. $("#dlg-title").textContent = title;
  1863. $("#dlg-body").innerHTML = bodyHtml;
  1864. const ok = $("#dlg-ok");
  1865. ok.style.display = "";
  1866. ok.textContent = "Confirm";
  1867. ok.className = "abtn" + (danger ? " danger" : "");
  1868. dlg = { ok: go, twoStep: null };
  1869. $("#dlg").hidden = false;
  1870. }
  1871. function openDialogHtml(title, bodyEl, go, opts) {
  1872. $("#dlg-title").textContent = title;
  1873. $("#dlg-body").innerHTML = "";
  1874. $("#dlg-body").appendChild(bodyEl);
  1875. const ok = $("#dlg-ok");
  1876. ok.style.display = "";
  1877. if (opts && opts.twoStep) {
  1878. ok.style.display = "none";
  1879. const wrap = document.createElement("div");
  1880. wrap.innerHTML = `<div style="font-size:12.5px;color:var(--muted)">Type <b>${esc(opts.twoStep)}</b> to confirm.</div>
  1881. <input id="dlg-type" placeholder="${esc(opts.twoStep)}" autocomplete="off">`; $("#dlg-body").appendChild(wrap);
  1882. const inp = wrap.querySelector("#dlg-type");
  1883. inp.oninput = () => {
  1884. if (inp.value === opts.twoStep) {
  1885. ok.style.display = "";
  1886. ok.textContent = "⚡ Confirm power action";
  1887. ok.className = "abtn danger";
  1888. } else { ok.style.display = "none"; }
  1889. };
  1890. // `go` (the parameter) is the no-op placeholder twoStep passes — the
  1891. // real action lives in opts.go; storing `go` made every two-step
  1892. // confirm (power on/off) close the dialog and do nothing
  1893. dlg = { ok: null, twoStep: opts.twoStep, go: opts.go };
  1894. } else {
  1895. dlg = { ok: go, twoStep: null };
  1896. }
  1897. $("#dlg").hidden = false;
  1898. }
  1899. $("#dlg-ok").onclick = () => {
  1900. const go = dlg.twoStep ? dlg.go : dlg.ok;
  1901. $("#dlg").hidden = true;
  1902. if (go) go();
  1903. };
  1904. $("#dlg-cancel").onclick = () => { $("#dlg").hidden = true; };
  1905. document.addEventListener("keydown", (e) => { if (e.key === "Escape") $("#dlg").hidden = true; });
  1906. // --- boot ---------------------------------------------------------------------------
  1907. function initManagedWindows() {
  1908. const W = innerWidth;
  1909. // vertical budget = the actual window layer (header/dock already excluded);
  1910. // +40 reserve for the dock, which appears when a window gets minimized
  1911. const L = Math.max(420, $("#winlayer").clientHeight);
  1912. // topology map: the primary window (left); state/jobs stack on the right
  1913. const tw = Math.max(560, Math.floor(W * 0.58));
  1914. const rx = tw + 30, rw = Math.max(340, W - rx - 12);
  1915. // the map is a fixed-aspect drawing: size its window to the drawing, or
  1916. // the SVG letterboxes itself with big empty bands above and below
  1917. const TH = Math.min(Math.round(tw * (TG_H / TG_W)) + 34, L - 260);
  1918. wins.topo = makeWin({
  1919. id: "win-topo", title: "Topology", x: 12, y: 12,
  1920. w: tw, h: TH,
  1921. bodyHtml: `<div id="topo"><div class="topo-empty">waiting for the first fleet scan…</div></div>`,
  1922. });
  1923. wins.jobs = makeWin({
  1924. id: "win-jobs", title: "Jobs", x: 12, y: TH + 24,
  1925. w: tw, h: L - TH - 24,
  1926. bodyHtml: `<div class="jobs" id="jobs"><div class="jobs-empty">no sm121 containers running, no actions yet — serve / stop / power started from this dashboard appear here</div></div>`,
  1927. });
  1928. wins.state = makeWin({
  1929. id: "win-state", title: "Cluster state", x: rx, y: 12,
  1930. w: rw, h: L - 12,
  1931. bodyHtml: `<div id="clusters"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></div>`,
  1932. });
  1933. // last session's layout wins over the defaults
  1934. const st = readWinState();
  1935. restoring = true;
  1936. for (const [k, h] of Object.entries(wins)) {
  1937. const g = st[k];
  1938. if (!g) continue;
  1939. if (g.closed) { h.close(); continue; }
  1940. h.setGeometry(g);
  1941. if (g.max) h.maximize();
  1942. else if (g.min) h.minimize();
  1943. }
  1944. restoring = false;
  1945. fitToLayer();
  1946. renderDock();
  1947. }
  1948. async function boot() {
  1949. initManagedWindows();
  1950. try {
  1951. const res = await fetch(auth("/api/state"));
  1952. if (res.status === 401) { showTokenPrompt(); }
  1953. if (res.ok) {
  1954. const snap = await res.json();
  1955. onState(snap);
  1956. // Restore log windows from other tabs / previous session (idempotent
  1957. // attach: a live stream is reused, a finished one re-streams history).
  1958. for (const a of snap.attaches || []) {
  1959. if (![...logWins.values()].some((w) => w.cluster === a.cluster && w.node === a.node)) {
  1960. openLog(a.cluster, a.node, a.recipe);
  1961. }
  1962. }
  1963. }
  1964. } catch {}
  1965. try {
  1966. const res = await fetch(auth("/api/recipes"));
  1967. if (res.ok) {
  1968. const d = await res.json();
  1969. state.recipes = (d.recipes || []).sort((a, b) => a.name.localeCompare(b.name));
  1970. if (state.snap) onState(state.snap, true); // force: sameSnapshot would skip the identical fleet
  1971. if (state.onRecipesReady) { const f = state.onRecipesReady; delete state.onRecipesReady; f(); }
  1972. }
  1973. } catch {}
  1974. connectSSE();
  1975. // 30 s heartbeat refresh (mirrors the server poll; harmless if state is identical)
  1976. addEventListener("resize", fitToLayer);
  1977. // optional windows (their own SSE/API calls are cheap and idempotent)
  1978. restoreWindow("recipes", openRecipes);
  1979. restoreWindow("raw", openRaw);
  1980. setInterval(async () => {
  1981. try {
  1982. const res = await fetch(auth("/api/state"));
  1983. if (res.ok) onState(await res.json());
  1984. } catch {}
  1985. }, 30000);
  1986. }
  1987. boot();
  1988. </script>
  1989. </body>
  1990. </html>