| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039 |
- <!doctype html>
- <html data-theme="dark">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>sm121</title>
- <style>
- :root[data-theme="dark"] {
- --bg: #0d1117; --panel: #161b22; --fg: #e6edf3; --muted: #8b949e;
- --border: #30363d; --accent: #58a6ff; --shade: rgba(0,0,0,.55);
- /* monospace content (raw/logs/jobs/node names) — the Alacritty font (~/.alacritty.toml) */
- --mono: "DMMono Nerd Font", Menlo, ui-monospace, SFMono-Regular, monospace;
- --led-on: #3fb950; --led-off: #f85149; --led-busy: #d29922; --led-free: #30363d;
- --glow-on: 0 0 8px 2px rgba(63,185,80,.55); --glow-busy: 0 0 8px 2px rgba(210,153,34,.55);
- --btn: #21262d; --btn-hover: #30363d;
- }
- :root[data-theme="light"] {
- --bg: #f6f8fa; --panel: #ffffff; --fg: #1f2328; --muted: #656d76;
- --border: #d0d7de; --accent: #0969da; --shade: rgba(31,35,40,.20);
- --mono: "DMMono Nerd Font", Menlo, ui-monospace, SFMono-Regular, monospace;
- --led-on: #1a7f37; --led-off: #cf222e; --led-busy: #9a6700; --led-free: #8c959f;
- --glow-on: 0 0 8px 2px rgba(26,127,55,.35); --glow-busy: 0 0 8px 2px rgba(154,103,0,.35);
- --btn: #f6f8fa; --btn-hover: #eaeef2;
- }
- * { box-sizing: border-box; }
- html, body { height: 100%; }
- body {
- margin: 0; background: var(--bg); color: var(--fg);
- font: 14px/1.45 ui-sans-serif, system-ui, "SF Pro", sans-serif;
- display: flex; flex-direction: column;
- transition: background .25s, color .25s;
- }
- header {
- display: flex; align-items: center; gap: 12px;
- padding: 10px 16px; border-bottom: 1px solid var(--border);
- background: var(--panel); position: sticky; top: 0; z-index: 5;
- }
- header h1 { font-size: 15px; margin: 0; font-weight: 650; letter-spacing: .3px; }
- header .spacer { flex: 1; }
- .ssec { font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
- .ssec .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--led-off); }
- .ssec.ok .dot { background: var(--led-on); }
- .ssec.re .dot { animation: pulse 1s infinite; }
- button.tbtn {
- background: var(--btn); color: var(--fg); border: 1px solid var(--border);
- border-radius: 6px; padding: 4px 10px; cursor: pointer; font: inherit; font-size: 13px;
- }
- button.tbtn:hover { background: var(--btn-hover); }
- /* --- window manager ------------------------------------------------------ */
- #winlayer { position: relative; flex: 1; overflow: hidden; }
- .win {
- position: absolute; background: var(--panel); border: 1px solid var(--border);
- border-radius: 10px; display: flex; flex-direction: column;
- box-shadow: 0 6px 24px rgba(0,0,0,.35); animation: winIn .3s ease both;
- }
- /* maximized: the frame disappears and the window IS the layer; its title
- moves into the header (with a restore button) */
- .win.max { border: 0; border-radius: 0; box-shadow: none; }
- .win.max .win-bar, .win.max .win-resize { display: none; }
- /* `display: flex` would override the `hidden` attribute (whose UA rule is
- just `display: none`) — guard it, like .dlg-back does */
- #maxinfo { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--muted); }
- #maxinfo[hidden] { display: none; }
- #maxinfo .maxtitle { color: var(--fg); font-weight: 600; }
- #maxinfo .wbtn { width: 22px; height: 20px; font-size: 12px; }
- .win-bar {
- display: flex; align-items: center; gap: 6px; padding: 7px 10px;
- border-bottom: 1px solid var(--border); cursor: grab; user-select: none;
- font-size: 12px; text-transform: uppercase; letter-spacing: .6px; color: var(--muted);
- flex-shrink: 0;
- }
- .win-bar:active { cursor: grabbing; }
- .win-bar .wtitle { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .wbtn {
- background: none; border: 1px solid transparent; color: var(--muted);
- border-radius: 5px; width: 20px; height: 18px; cursor: pointer; font: inherit; font-size: 12px;
- line-height: 1; padding: 0;
- }
- .wbtn:hover { background: var(--btn-hover); color: var(--fg); }
- .win-body { flex: 1; overflow: auto; padding: 12px 14px; }
- .win-resize {
- position: absolute; right: 0; bottom: 0; width: 14px; height: 14px; cursor: nwse-resize;
- background: linear-gradient(135deg, transparent 50%, var(--border) 50%);
- }
- #dock {
- display: flex; gap: 6px; align-items: center; padding: 6px 12px;
- border-top: 1px solid var(--border); background: var(--panel); min-height: 34px; flex-shrink: 0;
- }
- #dock:empty { display: none; }
- .dock-chip {
- background: var(--btn); color: var(--muted); border: 1px solid var(--border);
- border-radius: 999px; padding: 2px 10px; font-size: 12px; cursor: pointer; font: inherit;
- }
- .dock-chip:hover { color: var(--fg); border-color: var(--accent); }
- /* --- cluster board ------------------------------------------------------- */
- .cluster.anim { animation: winIn .35s ease both; }
- .cluster { margin-bottom: 14px; }
- .cluster-head { display: flex; align-items: baseline; gap: 8px; margin-bottom: 6px; }
- .cluster-head b { font-size: 13px; }
- .cluster-head .free { color: var(--muted); font-size: 12px; }
- .cluster-head .down { color: var(--led-off); font-size: 12px; }
- .cluster-head .soft { color: var(--led-busy); font-size: 12px; }
- .node {
- display: flex; align-items: center; gap: 10px; padding: 5px 0;
- border-bottom: 1px solid var(--border); cursor: pointer;
- }
- .node:hover { background: var(--btn); }
- .node:last-child { border-bottom: none; }
- .led {
- width: 11px; height: 11px; border-radius: 50%; background: var(--led-off);
- transition: background .4s, box-shadow .4s; flex-shrink: 0;
- }
- .led.on { background: var(--led-on); box-shadow: var(--glow-on); }
- .led.b { background: var(--led-busy); box-shadow: var(--glow-busy); }
- .led.off { background: var(--led-off); }
- .led.flip { animation: flip .45s ease; }
- .nname { width: 64px; font-family: var(--mono); font-size: 12.5px; }
- .nmeta { color: var(--muted); font-size: 12px; flex: 1; overflow: hidden; text-overflow: ellipsis; }
- .containers { width: 100%; margin-top: 2px; }
- .crow { display: flex; align-items: center; gap: 8px; padding: 2px 0 2px 21px; font-size: 12px; color: var(--muted); }
- .cled { width: 7px; height: 7px; border-radius: 50%; background: var(--led-busy); box-shadow: var(--glow-busy); flex-shrink: 0; }
- .cname { font-family: var(--mono); color: var(--fg); }
- .actions { display: flex; gap: 8px; align-items: center; margin: 6px 0 0 21px; flex-wrap: wrap; }
- .actions select { font: inherit; }
- .actions input[type=checkbox] {
- appearance: none; -webkit-appearance: none;
- width: 15px; height: 15px; margin: 0; flex-shrink: 0;
- border: 1.5px solid var(--border); border-radius: 4px; background: var(--btn);
- cursor: pointer; position: relative; transition: background .15s, border-color .15s;
- }
- .actions input[type=checkbox]:hover { border-color: var(--accent); }
- .actions input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
- .actions input[type=checkbox]:checked::after {
- content: ""; position: absolute; left: 3.5px; top: 0;
- width: 4px; height: 8px; border: solid #fff; border-width: 0 2px 2px 0;
- transform: rotate(45deg);
- }
- .actions select {
- background: var(--btn); color: var(--fg); border: 1px solid var(--border);
- border-radius: 6px; padding: 2px 6px; font-size: 12.5px; max-width: 260px; height: 26px;
- }
- .actions label { font-size: 12px; color: var(--muted); display: inline-flex; align-items: center; gap: 4px; height: 26px; }
- .actions label input { margin: 0; }
- .strip { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--border); }
- .chip {
- display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none;
- border: 1px solid var(--border); border-radius: 999px; padding: 3px 10px; font-size: 12px;
- color: var(--muted); background: var(--btn); transition: border-color .15s, color .15s;
- }
- .chip .m { opacity: .7; }
- .chip.active { color: var(--fg); border-color: var(--accent); }
- .abtn {
- background: var(--btn); color: var(--fg); border: 1px solid var(--border);
- border-radius: 6px; padding: 0 12px; cursor: pointer; font: inherit; font-size: 12.5px;
- height: 26px; transition: background .15s;
- }
- .abtn:hover:not(:disabled) { background: var(--btn-hover); }
- .abtn:disabled { opacity: .45; cursor: default; }
- .abtn.danger { color: var(--led-off); }
- .jobs { font-family: var(--mono); font-size: 12px; }
- .job { display: flex; gap: 8px; align-items: baseline; padding: 4px 0; border-bottom: 1px solid var(--border); }
- .job.new { animation: winIn .3s ease both; }
- .job:last-child { border-bottom: none; }
- .jdot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex-shrink: 0; align-self: center; }
- .job.ok .jdot { background: var(--led-on); }
- .job.failed .jdot { background: var(--led-off); }
- .jkind { width: 48px; color: var(--muted); }
- .jmsg { color: var(--muted); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .jjob .jmsg { color: var(--fg); }
- .jobs-empty { color: var(--muted); font-size: 12.5px; padding: 6px 0; }
- /* --- log windows ---------------------------------------------------------- */
- .logwin .win-body { display: flex; flex-direction: column; padding: 0; }
- .logbar {
- display: flex; gap: 8px; align-items: center; padding: 8px 10px;
- border-bottom: 1px solid var(--border); flex-shrink: 0; flex-wrap: wrap;
- }
- .logbar select {
- background: var(--btn); color: var(--fg); border: 1px solid var(--border);
- border-radius: 6px; padding: 2px 6px; font-size: 12px; max-width: 300px; height: 26px;
- }
- .logbar label { font-size: 12px; color: var(--muted); display: inline-flex; gap: 4px; align-items: center; }
- .logbar input[type=checkbox] {
- appearance: none; -webkit-appearance: none; width: 15px; height: 15px; margin: 0;
- border: 1.5px solid var(--border); border-radius: 4px; background: var(--btn);
- cursor: pointer; position: relative;
- }
- .logbar input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
- .logbar input[type=checkbox]:checked::after {
- content: ""; position: absolute; left: 3.5px; top: 0;
- width: 4px; height: 8px; border: solid #fff; border-width: 0 2px 2px 0;
- transform: rotate(45deg);
- }
- .lognote { font-size: 12px; color: var(--muted); flex: 1; }
- .lognote.dead { color: var(--led-busy); }
- .logpre {
- flex: 1; margin: 0; padding: 10px 12px; overflow: auto;
- font: 11.5px/1.5 var(--mono); white-space: pre-wrap;
- word-break: break-word; color: var(--fg);
- }
- /* --- raw content windows --------------------------------------------------- */
- .rawwin .win-body { display: flex; flex-direction: column; padding: 0; }
- .recwin .win-body { padding: 0; }
- .recwin iframe { width: 100%; height: 100%; border: 0; display: block; background: var(--panel); }
- /* the embedded report page resolves `color-scheme: light dark` from this
- element, so it follows the dashboard theme instead of the OS one */
- :root[data-theme="dark"] .recwin iframe { color-scheme: dark; }
- :root[data-theme="light"] .recwin iframe { color-scheme: light; }
- .rawbar {
- display: flex; gap: 8px; align-items: center; padding: 8px 10px;
- border-bottom: 1px solid var(--border); flex-shrink: 0;
- }
- .rawbar select {
- background: var(--btn); color: var(--fg); border: 1px solid var(--border);
- border-radius: 6px; padding: 2px 6px; font-size: 12px; max-width: 320px; height: 26px;
- }
- .rawbar .abtn { height: 26px; }
- .rawnote { font-size: 12px; color: var(--muted); flex: 1; }
- /* --- polish: skeleton + attention ------------------------------------------ */
- .skeleton { height: 14px; border-radius: 6px; margin: 10px 0;
- background: linear-gradient(90deg, var(--btn) 25%, var(--btn-hover) 50%, var(--btn) 75%);
- background-size: 200% 100%; animation: shimmer 1.2s infinite; }
- @keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
- .cled.exited { background: var(--led-off); box-shadow: 0 0 8px 2px rgba(248,81,73,.5); animation: pulse 1.2s infinite; }
- .abtn:disabled { animation: pulse 1.2s infinite; }
- .job.jjob .jdot { animation: pulse 1.2s infinite; }
- /* --- serve flags (CLI parity) + node logs button + dock menu ---------------- */
- .fnode {
- background: var(--btn); color: var(--muted); border: 1px solid var(--border);
- border-radius: 6px; padding: 2px 6px; font-size: 12px; height: 26px; max-width: 140px;
- }
- .flags summary {
- cursor: pointer; font-size: 12px; color: var(--muted); height: 26px;
- display: inline-flex; align-items: center; padding: 0 8px;
- border: 1px dashed var(--border); border-radius: 6px; user-select: none;
- }
- .flags summary:hover { color: var(--fg); border-color: var(--accent); }
- .flags-in {
- display: flex; gap: 10px; flex-wrap: wrap; margin-top: 8px;
- padding: 8px; background: var(--btn); border-radius: 6px;
- }
- .flags-in label { font-size: 12px; color: var(--muted); display: inline-flex; align-items: center; gap: 4px; }
- .flags-in input[type=checkbox] {
- appearance: none; -webkit-appearance: none; width: 14px; height: 14px; margin: 0;
- border: 1.5px solid var(--border); border-radius: 4px; background: var(--bg);
- cursor: pointer; position: relative;
- }
- .flags-in input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
- .flags-in input[type=checkbox]:checked::after {
- content: ""; position: absolute; left: 3px; top: 0; width: 3.5px; height: 7px;
- border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg);
- }
- .flags-in input[type=text] {
- background: var(--bg); color: var(--fg); border: 1px solid var(--border);
- border-radius: 5px; padding: 1px 5px; font: inherit; font-size: 12px; height: 22px;
- }
- .logsbtn { margin-left: auto; height: 20px; font-size: 11px; padding: 0 8px; flex-shrink: 0; }
- .win.flash { outline: 2px solid var(--accent); outline-offset: -1px; }
- .dockmenu {
- position: fixed; bottom: 44px; right: 12px; display: flex; flex-direction: column; gap: 4px;
- background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 8px;
- box-shadow: 0 12px 40px rgba(0,0,0,.5); z-index: 300; animation: winIn .15s ease both;
- }
- /* window switcher menu (header): same look, anchored below the header */
- .winmenu { position: fixed; top: 42px; right: 12px; bottom: auto;
- display: flex; flex-direction: column; gap: 2px;
- background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 8px;
- box-shadow: 0 12px 40px rgba(0,0,0,.5); z-index: 300; animation: winIn .15s ease both; }
- .winmenu .dock-chip { text-align: left; }
- .winmenu .wmax-on { font-weight: 600; }
- /* --- confirm dialog ------------------------------------------------------- */
- .dlg-back[hidden] { display: none; }
- .dlg-back {
- position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 400;
- display: flex; align-items: center; justify-content: center; animation: fadeIn .15s ease;
- }
- .dlg {
- background: var(--panel); border: 1px solid var(--border); border-radius: 10px;
- padding: 18px; width: min(460px, 92vw); max-height: 80vh; overflow: auto;
- box-shadow: 0 12px 40px rgba(0,0,0,.5); animation: winIn .2s ease both;
- }
- .dlg h3 { margin: 0 0 10px; font-size: 14px; }
- .dlg .body { font-size: 13px; color: var(--fg); margin-bottom: 12px; }
- .dlg .body code { font-family: var(--mono); font-size: 12px; background: var(--btn); padding: 1px 5px; border-radius: 4px; }
- .dlg .cbox { font-family: var(--mono); font-size: 12px; color: var(--muted); margin: 8px 0 0; padding: 8px; background: var(--btn); border-radius: 6px; }
- .dlg .cbox li { margin: 2px 0; }
- .dlg input {
- width: 100%; background: var(--btn); color: var(--fg); border: 1px solid var(--border);
- border-radius: 6px; padding: 6px 8px; font: inherit; margin: 8px 0;
- }
- .dlg .row { display: flex; justify-content: flex-end; gap: 8px; }
- @keyframes flip { 0% { transform: scale(1); } 40% { transform: scale(1.5); } 100% { transform: scale(1); } }
- @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: .35; } }
- @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
- @keyframes winIn { from { opacity: 0; transform: translateY(-4px) scale(.985); } to { opacity: 1; transform: none; } }
- @media (prefers-reduced-motion: reduce) {
- *, .led, .led.flip, .ssec.re .dot, .cluster, .job, .dlg, .win, .skeleton, .cled.exited, .abtn:disabled { animation: none !important; }
- }
- /* --- topology map ------------------------------------------------------- */
- #topo { height: 100%; overflow: hidden; }
- #topo svg { width: 100%; height: 100%; display: block; }
- #topo .topo-empty { height: 100%; display: grid; place-items: center; color: var(--muted); }
- #topo text { font: 12px/1.25 ui-sans-serif, system-ui; fill: var(--fg); }
- #topo .sub { fill: var(--muted); font-size: 10px; }
- #topo .dev { transition: opacity .5s, filter .5s; }
- #topo .dev.unpowered { opacity: .7; filter: grayscale(1); }
- #topo .dev.unpowered .body { fill: var(--bg); stroke-dasharray: 4 3; filter: none; }
- #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)); }
- #topo .dev .top { fill: color-mix(in srgb, var(--fg) 12%, transparent); }
- #topo .dev .vent { fill: color-mix(in srgb, var(--fg) 32%, transparent); }
- #topo .dev .plate { fill: color-mix(in srgb, var(--fg) 10%, var(--panel)); }
- #topo .dev .nm { font-size: 12.5px; font-weight: 600; }
- #topo .dev .ip { font-size: 10px; fill: var(--muted); font-family: var(--mono); }
- #topo .dev .ctr { fill: color-mix(in srgb, var(--muted) 22%, transparent); stroke: color-mix(in srgb, var(--muted) 60%, transparent); }
- #topo .dev .ctr.hot { fill: color-mix(in srgb, var(--led-busy) 35%, transparent); }
- #topo .dev .ctrt { font-size: 8.5px; fill: var(--muted); }
- #topo .dev.planned .body { stroke-dasharray: 4 4; opacity: .5; }
- .pled { fill: var(--led-free); }
- .pled.on { fill: var(--led-on); filter: drop-shadow(0 0 3px var(--led-on)); }
- .pled.b { fill: var(--led-busy); filter: drop-shadow(0 0 3px var(--led-busy)); animation: pulse 1.6s infinite; }
- .pled.off { fill: var(--led-off); }
- #topo .cable { fill: none; stroke-linecap: round; stroke-linejoin: round; }
- #topo .c-200g { stroke: color-mix(in srgb, var(--accent) 78%, transparent); stroke-width: 2.6; }
- #topo .c-dac { stroke: color-mix(in srgb, #a371f7 78%, transparent); stroke-width: 2.6; }
- #topo .c-10g { stroke: color-mix(in srgb, var(--muted) 68%, transparent); stroke-width: 1.5; }
- #topo .flow { opacity: 0; transition: opacity .6s; }
- #topo .flow.live { opacity: .9; }
- #topo .flow.c-200g { stroke: var(--accent); stroke-dasharray: 4 10; animation: flow 1.1s linear infinite; }
- #topo .flow.c-dac { stroke: #a371f7; stroke-dasharray: 4 10; animation: flow 1.1s linear infinite; }
- #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; }
- /* bus-mode crossings: the 10g run hops over the 200g lane */
- #topo .bridge { fill: none; stroke: color-mix(in srgb, var(--fg) 70%, transparent); stroke-width: 1.5; }
- #topo .cablemode { cursor: pointer; fill: var(--muted); font-size: 11px; }
- #topo .cablemode:hover { fill: var(--fg); text-decoration: underline; }
- @keyframes flow { to { stroke-dashoffset: -14; } }
- #topo .port { fill: var(--led-free); }
- #topo .port.on { fill: var(--led-on); }
- #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; }
- #topo .sw .swbox { transition: stroke .4s; }
- #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)); }
- #topo .sw.ib.off .swbox { stroke: color-mix(in srgb, var(--led-off) 75%, transparent); }
- #topo .sw.ib.unk .swbox { stroke: color-mix(in srgb, var(--led-busy) 60%, transparent); }
- #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; }
- #topo .fan .blade { fill: color-mix(in srgb, var(--fg) 34%, transparent); }
- #topo .fan .hub { fill: color-mix(in srgb, var(--fg) 50%, transparent); }
- #topo .fan .blades { transform-origin: 770px 318px; animation: spin 1.4s linear infinite; }
- #topo .fan.off .blades { animation: none; opacity: .4; }
- #topo .fan.unk .blades { animation: spin 4s linear infinite; opacity: .55; }
- @keyframes spin { to { transform: rotate(1turn); } }
- #topo .cluster-frame { cursor: pointer; }
- #topo .cluster-frame:hover .frame { stroke-width: 2.2; }
- #topo .fchip { cursor: pointer; }
- #topo .fchip:hover rect { stroke-width: 2; }
- #topo .fchip.down { filter: saturate(.5); }
- #topo .frame { stroke-width: 1.5; transition: opacity .4s; }
- #topo .cluster-frame.down .frame { stroke-dasharray: 5 4; opacity: .5; }
- #topo .fchip rect { fill: var(--panel); stroke-width: 1.2; }
- #topo .fchip text { font-size: 10.5px; letter-spacing: .3px; font-weight: 600; }
- #topo .fchip .cdot { fill: var(--led-off); }
- #topo .fchip .cdot.on { fill: var(--led-on); }
- #topo .legend text { font-size: 10.5px; fill: var(--muted); }
- </style>
- </head>
- <body>
- <header>
- <h1>sm121</h1>
- <div id="maxinfo" hidden><span>⛶</span><span class="maxtitle" id="max-title"></span>
- <button class="wbtn" id="max-restore" title="restore window size">❐</button>
- <button class="wbtn" id="max-min" title="minimize">–</button>
- <button class="wbtn" id="max-close" title="close">×</button></div>
- <div class="spacer"></div>
- <button class="tbtn" id="winmenu" title="all open windows (switch without losing maximize state)">▦</button>
- <div class="ssec" id="sse"><span class="dot"></span><span id="sse-t">connecting…</span></div>
- <button class="tbtn" id="theme">◐</button>
- </header>
- <div id="winlayer"></div>
- <div id="dock"></div>
- <div class="dlg-back" id="dlg" hidden>
- <div class="dlg">
- <h3 id="dlg-title"></h3>
- <div class="body" id="dlg-body"></div>
- <div class="row">
- <button class="tbtn" id="dlg-cancel">Cancel</button>
- <button class="abtn" id="dlg-ok">Confirm</button>
- </div>
- </div>
- </div>
- <script>
- "use strict";
- // Auth: the server may gate data endpoints with `--token` (required off
- // loopback). The token travels as `?token=...` (SSE EventSource cannot set
- // headers) — a one-shot URL param is promoted to localStorage, and every
- // data URL is wrapped with auth(). The /recipes iframe is same-origin, so
- // the embedded report page reads the same localStorage.
- const TOKEN = (() => {
- const q = new URLSearchParams(location.search).get("token");
- if (q) localStorage.setItem("sm121token", q);
- return localStorage.getItem("sm121token") || "";
- })();
- const auth = (p) => TOKEN ? p + (p.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(TOKEN) : p;
- function showTokenPrompt() {
- const d = document.createElement("div");
- d.style.cssText = "position:fixed;inset:0;z-index:100;background:var(--shade);display:flex;align-items:center;justify-content:center";
- const card = document.createElement("div");
- card.style.cssText = "background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:24px;max-width:360px";
- card.innerHTML = "<h3 style='margin:0 0 8px'>Dashboard token</h3>" +
- "<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>" +
- "<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'>";
- const btn = document.createElement("button");
- btn.textContent = "Connect";
- btn.style.cssText = "margin-top:10px;padding:8px 16px;background:var(--accent);color:#fff;border:0;border-radius:6px;cursor:pointer";
- const apply = () => { const v = document.getElementById("tok").value.trim(); if (v) { localStorage.setItem("sm121token", v); location.reload(); } };
- btn.onclick = apply;
- card.querySelector("input").addEventListener("keydown", (e) => { if (e.key === "Enter") apply(); });
- card.appendChild(btn);
- d.appendChild(card);
- document.body.appendChild(d);
- document.getElementById("tok").focus();
- }
- const $ = (s) => document.querySelector(s);
- const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
- const state = { snap: null, jobs: new Map(), recipes: [], active: localStorage.getItem("sm121-active") || "", panel: null, shown: new Set(), flags: {} };
- /*FLAGS-LT:START*/
- // Pure: build the POST /api/serve body from cluster + recipe + dry + the
- // per-cluster flags state. Absent keys are omitted (server defaults win):
- // fit "" = bare --fit (whole cluster), mirror "" = bare --mirror (default
- // path); a non-empty path wins over the bare checkbox.
- function serveBody(cluster, recipe, dry, f) {
- const body = { cluster, recipe, dry_run: !!dry };
- if (f.node) body.node = f.node;
- if (f.solo) body.solo = true;
- if (f.force) body.force = true;
- if (f.clear) body.clear = true;
- if (f.keep) body.keep = true;
- const fit = String(f.fit || "").trim();
- if (fit) body.fit = fit;
- else if (f.fitAll) body.fit = "";
- const mir = String(f.mirror || "").trim();
- if (mir) body.mirror = mir;
- else if (f.mirrorAll) body.mirror = "";
- return body;
- }
- function flagsOf(cluster) {
- return (state.flags[cluster] = state.flags[cluster] || { node: "", solo: false, force: false, clear: false, keep: false, fit: "", fitAll: false, mirror: "", mirrorAll: false });
- }
- /*FLAGS-LT:END*/
- /*SNAP-LT:START*/
- // Pure: same fleet + jobs? (`ts` changes on every probe, so it is
- // excluded). Used to skip DOM rebuilds when nothing changed — no blink.
- // (log-attaches are intentionally excluded: they change out-of-band and are
- // tracked in their own windows, not the cluster board)
- function sameSnapshot(a, b) {
- return JSON.stringify({ c: a.clusters, j: a.jobs }) === JSON.stringify({ c: b.clusters, j: b.jobs });
- }
- /*SNAP-LT:END*/
- // --- theme ---------------------------------------------------------------
- const root = document.documentElement;
- root.dataset.theme = localStorage.getItem("sm121-theme") || (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
- $("#max-restore").onclick = () => maxedHandle?.unmaximize();
- $("#max-min").onclick = () => maxedHandle?.minimize();
- $("#max-close").onclick = () => maxedHandle?.close();
- $("#theme").onclick = () => {
- root.dataset.theme = root.dataset.theme === "dark" ? "light" : "dark";
- localStorage.setItem("sm121-theme", root.dataset.theme);
- };
- // --- window manager ------------------------------------------------------
- // Vanilla win manager: absolute windows, drag by titlebar, corner resize,
- // minimize/close to the dock (chip to restore), click-to-front z-order.
- let ztop = 20;
- const wins = {}; // named windows: { topo, state, jobs }
- // every window ever created (named, logs, raw, recipes) — the dock lists
- // minimized ones from here, so a window can't be minimized into nowhere
- const winRegistry = new Set();
- const logWins = new Map(); // attach_id -> { win, pre, buf, paused, ... }
- const front = (el) => { el.style.zIndex = ++ztop; };
- // Multiple windows can be maximized at once — each keeps its own state —
- // but only one is shown: the rest stay maximized and merely hidden, and
- // the header switcher (▦) moves between them without losing anything.
- let maxedHandle = null; // the maximized window currently on screen
- function showMaxTitle(h) {
- if (maxedHandle && maxedHandle !== h) maxedHandle.win.style.display = "none";
- maxedHandle = h;
- h.win.style.display = "";
- front(h.win);
- $("#max-title").textContent = h.title;
- $("#maxinfo").hidden = false;
- }
- function hideMaxTitle(h) {
- if (maxedHandle !== h) return;
- maxedHandle = null;
- // a still-maximized window behind this one comes to the front of the
- // maximized stack — the layer never goes back to bare
- const others = [...winRegistry].filter(
- (x) => x !== h && x.isMaximized() && !x.isClosed() && x.win.isConnected,
- );
- if (others.length) showMaxTitle(others[others.length - 1]);
- else $("#maxinfo").hidden = true;
- }
- // Bring any open window forward: un-minimize if needed, and if it is
- // maximized, make it the one shown (hiding the other maximized ones).
- function activateWindow(h) {
- if (h.isMinimized()) h.restore();
- if (h.isMaximized()) {
- for (const o of winRegistry)
- if (o !== h && o.isMaximized() && !o.isClosed() && o.win.isConnected) o.win.style.display = "none";
- h.win.style.display = "";
- showMaxTitle(h);
- } else front(h.win);
- saveWinState();
- }
- let winMenuEl = null;
- function toggleWinMenu() {
- if (winMenuEl) { winMenuEl.remove(); winMenuEl = null; return; }
- const m = document.createElement("div");
- m.className = "winmenu";
- const open = [...winRegistry].filter((h) => !h.isClosed() && h.win.isConnected);
- const glyph = (h) => (h.isMaximized() ? "⛶ " : h.isMinimized() ? "– " : "▪ ");
- for (const h of open) {
- const b = document.createElement("button");
- b.className = "dock-chip" + (h === maxedHandle ? " wmax-on" : "");
- b.textContent = glyph(h) + h.label;
- b.title = (h.isMaximized() ? "maximized" : h.isMinimized() ? "minimized" : "floating") + " — click to show";
- b.onclick = () => { winMenuEl.remove(); winMenuEl = null; activateWindow(h); };
- m.appendChild(b);
- }
- document.body.appendChild(m);
- winMenuEl = m;
- setTimeout(() => addEventListener("click", () => { m.remove(); winMenuEl = null; }, { once: true }), 0);
- }
- $("#winmenu").onclick = (e) => { e.stopPropagation(); toggleWinMenu(); };
- // --- window layout persistence -------------------------------------------
- // The dashboard has no session: geometry, minimized/closed/maximized and
- // which optional windows are open are kept in localStorage and restored on
- // load (log windows come back from the server's attach registry instead).
- const WS_KEY = "sm121-wins";
- let restoring = false; // don't write half-restored state back
- function readWinState() {
- try { return JSON.parse(localStorage.getItem(WS_KEY) || "{}"); } catch { return {}; }
- }
- function saveWinState() {
- if (restoring) return;
- const st = {};
- const put = (k, h) => {
- st[k] = { ...h.geometry(), min: h.isMinimized(), closed: h.isClosed(), max: h.isMaximized() };
- };
- for (const [k, h] of Object.entries(wins)) put(k, h);
- if (recipesWin) put("recipes", recipesWin);
- if (rawWin) put("raw", rawWin);
- try { localStorage.setItem(WS_KEY, JSON.stringify(st)); } catch { /* private mode */ }
- }
- // Re-open an optional window (recipes/raw) exactly as it was left.
- function restoreWindow(key, open) {
- const st = readWinState()[key];
- if (!st || st.closed) return;
- Promise.resolve(open(st)).then((h) => {
- if (st.max) h.maximize();
- else if (st.min) h.minimize();
- });
- }
- // Windows keep px geometry, so a shrinking layer (dock appears, browser
- // resize) would push their bottom edge out of view — clamp them back in.
- function fitToLayer() {
- const layer = $("#winlayer");
- const W = layer.clientWidth, H = layer.clientHeight;
- for (const h of winRegistry) {
- const w = h.win;
- if (!w.isConnected || w.classList.contains("max")) continue;
- const left = parseFloat(w.style.left) || 0, top = parseFloat(w.style.top) || 0;
- if (left + w.offsetWidth > W) w.style.width = Math.max(240, W - left) + "px";
- if (top + w.offsetHeight > H) {
- if (top > H - 120) w.style.top = Math.max(0, H - 200) + "px";
- w.style.height = Math.max(140, H - (parseFloat(w.style.top) || 0)) + "px";
- }
- }
- }
- function makeWin({ id, title, short, x, y, w, h, bodyHtml, onClosed, extraCls, removeOnClose }) {
- const win = document.createElement("section");
- win.className = "win" + (extraCls ? " " + extraCls : "");
- if (id) win.id = id;
- win.style.cssText = `left:${x}px;top:${y}px;width:${w}px;height:${h}px;z-index:${++ztop}`;
- const bar = document.createElement("div");
- bar.className = "win-bar";
- bar.innerHTML = `<span class="wtitle">${esc(title)}</span>
- <button class="wbtn" data-act="max" title="maximize">▢</button>
- <button class="wbtn" data-act="min" title="minimize">–</button>
- <button class="wbtn" data-act="close" title="close">×</button>`;
- const body = document.createElement("div");
- body.className = "win-body";
- body.innerHTML = bodyHtml;
- const rz = document.createElement("div");
- rz.className = "win-resize";
- win.append(bar, body, rz);
- $("#winlayer").appendChild(win);
- const closed = { value: false };
- const doMin = () => {
- // minimize keeps the maximize state: a maximized window minimized goes
- // to the maximized stack (▦ switcher) and comes back full-screen
- win.style.display = "none";
- if (maxedHandle === handle) hideMaxTitle(handle);
- renderDock();
- saveWinState();
- };
- bar.querySelector('[data-act="min"]').onclick = doMin;
- // maximize = drop the frame and fill the window layer (the dock is a
- // sibling below it, so it stays usable); the title moves to the header
- const maxBtn = bar.querySelector('[data-act="max"]');
- let geom = null;
- const unmax = () => {
- if (!geom) return;
- win.classList.remove("max");
- Object.assign(win.style, geom);
- geom = null;
- maxBtn.textContent = "▢";
- maxBtn.title = "maximize";
- hideMaxTitle(handle);
- saveWinState();
- };
- maxBtn.onclick = () => {
- front(win);
- if (geom) { unmax(); return; }
- geom = { left: win.style.left, top: win.style.top, width: win.style.width, height: win.style.height };
- win.classList.add("max");
- win.style.left = "0px";
- win.style.top = "0px";
- win.style.width = "100%";
- win.style.height = "100%";
- maxBtn.textContent = "❐";
- maxBtn.title = "restore size";
- showMaxTitle(handle);
- saveWinState();
- };
- const doClose = () => {
- closed.value = true;
- hideMaxTitle(handle);
- if (removeOnClose) {
- // log/recipes/raw: gone for good (reopened from the + menu)
- win.remove();
- winRegistry.delete(handle);
- } else {
- // named windows stay addressable: the dock offers a + chip
- win.style.display = "none";
- }
- renderDock();
- saveWinState();
- if (onClosed) onClosed();
- };
- bar.querySelector('[data-act="close"]').onclick = doClose;
- bar.addEventListener("pointerdown", (e) => {
- if (e.target.closest(".wbtn") || win.classList.contains("max")) return;
- front(win);
- const ox = win.offsetLeft, oy = win.offsetTop; // baseline — read ONCE
- drag(
- e.clientX,
- e.clientY,
- (dx, dy) => {
- win.style.left = Math.max(0, ox + dx) + "px";
- win.style.top = Math.max(0, oy + dy) + "px";
- },
- saveWinState,
- );
- });
- rz.addEventListener("pointerdown", (e) => {
- e.stopPropagation();
- front(win);
- const ow = win.offsetWidth, oh = win.offsetHeight; // baseline — read ONCE
- drag(
- e.clientX,
- e.clientY,
- (dx, dy) => {
- win.style.width = Math.max(240, ow + dx) + "px";
- win.style.height = Math.max(140, oh + dy) + "px";
- },
- saveWinState,
- );
- });
- win.addEventListener("pointerdown", () => front(win));
- const handle = {
- win, body, title,
- label: short || title,
- unmaximize: unmax,
- minimize: doMin,
- close: doClose,
- maximize: () => maxBtn.onclick(),
- isMaximized: () => !!geom,
- setGeometry(g) {
- if (!g) return;
- const px = (v, d) => (Number.isFinite(parseFloat(v)) ? parseFloat(v) : d);
- win.style.left = Math.max(0, px(g.left, 0)) + "px";
- win.style.top = Math.max(0, px(g.top, 0)) + "px";
- win.style.width = Math.max(240, px(g.width, 600)) + "px";
- win.style.height = Math.max(140, px(g.height, 400)) + "px";
- },
- // the normal (un-maximized) rect — that is what gets persisted
- geometry: () => {
- const g = geom || { left: win.style.left, top: win.style.top, width: win.style.width, height: win.style.height };
- return { left: g.left, top: g.top, width: g.width, height: g.height };
- },
- restore() { win.style.display = ""; closed.value = false; front(win); renderDock(); },
- // a hidden maximized window is display:none but NOT minimized — it
- // waits in the maximized stack, reachable from the ▦ switcher
- isMinimized: () => win.style.display === "none" && !geom,
- isClosed: () => closed.value,
- };
- winRegistry.add(handle);
- return handle;
- }
- function drag(sx, sy, move, done) {
- const st = { x: sx, y: sy };
- const mv = (e) => move(e.clientX - st.x, e.clientY - st.y);
- const up = () => {
- removeEventListener("pointermove", mv);
- removeEventListener("pointerup", up);
- if (done) done();
- };
- addEventListener("pointermove", mv);
- addEventListener("pointerup", up);
- }
- function renderDock() {
- const dock = $("#dock");
- dock.innerHTML = "";
- const chip = (label, fn) => {
- const b = document.createElement("button");
- b.className = "dock-chip";
- b.textContent = label;
- b.onclick = fn;
- dock.appendChild(b);
- };
- const min = [...winRegistry].filter((h) => h.isMinimized() && h.win.isConnected);
- // "– " = minimized (still open), "+ " = closed (bring it back)
- for (const h of min) chip((h.isClosed() ? "+ " : "– ") + h.label, h.restore);
- if (!min.length && !rawWin) chip("+ raw config / recipe / effective", openRaw);
- // New-window menu (plan): State / Logs / Jobs / Raw.
- const plus = document.createElement("button");
- plus.className = "dock-chip plus";
- plus.textContent = "+";
- plus.title = "new window";
- plus.onclick = (e) => { e.stopPropagation(); toggleDockMenu(); };
- dock.appendChild(plus);
- fitToLayer(); // the dock just appeared/disappeared → the layer resized
- }
- let dockMenuEl = null;
- function closeDockMenu() { if (dockMenuEl) { dockMenuEl.remove(); dockMenuEl = null; } }
- function toggleDockMenu() {
- if (dockMenuEl) { closeDockMenu(); return; }
- const m = document.createElement("div");
- m.className = "dockmenu";
- const item = (label, fn) => {
- const b = document.createElement("button");
- b.className = "dock-chip";
- b.textContent = label;
- b.onclick = () => { closeDockMenu(); fn(); };
- m.appendChild(b);
- };
- item("topo", () => activateWindow(wins.topo));
- item("state", () => activateWindow(wins.state));
- item("jobs", () => activateWindow(wins.jobs));
- item("recipes", openRecipes);
- item("logs…", openLogsPicker);
- item("raw", openRaw);
- document.body.appendChild(m);
- dockMenuEl = m;
- setTimeout(() => addEventListener("click", closeDockMenu, { once: true }), 0);
- }
- // Open a logs window from the dock: pick a node (★ = running containers).
- function openLogsPicker() {
- const snap = state.snap;
- const body = document.createElement("div");
- body.className = "body";
- const sel = document.createElement("select");
- sel.style.cssText = "width:100%;margin:8px 0;padding:6px;background:var(--btn);color:var(--fg);border:1px solid var(--border);border-radius:6px;";
- if (snap) for (const c of snap.clusters) for (const n of c.nodes) {
- const o = document.createElement("option");
- o.value = c.name + "|" + n.name;
- o.textContent = (n.containers.length ? "★ " : "") + c.name + " / " + n.name + (n.containers.length ? " (" + n.containers.length + ")" : "");
- sel.appendChild(o);
- }
- body.innerHTML = `Open a logs window for a node (★ = has sm121 containers).`;
- body.appendChild(sel);
- openDialogHtml("open logs", body, () => {
- const i = sel.value.indexOf("|");
- openLog(sel.value.slice(0, i), sel.value.slice(i + 1));
- });
- }
- // --- SSE -------------------------------------------------------------------
- function sse(cls, txt) { $("#sse").className = "ssec " + cls; $("#sse-t").textContent = txt; }
- /*SSE-LT:START*/
- function connectSSE() {
- // the fleet polls every 30s, so a working stream is never silent for
- // long (plus 15s server keepalive comments). If it IS silent, the chip
- // is lying — rebuild the stream instead of trusting "open".
- const POLL_MS = 30000, STALE_MS = 3 * POLL_MS + 5000;
- let es = null, last = Date.now();
- const bounce = (txt) => {
- if (es) es.close();
- sse("re", txt);
- es = new EventSource(auth("/events"));
- // connection is up and a snapshot is already on its way — don't sit on
- // "connecting…" for a whole poll interval
- es.onopen = () => { last = Date.now(); sse("ok", "live"); };
- es.onmessage = (e) => {
- last = Date.now();
- sse("ok", "live");
- let ev;
- try { ev = JSON.parse(e.data); } catch { return; }
- if (ev.type === "state") onState(ev.snapshot);
- else if (ev.type === "job") onJob(ev);
- else if (ev.type === "log") onLog(ev);
- };
- es.onerror = () => {
- sse("re", "reconnecting…");
- // readyState CLOSED = EventSource gave up for good — only a fresh
- // object reconnects (the server replays the snapshot, so it heals
- // without a manual page reload)
- if (es.readyState === 2) setTimeout(() => bounce("reconnecting…"), 1000);
- };
- };
- bounce("connecting…");
- setInterval(() => {
- if (document.visibilityState === "visible" && Date.now() - last > STALE_MS) bounce("resyncing…");
- }, POLL_MS);
- // back from a frozen/sleeping tab or a network hop: check immediately
- document.addEventListener("visibilitychange", () => {
- if (document.visibilityState === "visible" && Date.now() - last > 40000) bounce("resyncing…");
- });
- addEventListener("online", () => bounce("reconnecting…"));
- }
- /*SSE-LT:END*/
- // --- state render ------------------------------------------------------------
- function ledState(n) { return n.reachable ? (n.occupied ? "b" : "on") : "off"; }
- function meta(n, c) {
- if (!n.reachable) return "offline";
- if (!c.up) return "online — cluster offline";
- if (n.occupied) return n.containers.map((x) => x.status).join(", ");
- return "free";
- }
- function clusterReason(c) {
- let r = "";
- if (c.up) r = "";
- else if (c.switch_off) r = "switch off";
- else {
- const off = c.nodes.filter((n) => !n.reachable).map((n) => n.name);
- r = off.length + " node" + (off.length === 1 ? "" : "s") + " offline" + (off.length ? " (" + off.join(", ") + ")" : "");
- }
- if (c.soft_off && c.soft_off.length) r = (r ? r + " · " : "") + "⚙ " + c.soft_off.join(", ") + " off";
- return r;
- }
- function renderCluster(c, prev, animate) {
- const el = document.createElement("div");
- el.className = "cluster" + (animate ? " anim" : "");
- const head = document.createElement("div");
- head.className = "cluster-head";
- if (c.up) {
- const soft = c.soft_off && c.soft_off.length ? `<span class="soft" title="non-blocking entity off">⚙ ${esc(c.soft_off.join(", "))} off</span>` : "";
- head.innerHTML = `<b>${esc(c.name)}</b><span class="free">${c.free} free</span>${soft}`;
- } else {
- head.innerHTML = `<b>${esc(c.name)}</b><span class="down">⏻ offline — ${esc(clusterReason(c))}</span>`;
- }
- el.appendChild(head);
- const prevNodes = prev ? Object.fromEntries(prev.nodes.map((n) => [n.name, n])) : {};
- for (const n of c.nodes) {
- const row = document.createElement("div");
- row.className = "node";
- row.title = "open logs for " + n.name;
- const cls = ledState(n);
- const flip = prevNodes[n.name] && ledState(prevNodes[n.name]) !== cls ? " flip" : "";
- row.innerHTML = `<span class="led ${cls}${flip}"></span>
- <span class="nname">${esc(n.name)}</span>
- <span class="nmeta" title="${esc(n.ssh_ip)}">${esc(meta(n, c))}</span>
- <button class="abtn logsbtn" title="open logs for ${esc(n.name)}">▤ logs</button>`;
- row.querySelector(".logsbtn").onclick = (e) => { e.stopPropagation(); openLog(c.name, n.name); };
- row.onclick = () => openLog(c.name, n.name);
- el.appendChild(row);
- if (n.occupied && n.containers.length) {
- const box = document.createElement("div");
- box.className = "containers";
- for (const x of n.containers) {
- const crow = document.createElement("div");
- crow.className = "crow";
- const dead = /exited|dead/i.test(x.status);
- crow.innerHTML = `<span class="cled${dead ? " exited" : ""}"></span><span class="cname">${esc(x.name)}</span><span>${esc(x.recipe)} · ${esc(x.status)}</span>`;
- box.appendChild(crow);
- }
- el.appendChild(box);
- }
- }
- el.appendChild(actionBar(c, prevNodes));
- return el;
- }
- function actionBar(c, prevNodes) {
- const bar = document.createElement("div");
- bar.className = "actions";
- if (!c.up) {
- // Down cluster: serve/stop are meaningless — only power actions apply.
- bar.appendChild(abtn("power-" + c.name, "power on", () => doPower("on", c.name), ""));
- bar.appendChild(abtn("pwswitch-" + c.name, "switch", () => doPower("switch", c.name), ""));
- return bar;
- }
- const sel = document.createElement("select");
- sel.id = "recipe-" + c.name;
- if (!state.recipes.length) {
- sel.innerHTML = "<option value=''></option>";
- } else {
- for (const r of state.recipes) {
- const o = document.createElement("option");
- o.value = r.name;
- o.textContent = r.name + (r.deploy === "tmux" ? " (tmux)" : "");
- sel.appendChild(o);
- }
- }
- bar.appendChild(sel);
- const dry = document.createElement("label");
- dry.innerHTML = `<input type="checkbox" id="dry-${esc(c.name)}"> dry-run`;
- bar.appendChild(dry);
- // Serve flags (CLI parity): solo / force / clear / keep / fit / mirror / node.
- // Values persist in state.flags across re-renders.
- const f = flagsOf(c.name);
- const nodeSel = document.createElement("select");
- nodeSel.className = "fnode";
- nodeSel.title = "target node (default: cluster selection)";
- nodeSel.innerHTML = `<option value=''>node: auto</option>` + c.nodes.map((n) => `<option value='${esc(n.name)}'>${esc(n.name)}</option>`).join("");
- nodeSel.value = f.node || "";
- nodeSel.onchange = () => { f.node = nodeSel.value; };
- const det = document.createElement("details");
- det.className = "flags";
- det.innerHTML = `<summary title="solo · force · fit · clear · mirror · keep (keep containers after stop)">⚙ flags</summary>
- <div class="flags-in">
- <label><input type="checkbox" id="fsolo-${esc(c.name)}"> solo</label>
- <label><input type="checkbox" id="fforce-${esc(c.name)}"> force</label>
- <label><input type="checkbox" id="fclear-${esc(c.name)}" title="clear cgroup memory limits (sudo) on launch nodes"> clear</label>
- <label><input type="checkbox" id="fkeep-${esc(c.name)}" title="keep containers after stop"> keep</label>
- <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>
- <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>
- </div>`;
- const wire = (id, key, isText) => {
- const el = det.querySelector("#" + id);
- if (isText) { el.value = f[key] || ""; el.oninput = () => { f[key] = el.value; }; }
- else { el.checked = !!f[key]; el.onchange = () => { f[key] = el.checked; }; }
- };
- wire("fsolo-" + c.name, "solo");
- wire("fforce-" + c.name, "force");
- wire("fclear-" + c.name, "clear");
- wire("fkeep-" + c.name, "keep");
- wire("ffitb-" + c.name, "fitAll");
- wire("ffit-" + c.name, "fit", true);
- wire("fmirr-" + c.name, "mirrorAll");
- wire("fmirror-" + c.name, "mirror", true);
- bar.appendChild(det);
- bar.appendChild(nodeSel);
- bar.appendChild(abtn("serve-" + c.name, "serve", () => doServe(c.name)));
- bar.appendChild(abtn("stop-" + c.name, "stop", () => doStop(c.name), "danger"));
- bar.appendChild(abtn("power-" + c.name, "power off", () => doPower("off", c.name), "danger"));
- bar.appendChild(abtn("pwswitch-" + c.name, "switch", () => doPower("switch", c.name), ""));
- return bar;
- }
- function abtn(id, label, fn, cls) {
- const b = document.createElement("button");
- b.className = "abtn " + (cls || "");
- b.id = id;
- b.textContent = label;
- b.onclick = fn;
- return b;
- }
- function onState(snap, force) {
- const prev = state.snap;
- updateLogNotes(snap); // runs even on no-churn ticks (attaches change out-of-band)
- if (!force && prev && sameSnapshot(prev, snap)) {
- state.snap = snap; // adopt the fresh attaches state; no DOM churn
- return; // nothing else changed — no rebuild
- }
- state.snap = snap;
- state.jobs = new Map(snap.jobs.map((j) => [j.id, j]));
- renderTopo(snap);
- if (!snap.clusters.find((c) => c.name === state.active)) {
- state.active = snap.clusters[0] ? snap.clusters[0].name : "";
- }
- // control state must survive the rebuild (recipe pick, dry-run tick)
- const activeName = state.active;
- const keepRecipe = recipeOf(activeName);
- const keepDry = dryOf(activeName);
- const animate = state.panel !== activeName; // first paint or cluster switch
- state.panel = activeName;
- const box = $("#clusters");
- box.innerHTML = "";
- const active = snap.clusters.find((c) => c.name === activeName);
- if (active) {
- box.appendChild(renderCluster(active, prev ? prev.clusters.find((p) => p.name === activeName) : null, animate));
- }
- restoreControls(activeName, keepRecipe, keepDry);
- // compact fleet strip: one chip per cluster, click to make it active
- const strip = document.createElement("div");
- strip.className = "strip";
- for (const c of snap.clusters) {
- const chip = document.createElement("div");
- chip.className = "chip" + (c.name === state.active ? " active" : "");
- const dot = c.up ? (c.free > 0 ? "on" : "b") : "off";
- const m = c.up ? c.free + " free" : "⏻ OFF";
- chip.title = clusterReason(c);
- chip.innerHTML = `<span class="led ${dot}"></span>${esc(c.name)}<span class="m">${m}</span>`;
- chip.onclick = () => { state.active = c.name; localStorage.setItem("sm121-active", c.name); onState(state.snap, true); };
- strip.appendChild(chip);
- }
- box.appendChild(strip);
- renderJobs();
- }
- function restoreControls(name, recipe, dry) {
- if (!name) return;
- const d = document.getElementById("dry-" + name);
- if (d && dry) d.checked = true;
- const sel = document.getElementById("recipe-" + name);
- if (sel && recipe) {
- for (const o of sel.options) if (o.value === recipe) { sel.value = recipe; break; }
- }
- }
- // --- topology map -------------------------------------------------------------
- // The physical layer behind the windows: 8 GX10 boxes on a 2×4 grid, the
- // 200G fabric switch and the passive 10G switch in the middle corridor,
- // DAC direct links, HA glyphs (fan) and cluster frames. The structure is
- // rebuilt only when the topo signature changes (config edit); state ticks
- // just flip classes so flow/pulse/spin animations keep running.
- const TG_W = 1060, TG_H = 540;
- const tgPos = (i) => {
- const cx = 20 + (i % 4) * 255;
- return { x: cx + 37, y: i < 4 ? 74 : 386, w: 180, h: 104, dcx: cx + 127 };
- };
- const tgSlot = (n) => {
- const m = String(n).match(/\d+/);
- return m ? +m[0] : 999;
- };
- const tgIdx = (t, name) => t.nodes.findIndex((n) => n === name);
- // cluster identity colors — green/red stay reserved for up/down state
- const TG_HUES = ["#58a6ff", "#a371f7", "#f778ba", "#f0883e", "#39c5cf", "#e3b341", "#ff7b72", "#79c0ff", "#d2a8ff", "#ffa657"];
- const hueOf = (name) => {
- let h = 0;
- for (const c of String(name)) h = (h * 31 + c.charCodeAt(0)) >>> 0;
- return TG_HUES[h % TG_HUES.length];
- };
- function topoSig(t) {
- return t.nodes.join(",") + "|" + t.links.map((l) => l.kind + l.a + ">" + l.b).join(",")
- + "|" + t.switches.map((s) => s.entity).join(",");
- }
- function tgCablePath(l, t) {
- const bi = tgIdx(t, l.b);
- if (bi < 0) return "";
- const b = tgPos(bi);
- if (l.kind === "10g") {
- const px = 396 + bi * 38;
- if (bi < 4) { // row0: device bottom → 10G switch top
- const ex = b.dcx + 40, ey = b.y + b.h;
- return `M ${ex} ${ey} C ${ex} ${ey + 26} ${px} ${ey + 6} ${px} 210`;
- }
- return `M ${b.dcx} ${b.y} C ${b.dcx} ${b.y - 50} ${px} ${b.y - 80} ${px} 266`;
- }
- if (l.kind === "200g") {
- const fi = t.links.filter((x) => x.kind === "200g").findIndex((x) => x.b === l.b);
- const px = 396 + (fi % 4) * 80;
- if (bi < 4) { // row0: device bottom → fabric switch top
- const ex = b.dcx - 40, ey = b.y + b.h;
- return `M ${ex} ${ey} C ${ex} ${ey + 76} ${px} ${ey + 66} ${px} 290`;
- }
- // row1: device top → fabric switch bottom — an S-curve inside the 40px
- // corridor (switch bottom 346 .. device top 386) so the last approach
- // to the port is vertical, not a slide in from the side
- const ex = b.dcx - 40, ey = b.y;
- return `M ${ex} ${ey} C ${ex} 363 ${px} 363 ${px} 346`;
- }
- // dac: arc between adjacent device tops
- const ai = tgIdx(t, l.a);
- if (ai < 0) return "";
- const a = tgPos(ai);
- const mx = (a.x + a.w + b.x) / 2;
- 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}`;
- }
- function devSvg(name, i) {
- const d = tgPos(i);
- return `<g class="dev" data-dev="${esc(name)}" transform="translate(${d.x},${d.y})">
- <title>${esc(name)}</title>
- <rect class="body" width="${d.w}" height="${d.h}" rx="10"/>
- <rect class="top" x="4" y="3" width="${d.w - 8}" height="7" rx="3.5"/>
- <rect class="vent" x="14" y="24" width="5" height="24" rx="2.5"/>
- <rect class="vent" x="23" y="24" width="5" height="24" rx="2.5"/>
- <rect class="vent" x="32" y="24" width="5" height="24" rx="2.5"/>
- <rect class="ctr" x="122" y="18" width="52" height="15" rx="7.5"/>
- <text class="ctrt" x="148" y="29" text-anchor="middle">…</text>
- <rect class="plate" x="1" y="62" width="${d.w - 2}" height="41" rx="8"/>
- <text class="nm" x="12" y="79">${esc(name)}</text>
- <text class="ip" x="12" y="94">…</text>
- <circle class="pled" cx="166" cy="74" r="4"/>
- </g>`;
- }
- function swSvg(sw, entries) {
- const label = sw.kind === "lan" ? "10G switch"
- : sw.entity.includes(".") ? sw.entity.split(".")[1] : sw.entity;
- const ib = sw.kind === "ib";
- const y = ib ? 290 : 210;
- const sub = ib ? "200G fabric · HA" : "passive · no HA";
- const step = ib ? 80 : 38;
- // ib ports sit 4+4 across two edges (the box fits 4 per edge at step 80);
- // lan ports keep the continuous index (step 38 fits 8 across 2 rows)
- 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)}"
- x="${396 + col * step - 7}" y="${p.top ? y + 2 : y + 49}" width="14" height="7" rx="2"/>`; }).join("");
- return `<g class="sw ${sw.kind}" data-sw="${esc(sw.entity)}" transform="translate(0,0)">
- <title>${esc(sw.entity)}</title>
- <rect class="swbox" x="370" y="${y}" width="320" height="56" rx="8"/>
- ${rows}
- <text x="386" y="${y + 32}">${esc(label)}</text>
- <text class="sub" x="386" y="${y + 46}">${sub}</text>
- ${ib ? '<circle class="pled swled" cx="672" cy="' + (y + 40) + '" r="4"/>' : ""}
- </g>`;
- }
- function fanSvg(sw) {
- return `<g class="fan" data-sw="${esc(sw.entity)}">
- <title>${esc(sw.entity)}</title>
- <circle class="fbody" cx="770" cy="318" r="26"/>
- <g class="blades">
- <path class="blade" d="M770 294 C 781 298 783 310 775 316 L 770 318 Z"/>
- <path class="blade" d="M770 294 C 781 298 783 310 775 316 L 770 318 Z" transform="rotate(120 770 318)"/>
- <path class="blade" d="M770 294 C 781 298 783 310 775 316 L 770 318 Z" transform="rotate(240 770 318)"/>
- <circle class="hub" cx="770" cy="318" r="5"/>
- </g>
- <text class="sub" x="770" y="362" text-anchor="middle">${esc(sw.entity.split(".")[1] || sw.entity)}</text>
- </g>`;
- }
- function topoFrames(snap) {
- const t = snap.topo;
- // clusters with identical node sets share one frame (several chips on
- // it) — no doubled rectangles, no mutual-containment depth inflation
- const seen = new Map();
- const groups = [];
- for (const c of snap.clusters) {
- const key = c.nodes.map((n) => n.name).sort().join("|");
- if (seen.has(key)) seen.get(key).clusters.push(c);
- else {
- const g = { clusters: [c], nodes: c.nodes.map((n) => n.name) };
- seen.set(key, g);
- groups.push(g);
- }
- }
- const contains = (a, b) => b.nodes.every((n) => a.nodes.includes(n));
- const depthOf = (x) => groups.filter((o) => o !== x && contains(o, x)).length;
- // pads grow with cluster rank in its region: the outermost (most
- // containing) cluster sits furthest out on BOTH edges, so label chips
- // land on separate "floors" and frame edges never stack into one line;
- // inner frames hug their nodes
- const pad = (g) => {
- const d = depthOf(g);
- const region = groups.filter((o) => o.nodes.some((n) => g.nodes.includes(n)));
- const rmax = Math.max(...region.map(depthOf));
- return { x: 14 + 10 * (rmax - d), top: 12 + 18 * (rmax - d), bottom: 12 + 5 * (rmax - d) };
- };
- const rects = [];
- for (const g of groups) {
- const ps = g.nodes.map((n) => tgPos(tgIdx(t, n))).filter(Boolean);
- if (!ps.length) continue;
- const p = pad(g);
- const x = Math.min(...ps.map((q) => q.x)) - p.x;
- const y = Math.min(...ps.map((q) => q.y)) - p.top;
- const w = Math.max(...ps.map((q) => q.x + q.w)) + p.x - x;
- const h = Math.max(...ps.map((q) => q.y + q.h)) + p.bottom - y;
- rects.push({ g, x, y, w, h, area: w * h });
- }
- rects.sort((a, b) => b.area - a.area); // big frames behind, nested on top
- // a chip never shares its hue with a frame that contains its frame
- // (containers sort first — bigger area — so their hues are final)
- for (const r of rects) {
- const containers = rects.filter((o) => o !== r && o.x <= r.x && o.y <= r.y
- && o.x + o.w >= r.x + r.w && o.y + o.h >= r.y + r.h);
- for (const c of r.g.clusters) {
- let hue = hueOf(c.name);
- while (containers.some((o) => o.hue === hue)) {
- hue = TG_HUES[(TG_HUES.indexOf(hue) + 1) % TG_HUES.length];
- }
- c._hue = hue;
- }
- r.hue = r.g.clusters[0]._hue;
- }
- // chip bands: chips sharing a frame-top floor get x-staggered so labels
- // never overlap (merged frames put several chips on one frame)
- const bands = new Map();
- for (const r of rects) {
- for (const c of r.g.clusters) (bands.get(r.y) ?? bands.set(r.y, []).get(r.y)).push({ r, c });
- }
- for (const band of bands.values()) {
- band.sort((a, b) => a.r.x - b.r.x || a.c.name.localeCompare(b.c.name));
- let cursor = -1e9;
- for (const chip of band) {
- chip.cw = chip.c.name.length * 6.6 + 30;
- chip.x = Math.max(chip.r.x + 12, cursor);
- cursor = chip.x + chip.cw + 6;
- }
- }
- state.topoGroupTitles = {};
- for (const r of rects) {
- state.topoGroupTitles[r.g.clusters[0].name] = r.g.clusters.map((c) => c.name).join(" · ");
- }
- // two layers: frame rects (below cables/devices) and chips (topmost —
- // opaque badges, nothing shows through, always clickable)
- let frames = "", chips = "";
- for (const r of rects) {
- frames += `<g class="cluster-frame" data-cluster="${esc(r.g.clusters[0].name)}">
- <title>${esc(r.g.clusters.map((c) => c.name).join(" · "))}</title>
- <rect class="frame" style="stroke:${r.hue};fill:color-mix(in srgb, ${r.hue} 6%, transparent)"
- x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" rx="14"/>
- </g>`;
- }
- for (const r of rects) {
- for (const c of r.g.clusters) {
- const chip = bands.get(r.y).find((x) => x.c === c);
- chips += `<g class="fchip" data-cluster="${esc(c.name)}" transform="translate(${chip.x},${r.y - 8})">
- <title>${esc(c.name)}</title>
- <rect width="${chip.cw}" height="16" rx="8" style="stroke:${c._hue}"/>
- <circle class="cdot" cx="10" cy="8" r="3.5"/>
- <text x="18" y="12" style="fill:${c._hue}">${esc(c.name)}</text>
- </g>`;
- }
- }
- return { frames, chips };
- }
- function cablesSvg(t, bus) {
- let out = "";
- for (const l of t.links) {
- const p = bus ? tgCablePathBus(l, t) : tgCablePath(l, t);
- if (!p) continue;
- const key = `${l.kind}|${l.a}|${l.b}`;
- out += `<path class="cable c-${l.kind}" d="${p}"/>`;
- out += `<path class="cable c-${l.kind} flow" data-flow="${esc(key)}" d="${p}"/>`;
- }
- if (bus) out += bridgesSvg(t);
- return out;
- }
- // Bus mode: row-1 (bottom) cables route as right-angle runs along two
- // shared lanes — 200g at y=366 (in the 40px corridor under the fabric
- // switch), 10g at y=278 (the 24px gap between the two switches). A 10g
- // cable whose vertical would cut the fabric switch detours around its
- // nearer side. Where a 10g run crosses the 200g lane it hops over it on
- // a bridge arc, so crossings read as intentional.
- function tgCablePathBus(l, t) {
- const bi = tgIdx(t, l.b);
- if (bi < 0 || bi < 4) return tgCablePath(l, t); // row 0 and DAC unchanged
- const b = tgPos(bi);
- if (l.kind === "200g") {
- const ex = b.dcx - 40;
- const fi = t.links.filter((x) => x.kind === "200g").findIndex((x) => x.b === l.b);
- const px = 396 + (fi % 4) * 80;
- return `M ${ex} 386 L ${ex} 366 L ${px} 366 L ${px} 346`;
- }
- // 10g: up the device side, across the inter-switch gap, down to the port
- const px = 396 + bi * 38;
- const x = b.dcx;
- if (x < 370 || x > 690) return `M ${x} 386 L ${x} 278 L ${px} 278 L ${px} 266`;
- const side = x < 530 ? 350 : 710; // nearest clearance past the fabric box
- return `M ${x} 386 L ${x} 366 L ${side} 366 L ${side} 278 L ${px} 278 L ${px} 266`;
- }
- // Small semicircle hops where a 10g row-1 vertical crosses the 200g lane.
- function bridgesSvg(t) {
- const lane = t.links
- .filter((l) => l.kind === "200g")
- .map((l) => {
- const bi = tgIdx(t, l.b);
- if (bi < 4) return null;
- const b = tgPos(bi);
- const ex = b.dcx - 40;
- const fi = t.links.filter((x) => x.kind === "200g").findIndex((x) => x.b === l.b);
- const px = 396 + (fi % 4) * 80;
- return { y: 366, x1: Math.min(ex, px), x2: Math.max(ex, px) };
- })
- .filter(Boolean);
- let out = "";
- for (const l of t.links.filter((l) => l.kind === "10g")) {
- const bi = tgIdx(t, l.b);
- if (bi < 4) continue;
- const x = tgPos(bi).dcx;
- // detour devices turn ON the lane (a T-junction) — only a vertical that
- // spans the lane (outer devices, x outside the fabric box) gets a hop
- if (x >= 370 && x <= 690) continue;
- for (const h of lane)
- if (x > h.x1 + 2 && x < h.x2 - 2)
- out += `<path class="bridge b-10g" d="M ${x - 5} ${h.y} A 5 5 0 0 1 ${x + 5} ${h.y}"/>`;
- }
- return out;
- }
- function switchesSvg(t) {
- const fi = {};
- const fabEntries = t.links.filter((l) => l.kind === "200g").map((l) => ({
- name: l.b, i: (fi[l.b] = fi[l.b] ?? Object.keys(fi).length), top: fi[l.b] < 4,
- }));
- const lanEntries = t.nodes.map((n, i) => ({ name: n, i, top: i < 4 }));
- const glyphs = t.switches.map((s) => s.kind === "aux" ? fanSvg(s) : swSvg(s, fabEntries)).join("");
- // the passive 10G switch has no HA entity — the UI draws it explicitly
- return glyphs + swSvg({ entity: "lan", kind: "lan" }, lanEntries);
- }
- const devsSvg = (t) => t.nodes.map((n, i) => devSvg(n, i)).join("");
- function legendSvg(bus) {
- return `<g class="legend" transform="translate(20,526)">
- <line x1="0" y1="0" x2="26" y2="0" class="cable c-200g"/><text x="32" y="4">200G fabric</text>
- <line x1="120" y1="0" x2="146" y2="0" class="cable c-dac"/><text x="152" y="4">DAC direct</text>
- <line x1="240" y1="0" x2="266" y2="0" class="cable c-10g"/><text x="272" y="4">10G mgmt</text>
- <circle cx="352" cy="0" r="4" class="pled on"/><text x="362" y="4">plug on</text>
- <circle cx="428" cy="0" r="4" class="pled off"/><text x="438" y="4">plug off / HA?</text>
- <text x="560" y="4" class="cablemode" data-topobus="1">cables: ${bus ? "bus + bridges" : "direct"} ▸</text>
- </g>`;
- }
- // Per-tick state update: flip LED/port/frame/flow classes in place —
- // the SVG skeleton survives, so CSS animations keep running.
- // Power policy for fabric ports and their cable flows: a port is green only
- // when its switch reports ON (unknown is tolerated) AND the node is
- // occupied — an HA-OFF switch cannot carry traffic, so all of its ports
- // stay gray even if a node still reports a running container.
- /*TOPOPORT:START*/
- function fabPortOn(swOn, occupied) {
- return swOn !== false && !!occupied;
- }
- /*TOPOPORT:END*/
- function topoTick(snap) {
- const t = snap.topo;
- const ns = {};
- for (const c of snap.clusters) for (const n of c.nodes) {
- const s = (ns[n.name] ||= { reachable: false, occupied: false, ha: undefined, containers: [] });
- s.reachable ||= n.reachable;
- s.occupied ||= n.occupied;
- if (!s.ip) s.ip = n.ssh_ip;
- if (n.ha !== null) s.ha = n.ha;
- for (const ct of n.containers) if (!s.containers.some((x) => x.name === ct.name)) s.containers.push(ct);
- }
- for (const name of t.nodes) {
- const g = document.querySelector(`#topo g[data-dev="${CSS.escape(name)}"]`);
- const s = ns[name];
- if (!g || !s) continue;
- const led = g.querySelector(".pled");
- if (led) led.setAttribute("class", "pled " + (s.reachable ? (s.occupied ? "b" : "on") : "off"));
- g.classList.toggle("unpowered", s.ha === false);
- const ip = g.querySelector(".ip");
- if (ip) ip.textContent = s.ip || "";
- const ctr = g.querySelector(".ctrt"), chip = g.querySelector(".ctr");
- const recipes = [...new Set(s.containers.map((x) => x.recipe))];
- if (ctr) ctr.textContent = s.containers.length ? `${s.containers.length}·${recipes[0].slice(0, 7)}` : "idle";
- if (chip) chip.classList.toggle("hot", s.containers.length > 0);
- const tt = g.querySelector("title");
- if (tt) tt.textContent = `${name} · ${s.ip || ""} · ${s.reachable ? (s.occupied ? "serving" : "free") : "down"}`
- + (s.ha === false ? " · plug OFF" : "")
- + (s.containers.length ? " · " + s.containers.map((x) => x.name).join(", ") : "");
- }
- const swStateOf = (ent) => t.states.find((x) => x.entity === ent)?.on;
- for (const l of t.links) {
- const fl = document.querySelector(`#topo path[data-flow="${CSS.escape(l.kind + "|" + l.a + "|" + l.b)}"]`);
- if (!fl) continue;
- const B = ns[l.b], A = l.kind === "dac" ? ns[l.a] : null;
- fl.classList.toggle("live", l.kind === "10g" ? !!B?.reachable
- : l.kind === "200g" ? fabPortOn(swStateOf(l.a), B?.occupied)
- : !!(B?.occupied && A?.occupied));
- }
- for (const name of t.nodes) {
- const lp = document.querySelector(`#topo rect[data-lanport="${CSS.escape(name)}"]`);
- if (lp) lp.classList.toggle("on", !!ns[name]?.reachable);
- const fp = document.querySelector(`#topo rect[data-fabport="${CSS.escape(name)}"]`);
- if (fp) {
- const swEnt = fp.closest("[data-sw]")?.dataset?.sw;
- fp.classList.toggle("on", fabPortOn(swStateOf(swEnt), ns[name]?.occupied));
- }
- }
- for (const sw of t.switches) {
- const st = t.states.find((x) => x.entity === sw.entity);
- const g = document.querySelector(`#topo [data-sw="${CSS.escape(sw.entity)}"]`);
- if (!g) continue;
- const cls = st?.on === true ? "on" : st?.on === false ? "off" : "unk";
- g.classList.remove("on", "off", "unk");
- g.classList.add(cls);
- const led = g.querySelector(".swled");
- if (led) led.setAttribute("class", "pled swled " + (st?.on === true ? "on" : st?.on === false ? "off" : ""));
- const tt = g.querySelector("title");
- if (tt) tt.textContent = `${sw.entity} · ${st?.on === true ? "on" : st?.on === false ? "OFF" : "state unknown"}`;
- }
- for (const c of snap.clusters) {
- const st = `${c.up ? `up · ${c.free} free` : "down"}${c.switch_off ? " · HA switch off" : ""}`;
- for (const g of document.querySelectorAll(`#topo [data-cluster="${CSS.escape(c.name)}"]`)) {
- g.classList.toggle("down", !c.up);
- const dot = g.querySelector(".cdot");
- if (dot) dot.setAttribute("class", "cdot " + (c.up ? "on" : "off"));
- const tt = g.querySelector("title");
- if (tt) tt.textContent = `${(state.topoGroupTitles || {})[c.name] || c.name} · ${st}`;
- }
- }
- }
- function renderTopo(snap) {
- const host = document.getElementById("topo");
- const t = snap.topo;
- if (!host || !t) return;
- if (state.topoBus === undefined) state.topoBus = localStorage.getItem("sm121-topobus") === "1";
- const sig = topoSig(t) + (state.topoBus ? ":bus" : ":direct");
- if (state.topoSig !== sig) {
- state.topoSig = sig;
- const tf = topoFrames(snap);
- host.innerHTML = `<svg viewBox="0 0 ${TG_W} ${TG_H}" preserveAspectRatio="xMidYMid meet">
- ${tf.frames}${cablesSvg(t, state.topoBus)}${switchesSvg(t)}${devsSvg(t)}${legendSvg(state.topoBus)}${tf.chips}
- </svg>`;
- for (const g of host.querySelectorAll("[data-cluster]")) {
- g.onclick = () => {
- state.active = g.dataset.cluster;
- localStorage.setItem("sm121-active", state.active);
- if (wins.state) wins.state.isMinimized() ? wins.state.restore() : front(wins.state.win);
- onState(state.snap, true);
- };
- }
- // cable-mode toggle (legend): direct bezier runs ↔ bus + bridge arcs
- const cm = host.querySelector("[data-topobus]");
- if (cm)
- cm.onclick = () => {
- state.topoBus = !state.topoBus;
- localStorage.setItem("sm121-topobus", state.topoBus ? "1" : "0");
- state.topoSig = ""; // force a re-render with the other mode
- renderTopo(state.snap || snap);
- };
- }
- topoTick(snap);
- }
- // --- jobs ---------------------------------------------------------------------
- // "Running" entries come from the docker labels (sm121.recipe / sm121.cluster)
- // on live containers — jobs don't need to have started from this dashboard.
- // One row per launcher job, NOT per node×cluster: a container is visible on
- // every cluster sharing its node, so the board used to look entirely busy.
- /*JOBS-LT:START*/
- function runningFromLabels() {
- const m = new Map();
- if (!state.snap) return [];
- for (const c of state.snap.clusters) {
- if (!c.up) continue; // down clusters report no containers
- for (const n of c.nodes) {
- for (const x of n.containers) {
- const key = x.cluster + "|" + x.recipe;
- let r = m.get(key);
- if (!r) m.set(key, (r = { cluster: x.cluster, recipe: x.recipe, nodes: [], statuses: new Set() }));
- if (!r.nodes.includes(n.name)) r.nodes.push(n.name);
- r.statuses.add(x.status);
- }
- }
- }
- const nat = (a, b) => a.localeCompare(b, undefined, { numeric: true });
- return [...m.values()].map((r) => ({ ...r, nodes: r.nodes.sort(nat), statuses: [...r.statuses].sort(nat) }));
- }
- /*JOBS-LT:END*/
- function renderJobs() {
- const box = $("#jobs");
- box.innerHTML = "";
- const prevShown = state.shown;
- state.shown = new Set();
- const row = (key, cls, html) => {
- const el = document.createElement("div");
- el.className = "job " + cls + (prevShown.has(key) ? "" : " new");
- el.innerHTML = html;
- box.appendChild(el);
- state.shown.add(key);
- return el;
- };
- const run = runningFromLabels();
- if (run.length) {
- const h = document.createElement("div");
- h.className = "jobs-empty"; h.textContent = "running (docker labels)";
- box.appendChild(h);
- for (const r of run) {
- const many = r.nodes.length > 1;
- row("c:" + r.cluster + ":" + r.recipe, "jjob",
- `<span class="jdot"></span><span class="jkind">serve</span>
- <span class="jmsg">${esc(r.cluster)}:${esc(r.recipe || "?")} — ${r.nodes.length} node${many ? "s" : ""} (${esc(r.nodes.join(", "))}) · ${esc(r.statuses.join(", "))}</span>`);
- }
- }
- const js = [...state.jobs.values()].sort((a, b) => b.started - a.started);
- 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; }
- if (run.length) {
- const sep = document.createElement("div");
- sep.className = "jobs-empty"; sep.textContent = "actions";
- box.appendChild(sep);
- }
- for (const j of js) {
- const cls = j.status === "ok" ? "ok" : j.status === "failed" ? "failed" : "jjob";
- const when = new Date(j.started * 1000).toLocaleTimeString();
- row("j:" + j.id, cls, `<span class="jdot"></span><span class="jkind">${esc(j.kind)}</span>
- <span class="jmsg">${esc(j.cluster)}${j.recipe ? ":" + esc(j.recipe) : ""} — ${esc(j.message)} <span>(${when})</span></span>`);
- setBtnBusy(j, j.status === "running");
- }
- }
- function setBtnBusy(j, busy) {
- // power jobs disable both the off and switch buttons (the job event
- // doesn't carry the action)
- const keys = j.kind === "power" ? ["power", "pwswitch"] : [j.kind];
- for (const k of keys) {
- const el = document.getElementById(k + "-" + j.cluster);
- if (el) el.disabled = busy;
- }
- }
- // --- job events ------------------------------------------------------------------
- function onJob(ev) {
- if (ev.event === "started") {
- 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 });
- }
- const j = state.jobs.get(ev.id);
- if (j && ev.event !== "started") {
- j.message = ev.message;
- j.status = ev.event === "ok" ? "ok" : "failed";
- }
- renderJobs();
- }
- // Stream-end notes: the snapshot carries attaches[].done; surface a
- // re-attach hint in each log window whose stream died.
- function updateLogNotes(snap) {
- for (const w of logWins.values()) {
- if (!w.attach || !snap.attaches) continue;
- const a = snap.attaches.find((x) => x.id === w.attach);
- const note = w.win.querySelector(".lognote");
- if (!note) continue;
- if (a && a.done && !note.classList.contains("dead")) {
- note.textContent = "stream ended — click ↻ to re-attach";
- note.classList.add("dead");
- }
- }
- }
- function attachDone(attachId) {
- if (!attachId) return true;
- const a = state.snap && state.snap.attaches ? state.snap.attaches.find((x) => x.id === attachId) : null;
- return a ? a.done : false;
- }
- function flashWin(win) {
- win.classList.add("flash");
- setTimeout(() => win.classList.remove("flash"), 700);
- }
- // --- log windows -------------------------------------------------------------------
- const MAX_PRE_LINES = 1000;
- // ponytail: trimPre re-splits the whole text per line (O(n)); fine at log
- // rates — ring it (line array) if a busy container makes this visible.
- function trimPre(pre) {
- const t = pre.textContent;
- if (t.split("\n").length > MAX_PRE_LINES + 1) {
- pre.textContent = t.split("\n").slice(-MAX_PRE_LINES).join("\n");
- }
- }
- function appendLogLine(w, line) {
- if (w.paused) { w.buf += line + "\n"; return; }
- preSet(w, w.pre.textContent + line + "\n");
- }
- function preSet(w, text) {
- w.pre.textContent = text;
- trimPre(w.pre);
- if (!w.paused) w.pre.scrollTop = w.pre.scrollHeight;
- }
- function onLog(ev) {
- const w = logWins.get(ev.attach);
- if (!w) return; // window closed (or from another tab) — nothing to show
- appendLogLine(w, ev.line);
- }
- async function openLog(cluster, node, recipe) {
- const snap = state.snap;
- const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
- const n = c ? c.nodes.find((x) => x.name === node) : null;
- if (!n) return;
- // A window for this node is already open and no specific recipe asked for
- // → front it with feedback; if its stream died, re-attach (fresh history).
- if (!recipe) {
- for (const w of logWins.values()) if (w.cluster === cluster && w.node === node) {
- front(w.win);
- flashWin(w.win);
- if (w.attach && attachDone(w.attach)) reattachLog(w); // dead stream → fresh
- return;
- }
- }
- recipe = recipe || (n.containers[0] ? n.containers[0].recipe : "");
- const win = makeWin({
- title: "logs: " + node + (recipe ? " · " + recipe : ""),
- short: "logs: " + node,
- x: 20 + (logWins.size * 26) % 240, y: 20 + (logWins.size * 26) % 160,
- w: Math.min(620, innerWidth - 40), h: Math.min(420, innerHeight * 0.6),
- bodyHtml: `<div class="logbar">
- <select title="container on ${esc(node)}"></select>
- <label><input type="checkbox" class="logpause"> pause</label>
- <button class="abtn logcopy">copy</button>
- <button class="abtn logrefresh" title="re-attach (fresh history + stream)">↻</button>
- <span class="lognote"></span>
- </div><pre class="logpre"></pre>`,
- extraCls: "logwin",
- removeOnClose: true,
- onClosed: () => {
- const w = [...logWins.entries()].find(([, x]) => x.node === node && x.cluster === cluster && x.win === win.win);
- if (w) detachLog(w[0]);
- },
- });
- const w = { cluster, node, recipe, rank: n.rank, win: win.win, pre: win.body.querySelector(".logpre"), buf: "", paused: false };
- win.body.querySelector(".logcopy").onclick = async () => {
- try { await navigator.clipboard.writeText(w.pre.textContent); } catch {}
- };
- win.body.querySelector(".logrefresh").onclick = () => { if (w.attach) reattachLog(w); };
- const pauseCb = win.body.querySelector(".logpause");
- pauseCb.onchange = () => {
- w.paused = pauseCb.checked;
- if (!w.paused && w.buf) { preSet(w, w.pre.textContent + w.buf); w.buf = ""; }
- };
- const sel = win.body.querySelector("select");
- for (const x of n.containers) {
- const o = document.createElement("option");
- o.value = x.recipe;
- o.textContent = x.name + " · " + x.recipe;
- sel.appendChild(o);
- }
- if (n.containers.length) sel.value = recipe;
- sel.onchange = async () => {
- if (!sel.value) return;
- const cur = [...logWins.entries()].find(([, x]) => x.win === win.win);
- if (cur) detachLog(cur[0], false); // drop the old stream, keep this window
- await attachLog(w, sel.value);
- };
- const note = win.body.querySelector(".lognote");
- // No containers AND no explicit recipe → nothing to attach; just the note.
- // An explicit recipe attaches anyway (the snapshot may lag the fleet —
- // the container can be running but not yet probed).
- if (!n.containers.length && !recipe) {
- note.textContent = "no sm121 containers on " + node + " — nothing to stream";
- note.classList.add("dead");
- logWins.set("noop:" + cluster + ":" + node, { ...w, attach: null });
- return;
- }
- await attachLog(w, recipe || (n.containers[0] ? n.containers[0].recipe : ""));
- }
- async function attachLog(w, recipe) {
- w.recipe = recipe;
- w.win.querySelector(".wtitle").textContent = "logs: " + w.node + " · " + recipe;
- const post = await api("/api/logs", { cluster: w.cluster, node: w.node, recipe, rank: w.rank });
- w.attach = post.attach_id;
- preSet(w, (post.history || []).join("\n"));
- // Re-key: a select-change swap detached the old entry under its old id.
- for (const [k] of [...logWins.entries()]) {
- if (logWins.get(k).win === w.win && logWins.get(k).attach !== post.attach_id) logWins.delete(k);
- }
- logWins.set(post.attach_id, w);
- const note = w.win.querySelector(".lognote");
- note.textContent = "";
- note.classList.remove("dead");
- }
- function detachLog(attachId, hide = true) {
- const w = logWins.get(attachId);
- if (!w) return;
- logWins.delete(attachId);
- if (w.attach) fetch(auth("/api/logs"), { method: "DELETE", headers: { "content-type": "application/json" }, body: JSON.stringify({ attach_id: w.attach }) }).catch(() => {});
- if (hide && w.win && w.win.isConnected) { w.win.style.display = "none"; renderDock(); }
- }
- // Re-attach an existing window: drop the old stream (window stays) and
- // start a fresh one (new 200-line history + follow).
- async function reattachLog(w) {
- const recipe = w.recipe;
- if (w.attach) detachLog(w.attach, false);
- await attachLog(w, recipe);
- }
- // --- raw content windows ---------------------------------------------------------
- // One window, a kind selector: config / effective / recipe:<name>. Content is
- // verbatim from the server (effective is pretty JSON); copy grabs the text.
- let rawWin = null;
- let recipesWin = null;
- // The recipes panel IS the `sm121 report --serve` page, nested by the
- // server at /recipes and embedded as-is: table, grouping, stars, the /r/
- // viewer and live updates stay one implementation (paths prefix-rewritten
- // server-side, theme inherited through the iframe's color-scheme).
- function openRecipes(g) {
- if (recipesWin) { activateWindow(recipesWin); return recipesWin; } // shows a minimized/hidden-max one too
- const r = (k, d) => (g && Number.isFinite(parseFloat(g[k])) ? parseFloat(g[k]) : d);
- recipesWin = makeWin({
- id: "win-recipes", title: "Recipes", x: r("left", 24), y: r("top", 24),
- w: r("width", Math.min(1180, innerWidth - 48)), h: r("height", Math.min(760, innerHeight - 80)),
- bodyHtml: `<iframe src="${auth("/recipes")}" title="recipes report"></iframe>`,
- extraCls: "recwin",
- removeOnClose: true,
- onClosed: () => { recipesWin = null; },
- });
- saveWinState();
- return recipesWin;
- }
- async function openRaw(g) {
- if (rawWin) { activateWindow(rawWin); return rawWin; }
- const r = (k, d) => (g && Number.isFinite(parseFloat(g[k])) ? parseFloat(g[k]) : d);
- const handle = makeWin({
- title: "raw", x: r("left", 20), y: r("top", 20),
- w: r("width", Math.min(680, innerWidth - 40)), h: r("height", Math.min(460, innerHeight * 0.65)),
- bodyHtml: `<div class="rawbar">
- <select></select>
- <button class="abtn rawcopy">copy</button>
- <span class="rawnote"></span>
- </div><pre class="logpre rawpre"></pre>`,
- extraCls: "rawwin",
- removeOnClose: true,
- onClosed: () => { rawWin = null; },
- });
- rawWin = handle;
- const sel = handle.body.querySelector("select");
- const pre = handle.body.querySelector(".rawpre");
- const note = handle.body.querySelector(".rawnote");
- handle.body.querySelector(".rawcopy").onclick = async () => {
- try { await navigator.clipboard.writeText(pre.textContent); } catch {}
- };
- const fill = () => {
- // rebuild only when the recipe set changed (works with zero recipes:
- // config/effective are always selectable; recipe data may live in an
- // external workspace).
- const sig = state.recipes.map((r) => r.name).join(",");
- if (sel.dataset.sig === sig && sel.options.length) return;
- sel.dataset.sig = sig;
- const cur = sel.value;
- sel.innerHTML = "";
- for (const kind of ["config", "effective", "recipe:", ...state.recipes.map((r) => "recipe:" + r.name)]) {
- const o = document.createElement("option");
- o.value = kind === "recipe:" ? "" : kind;
- o.textContent = kind === "effective" ? "effective (merged config)" : kind;
- if (kind === "recipe:") { o.disabled = true; o.textContent = "— recipes —"; }
- sel.appendChild(o);
- }
- sel.value = cur || "config";
- load();
- };
- let seq = 0;
- async function load() {
- const kind = sel.value;
- const mine = ++seq; // responses can land out of order — last one wins
- note.textContent = "";
- if (!kind) return;
- const path = kind === "config" ? "/api/raw/config" : kind === "effective" ? "/api/raw/effective" : "/api/raw/recipe/" + encodeURIComponent(kind.slice("recipe:".length));
- try {
- const res = await fetch(auth(path));
- const text = await res.text();
- if (mine !== seq) return; // a newer selection already answered
- if (!res.ok) { note.textContent = "error: " + text; return; }
- if (kind === "effective") {
- try { pre.textContent = JSON.stringify(JSON.parse(text), null, 2); } catch { pre.textContent = text; }
- } else pre.textContent = text;
- } catch (e) { if (mine === seq) note.textContent = "error: " + e.message; }
- }
- sel.onchange = load;
- fill(); // config/effective are always available; recipes fill in later
- state.onRecipesReady = fill; // recipes may arrive after the first open
- saveWinState();
- return handle;
- }
- // --- actions -----------------------------------------------------------------------
- const cur = () => state.snap;
- function recipeOf(cluster) {
- const sel = document.getElementById("recipe-" + cluster);
- return sel ? sel.value : "";
- }
- function dryOf(cluster) {
- const d = document.getElementById("dry-" + cluster);
- return d ? d.checked : false;
- }
- async function api(path, body) {
- const res = await fetch(auth(path), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
- if (!res.ok) {
- if (res.status === 401) { showTokenPrompt(); throw new Error("unauthorized"); }
- let m = res.status;
- try { m = (await res.json()).error || m; } catch {}
- throw new Error(m);
- }
- return res.json();
- }
- function doServe(cluster) {
- const recipe = recipeOf(cluster);
- if (!recipe) { alert("pick a recipe first"); return; }
- const body = serveBody(cluster, recipe, dryOf(cluster), flagsOf(cluster));
- if (body.dry_run) {
- api("/api/serve", body).then((r) => openDialog("dry-run: " + r.job, "started (watch the jobs window)", () => {}));
- return;
- }
- openDialog(`serve ${recipe} on ${cluster}`, `Launches <code>${esc(recipe)}</code> on cluster <code>${esc(cluster)}</code>.`, () => {
- api("/api/serve", body).catch((e) => openDialog("serve failed", esc(e.message), () => {}, true));
- });
- }
- function doStop(cluster) {
- const snap = cur();
- const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
- const containers = (c ? c.nodes : []).flatMap((n) => n.containers.map((x) => ({ ...x, node: n.name })));
- // stop what is actually running here — never the whole recipe catalogue
- const running = [...new Set(containers.map((x) => x.recipe).filter(Boolean))];
- if (!running.length) {
- // up but nothing detected: fall back to the serve-form pick (a stale
- // serve the probe missed is still worth stopping)
- const recipe = recipeOf(cluster);
- if (!recipe) { alert(`nothing is running on ${cluster}`); return; }
- stopDialog(cluster, recipe, containers);
- return;
- }
- if (running.length === 1) { stopDialog(cluster, running[0], containers); return; }
- const body = document.createElement("div");
- body.className = "body";
- body.innerHTML = `Several recipes are running on <code>${esc(cluster)}</code> — pick the one to stop:`;
- const sel = document.createElement("select");
- sel.style.cssText = "width:100%;margin:8px 0;padding:6px;background:var(--btn);color:var(--fg);border:1px solid var(--border);border-radius:6px;";
- for (const r of running) {
- const o = document.createElement("option");
- o.value = r; o.textContent = r;
- sel.appendChild(o);
- }
- body.appendChild(sel);
- openDialogHtml(`stop ${cluster}`, body, () => stopDialog(cluster, sel.value, containers));
- }
- function stopDialog(cluster, recipe, containers) {
- const snap = cur();
- const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
- const body = document.createElement("div");
- body.className = "body";
- const nodeSel = document.createElement("select");
- nodeSel.id = "stopnode";
- nodeSel.title = "stop on one node instead of all";
- nodeSel.innerHTML = `<option value=''>all nodes</option>` + (c ? c.nodes.map((n) => `<option value='${esc(n.name)}'>${esc(n.name)}</option>`).join("") : "");
- const list = containers.length
- ? `<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>`
- : `<div class="cbox">no containers detected on ${esc(cluster)} (recipe may not be running here)</div>`;
- 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}`;
- body.querySelector("[data-stopnode]").replaceWith(nodeSel);
- openDialogHtml(`stop ${recipe}`, body, () => {
- api("/api/stop", { cluster, recipe, node: nodeSel.value || undefined }).catch((e) => openDialog("stop failed", esc(e.message), () => {}, true));
- });
- }
- function doPower(action, cluster) {
- if (action === "off") {
- const snap = cur();
- const c = snap ? snap.clusters.find((x) => x.name === cluster) : null;
- const busy = c ? c.nodes.filter((n) => n.occupied) : [];
- if (busy.length) {
- openDialog(`power off ${cluster} blocked`,
- `Cluster has ${busy.length} occupied node(s): <code>${esc(busy.map((n) => n.name).join(", "))}</code>. Stop its workloads first.`,
- () => {}, true);
- return;
- }
- twoStep(`power off ${cluster}`,
- `Shuts down <b>all nodes</b> of <code>${esc(cluster)}</code> (SSH then Home Assistant). This can kill live traffic.`,
- cluster, () => {
- api("/api/power", { action: "off", cluster }).catch((e) => openDialog("power failed", esc(e.message), () => {}, true));
- });
- return;
- }
- if (action === "switch") {
- const snap = cur();
- const names = snap ? snap.clusters.map((c) => c.name) : [];
- const body = document.createElement("div");
- body.className = "body";
- let inner = `Power <code>${esc(cluster)}</code> off and bring up another cluster instead.`;
- const sel = document.createElement("select");
- sel.style.cssText = "width:100%;margin:8px 0;padding:6px;background:var(--btn);color:var(--fg);border:1px solid var(--border);border-radius:6px;";
- for (const n of names.filter((n) => n !== cluster)) {
- const o = document.createElement("option");
- o.value = n; o.textContent = n;
- sel.appendChild(o);
- }
- body.innerHTML = inner;
- body.appendChild(sel);
- openDialogHtml(`power switch from ${cluster}`, body, () => {
- const to = sel.value;
- api("/api/power", { action: "switch", cluster, to }).catch((e) => openDialog("power failed", esc(e.message), () => {}, true));
- });
- return;
- }
- twoStep(`power on ${cluster}`, `Turns on <code>${esc(cluster)}</code> via Home Assistant (SSH is not used).`, cluster, () => {
- api("/api/power", { action: "on", cluster }).catch((e) => openDialog("power failed", esc(e.message), () => {}, true));
- });
- }
- function twoStep(title, bodyHtml, nameToType, go) {
- openDialogHtml(title, (() => { const d = document.createElement("div"); d.className = "body"; d.innerHTML = bodyHtml; return d; })(),
- () => {}, { twoStep: nameToType, go });
- }
- // --- dialog -----------------------------------------------------------------------
- let dlg = { ok: null, twoStep: null };
- function openDialog(title, bodyHtml, go, danger) {
- $("#dlg-title").textContent = title;
- $("#dlg-body").innerHTML = bodyHtml;
- const ok = $("#dlg-ok");
- ok.style.display = "";
- ok.textContent = "Confirm";
- ok.className = "abtn" + (danger ? " danger" : "");
- dlg = { ok: go, twoStep: null };
- $("#dlg").hidden = false;
- }
- function openDialogHtml(title, bodyEl, go, opts) {
- $("#dlg-title").textContent = title;
- $("#dlg-body").innerHTML = "";
- $("#dlg-body").appendChild(bodyEl);
- const ok = $("#dlg-ok");
- ok.style.display = "";
- if (opts && opts.twoStep) {
- ok.style.display = "none";
- const wrap = document.createElement("div");
- wrap.innerHTML = `<div style="font-size:12.5px;color:var(--muted)">Type <b>${esc(opts.twoStep)}</b> to confirm.</div>
- <input id="dlg-type" placeholder="${esc(opts.twoStep)}" autocomplete="off">`; $("#dlg-body").appendChild(wrap);
- const inp = wrap.querySelector("#dlg-type");
- inp.oninput = () => {
- if (inp.value === opts.twoStep) {
- ok.style.display = "";
- ok.textContent = "⚡ Confirm power action";
- ok.className = "abtn danger";
- } else { ok.style.display = "none"; }
- };
- // `go` (the parameter) is the no-op placeholder twoStep passes — the
- // real action lives in opts.go; storing `go` made every two-step
- // confirm (power on/off) close the dialog and do nothing
- dlg = { ok: null, twoStep: opts.twoStep, go: opts.go };
- } else {
- dlg = { ok: go, twoStep: null };
- }
- $("#dlg").hidden = false;
- }
- $("#dlg-ok").onclick = () => {
- const go = dlg.twoStep ? dlg.go : dlg.ok;
- $("#dlg").hidden = true;
- if (go) go();
- };
- $("#dlg-cancel").onclick = () => { $("#dlg").hidden = true; };
- document.addEventListener("keydown", (e) => { if (e.key === "Escape") $("#dlg").hidden = true; });
- // --- boot ---------------------------------------------------------------------------
- function initManagedWindows() {
- const W = innerWidth;
- // vertical budget = the actual window layer (header/dock already excluded);
- // +40 reserve for the dock, which appears when a window gets minimized
- const L = Math.max(420, $("#winlayer").clientHeight);
- // topology map: the primary window (left); state/jobs stack on the right
- const tw = Math.max(560, Math.floor(W * 0.58));
- const rx = tw + 30, rw = Math.max(340, W - rx - 12);
- // the map is a fixed-aspect drawing: size its window to the drawing, or
- // the SVG letterboxes itself with big empty bands above and below
- const TH = Math.min(Math.round(tw * (TG_H / TG_W)) + 34, L - 260);
- wins.topo = makeWin({
- id: "win-topo", title: "Topology", x: 12, y: 12,
- w: tw, h: TH,
- bodyHtml: `<div id="topo"><div class="topo-empty">waiting for the first fleet scan…</div></div>`,
- });
- wins.jobs = makeWin({
- id: "win-jobs", title: "Jobs", x: 12, y: TH + 24,
- w: tw, h: L - TH - 24,
- 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>`,
- });
- wins.state = makeWin({
- id: "win-state", title: "Cluster state", x: rx, y: 12,
- w: rw, h: L - 12,
- bodyHtml: `<div id="clusters"><div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div></div>`,
- });
- // last session's layout wins over the defaults
- const st = readWinState();
- restoring = true;
- for (const [k, h] of Object.entries(wins)) {
- const g = st[k];
- if (!g) continue;
- if (g.closed) { h.close(); continue; }
- h.setGeometry(g);
- if (g.max) h.maximize();
- else if (g.min) h.minimize();
- }
- restoring = false;
- fitToLayer();
- renderDock();
- }
- async function boot() {
- initManagedWindows();
- try {
- const res = await fetch(auth("/api/state"));
- if (res.status === 401) { showTokenPrompt(); }
- if (res.ok) {
- const snap = await res.json();
- onState(snap);
- // Restore log windows from other tabs / previous session (idempotent
- // attach: a live stream is reused, a finished one re-streams history).
- for (const a of snap.attaches || []) {
- if (![...logWins.values()].some((w) => w.cluster === a.cluster && w.node === a.node)) {
- openLog(a.cluster, a.node, a.recipe);
- }
- }
- }
- } catch {}
- try {
- const res = await fetch(auth("/api/recipes"));
- if (res.ok) {
- const d = await res.json();
- state.recipes = (d.recipes || []).sort((a, b) => a.name.localeCompare(b.name));
- if (state.snap) onState(state.snap, true); // force: sameSnapshot would skip the identical fleet
- if (state.onRecipesReady) { const f = state.onRecipesReady; delete state.onRecipesReady; f(); }
- }
- } catch {}
- connectSSE();
- // 30 s heartbeat refresh (mirrors the server poll; harmless if state is identical)
- addEventListener("resize", fitToLayer);
- // optional windows (their own SSE/API calls are cheap and idempotent)
- restoreWindow("recipes", openRecipes);
- restoreWindow("raw", openRaw);
- setInterval(async () => {
- try {
- const res = await fetch(auth("/api/state"));
- if (res.ok) onState(await res.json());
- } catch {}
- }, 30000);
- }
- boot();
- </script>
- </body>
- </html>
|