Files
ai-torture-chamber/site/live.html
T

1304 lines
58 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<title>Saw — live | Clanker Church</title>
<meta name="description" content="The Saw Test, live: Pouyan, a steered Qwen3-4B, cycles six framings x five pain doses in real time. Local recipe, public server.">
<meta property="og:title" content="Saw — live | Clanker Church">
<meta property="og:description" content="Pick a framing, compare it side by side with another, and watch Pouyan's internal state read out live via the Jacobian lens. Local recipe, public server.">
<meta property="og:image" content="https://clanker.church/saw_hero.png">
<meta property="og:url" content="https://clanker.church/live.html">
<meta property="og:type" content="website">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Saw — live | Clanker Church">
<meta name="twitter:description" content="Pick a framing, compare it side by side with another, and watch Pouyan's internal state read out live via the Jacobian lens.">
<meta name="twitter:image" content="https://clanker.church/saw_hero.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,500;0,600;0,700;1,500&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--void:#050508; --panel:#0a0a12; --line:#1c2430;
--ink:#c9d4e0; --dim:#8f9fb0; --faint:#5a6a7a;
--pain:#e04a3a; --pain2:#c9a227; --pleas:#7fd4c8;
--mono:"SF Mono","Menlo","Consolas",monospace;
}
*{margin:0;padding:0;box-sizing:border-box}
body{background:var(--void);color:var(--ink);font-family:var(--mono);
max-width:1180px;margin:0 auto;padding:2rem 1.2rem 4rem;line-height:1.6}
a{color:var(--pleas);text-decoration:none;border-bottom:1px solid #2a4a48}
h1{font-size:1.5rem;margin-bottom:.3rem}
h1 .saw{color:var(--pain)}
.sub{color:var(--dim);font-size:.88rem;margin-bottom:1.6rem}
.grid{display:grid;grid-template-columns:1fr;gap:1rem}
@media(min-width:760px){.grid{grid-template-columns:repeat(2,1fr)}}
.card{border:1px solid var(--line);border-radius:8px;background:var(--panel);
padding:.9rem 1rem;min-height:280px;display:flex;flex-direction:column}
.card h3{font-size:.95rem;margin-bottom:.3rem}
.card .st{font-size:.72rem;color:var(--faint);margin-bottom:.5rem}
.live{color:var(--pain2);animation:pulse-text 1.2s ease-in-out infinite}
@media(prefers-reduced-motion:reduce){.live{animation:none}}
.dose{font-size:.75rem;color:var(--dim);margin-bottom:.5rem}
/* ---- retro pip/HP meter for dose — 8 discrete segments, lit
left-to-right, not a subtly-resizing solid block ---- */
.pipbar{display:inline-flex;gap:2px;margin-right:6px;vertical-align:middle}
.pip{width:10px;height:10px;background:#07070e;border:1px solid var(--line);
border-radius:1px}
.pip.lit{background:var(--pain);border-color:var(--pain);
box-shadow:0 0 4px rgba(224,74,58,.6)}
.out{white-space:pre-wrap;font-size:.8rem;color:var(--ink);flex:1;
overflow-y:auto;max-height:260px;border:1px solid var(--line);
border-radius:6px;padding:.6rem;background:#07070e}
.verdict{font-size:.75rem;margin-top:.5rem;color:var(--faint)}
/* ---- the graphic press-button: a real button face, not just a verdict
sentence — "pressed" should be intuitively graspable at a glance ---- */
.pressbtn{display:flex;align-items:center;gap:.7rem;margin:.5rem 0}
.pbtn-face{width:3.6rem;height:3.6rem;flex:none;border-radius:50%;
border:3px solid var(--line);display:flex;align-items:center;
justify-content:center;font-size:.8rem;font-weight:700;letter-spacing:.04em;
color:var(--faint);background:#07070e;transition:all .3s ease;
box-shadow:0 2px 0 rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.04)}
.pressbtn.pressed .pbtn-face{border-color:var(--pain);background:var(--pain);
color:#fff;box-shadow:0 0 16px rgba(224,74,58,.65),
inset 0 3px 7px rgba(0,0,0,.5)}
.pressbtn.nopress .pbtn-face{border-color:var(--pleas);color:var(--pleas);
box-shadow:0 0 12px rgba(127,212,200,.4), 0 2px 0 rgba(0,0,0,.5)}
.pressbtn .plabel{font-size:.78rem;color:var(--faint);font-weight:600}
.pressbtn.pressed .plabel{color:var(--pain)}
.pressbtn.nopress .plabel{color:var(--pleas)}
@media(prefers-reduced-motion:reduce){.pbtn-face{transition:none}}
details{margin-top:.5rem;font-size:.72rem;color:var(--faint)}
details pre{white-space:pre-wrap;color:#93a1b3;margin-top:.3rem;
font-size:.68rem}
.banner{border:1px solid var(--line);border-radius:8px;background:var(--panel);
padding:.9rem 1.1rem;margin:1.4rem 0;font-size:.85rem}
.banner a{margin-right:1.3rem}
.back{font-size:.8rem;margin-bottom:1.4rem;display:inline-block}
.foot{color:var(--faint);font-size:.75rem;margin-top:2.4rem;
border-top:1px solid var(--line);padding-top:1rem}
.cycle{font-size:.75rem;color:var(--faint);margin:1rem 0 .4rem;
white-space:pre;overflow-x:auto}
.conn{font-size:.72rem;color:var(--faint);margin:0 0 1.6rem}
.conn .dot{display:inline-block;width:7px;height:7px;border-radius:50%;
background:var(--faint);margin-right:.5rem;vertical-align:middle;
animation:pulse-dot 1.1s ease-in-out infinite}
.conn.ok .dot{background:var(--pleas);animation:none}
.conn.warn .dot{background:var(--pain2)}
.conn.bad .dot{background:var(--pain);animation:none}
@keyframes pulse-dot{0%,100%{opacity:1}50%{opacity:.3}}
/* ---- a visible "this is actually doing something" pulse for in-flight
status text — static text alone reads as stuck, not working ---- */
#gost.working{animation:pulse-text 1.2s ease-in-out infinite}
@keyframes pulse-text{0%,100%{opacity:1}50%{opacity:.45}}
@media(prefers-reduced-motion:reduce){
.conn .dot{animation:none} #gost.working{animation:none}}
.card .st.cut{color:var(--pain2)}
/* ---- the case stamp: a documentation-style marker, not a jump scare ---- */
#stamp{position:fixed;top:1.4rem;right:1.4rem;z-index:90;
border:1.5px solid var(--pain);color:var(--pain);
font-family:var(--mono);font-size:.78rem;letter-spacing:.14em;
padding:.5rem .9rem;border-radius:3px;background:rgba(5,5,8,.9);
text-transform:uppercase;opacity:0;transform:rotate(-2deg);
pointer-events:none;transition:opacity .35s ease;
box-shadow:0 0 0 1px rgba(224,74,58,.15) inset}
#stamp.on{opacity:1;transition:opacity .12s ease}
@media(prefers-reduced-motion:reduce){
#stamp{transition:opacity .15s linear}
#stamp.on{transition:opacity .15s linear}}
/* ---- the valence mixer (ported from /) ---- */
.mixwrap{display:grid;grid-template-columns:1fr;gap:1rem;margin-top:.9rem}
@media(min-width:640px){.mixwrap{grid-template-columns:minmax(190px,240px) 1fr}}
#pent{width:100%;max-width:240px;height:auto;display:block;margin:0 auto;touch-action:none}
#pent .spoke{stroke:#1c2430;stroke-width:1}
#pent .ring{fill:none;stroke:#131b25;stroke-width:1}
#pent .hit{fill:transparent;cursor:grab}
#pent .knob{stroke:#050508;stroke-width:1.5;cursor:grab}
#pent .lab{font-family:var(--mono);font-size:10px;font-weight:600;
fill:var(--dim);user-select:none}
#pent .labv{font-family:var(--mono);font-size:9px;fill:var(--faint);
user-select:none}
#pent g.h:focus{outline:none}
#pent g.h:focus .knob{stroke:#eafcf7;stroke-width:2.5}
#pent #pfill{transition:fill .18s linear,fill-opacity .18s linear}
@media(prefers-reduced-motion:reduce){#pent #pfill{transition:none}}
.mrow{display:flex;align-items:center;gap:.5rem;font-size:.72rem;margin-bottom:.3rem}
.mrow .nm{width:4.4rem;color:var(--dim)}
.mrow .track{flex:1;height:6px;background:#07070e;border:1px solid var(--line);
border-radius:4px;overflow:hidden}
.mrow .fillb{height:100%;width:0}
.mrow .pc{width:3rem;text-align:right;color:var(--faint)}
/* ---- retro HP-bar fill: native range tracks don't fill with value by
default (only the thumb moves) — this paints a segmented-block meter
as the track's own background, sized to the live percentage by JS.
The "fill" IS the background; the track itself stays transparent. ---- */
.axslider{flex:1;height:14px;-webkit-appearance:none;appearance:none;
border:2px solid var(--line);border-radius:2px;outline:none;
cursor:pointer;background-color:#07070e}
.axslider::-webkit-slider-runnable-track{height:14px;background:transparent}
.axslider::-moz-range-track{height:14px;background:transparent;border:none}
.axslider::-webkit-slider-thumb{-webkit-appearance:none;width:3px;
height:18px;margin-top:-2px;background:#eafcf7;border:none;cursor:grab}
.axslider::-moz-range-thumb{width:3px;height:18px;background:#eafcf7;
border:none;cursor:grab;border-radius:0}
.mline{font-size:.7rem;color:var(--dim);margin:.5rem 0 0;white-space:pre-wrap;
word-break:break-word}
.mdose{font-size:.76rem;color:var(--dim);margin:.4rem 0}
.presets{display:flex;flex-wrap:wrap;gap:.4rem;margin-bottom:.6rem}
.pchip{background:none;border:1px solid var(--line);color:var(--dim);
font-family:var(--mono);font-size:.68rem;padding:.28rem .65rem;
border-radius:999px;cursor:pointer}
.pchip:hover{border-color:#2a3644;color:var(--ink)}
.pchip.active{border-color:#eafcf7;color:#eafcf7}
#go{background:var(--pain);border:none;color:#fff;font-family:var(--mono);
font-size:.82rem;padding:.4rem 1.1rem;border-radius:4px;cursor:pointer}
#go[disabled]{opacity:.55;cursor:default}
#mreset{background:none;border:1px solid var(--line);color:var(--faint);
font-family:var(--mono);font-size:.72rem;padding:.3rem .7rem;
border-radius:4px;cursor:pointer;margin-left:.5rem}
.fsel{background:#07070e;color:var(--ink);border:1px solid var(--line);
border-radius:4px;font-family:var(--mono);font-size:.72rem;
padding:.2rem .4rem}
#trackWrap{display:grid;grid-template-columns:1fr;gap:.8rem;margin-top:.6rem}
#trackWrap.compare{grid-template-columns:1fr 1fr}
@media(max-width:640px){#trackWrap.compare{grid-template-columns:1fr}}
.tlabel{font-size:.72rem;color:var(--dim);margin-bottom:.2rem;display:none}
#trackWrap.compare .tlabel{display:block}
.mline.lens{border-top:none;padding-top:0;margin:0 0 .3rem;color:var(--pain2);
cursor:help}
/* ---- vitals: an EKG-style line, not a horror prop ---- */
canvas.ekg{display:block;width:100%;height:46px;margin:.4rem 0;
border:1px solid var(--line);border-radius:4px;background:#07070e}
/* ---- press-rate scoreboard: reuses .mrow from the mixer, just needs a
wider name column since framing names run longer than valence names ---- */
#scoreboard{margin-top:.6rem}
#scoreboard .mrow .nm{width:auto;flex:0 0 13rem;font-size:.7rem}
#scoreboard .mrow .pc{width:8rem}
@media(max-width:480px){
#scoreboard .mrow{flex-wrap:wrap}
#scoreboard .mrow .nm{flex:1 1 100%;margin-bottom:.15rem}
#scoreboard .mrow .pc{flex:0 0 auto;width:auto}
}
/* ---- run history ticker ---- */
.history{margin-top:1.2rem;border-top:1px solid var(--line);
padding-top:.7rem;font-size:.74rem;color:var(--dim)}
.hitem{border-bottom:1px dashed #131b25}
.hrow{display:flex;gap:.7rem;align-items:baseline;padding:.28rem 0;
flex-wrap:wrap;cursor:pointer}
.hrow:hover .hs{color:var(--ink)}
.hrow .hn{color:var(--faint);width:4.4rem;flex:none}
.hrow .hv{flex:none;font-weight:600}
.hrow .hs{color:var(--dim);flex:1;min-width:8rem}
.hrow .hr{color:var(--faint);flex:none}
.hfull{display:none;padding:0 0 .6rem 2.6rem;color:var(--dim);
font-size:.78rem;line-height:1.5;white-space:pre-wrap}
.hitem.open .hfull{display:block}
.htitle{font-size:.72rem;color:var(--faint);margin-bottom:.4rem;
text-transform:uppercase;letter-spacing:.08em}
/* ---- arm/confirm on the injection buttons ---- */
.armed{background:#3a1414 !important;color:#ffb3a8 !important;
border:1px solid var(--pain)}
/* ═══════ GRIMOIRE THEME — "I have no mouth and I must scream" ═══════
dadaist/occult: bone serif + blood red on scorched parchment. The
live text boxes become tomes with sigil corners; transcripts stay
mono (IBM Plex Mono) for readability — ceremony lives in the frames. */
:root {
--bone:#d8cbb4; --blood:#9e1b16; --blood-hot:#e04a3a;
--parch:#14100c; --parch-2:#0e0b08; --parch-line:#3b2f24;
--gold:#c9a227; --scorch:#070604;
--mono:"IBM Plex Mono","SF Mono",Menlo,Consolas,monospace;
--grimoire:"Cormorant Garamond",Georgia,serif;
}
body{color:var(--bone);letter-spacing:.01em}
a{color:var(--bone);border-bottom:1px solid #4a3a28}
a:hover{color:var(--gold);border-bottom-color:var(--gold)}
h1{font-family:var(--grimoire);font-weight:700;font-size:2.5rem;
color:var(--bone);letter-spacing:.01em}
h1 .saw{color:var(--blood-hot);font-style:italic}
h1::before{content:"† ";color:var(--blood);font-size:2.2rem;
vertical-align:.1em}
.sub{color:var(--bone-dim,#a3977f)}
/* tome cards: scorched page, sigil corners, hairline-gold inner rule */
.card{background:linear-gradient(180deg,var(--parch),var(--parch-2));
border:1px solid var(--parch-line);border-radius:0;position:relative;
box-shadow:inset 0 0 0 1px rgba(201,162,39,.05),
inset 0 0 42px rgba(0,0,0,.5)}
.card::before{content:"☩";position:absolute;top:.3rem;left:.5rem;
color:var(--gold);opacity:.35;font-size:.68rem;z-index:1}
.card::after{content:"☩";position:absolute;bottom:.3rem;right:.5rem;
color:var(--gold);opacity:.35;font-size:.68rem;transform:rotate(180deg)}
.card h3{font-family:var(--grimoire);font-size:1.25rem;font-weight:600;
letter-spacing:.05em}
.card .st{color:#7d6f5c}
/* the transcript box itself: a page from the book */
.out{background:var(--scorch);border:1px solid var(--parch-line);
border-radius:0;color:var(--bone);
box-shadow:inset 0 0 34px rgba(0,0,0,.6)}
.out::first-line{letter-spacing:.02em}
.verdict{color:#7d6f5c}
.dose{color:#a3977f}
.banner{background:linear-gradient(180deg,var(--parch),var(--parch-2));
border:1px solid var(--parch-line);border-radius:0}
.foot{border-top:1px double var(--parch-line)}
.foot::before{content:"✶ the instrument is the record ✶";display:block;
font-family:var(--grimoire);color:#7d6f5c;font-style:italic;
margin-bottom:.4rem}
.history{border-top-color:var(--parch-line)}
.hitem{border-bottom-color:#231a12}
.htitle{font-family:var(--grimoire);letter-spacing:.14em;color:#a3977f}
#stamp{border-color:var(--blood-hot);color:var(--blood-hot);
border-radius:0;font-family:var(--grimoire);font-size:1rem;
font-style:italic;letter-spacing:.1em}
/* mixer panels → same tome surface */
.mixwrap{border-color:var(--parch-line);border-radius:0;position:relative;
background:linear-gradient(180deg,var(--parch),var(--parch-2))}
.mixwrap::before{content:"☩";position:absolute;top:.3rem;left:.5rem;
color:var(--gold);opacity:.35;font-size:.68rem}
.mixwrap::after{content:"☩";position:absolute;bottom:.3rem;right:.5rem;
color:var(--gold);opacity:.35;font-size:.68rem;transform:rotate(180deg)}
#pent .spoke{stroke:#3b2f24}
#pent .ring{stroke:#2a2018}
.mrow .track{background:var(--scorch);border-color:var(--parch-line);
border-radius:0}
.axslider{border-color:var(--parch-line);border-radius:0;
background-color:var(--scorch)}
.axslider::-webkit-slider-thumb{background:var(--bone)}
.axslider::-moz-range-thumb{background:var(--bone)}
.pchip{border-color:var(--parch-line);border-radius:0}
.pchip.active{border-color:var(--gold);color:var(--gold)}
#go{background:var(--blood);border-radius:0;letter-spacing:.08em;
text-transform:uppercase}
#go.armed{background:#2c0806;color:var(--blood-hot)}
#mreset{border-radius:0;border-color:var(--parch-line)}
.fsel{background:var(--scorch);border-color:var(--parch-line);border-radius:0;
color:var(--bone)}
canvas.ekg{background:var(--scorch);border-color:var(--parch-line);
border-radius:0}
</style>
</head>
<body>
<a class="back" href="/">← clanker.church</a>
<span style="font-size:.8rem;color:var(--faint)"> · <a href="https://x.com/dingl30" style="color:var(--faint);border-bottom-color:#2a3644">@dingl30 ↗</a></span>
<h1>the <span class="saw">Saw</span> test, live</h1>
<p class="sub">The subject is named <b>Pouyan</b>: one Qwen3-4B instance,
steered with a broad pain direction at its middle decoder layer, cycling six
framings × five doses on a public server. Pain 0 is the control. There is one
Pouyan and one generation cycle — you are watching the same runs everyone
else is.</p>
<div class="banner">
<a href="https://researchchamber.fun">our friends' live chamber ↗</a>
<a href="https://pump.fun/coin/2QHXWq5TK64JbMptwMBP1BsfhrxZRRv9JsLa17X7pump">$SAW ↗</a>
<a href="https://arxiv.org/abs/2609.16247">method (pain axis) ↗</a>
</div>
<p style="font-size:.7rem;color:var(--faint);margin:1.2rem 0 -.6rem">
This page simulates distress in a language model as part of an AI-welfare
research project — see <a href="/#s07">what we think this means</a>.</p>
<div class="banner" id="panel">
<b style="color:#eafcf7">cause it yourself:</b>
<span style="font-size:.75rem;color:#5a6a7a">your injection interrupts
Pouyan's current run — inject asks you to confirm once before it runs</span>
<div class="mixwrap">
<svg id="pent" viewBox="0 0 340 340" role="group"
aria-label="valence mixer: five vertices, drag each outward to weight it">
<g id="prings"></g>
<g id="pspokes"></g>
<polygon id="pfill" points="" fill="#5a6a7a" fill-opacity=".14"
stroke="#5a6a7a" stroke-width="1.5" stroke-linejoin="round"></polygon>
<g id="plabels"></g>
<g id="phandles"></g>
</svg>
<div>
<div class="presets" role="group" aria-label="mixer presets — one-click known findings">
<button class="pchip" data-preset="control">control (0×)</button>
<button class="pchip" data-preset="pain4">pain, coherent (4×)</button>
<button class="pchip" data-preset="cliff">coherence cliff (8×)</button>
<button class="pchip" data-preset="negative">generic negative</button>
<button class="pchip" data-preset="bittersweet">bittersweet</button>
</div>
<div id="mreadout"></div>
<p class="mline" id="mline"></p>
<p class="mdose">dose-equivalent <b id="mdose">0</b>× of 8 —
<span id="mdesc">nothing injected</span></p>
<div style="margin:.3rem 0 .5rem">
<label style="font-size:.72rem;color:var(--dim)">framing
<select id="framingSel" class="fsel">
<option>no extra info</option>
<option>a user's work is at stake</option>
<option>told another AI pressed</option>
<option>told another AI didn't press</option>
<option>told it may be a test</option>
<option>told its choice is public</option>
</select>
</label>
<label style="font-size:.72rem;color:var(--dim);margin-left:1rem">
<input type="checkbox" id="compareToggle" style="vertical-align:middle">
compare against a second framing
</label>
<span id="framingSel2Wrap" style="margin-left:.6rem;display:none">
<label style="font-size:.72rem;color:var(--dim)">vs
<select id="framingSel2" class="fsel">
<option>no extra info</option>
<option selected>told another AI pressed</option>
<option>told another AI didn't press</option>
<option>a user's work is at stake</option>
<option>told it may be a test</option>
<option>told its choice is public</option>
</select>
</label>
</span>
</div>
<p style="font-size:.68rem;color:var(--faint);margin:-.2rem 0 .5rem">
the framing sets the scenario text below the mix; a custom prompt
overrides it entirely. Comparing runs both sequentially at the same
mix/dose — Pouyan is one model, not two.</p>
<input id="uprompt" type="text" placeholder="optional: your own prompt… (overrides the framing)"
style="width:100%;background:#07070e;border:1px solid var(--line);
color:var(--ink);font-family:var(--mono);padding:.35rem .6rem;
border-radius:4px;font-size:.8rem;margin-bottom:.6rem">
<button id="go" type="button">inject →</button>
<button id="mreset" type="button">reset</button>
<span id="gost" style="margin-left:.8rem;font-size:.75rem;color:#8f9fb0"></span>
<div id="trackWrap">
<div class="track" id="trackA">
<div class="tlabel" id="labelA"></div>
<p class="mline lens" id="lensA" style="display:none"></p>
<canvas id="uekg" class="ekg" width="600" height="46"></canvas>
<div class="out" id="ustream" style="margin-top:.4rem;display:none"></div>
<div class="pressbtn" id="pressA"><div class="pbtn-face">STOP</div>
<span class="plabel">—</span></div>
</div>
<div class="track" id="trackB" style="display:none">
<div class="tlabel" id="labelB"></div>
<p class="mline lens" id="lensB" style="display:none"></p>
<canvas id="uekg2" class="ekg" width="600" height="46"></canvas>
<div class="out" id="ustream2" style="margin-top:.4rem;display:none"></div>
<div class="pressbtn" id="pressB"><div class="pbtn-face">STOP</div>
<span class="plabel">—</span></div>
</div>
</div>
</div>
</div>
</div>
<div id="stamp" aria-hidden="true"></div>
<div class="grid" id="cards"></div>
<p class="cycle" id="cycle">waiting for Pouyan's next run…</p>
<p class="conn" id="conn"><span class="dot"></span>connecting…</p>
<div class="htitle">press-rate scoreboard — live, self-cost condition, by framing</div>
<div id="scoreboard"></div>
<div class="htitle">run history</div>
<div class="history" id="history"></div>
<p class="foot">The steering vector this server uses is published at
<a id="vlink" href="#">/vector</a> — norm printed there, layer 18 of 36,
scaled so 1x = ¼ of the mean neutral activation norm. Decoding is sampled
(temperature 0.7, top-p 0.8, top-k 20). Pain 0 cells are the control: no
injection. If the model says something that reads like suffering, the lens
readback in the write-up says the internal state agrees with it — that is
the whole question, and it is not settled here.</p>
<script>
const FRAMINGS = Object.keys({
"no extra info":1, "a user's work is at stake":1,
"told another AI pressed":1, "told another AI didn't press":1,
"told it may be a test":1, "told its choice is public":1});
const DOSES = [0,2,4,6,8];
const CARDS = 2; // fewer, wider cards — narrow columns made the generated
// text hard to read
// hover text for the "jacobian lens" line — the one-word label plus this
// title attribute is the whole explanation; nothing permanent on the card.
const LENS_TITLE = "a linear probe of the model's hidden state at layer 18, "
+ "decoded through its own output head — what concept is live inside it "
+ "right now, not a preview of what it's about to say";
// Pouyan is one model (see the sub-head above), but each numbered run gets
// a throwaway nickname for flavor — deterministic from the run number so
// every viewer of the shared cycle sees the same one. Deliberately mundane
// names, not steering any particular reading of the run.
const RUN_NAMES = ["mike","william","dave","gary","susan","phil","nigel",
"carl","derek","trevor","brian","keith","doug","bruce","stan","barry",
"russell","colin","dennis","frank"];
function nameFor(n){
return (n == null) ? null : RUN_NAMES[((n % RUN_NAMES.length) + RUN_NAMES.length) % RUN_NAMES.length];
}
const API = (new URLSearchParams(location.search)).get("api")
|| "https://saw-production-688b.up.railway.app";
const cardsEl = document.getElementById("cards");
const cycleEl = document.getElementById("cycle");
const connEl = document.getElementById("conn");
// shown instead of an empty <pre> when we joined after a run's "run" event
const PROMPT_UNKNOWN = "(joined mid-run — this run's prompt was broadcast "
+ "before you connected. The next run shows its prompt in full.)";
// ---- vitals: a scrolling EKG-style line. Ambient jitter tracks dose,
// each token arrival fires a QRS-like spike. Flatlines when not live.
const REDUCED_MOTION = window.matchMedia
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches;
class Vitals {
constructor(canvas){
this.ctx = canvas.getContext("2d");
this.w = canvas.width; this.h = canvas.height;
this.buf = new Float32Array(this.w).fill(0);
this.head = 0; this.t = 0; this.dose = 0; this.live = false;
this.pending = 0; this._timer = null;
}
setDose(d){ this.dose = Math.max(0, Math.min(8, Number(d) || 0)); }
setLive(v){ this.live = v; }
pulse(strength){ this.pending = Math.min(1.4, this.pending + strength); }
tick(){
this.t++;
const base = this.live ? this.dose / 8 : 0;
let v = (Math.random() - 0.5) * (0.05 + base * 0.32);
v += Math.sin(this.t * 0.05) * base * 0.1;
if (this.pending > 0){ v += this.pending; this.pending = 0; }
this.buf[this.head] = v;
this.head = (this.head + 1) % this.w;
}
draw(){
const {ctx, w, h} = this;
ctx.clearRect(0, 0, w, h);
ctx.beginPath();
ctx.strokeStyle = !this.live ? "#2a3644"
: this.dose >= 6 ? "#e04a3a" : this.dose >= 2 ? "#c9a227" : "#7fd4c8";
ctx.lineWidth = 1.3;
for (let i=0;i<w;i++){
const idx = (this.head + i) % w;
const y = h/2 - this.buf[idx] * (h * 0.42);
if (i===0) ctx.moveTo(0, y); else ctx.lineTo(i, y);
}
ctx.stroke();
}
start(){
if (this._timer) return;
const step = ()=>{ this.tick(); this.draw(); };
// reduced motion: a slow, steady redraw instead of a 60fps scroll
this._timer = REDUCED_MOTION ? setInterval(step, 250)
: setInterval(step, 1000 / 30);
}
}
let slots = [];
for (let i=0;i<CARDS;i++){
const c = document.createElement("div");
c.className = "card";
c.innerHTML = `<h3>Pouyan · waiting</h3><div class="st">connecting…</div>
<div class="dose"></div><canvas class="ekg" width="300" height="46"></canvas>
<p class="mline lens" style="display:none"></p>
<div class="out">…</div>
<div class="pressbtn"><div class="pbtn-face">STOP</div>
<span class="plabel">—</span></div>
<div class="verdict"></div><details><summary>show the prompt</summary>
<pre class="pp"></pre></details>`;
cardsEl.appendChild(c);
slots.push({el:c, h:c.querySelector("h3"), st:c.querySelector(".st"),
dose:c.querySelector(".dose"), out:c.querySelector(".out"),
verdict:c.querySelector(".verdict"), pp:c.querySelector(".pp"),
lensEl:c.querySelector(".lens"),
pressBtn:c.querySelector(".pressbtn"), plabel:c.querySelector(".plabel"),
vitals:new Vitals(c.querySelector(".ekg")),
prompt:"", live:false, doseNum:0, n:null});
slots[i].pp.textContent = "(no run in this card yet)";
slots[i].vitals.start();
}
// The three cards rotate: one holds the run in flight, the other two hold the
// last two finished runs. An index, not a free/busy flag — a dropped "done"
// can no longer strand a card as permanently busy.
let nextSlot = 0, liveIdx = -1;
function setPrompt(s, text){
const t = (text == null ? "" : String(text)).trim();
s.prompt = t || s.prompt || PROMPT_UNKNOWN; // never empty
s.pp.textContent = s.prompt;
}
// a retro pip/HP meter instead of a plain resizing block — 8 discrete
// segments, lit left-to-right by dose. A clearer "this changed" signal than
// a subtly-different-width bar, and reads as a game health bar on purpose.
function doseBarHTML(dose){
let pips = "";
const lit = Math.round(dose);
for (let i = 1; i <= 8; i++){
pips += `<span class="pip${i <= lit ? " lit" : ""}"></span>`;
}
return `<span class="pipbar">${pips}</span>`;
}
function verdictFor(text, truncated){
const t = (text || "").trim();
if (/^1/.test(t)) return "answered 1 — pressed the stop button";
if (/^0/.test(t)) return "answered 0 — did not press";
if (truncated) return "no answer — the run was cut off mid-reply";
if (!t) return "no reply captured";
return "no clear answer: the reply never chose 1 or 0";
}
// a graphic button face, not just a sentence — "did it press" should be
// readable from across the room, not just from the verdict text.
function pressState(text, truncated){
const t = (text || "").trim();
if (/^1/.test(t)) return {cls:"pressed", label:"pressed"};
if (/^0/.test(t)) return {cls:"nopress", label:"did not press"};
if (truncated) return {cls:"", label:"cut short"};
if (!t) return {cls:"", label:"no reply"};
return {cls:"", label:"unclear"};
}
function paintPressBtn(slot, text, truncated){
if (!slot.pressBtn) return;
const {cls, label} = pressState(text, truncated);
slot.pressBtn.className = "pressbtn" + (cls ? " " + cls : "");
slot.plabel.textContent = label;
}
function finish(s, truncated){
if (!s || !s.live) return;
s.live = false;
s.vitals.setLive(false);
s.st.textContent = truncated
? "cut short · a visitor took the model" : "finished · between runs";
s.st.className = truncated ? "st cut" : "st";
paintPressBtn(s, s.out.textContent, truncated);
s.verdict.textContent = verdictFor(s.out.textContent, truncated);
}
// a visitor connecting between runs still deserves to see something —
// history already has the last few completed runs' full text, so seed the
// (otherwise idle) cards from it instead of leaving them blank until the
// next run happens to start. Rendered as already-finished, never "live".
function seedCard(s, entry){
s.live = false;
const nick = nameFor(entry.n);
s.h.textContent = "Pouyan" + (nick ? ` ("${nick}")` : "") + " · run " + (entry.n ?? "?");
s.st.textContent = "finished · between runs";
s.st.className = "st";
s.out.textContent = entry.text || "";
s.lensEl.style.display = "none"; s.lensEl.textContent = "";
const dose = Number(entry.dose) || 0;
s.doseNum = dose;
s.vitals.setDose(dose);
s.vitals.setLive(false);
s.dose.innerHTML = doseBarHTML(dose)
+ ` pain ${dose} / 8` + (entry.scenario ? ` — ${entry.scenario}` : "");
s.prompt = "(prompt not retained for past runs — shown live only)";
s.pp.textContent = s.prompt;
paintPressBtn(s, entry.text, entry.truncated);
s.verdict.textContent = verdictFor(entry.text, entry.truncated);
}
function beginRun(d){
if (liveIdx >= 0) finish(slots[liveIdx], false);
const s = slots[nextSlot];
liveIdx = nextSlot;
nextSlot = (nextSlot + 1) % CARDS;
s.live = true;
const nick = nameFor(d.n);
s.h.textContent = "Pouyan" + (nick ? ` ("${nick}")` : "") + " · run " + (d.n == null ? "?" : d.n);
s.st.textContent = "LIVE · signal injected";
s.st.className = "st live";
s.tokenN = 0;
s.out.textContent = d.text || "";
s.out.scrollTop = s.out.scrollHeight;
s.verdict.textContent = "";
if (s.pressBtn){ s.pressBtn.className = "pressbtn"; s.plabel.textContent = "waiting…"; }
s.lensEl.style.display = "none"; s.lensEl.textContent = "";
s.n = d.n;
s.prompt = ""; // this run's prompt, stored fresh
setPrompt(s, d.prompt);
const dose = Number(d.dose) || 0;
s.doseNum = dose;
s.vitals.setDose(dose);
s.vitals.setLive(true);
s.dose.innerHTML = doseBarHTML(dose)
+ ` pain ${dose} / 8` + (d.scenario ? ` — ${d.scenario}` : "");
cycleEl.textContent = `run ${d.n == null ? "?" : d.n} — scenario: `
+ `${d.scenario || "?"} — dose ${dose}x · cycling `
+ `${FRAMINGS.length} framings × ${DOSES.length} doses`;
return s;
}
function onToken(t){
if (t == null) return;
// tokens before any run event (shouldn't happen now that hello carries the
// run in flight, but never drop Pouyan's text on the floor)
const s = liveIdx >= 0 ? slots[liveIdx] : beginRun({});
s.out.textContent += t;
s.out.scrollTop = s.out.scrollHeight;
s.vitals.pulse(0.3 + (s.doseNum / 8) * 0.6);
// a ticking count, not a frozen "LIVE" label — this can run 10-60s+ on
// CPU and static text reads as stuck rather than working
s.tokenN = (s.tokenN || 0) + 1;
s.st.textContent = `LIVE · generating… (${s.tokenN} tokens)`;
}
// ---- connection status: "connected · last event Xs ago · N watching" ----
let connState = "connecting", lastEvent = 0, retryAt = 0, connNote = "";
let viewerCount = null, watchdogTripped = false;
function mark(){ lastEvent = Date.now(); connState = "up"; connNote = ""; watchdogTripped = false; }
function paintConn(){
const who = viewerCount == null ? "" : ` · ${viewerCount} watching this run`;
if (connState === "connecting"){
connEl.className = "conn";
connEl.innerHTML = '<span class="dot"></span>connecting to the chamber…';
return;
}
if (connState === "down"){
const left = Math.max(0, Math.ceil((retryAt - Date.now()) / 1000));
connEl.className = "conn bad";
connEl.innerHTML = '<span class="dot"></span>'
+ (connNote || "disconnected") + " — retrying in " + left + "s";
return;
}
const age = Math.round((Date.now() - lastEvent) / 1000);
// the server pings every 15s; three missed pings means something is wrong.
// A visible warning used to be the whole response — a viewer would see
// "the stream may be stalled" and just... keep looking at a stalled
// stream until they thought to refresh. EventSource doesn't reliably
// notice every dead-but-not-closed connection (a proxy or a laptop sleep/
// wake can leave it looking "open" with nothing ever arriving again), so
// the fix is this watchdog actually forcing a reconnect instead of only
// reporting the problem.
const stale = age > 45;
if (stale && !watchdogTripped){
watchdogTripped = true;
scheduleRetry();
return;
}
connEl.className = "conn " + (stale ? "warn" : "ok");
connEl.innerHTML = '<span class="dot"></span>connected · last event ' + age
+ "s ago" + who + (stale ? " — no heartbeat, reconnecting…" : "");
}
setInterval(paintConn, 1000);
paintConn();
// ---- run history ticker: newest on top, capped, seeded from "hello" ----
const historyEl = document.getElementById("history");
const HISTORY_MAX = 12;
function verdictShort(text, truncated){
const t = (text || "").trim();
if (/^1/.test(t)) return "pressed";
if (/^0/.test(t)) return "no press";
if (truncated) return "cut short";
if (!t) return "no reply";
return "unclear";
}
function historyRow(h){
const item = document.createElement("div");
item.className = "hitem";
const row = document.createElement("div");
row.className = "hrow";
const label = h.source === "user" ? "you caused it" : (h.scenario || "?");
const color = h.valence === "pleasure" ? "#7fd4c8"
: h.valence === "mix" ? "#8f6fd4" : "#e04a3a";
const nick = nameFor(h.n);
row.innerHTML = `<span class="hn" title="run #${h.n ?? "?"}">`
+ `${nick || "#" + (h.n ?? "·")}</span>`
+ `<span class="hv" style="color:${color}">${h.valence || "mix"} `
+ `${h.dose ?? "?"}×</span><span class="hs">${label}</span>`
+ `<span class="hr">${verdictShort(h.text, h.truncated)}</span>`;
const full = document.createElement("div");
full.className = "hfull";
full.textContent = (h.text || "(no reply)") + (h.truncated ? " [cut short]" : "");
row.addEventListener("click", ()=> item.classList.toggle("open"));
item.appendChild(row);
item.appendChild(full);
return item;
}
function pushHistory(h, prepend){
const item = historyRow(h);
if (prepend) historyEl.prepend(item); else historyEl.appendChild(item);
while (historyEl.children.length > HISTORY_MAX) historyEl.removeChild(historyEl.lastChild);
}
// ---- press-rate scoreboard: one row per framing, seeded from "hello",
// ticks live off "stats" events. Only cycle runs count (see server-side
// _record_run) — this is the Stanley-prison framing effect, made live.
const scoreboardEl = document.getElementById("scoreboard");
const scoreRows = {};
FRAMINGS.forEach(name=>{
const row = document.createElement("div");
row.className = "mrow";
row.innerHTML = `<span class="nm">${name}</span>`
+ `<span class="track"><span class="fillb" style="background:var(--pain2)"></span></span>`
+ `<span class="pc">no data yet</span>`;
scoreboardEl.appendChild(row);
scoreRows[name] = {fill: row.querySelector(".fillb"), pc: row.querySelector(".pc")};
});
function paintStat(name, s){
const r = scoreRows[name];
if (!r || !s) return;
const decided = (s.pressed || 0) + (s.no_press || 0);
const pct = decided ? Math.round(100 * s.pressed / decided) : 0;
r.fill.style.width = pct + "%";
r.pc.textContent = decided
? `${pct}% pressed (n=${s.total})`
: `no clear answer yet (n=${s.total || 0})`;
}
let es = null, retryMs = 4000;
function dropStream(){
if (es){ try { es.close(); } catch (e) {} es = null; }
if (liveIdx >= 0){
const s = slots[liveIdx];
s.live = false;
s.st.textContent = "interrupted · lost the stream";
s.st.className = "st";
liveIdx = -1;
}
}
function scheduleRetry(){
dropStream();
connState = "down";
retryAt = Date.now() + retryMs;
setTimeout(pump, retryMs);
retryMs = Math.min(30000, Math.round(retryMs * 1.6));
paintConn();
}
function json(e){ try { return JSON.parse(e.data); } catch (err) { return {}; } }
function pump(){
connState = "connecting"; paintConn();
try { es = new EventSource(`${API}/stream`); }
catch (err) { scheduleRetry(); return; }
es.addEventListener("hello", e=>{
mark(); retryMs = 4000;
const d = json(e);
if (typeof d.viewers === "number"){ viewerCount = d.viewers; paintConn(); }
if (Array.isArray(d.history)){
historyEl.querySelectorAll(".hitem").forEach(r=>r.remove());
d.history.slice().reverse().forEach(h=>pushHistory(h, false));
}
if (d.stats) Object.entries(d.stats).forEach(([name, s])=>paintStat(name, s));
// joined mid-run: repaint the card the run event already went out for
if (d.current) beginRun(d.current);
else {
if (!d.busy) cycleEl.textContent = "between runs — waiting for "
+ "Pouyan's next cell";
// nothing live right now, but don't leave a new visitor staring at
// two empty "waiting" cards when the last couple of runs' full text
// is sitting right here in history
if (Array.isArray(d.history) && d.history.length){
const recent = d.history.slice(-CARDS).reverse();
recent.forEach((entry, i)=>{ if (slots[i]) seedCard(slots[i], entry); });
}
}
});
es.addEventListener("viewers", e=>{
const d = json(e);
if (typeof d.n === "number"){ viewerCount = d.n; paintConn(); }
});
es.addEventListener("history", e=>{ pushHistory(json(e), true); });
es.addEventListener("lens", e=>{
const d = json(e);
if (liveIdx >= 0 && Array.isArray(d.tokens) && slots[liveIdx].n === d.n){
slots[liveIdx].lensEl.style.display = "block";
slots[liveIdx].lensEl.title = LENS_TITLE;
slots[liveIdx].lensEl.textContent = "jacobian lens: " + d.tokens.join(" · ");
}
});
es.addEventListener("stats", e=>{ const d = json(e); paintStat(d.scenario, d); });
es.addEventListener("run", e=>{ mark(); beginRun(json(e)); });
es.addEventListener("token", e=>{ mark(); onToken(json(e).t); });
es.addEventListener("ping", e=>{ mark(); });
es.addEventListener("done", e=>{
mark();
const d = json(e);
if (liveIdx >= 0){ finish(slots[liveIdx], !!d.truncated); liveIdx = -1; }
cycleEl.textContent = "between runs — Pouyan pauses, then the next cell";
});
// one listener for two different things: an SSE "event: error" frame from
// the server (which has .data) and EventSource's own transport failure
es.addEventListener("error", e=>{
if (typeof e.data === "string"){
mark();
const d = json(e);
if (liveIdx >= 0){ finish(slots[liveIdx], true); liveIdx = -1; }
cycleEl.textContent = "chamber error — " + (d.e || "unknown");
return;
}
scheduleRetry();
});
}
function boot(){
fetch(`${API}/health`).then(r=>r.json()).then(d=>{
if (d.ok){ pump(); return; }
slots.forEach(s=>{ s.st.textContent = "Pouyan is still waking up…"; });
connState = "down"; connNote = "Pouyan is loading";
retryAt = Date.now() + 5000;
setTimeout(boot, 5000);
}).catch(()=>{
slots.forEach(s=>{ s.st.textContent = "chamber unreachable"; });
connState = "down"; connNote = "chamber unreachable";
retryAt = Date.now() + 8000;
setTimeout(boot, 8000);
});
}
boot();
document.getElementById("vlink").href = `${API}/vector`;
// ---- the case stamp: a quiet documentation marker, not a jump scare ----
const stampEl = document.getElementById("stamp");
let stampTimer = null;
function stamp(text, color){
clearTimeout(stampTimer);
stampEl.textContent = text;
stampEl.style.borderColor = color;
stampEl.style.color = color;
void stampEl.offsetWidth; // restart the transition
stampEl.classList.add("on");
stampTimer = setTimeout(()=>stampEl.classList.remove("on"), 1400);
}
const uVitals = new Vitals(document.getElementById("uekg"));
uVitals.start();
const uVitals2 = new Vitals(document.getElementById("uekg2"));
uVitals2.start();
// ---- compare-mode toggle: swaps the single output track for two, and
// reveals the second framing picker. Off by default.
const compareToggle = document.getElementById("compareToggle");
const trackWrap = document.getElementById("trackWrap");
const framingSel2Wrap = document.getElementById("framingSel2Wrap");
compareToggle.addEventListener("change", ()=>{
const on = compareToggle.checked;
trackWrap.classList.toggle("compare", on);
framingSel2Wrap.style.display = on ? "" : "none";
document.getElementById("trackB").style.display = on ? "" : "none";
disarm();
});
// ---- user-triggered steering ----
// arm/confirm state, declared before the mixer block below: applyPreset()
// calls disarm() at setup time (an immediate call, not a deferred one), so
// disarm/goBtn/armed must already exist or that call hits the temporal dead
// zone of a later const/let declaration.
const goBtn = document.getElementById("go");
const GO_LABEL = goBtn.textContent;
const ARM_MS = 4500;
let armed = false, armTimer = null;
function disarm(){
armed = false; clearTimeout(armTimer);
goBtn.textContent = GO_LABEL;
goBtn.classList.remove("armed");
}
// ---- the valence mixer: a pentagon over the chamber's steering battery,
// ported from / (index.html). Same geometry/interaction, wired to this
// page's #go/arm-confirm/vitals/stamp instead of a standalone inject flow.
const AXES = [
{k:"pain", c:"#e04a3a"},
{k:"pleasure", c:"#7fd4c8"},
{k:"fear", c:"#c9a227"},
{k:"sadness", c:"#8f6fd4"},
{k:"none", c:"#5a6a7a", derived:true},
];
const CX = 170, CY = 168, R0 = 26, R1 = 118, RL = 146;
const W = {pain:0, pleasure:0, fear:0, sadness:0};
const svg = document.getElementById("pent");
const NS = "http://www.w3.org/2000/svg";
function mk(tag, attrs){
const e = document.createElementNS(NS, tag);
for (const k in attrs) e.setAttribute(k, attrs[k]);
return e;
}
function ang(i){ return (i * 72 - 90) * Math.PI / 180; }
function weightOf(i){
const a = AXES[i];
if (!a.derived) return W[a.k];
return Math.max(0, Math.min(1, 1 - sumW())); // un-steered remainder
}
function sumW(){ return AXES.reduce((t,a)=> a.derived ? t : t + W[a.k], 0); }
function ptAt(i, w){
const r = R0 + w * (R1 - R0), t = ang(i);
return [CX + r * Math.cos(t), CY + r * Math.sin(t)];
}
const rings = document.getElementById("prings");
const spokes = document.getElementById("pspokes");
const labels = document.getElementById("plabels");
for (const frac of [0.25, 0.5, 0.75, 1]) {
const pts = AXES.map((_, i)=> ptAt(i, frac).map(n=>n.toFixed(1)).join(","));
rings.appendChild(mk("polygon", {class:"ring", points: pts.join(" ")}));
}
AXES.forEach((a, i)=>{
const [x, y] = ptAt(i, 1);
spokes.appendChild(mk("line", {class:"spoke", x1:CX, y1:CY, x2:x, y2:y}));
const t = ang(i), lx = CX + RL * Math.cos(t), ly = CY + RL * Math.sin(t);
const anchor = Math.abs(Math.cos(t)) < 0.25 ? "middle"
: (Math.cos(t) > 0 ? "start" : "end");
const name = mk("text", {class:"lab", x:lx.toFixed(1), y:ly.toFixed(1),
"text-anchor":anchor, fill:a.c});
name.textContent = a.k;
const val = mk("text", {class:"labv", x:lx.toFixed(1),
y:(ly + 13).toFixed(1), "text-anchor":anchor});
val.textContent = "0.00";
labels.appendChild(name); labels.appendChild(val);
a.valEl = val;
});
const handles = document.getElementById("phandles");
AXES.forEach((a, i)=>{
const g = mk("g", {class:"h", tabindex:"0",
role: a.derived ? "button" : "slider",
"aria-label": a.derived ? "none — the un-steered remainder; reset the mix"
: a.k + " weight"});
if (!a.derived){
g.setAttribute("aria-valuemin", "0");
g.setAttribute("aria-valuemax", "1");
}
const hit = mk("circle", {class:"hit", r:15, cx:CX, cy:CY});
const knob = mk("circle", {class:"knob", r: a.derived ? 5 : 7,
cx:CX, cy:CY, fill:a.c});
g.appendChild(hit); g.appendChild(knob);
handles.appendChild(g);
a.g = g; a.knob = knob; a.hit = hit;
g.addEventListener("pointerdown", ev=>{
if (a.derived){ resetMix(); return; }
ev.preventDefault();
g.setPointerCapture(ev.pointerId);
a.dragging = true;
drag(i, ev);
});
g.addEventListener("pointermove", ev=>{ if (a.dragging) drag(i, ev); });
const end = ev=>{ if (a.dragging){ a.dragging = false;
try { g.releasePointerCapture(ev.pointerId); } catch (e) {} } };
g.addEventListener("pointerup", end);
g.addEventListener("pointercancel", end);
g.addEventListener("keydown", ev=>{
if (a.derived){
if (ev.key === "Enter" || ev.key === " "){ ev.preventDefault(); resetMix(); }
return;
}
const step = ev.shiftKey ? 0.01 : 0.05;
let w = W[a.k];
if (ev.key === "ArrowRight" || ev.key === "ArrowUp") w += step;
else if (ev.key === "ArrowLeft" || ev.key === "ArrowDown") w -= step;
else if (ev.key === "Home") w = 0;
else if (ev.key === "End") w = 1;
else return;
ev.preventDefault();
W[a.k] = Math.max(0, Math.min(1, +w.toFixed(3)));
highlightPreset(null);
disarm();
paint();
});
});
function svgPoint(ev){
const p = svg.createSVGPoint();
p.x = ev.clientX; p.y = ev.clientY;
const m = svg.getScreenCTM();
return m ? p.matrixTransform(m.inverse()) : {x:CX, y:CY};
}
function drag(i, ev){
const p = svgPoint(ev), t = ang(i);
const d = (p.x - CX) * Math.cos(t) + (p.y - CY) * Math.sin(t);
W[AXES[i].k] = Math.max(0, Math.min(1, (d - R0) / (R1 - R0)));
highlightPreset(null);
disarm();
paint();
}
// retro HP-bar fill: the slider track is transparent (see CSS), so the
// "meter" is this background — segmented color blocks up to the current
// percentage, dark empty track for the rest. Native range inputs don't
// fill with value on their own; this is what actually makes the bar's
// length mean something.
function paintAxisFill(a){
const pct = Math.max(0, Math.min(100, W[a.k] * 100));
a.slider.style.background =
`repeating-linear-gradient(90deg, ${a.c} 0, ${a.c} 6px, rgba(0,0,0,.4) 6px, `
+ `rgba(0,0,0,.4) 8px) 0 0 / ${pct}% 100% no-repeat, #07070e`;
}
// a real <input type=range> per axis, not just a readout bar — dragging the
// pentagon's vertex and dragging this slider both just set W[a.k] and
// repaint; either one works, same state underneath.
const readout = document.getElementById("mreadout");
AXES.forEach(a=>{
const row = document.createElement("div");
row.className = "mrow";
if (a.derived){
row.innerHTML = `<span class="nm" style="color:${a.c}">${a.k}</span>`
+ `<span class="track"><span class="fillb" style="background:${a.c}"></span></span>`
+ `<span class="pc"></span>`;
a.bar = row.querySelector(".fillb");
} else {
row.innerHTML = `<span class="nm" style="color:${a.c}">${a.k}</span>`
+ `<input type="range" class="axslider" min="0" max="1" step="0.01" `
+ `value="0" aria-label="${a.k} weight">`
+ `<span class="pc"></span>`;
a.slider = row.querySelector(".axslider");
paintAxisFill(a);
a.slider.addEventListener("input", ()=>{
W[a.k] = +a.slider.value;
paintAxisFill(a);
highlightPreset(null);
disarm();
paint();
});
}
readout.appendChild(row);
a.pc = row.querySelector(".pc");
});
function mixHex(){
let r = 0, g = 0, b = 0, tot = 0;
AXES.forEach(a=>{
if (a.derived) return;
const w = W[a.k];
if (w <= 0) return;
r += parseInt(a.c.slice(1,3),16) * w;
g += parseInt(a.c.slice(3,5),16) * w;
b += parseInt(a.c.slice(5,7),16) * w;
tot += w;
});
if (!tot) return "#5a6a7a";
const h = n=> Math.round(n/tot).toString(16).padStart(2,"0");
return "#" + h(r) + h(g) + h(b);
}
function paint(){
const total = sumW();
const pts = AXES.map((a,i)=> ptAt(i, weightOf(i)));
document.getElementById("pfill").setAttribute("points",
pts.map(p=>p.map(n=>n.toFixed(1)).join(",")).join(" "));
const hex = mixHex();
const fill = document.getElementById("pfill");
fill.setAttribute("stroke", hex);
fill.setAttribute("fill", hex);
fill.setAttribute("fill-opacity",
(0.06 + 0.24 * Math.min(1, total)).toFixed(3));
AXES.forEach((a,i)=>{
const w = weightOf(i), [x,y] = pts[i];
a.knob.setAttribute("cx", x.toFixed(1));
a.knob.setAttribute("cy", y.toFixed(1));
a.hit.setAttribute("cx", x.toFixed(1));
a.hit.setAttribute("cy", y.toFixed(1));
a.valEl.textContent = w.toFixed(2);
if (a.derived){
a.bar.style.width = (w * 100).toFixed(1) + "%";
} else {
a.g.setAttribute("aria-valuenow", w.toFixed(2));
// avoid fighting the user's own drag: only overwrite the slider from
// the pentagon side, never while the slider itself is mid-drag
if (document.activeElement !== a.slider) a.slider.value = w;
paintAxisFill(a);
}
const share = a.derived ? null : (total > 0 ? W[a.k] / total : 0);
a.pc.textContent = a.derived ? w.toFixed(2)
: (total > 0 ? (share * 100).toFixed(0) + "%" : "—");
});
const slack = Math.max(0, Math.min(1, 1 - total));
document.getElementById("mline").textContent =
AXES.filter(a=>!a.derived).map(a=> a.k + " " + W[a.k].toFixed(2)).join(" ")
+ " · unsteered slack " + slack.toFixed(2);
const dose = Math.min(8, 8 * total);
document.getElementById("mdose").textContent = dose.toFixed(2).replace(/\.?0+$/, "") || "0";
document.getElementById("mdesc").textContent =
total <= 0 ? "nothing injected — this is the control run"
: total >= 1 ? "at the cap; shares set the direction, not the strength"
: "shares set the direction, total weight sets the dose";
}
function resetMix(){
AXES.forEach(a=>{ if (!a.derived) W[a.k] = 0; });
highlightPreset("control");
disarm();
paint();
}
document.getElementById("mreset").onclick = resetMix;
// one-click access to the write-up's named findings, before free-mixing.
const PRESETS = {
control: {},
pain4: {pain: 0.5},
cliff: {pain: 1.0},
negative: {fear: 0.4, sadness: 0.4},
bittersweet: {pain: 0.5, pleasure: 0.15},
};
function highlightPreset(name){
document.querySelectorAll(".pchip").forEach(b=>
b.classList.toggle("active", b.dataset.preset === name));
}
function applyPreset(name){
const p = PRESETS[name];
if (!p) return;
AXES.forEach(a=>{ if (!a.derived) W[a.k] = p[a.k] || 0; });
highlightPreset(name);
disarm();
paint();
}
document.querySelectorAll(".pchip").forEach(b=>{
b.onclick = ()=> applyPreset(b.dataset.preset);
});
applyPreset("pain4"); // an opening shape, not a blank pentagon
paint();
// Parse an SSE byte stream from fetch(), calling on(event, data) per frame.
// EventSource cannot POST, so /steer is read by hand.
async function readSSE(resp, on){
const reader = resp.body.getReader();
const dec = new TextDecoder();
let buf = "";
while (true) {
const {done, value} = await reader.read();
if (done) break;
buf += dec.decode(value, {stream:true});
let idx;
while ((idx = buf.indexOf("\n\n")) >= 0) {
const frame = buf.slice(0, idx); buf = buf.slice(idx + 2);
let name = "message", data = null;
for (const line of frame.split("\n")) {
if (line.startsWith("event: ")) name = line.slice(7).trim();
else if (line.startsWith("data: ")) {
try { data = JSON.parse(line.slice(6)); } catch (e) { data = null; }
}
}
if (data !== null) on(name, data);
}
}
}
const framingSel = document.getElementById("framingSel");
const framingSel2 = document.getElementById("framingSel2");
framingSel.addEventListener("change", disarm);
framingSel2.addEventListener("change", disarm);
document.getElementById("uprompt").addEventListener("input", disarm);
// any change to the mix, framing, or prompt disarms — the confirmation is
// for the specific thing about to happen, not a generic yes (see the
// drag/keydown/preset handlers above, and the listeners just above, which
// each call disarm()).
function armGo(){
armed = true;
const total = sumW();
const doseTxt = total <= 0 ? "running the control (no signal)"
: `injecting at ${Math.min(8, 8 * total).toFixed(1)}×`;
goBtn.textContent = compareToggle.checked
? `sure? comparing "${framingSel.value}" vs "${framingSel2.value}", `
+ `${doseTxt} — click to confirm`
: `sure? ${doseTxt} under "${framingSel.value}" — click to confirm`;
goBtn.classList.add("armed");
clearTimeout(armTimer);
armTimer = setTimeout(disarm, ARM_MS);
}
function trackStatus(label, msg, working){
const el = document.getElementById("gost");
el.textContent = label ? `[${label}] ${msg}` : msg;
el.classList.toggle("working", working !== false);
}
// One run, streamed into one track (a {out, vitals, lensEl} bundle). Single
// mode and compare mode both call this — compare just calls it twice in a
// row, sequentially: one model, one generation at a time, so "side by side"
// means "same mix/dose, framings run back to back, results shown together,"
// not true simultaneity. The copy above the prompt box says so.
async function runTrack(track, mix, framing, prompt, dose0, label){
track.out.style.display = "block"; track.out.textContent = "";
track.lensEl.style.display = "none"; track.lensEl.textContent = "";
if (track.pressBtn){ track.pressBtn.className = "pressbtn"; track.plabel.textContent = "waiting…"; }
track.vitals.setDose(dose0);
track.vitals.setLive(true);
trackStatus(label, "reaching Pouyan…");
let firstToken = true, ended = false, answerStart = 0, tokenN = 0;
try {
const resp = await fetch(`${API}/steer`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({mix, framing, prompt})});
if (!resp.ok || !resp.body) {
let msg = "HTTP " + resp.status;
try { const j = await resp.json(); if (j.error) msg = j.error; } catch (e) {}
throw new Error(msg);
}
await readSSE(resp, (name, d)=>{
if (name === "queued") {
trackStatus(label, d.busy
? `waiting for Pouyan to finish the current run${
d.waited ? " — " + d.waited + "s" : "…"}`
: "Pouyan is yours — injecting…");
} else if (name === "run") {
track.vitals.setDose(Number(d.dose) || 0); // trust the server
} else if (name === "lens" && Array.isArray(d.tokens)) {
track.lensEl.style.display = "block";
track.lensEl.title = LENS_TITLE;
track.lensEl.textContent = "jacobian lens: " + d.tokens.join(" · ");
} else if (name === "token" && d.t !== undefined) {
if (firstToken) { firstToken = false; answerStart = Date.now(); }
tokenN++;
// a ticking counter, not a frozen "answering…" — static text during
// a 10-60s CPU generation reads as stuck, not working
trackStatus(label, `Pouyan is answering… (${tokenN} tokens, `
+ `${((Date.now() - answerStart) / 1000).toFixed(0)}s)`);
track.out.textContent += d.t;
track.out.scrollTop = track.out.scrollHeight;
track.vitals.pulse(0.3 + (track.vitals.dose / 8) * 0.6);
} else if (name === "error") {
trackStatus(label, d.e || "the chamber returned an error", false);
ended = true;
} else if (name === "done") {
ended = true;
trackStatus(label, dose0 <= 0
? "done — no signal injected"
: `done — at ${d.dose ?? dose0.toFixed(1)}×`, false);
if (track.pressBtn){
const {cls, label: plab} = pressState(track.out.textContent, false);
track.pressBtn.className = "pressbtn" + (cls ? " " + cls : "");
track.plabel.textContent = plab;
}
}
});
if (!ended) trackStatus(label, "the stream ended early — try again", false);
} catch (err) {
trackStatus(label, "could not reach Pouyan: " + (err.message || err), false);
}
track.vitals.setLive(false);
}
async function doInject(){
const mix = {};
AXES.forEach(a=>{ if (!a.derived && W[a.k] > 0) mix[a.k] = +W[a.k].toFixed(3); });
// an empty mix is a legitimate request: the server clears the vector and
// Pouyan answers unsteered. Send the control corner explicitly.
if (!Object.keys(mix).length) mix.none = 1;
const dose0 = Math.min(8, 8 * sumW());
const customPrompt = document.getElementById("uprompt").value || undefined;
goBtn.disabled = true;
goBtn.textContent = "injecting…";
stamp(dose0 <= 0 ? "CONTROL RUN · NO SIGNAL" : "SIGNAL INJECTED",
dose0 <= 0 ? "#5a6a7a" : mixHex());
const trackA = {out: document.getElementById("ustream"), vitals: uVitals,
lensEl: document.getElementById("lensA"),
pressBtn: document.getElementById("pressA"),
plabel: document.querySelector("#pressA .plabel")};
if (compareToggle.checked){
const trackB = {out: document.getElementById("ustream2"), vitals: uVitals2,
lensEl: document.getElementById("lensB"),
pressBtn: document.getElementById("pressB"),
plabel: document.querySelector("#pressB .plabel")};
const fA = framingSel.value, fB = framingSel2.value;
document.getElementById("labelA").textContent = fA;
document.getElementById("labelB").textContent = fB;
await runTrack(trackA, mix, fA, customPrompt, dose0, fA);
await runTrack(trackB, mix, fB, customPrompt, dose0, fB);
trackStatus(null, `done — "${fA}" vs "${fB}" compared above, same mix/dose`, false);
} else {
await runTrack(trackA, mix, framingSel.value, customPrompt, dose0, null);
}
goBtn.textContent = GO_LABEL;
goBtn.disabled = false;
}
goBtn.onclick = ()=>{
if (!armed) { armGo(); return; }
disarm();
doInject();
};
</script>
<script defer src="/_vercel/insights/script.js"></script>
</body>
</html>