ui.html 78 KB

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