ui.html 113 KB

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