Spaces:
Running on Zero
Running on Zero
Add optional projected original-dimension axis guides with opacity and origin controls
9d3e0c7 verified Download token_space.js from jejunepixels/automatic-writing: direct link, hf CLI and curl.
- Browser
- Download file 47.6 kB
-
https://huggingface.co/spaces/jejunepixels/automatic-writing/resolve/main/token_space.js
- Command line
-
hf download hf://spaces/jejunepixels/automatic-writing/token_space.js
-
curl -L -o token_space.js https://huggingface.co/spaces/jejunepixels/automatic-writing/resolve/main/token_space.js
47.6 kB
| () => { | |
| if (window.__letItFlowSpace) window.__letItFlowSpace(); | |
| let root,canvas,ctx,resize,observer,timer,stream=null,seen=-1,payload='',disposed=false; | |
| let history=[],hits=[],selected=null,yaw=.35,pitch=-.15,zoom=1,target=[0,0,0],panX=0,panY=0; | |
| let dragging=false,panning=false,moved=false,lastX=0,lastY=0,width=0,height=0; | |
| let lastTime=Date.now(),mode='live',connections='attention'; | |
| const lifetime=6000; | |
| let lastText=''; | |
| let layerCount=0,layerRows=new Map(),layerTargets=new Map(); | |
| let layerMode='three',layerLimit=3,minimumWeight=.01,hiddenLayers=new Set(),legendFocus=null; | |
| let edgeHits=[],hoverEdge=null,lastNarrow=null; | |
| let dimensionAxesEnabled=false,dimensionAxisOpacity=.04,dimensionAxisOrigin='mean'; | |
| let embeddingDimensionAxes=null,representationDimensionAxes=null,dimensionAxisHits=[],hoverDimensionAxis=null; | |
| let paused=false, previousMode='live'; | |
| let positionMode='embeddings',representationMeta=null,representationPoints=new Map(); | |
| let representationStage=0,representationPlaying=false,representationTrail=true,lastRepresentationLayer=-1; | |
| let textView=null,externalSelected=null,reader=null,readerSignature='',lastHighlighted=null; | |
| let running=false,awaitingGPU=false,ended=false,togglePending=false,toggleButton=null; | |
| function generationClick(){ | |
| if(togglePending||(running&&paused))return; | |
| const pausing=(running||awaitingGPU)&&!paused; | |
| const host=document.querySelector(pausing?'#generation-pause':ended?'#generation-new':'#generation-run'); | |
| const proxy=host?.querySelector?.('button')||host; | |
| if(typeof proxy?.click!=='function')return; | |
| togglePending=true;toggleButton.textContent=pausing?'Pausing...':'Starting...';toggleButton.disabled=true; | |
| proxy.click(); | |
| } | |
| function mountGenerationControl(){ | |
| const button=document.querySelector('[data-generation-toggle]'); | |
| if(!button||typeof button.addEventListener!=='function')return; | |
| if(button!==toggleButton){ | |
| toggleButton?.removeEventListener?.('click',generationClick);toggleButton=button; | |
| toggleButton.addEventListener('click',generationClick); | |
| } | |
| const label=togglePending?toggleButton.textContent:(running||awaitingGPU)?(paused?'Pausing...':'Pause'):paused&&!ended?'Resume':seen>=0&&!ended?'Resume':'Start'; | |
| if(toggleButton.textContent!==label)toggleButton.textContent=label; | |
| toggleButton.disabled=togglePending||(running&&paused); | |
| } | |
| function dimensionAxisGeometry(){return positionMode==='representations'?representationDimensionAxes:embeddingDimensionAxes;} | |
| function dimensionAxisControls(){ | |
| const host=root?.querySelector('.dimension-axes-controls');if(!host?.querySelector)return; | |
| const geometry=dimensionAxisGeometry(),count=host.querySelector('[data-dimension-count]'); | |
| host.querySelector('[data-dimension-axes]').checked=dimensionAxesEnabled; | |
| count.textContent=geometry?`(${geometry.count})`:''; | |
| const status=host.querySelector('[data-dimension-status]'); | |
| status.textContent=geometry?`${geometry.count} feature dimensions / ${geometry.space==='input_embeddings'?'input-embedding projection':'normalised hidden-state projection'} / ${dimensionAxisOrigin==='raw'?'projected zero-vector origin':'centred at the PCA mean'}. Short or overlapping projections may be hard to distinguish.`: | |
| positionMode==='representations'?'Axes appear once the shared representation projection is ready. Generate a few tokens and pause.':'Load a model to prepare the original dimension directions.'; | |
| } | |
| function displayedPosition(point){ | |
| if(positionMode!=='representations')return point.xyz; | |
| const layers=representationPoints.get(point.n);if(!layers?.length)return null; | |
| const stage=Math.max(0,Math.min(layers.length-1,representationStage)),a=Math.floor(stage),b=Math.min(a+1,layers.length-1),t=stage-a; | |
| return layers[a].map((value,i)=>value*(1-t)+layers[b][i]*t); | |
| } | |
| function representationControls(){ | |
| if(root?.dataset)root.dataset.positionMode=positionMode; | |
| const extra=root?.querySelector('.representation-connection-details'); | |
| if(extra?.dataset){ | |
| const key=`${positionMode}:${window.innerWidth<=640}`; | |
| if(extra.dataset.layout!==key){extra.open=!(positionMode==='representations'&&window.innerWidth<=640);extra.dataset.layout=key;} | |
| } | |
| const host=root?.querySelector('.representation-controls');if(!host?.querySelector)return; | |
| host.hidden=positionMode!=='representations';dimensionAxisControls();if(host.hidden)return; | |
| const note=host.querySelector('[data-representation-note]'),slider=host.querySelector('[data-representation-layer]'); | |
| const play=host.querySelector('[data-representation-play]'),caption=host.querySelector('[data-representation-stage]'); | |
| const ready=Boolean(representationMeta?.ready),maximum=Math.max(0,(representationMeta?.stages||1)-1); | |
| representationStage=Math.min(representationStage,maximum);slider.max=maximum;slider.value=Math.round(representationStage); | |
| slider.disabled=!ready||!paused;play.disabled=!ready||!paused; | |
| play.textContent=representationPlaying?'Pause layers':'Play layers'; | |
| const stage=Math.round(representationStage),between=Math.abs(representationStage-stage)>.04; | |
| caption.textContent=stage===0?'Input to first layer':`After layer ${stage-1}${stage===maximum?' + final normalisation':''}`; | |
| if(between)caption.textContent+=' / interpolating'; | |
| slider.setAttribute('aria-valuetext',caption.textContent); | |
| let message=!representationMeta?'Enable Capture layer representations in Settings, then generate a new stream.': | |
| !ready?`Collecting token states: ${representationMeta.calibrating} / ${representationMeta.calibration_target}. Pause after a few tokens to fit the shared projection.`: | |
| `${[...representationPoints.keys()].filter(n=>n>=0).length} token trajectories / ${maximum} layers / one fixed projection.`; | |
| if(ready&&selected!=null&&!representationPoints.has(selected))message+=' This token has no saved trajectory: it may be outside the 128-token history, or the latest token has not been processed yet.'; | |
| if(ended&&!ready)message='The stream ended before a generated token could be processed. Start a new stream to capture trajectories.'; | |
| if(!paused)message+=' Pause generation to scrub or play layers.'; | |
| note.textContent=message; | |
| } | |
| function setPositionView(value){ | |
| representationPlaying=false; | |
| if(value==='representations'){ | |
| positionMode='representations';mode='history';representationStage=0;connections='attention';legendFocus=null; | |
| const links=root?.querySelector('[data-space-links]');if(links)links.value='attention'; | |
| target=[0,0,0];panX=panY=0;zoom=window.innerWidth<=640?.8:1; | |
| if(selected==null||!representationPoints.has(selected))selected=Math.max(-1,...[...representationPoints.keys()].filter(n=>n>=0)); | |
| if(selected<0)selected=history.at(-1)?.n??null; | |
| if(!paused){ | |
| const proxy=document.querySelector('#generation-pause');(proxy?.querySelector?.('button')||proxy)?.click(); | |
| } | |
| }else{positionMode='embeddings';mode=value;target=[0,0,0];panX=panY=0;zoom=1;} | |
| representationControls();details(); | |
| } | |
| function sourcePoint(){ | |
| const pinned=history.find(p=>p.n===selected)||externalSelected; | |
| if(paused)return pinned; | |
| if(pinned?.attention&&(mode==='history'||Date.now()-Math.max(pinned.born,pinned.attentionBorn??0)<lifetime))return pinned; | |
| return [...history].reverse().find(p=>p.attention&&(mode==='history'||Date.now()-Math.max(p.born,p.attentionBorn??0)<lifetime)); | |
| } | |
| function chooseToken(index,focus=true){ | |
| if(!paused)return; | |
| const point=history.find(p=>p.n===index)||textView?.points.find(p=>p.n===index); | |
| if(!point)return; | |
| selected=index;externalSelected=history.some(p=>p.n===index)?null:point;connections='attention'; | |
| const input=root.querySelector('[data-space-links]');if(input)input.value=connections; | |
| const shown=displayedPosition(point); | |
| if(focus&&shown){target=[...shown];panX=panY=0;zoom=Math.min(3,Math.max(1,zoom));} | |
| details();syncTextSelection(); | |
| } | |
| function stepToken(direction){ | |
| const items=(textView?.points||history).filter(p=>positionMode!=='representations'||representationPoints.has(p.n)); | |
| if(!paused||!items.length)return; | |
| let index=items.findIndex(p=>p.n===selected); | |
| if(index<0){const next=direction>0?items.find(p=>p.n>selected):[...items].reverse().find(p=>p.n<selected);if(next)chooseToken(next.n);return;} | |
| index=Math.max(0,Math.min(items.length-1,index+direction)); | |
| chooseToken(items[index].n); | |
| } | |
| function syncTextSelection(){ | |
| if(!reader||lastHighlighted===selected)return; | |
| lastHighlighted=selected;let first=null; | |
| for(const button of reader.querySelectorAll('[data-flow-indices]')){ | |
| const on=button.dataset.flowIndices.split(',').map(Number).includes(selected); | |
| button.classList.toggle('is-selected',on); | |
| button.setAttribute('aria-pressed',String(on)); | |
| if(on&&!first)first=button; | |
| } | |
| first?.scrollIntoView({block:'nearest',inline:'nearest'}); | |
| } | |
| function inspectText(){ | |
| const host=document.querySelector('#page');if(!host)return; | |
| if(!paused||!textView){ | |
| host.querySelector('[data-token-reader]')?.remove();host.removeAttribute('data-token-inspection'); | |
| reader=null;readerSignature='';lastHighlighted=null;return; | |
| } | |
| const signature=`${stream}:${textView.points.length}:${textView.segments.length}`; | |
| if(readerSignature===signature&&host.querySelector('[data-token-reader]')===reader){syncTextSelection();return;} | |
| host.querySelector('[data-token-reader]')?.remove(); | |
| reader=document.createElement('div');reader.setAttribute('data-token-reader','');reader.className='paused-token-reader'; | |
| const hint=document.createElement('div');hint.className='token-reader-hint';hint.textContent='PAUSED / Click a token to locate it and inspect its attention.'; | |
| const content=document.createElement('div');content.className='paused-token-content'; | |
| const choices=document.createElement('div');choices.className='token-piece-choices'; | |
| function button(indices,label){ | |
| const node=document.createElement('button');node.type='button';node.textContent=label; | |
| node.dataset.flowIndices=indices.join(',');node.className='text-token'; | |
| node.title=indices.map(n=>{const p=textView.points[n];return `Token #${n+1} / ID ${p.id}`;}).join(' / '); | |
| node.addEventListener('click',()=>{ | |
| if(!paused||!textView)return; | |
| chooseToken(indices.at(-1));choices.replaceChildren(); | |
| if(indices.length>1){ | |
| const label=document.createElement('span');label.textContent='This text shares multiple tokens: ';choices.appendChild(label); | |
| for(const n of indices){const point=textView.points[n];choices.appendChild(button([n],`#${n+1} ${JSON.stringify(point.label)} `));} | |
| } | |
| lastHighlighted=null;syncTextSelection(); | |
| });return node; | |
| } | |
| if(textView.segments.length){ | |
| for(const segment of textView.segments){ | |
| content.appendChild(segment.indices.length?button(segment.indices,segment.text):document.createTextNode(segment.text)); | |
| } | |
| }else{ | |
| const prose=document.createElement('div');prose.textContent=textView.text;content.appendChild(prose); | |
| hint.textContent='PAUSED / Select a token piece below to inspect it in 3D.'; | |
| for(const point of textView.points)content.appendChild(button([point.n],JSON.stringify(point.label)+' ')); | |
| } | |
| reader.appendChild(hint);reader.appendChild(content);reader.appendChild(choices);host.appendChild(reader); | |
| host.setAttribute('data-token-inspection','true');readerSignature=signature;lastHighlighted=null;syncTextSelection(); | |
| } | |
| function resetCamera(){yaw=.35;pitch=-.15;zoom=1;target=[0,0,0];panX=panY=0;} | |
| function pick(e){ | |
| const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top; | |
| return hits.filter(p=>Math.hypot(p.x-x,p.y-y)<22).sort((a,b)=>Math.hypot(a.x-x,a.y-y)-Math.hypot(b.x-x,b.y-y))[0]; | |
| } | |
| function layerRGB(index){ | |
| const t=layerCount>1?index/(layerCount-1):1; | |
| const stops=[[113,183,255],[183,155,232],[244,191,103]]; | |
| const a=t<.5?stops[0]:stops[1],b=t<.5?stops[1]:stops[2],u=t<.5?t*2:(t-.5)*2; | |
| return a.map((value,i)=>Math.round(value+(b[i]-value)*u)).join(','); | |
| } | |
| function contextPoint(n){return layerTargets.get(n)||textView?.points[n]||history.find(p=>p.n===n);} | |
| function attentionRows(point,includeHidden=false){ | |
| if(!point)return []; | |
| const saved=layerRows.get(point.n); | |
| let rows=[]; | |
| if(saved&&(layerMode!=='selected'||positionMode==='representations')){ | |
| const count=saved.indices.length; | |
| const chosen=positionMode==='representations'?(Math.round(representationStage)>0?[Math.min(count-1,Math.round(representationStage)-1)]:[]):layerMode==='all'?Array.from({length:count},(_,i)=>i):[...new Set([0,Math.floor((count-1)/2),count-1])]; | |
| rows=chosen.map(layer=>({query:point.n,layer,head:-1,keys:saved.keys[layer], | |
| links:saved.indices[layer].map((n,i)=>({n,score:saved.scores[layer][i],...contextPoint(n)})).filter(link=>link.n>=-1&&link.score>0)})); | |
| }else if(point.attention&&positionMode!=='representations')rows=[point.attention]; | |
| return rows.filter(row=>positionMode==='representations'||includeHidden||!hiddenLayers.has(row.layer)).map(row=>{ | |
| const links=row.links.filter(link=>link.score>=minimumWeight).slice(0,layerLimit); | |
| return {...row,links,shown_mass:links.reduce((sum,link)=>sum+link.score,0)}; | |
| }); | |
| } | |
| function edgeTooltip(edge,event){ | |
| const box=root?.querySelector('.space-edge-tooltip');if(!box)return; | |
| box.hidden=!edge;if(!edge)return; | |
| if(edge.type==='dimension-axis'){ | |
| const geometry=dimensionAxisGeometry(); | |
| box.textContent=`Dimension ${edge.dimension} / ${geometry?.count??'?'} original feature dimensions / projected direction, not a model parameter`; | |
| }else{ | |
| const label=edge.n===-1?'Start boundary':JSON.stringify(contextPoint(edge.n)?.label??('#'+(edge.n+1))); | |
| box.textContent=`Layer ${edge.layer} / ${label} / ${(100*edge.score).toFixed(2)}% attention`; | |
| } | |
| box.style.left=`${Math.max(8,Math.min(window.innerWidth-280,event.clientX+12))}px`; | |
| box.style.top=`${Math.max(8,Math.min(window.innerHeight-65,event.clientY+12))}px`; | |
| } | |
| function details(){ | |
| const box=root?.querySelector('.connection-detail');if(!box)return; | |
| const point=history.find(p=>p.n===selected)||externalSelected||(connections==='attention'?sourcePoint():null); | |
| if(positionMode==='representations'&&connections==='attention'&&Math.round(representationStage)===0){ | |
| delete box.dataset.attentionSignature;delete box.dataset.connectionSignature; | |
| box.textContent='Input stage: no attention layer has been applied yet. Advance the slider to inspect layers. Attention appears if it was captured; only targets with recorded representations can be drawn.'; | |
| return; | |
| } | |
| if(connections!=='attention'){ | |
| const signature=JSON.stringify([connections,point?.n,point?.label,point?.links,positionMode]); | |
| if(box.dataset.connectionSignature===signature)return; | |
| delete box.dataset.attentionSignature;box.dataset.connectionSignature=signature; | |
| box.replaceChildren(); | |
| function add(parent,tag,className,text){ | |
| const node=document.createElement(tag);node.className=className; | |
| if(text!=null)node.textContent=text;parent.appendChild(node);return node; | |
| } | |
| const titles={order:'Generation order',similarity:'Embedding similarity',none:'Tokens only'}; | |
| add(box,'h3','attention-title',titles[connections]||'Connections'); | |
| if(connections==='order'){ | |
| add(box,'p','connection-explanation','Teal lines connect consecutive tokens in the order they were generated. Follow them to trace the stream through the 3D space.'); | |
| add(box,'p','connection-note','These lines show sequence, not attention, similarity, or how strongly one token influenced another.'); | |
| if(point){ | |
| add(box,'p','connection-selected',`Selected: #${point.n+1} ${JSON.stringify(point.label)} / token ID ${point.id}`); | |
| const previous=contextPoint(point.n-1); | |
| add(box,'p','connection-note',point.n===0?'This is the first generated token.':`Previous token: #${point.n}${previous?' '+JSON.stringify(previous.label):''}. A line appears when both tokens are visible.`); | |
| }else add(box,'p','connection-note','Click a token to see its place in the sequence. Faded tokens can leave gaps; use History or pause to inspect earlier tokens.'); | |
| }else if(connections==='similarity'){ | |
| add(box,'p','connection-explanation','Amber lines connect each token to up to three earlier tokens with the most similar learned input embeddings.'); | |
| add(box,'p','connection-note',positionMode==='representations'?'These links still compare input embeddings, even though node positions now show layer representations.':'The matches are calculated from the original embedding vectors, not the distances you see in 3D.'); | |
| if(point){ | |
| add(box,'p','connection-selected',`Selected: #${point.n+1} ${JSON.stringify(point.label)} / token ID ${point.id}`); | |
| const matches=(point.links||[]).map(link=>({...link,other:contextPoint(link.n)})); | |
| if(matches.length){ | |
| add(box,'p','connection-note','Closest saved earlier matches:'); | |
| const list=add(box,'div','connection-matches'); | |
| for(const link of matches){ | |
| const item=add(list,'div','connection-match'); | |
| add(item,'span','connection-token',`${link.other?JSON.stringify(link.other.label):'Token'} (#${link.n+1})`); | |
| add(item,'span','connection-score',`cosine ${link.score.toFixed(3)}`); | |
| } | |
| }else add(box,'p','connection-note','No saved similarity matches for this token in the retained history.'); | |
| }else add(box,'p','connection-note','Click a token to see its closest saved matches and their similarity scores.'); | |
| const help=add(box,'details','attention-help'); | |
| add(help,'summary','','How to read similarity'); | |
| add(help,'p','','Cosine similarity compares the direction of embedding vectors. Higher scores mean more aligned vectors; only positive matches are drawn. The score is not a probability or an attention weight. We compare distinct token IDs within the preceding 512 tokens. Compressing embeddings to three dimensions can distort apparent distances.'); | |
| }else{ | |
| add(box,'p','connection-explanation',positionMode==='representations'?'No connection lines are drawn. Nodes show their captured hidden states at the chosen layer, using one shared projection.':'No connection lines are drawn. Token positions still come from the fixed 3D projection of their input embeddings.'); | |
| add(box,'p','connection-note','Use this view to explore the token cloud without lines. Changing connection modes only changes the visualisation; it does not change how text is generated.'); | |
| if(point)add(box,'p','connection-selected',`Selected: #${point.n+1} ${JSON.stringify(point.label)} / token ID ${point.id}`); | |
| } | |
| return; | |
| } | |
| delete box.dataset.connectionSignature; | |
| let content='Attention weights show which context tokens each layer attended to while predicting the following token. Generate text, then pause and click a token to compare saved layers.'; | |
| if(point){ | |
| const neighbours=(point.links||[]).map(link=>{ | |
| const other=history.find(p=>p.n===link.n); | |
| return other?`${JSON.stringify(other.label)} (#${other.n+1}, cosine ${link.score.toFixed(3)})`:null; | |
| }).filter(Boolean); | |
| content=`Token #${point.n+1} ${JSON.stringify(point.label)} | ID ${point.id}. Earlier neighbours: ${neighbours.join('; ')||'none with positive cosine similarity in the retained window'}.`; | |
| } | |
| if(point && connections==='attention'){ | |
| const available=attentionRows(point,true),rows=attentionRows(point); | |
| if(available.length){ | |
| const signature=JSON.stringify([point.n,point.label,available,layerMode,layerLimit,minimumWeight,[...hiddenLayers],positionMode,Math.round(representationStage)]); | |
| if(box.dataset.attentionSignature===signature)return; | |
| const explanationOpen=Boolean(box.querySelector('details')?.open),scroll=box.scrollTop||0; | |
| box.dataset.attentionSignature=signature; | |
| function add(parent,tag,className,text){ | |
| const node=document.createElement(tag);node.className=className; | |
| if(text!=null)node.textContent=text;parent.appendChild(node);return node; | |
| } | |
| let headingHost=box.querySelector('.attention-header'); | |
| if(!headingHost){ | |
| box.replaceChildren(); | |
| headingHost=add(box,'div','attention-header'); | |
| add(box,'div','layer-ui'); | |
| add(box,'div','attention-body'); | |
| } | |
| const ui=box.querySelector('.layer-ui'),body=box.querySelector('.attention-body'); | |
| headingHost.replaceChildren();body.replaceChildren(); | |
| add(headingHost,'h3','attention-title',`Attention from #${point.n+1} ${JSON.stringify(point.label)}`); | |
| add(headingHost,'p','attention-intro','What this token attended to while predicting the next token.'); | |
| ui.hidden=!layerRows.has(point.n)||positionMode==='representations'; | |
| const controlKey=JSON.stringify([layerMode,layerLimit,available.map(row=>row.layer),[...hiddenLayers]]); | |
| if(!ui.hidden&&ui.dataset.controlKey!==controlKey){ | |
| const settingsOpen=ui.querySelector('.layer-settings')?.open??(window.innerWidth>640); | |
| ui.replaceChildren();ui.dataset.controlKey=controlKey; | |
| const settings=add(ui,'details','layer-settings');settings.open=settingsOpen; | |
| add(settings,'summary','','Layers & filtering'); | |
| const controls=add(settings,'div','layer-controls'); | |
| function select(label,choices,value,change){ | |
| const field=add(controls,'label','',label),input=add(field,'select',''); | |
| for(const [key,text] of choices){const option=add(input,'option','',text);option.value=key;} | |
| input.value=value;input.addEventListener('change',event=>{change(event.target.value);legendFocus=null;details();}); | |
| } | |
| select('Layers',[['three','Early / middle / final'],['all','All layers'],['selected','Selected layer / head']],layerMode,value=>{layerMode=value;hiddenLayers.clear();}); | |
| select('Links per layer',[1,2,3,5,8].map(n=>[String(n),String(n)]),String(layerLimit),value=>layerLimit=Number(value)); | |
| const filter=add(controls,'label','layer-filter','Minimum weight '),readout=add(filter,'span','',`${Math.round(minimumWeight*100)}%`); | |
| const slider=add(filter,'input','');slider.type='range';slider.min=0;slider.max=30;slider.step=1;slider.value=minimumWeight*100; | |
| slider.setAttribute('aria-label','Minimum attention weight'); | |
| slider.addEventListener('input',event=>{minimumWeight=Number(event.target.value)/100;readout.textContent=`${Math.round(minimumWeight*100)}%`;}); | |
| slider.addEventListener('change',()=>details()); | |
| const caption=add(ui,'p','layer-caption'); | |
| add(caption,'span','layer-caption-desktop','Colour = layer. Thickness = weight. Click a colour to hide it; Shift-click to isolate it. Hover a colour to highlight it.'); | |
| add(caption,'span','layer-caption-mobile','Tap a layer colour to hide/show it.'); | |
| const legend=add(ui,'div','layer-legend'); | |
| for(const row of available){ | |
| const button=add(legend,'button','layer-chip',`L${row.layer}`);button.type='button'; | |
| button.style.color=`rgb(${layerRGB(row.layer)})`;button.style.borderColor=`rgb(${layerRGB(row.layer)})`; | |
| button.setAttribute('aria-pressed',String(!hiddenLayers.has(row.layer)));button.title=`Layer ${row.layer}: click to hide/show; Shift-click to isolate`; | |
| button.addEventListener('mouseenter',()=>legendFocus=row.layer);button.addEventListener('mouseleave',()=>legendFocus=null); | |
| button.addEventListener('click',event=>{ | |
| if(event.shiftKey){hiddenLayers=new Set(available.filter(other=>other.layer!==row.layer).map(other=>other.layer));} | |
| else if(hiddenLayers.has(row.layer))hiddenLayers.delete(row.layer);else hiddenLayers.add(row.layer); | |
| legendFocus=null;details(); | |
| }); | |
| } | |
| if(hiddenLayers.size){const restore=add(legend,'button','layer-restore','Restore layers');restore.type='button';restore.addEventListener('click',()=>{hiddenLayers.clear();details();});} | |
| } | |
| if(!rows.length)add(body,'p','attention-meta','All layers are hidden. Restore a layer using the legend.'); | |
| for(const row of rows){ | |
| const group=add(body,'section','attention-layer'); | |
| const heading=add(group,'p','attention-meta',`layer ${row.layer} / ${row.head===-1?'average across attention heads':'head '+row.head}`); | |
| heading.style.borderLeftColor=`rgb(${layerRGB(row.layer)})`; | |
| const list=add(group,'div','attention-list'); | |
| for(const link of row.links){ | |
| const other=contextPoint(link.n); | |
| const label=link.n===-1?'Start boundary':JSON.stringify(other?.label??link.label??('#'+(link.n+1))); | |
| const item=add(list,'div','attention-item'); | |
| const token=add(item,'span','attention-token',label);token.title=link.n===-1?'The special token used to start this stream.':`Token #${link.n+1}`; | |
| const track=add(item,'span','attention-bar');track.setAttribute('aria-hidden','true'); | |
| const fill=add(track,'span','attention-bar-fill');fill.style.width=`${Math.max(0,Math.min(100,100*link.score))}%`;fill.style.background=`rgb(${layerRGB(row.layer)})`; | |
| add(item,'span','attention-percent',`${(100*link.score).toFixed(1)}%`); | |
| } | |
| if(!row.links.length)add(group,'p','attention-meta','No saved links meet this minimum weight.'); | |
| add(group,'p','attention-coverage',`${row.links.length} strongest connections shown: ${(100*row.shown_mass).toFixed(1)}% of total attention. Others: ${(100*Math.max(0,1-row.shown_mass)).toFixed(1)}%.`); | |
| } | |
| let explanation=box.querySelector('.attention-help'); | |
| if(!explanation){ | |
| explanation=add(box,'details','attention-help');explanation.open=explanationOpen; | |
| add(explanation,'summary','','How to read this'); | |
| add(explanation,'p','','Longer bars mean more attention to that context token, not a higher chance of generating it. Coloured curves compare layers using the same token positions. Multi-layer views average across heads. Start boundary begins the stream. Only the eight strongest links per layer are saved; filters can show fewer. Layer and head indices start at 0. Attention is not a complete explanation of the decision.'); | |
| } | |
| box.scrollTop=scroll; | |
| return; | |
| }else content=externalSelected?'This token is outside the retained 512-token attention history. Its embedding is shown; no saved attention row is available.':'No attention captured for this token yet. Enable Capture attention and generate more tokens.'; | |
| } | |
| delete box.dataset.attentionSignature; | |
| if(box.textContent!==content)box.textContent=content; | |
| } | |
| function mount(){ | |
| const next=document.querySelector('#token-universe'),nextCanvas=next?.querySelector('canvas'); | |
| if(!nextCanvas||(next===root&&nextCanvas===canvas))return; | |
| root=next;canvas=nextCanvas;ctx=canvas.getContext('2d'); | |
| if(resize)resize.disconnect(); | |
| resize=new ResizeObserver(()=>{ | |
| const r=canvas.getBoundingClientRect();width=r.width;height=r.height; | |
| const narrow=window.innerWidth<=640; | |
| if(narrow!==lastNarrow){const settings=root.querySelector('.layer-settings');if(settings)settings.open=!narrow;lastNarrow=narrow;} | |
| const dpr=Math.min(window.devicePixelRatio||1,2); | |
| canvas.width=Math.round(width*dpr);canvas.height=Math.round(height*dpr);ctx.setTransform(dpr,0,0,dpr,0,0); | |
| });resize.observe(canvas); | |
| canvas.addEventListener('pointerdown',e=>{ | |
| dragging=true;panning=e.shiftKey||e.button===2;moved=false;lastX=e.clientX;lastY=e.clientY;canvas.setPointerCapture(e.pointerId); | |
| }); | |
| canvas.addEventListener('pointermove',e=>{ | |
| if(!dragging){ | |
| const rect=canvas.getBoundingClientRect(),x=e.clientX-rect.left,y=e.clientY-rect.top; | |
| hoverEdge=null;let nearest=7; | |
| for(const edge of edgeHits)for(let i=1;i<edge.path.length;i++){ | |
| const a=edge.path[i-1],b=edge.path[i],dx=b.x-a.x,dy=b.y-a.y; | |
| const t=Math.max(0,Math.min(1,((x-a.x)*dx+(y-a.y)*dy)/(dx*dx+dy*dy||1))); | |
| const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy); | |
| if(distance<nearest){nearest=distance;hoverEdge=edge;} | |
| } | |
| hoverDimensionAxis=null; | |
| if(!hoverEdge&&dimensionAxesEnabled){ | |
| let nearestAxis=3; | |
| for(const axis of dimensionAxisHits){ | |
| const a=axis.path[0],b=axis.path[1],dx=b.x-a.x,dy=b.y-a.y; | |
| const t=Math.max(0,Math.min(1,((x-a.x)*dx+(y-a.y)*dy)/(dx*dx+dy*dy||1))); | |
| const distance=Math.hypot(x-a.x-t*dx,y-a.y-t*dy); | |
| if(distance<nearestAxis){nearestAxis=distance;hoverDimensionAxis=axis;} | |
| } | |
| } | |
| edgeTooltip(hoverEdge||hoverDimensionAxis,e);return; | |
| }const dx=e.clientX-lastX,dy=e.clientY-lastY; | |
| if(Math.abs(dx)+Math.abs(dy)>2)moved=true; | |
| if(panning){panX+=dx;panY+=dy;}else{yaw+=dx*.006;pitch=Math.max(-1.5,Math.min(1.5,pitch+dy*.006));} | |
| lastX=e.clientX;lastY=e.clientY; | |
| }); | |
| canvas.addEventListener('pointerup',()=>dragging=false); | |
| canvas.addEventListener('pointerleave',event=>{hoverEdge=null;hoverDimensionAxis=null;edgeTooltip(null,event);}); | |
| canvas.addEventListener('pointercancel',()=>dragging=false); | |
| canvas.addEventListener('contextmenu',e=>e.preventDefault()); | |
| canvas.addEventListener('click',e=>{if(moved)return;const p=pick(e);selected=p?p.n:null;details();}); | |
| canvas.addEventListener('dblclick',e=>{ | |
| const p=pick(e);if(p){target=[...p.xyz];selected=p.n;panX=panY=0;zoom=Math.max(zoom,3);details();}else resetCamera(); | |
| }); | |
| canvas.addEventListener('wheel',e=>{e.preventDefault();zoom=Math.max(.15,Math.min(40,zoom*Math.exp(-e.deltaY*.0015)));},{passive:false}); | |
| const modeInput=root.querySelector('[data-space-mode]'); | |
| if(modeInput){modeInput.value=positionMode==='representations'?'representations':mode;modeInput.addEventListener('change',e=>setPositionView(e.target.value));} | |
| const linksInput=root.querySelector('[data-space-links]'); | |
| if(linksInput){linksInput.value=connections;linksInput.addEventListener('change',e=>{connections=e.target.value;details();});} | |
| root.querySelector('[data-representation-layer]')?.addEventListener('input',event=>{ | |
| representationPlaying=false;representationStage=Number(event.target.value);representationControls();details(); | |
| }); | |
| root.querySelector('[data-representation-play]')?.addEventListener('click',()=>{ | |
| if(!paused||!representationMeta?.ready)return; | |
| if(representationStage>=representationMeta.stages-1)representationStage=0; | |
| representationPlaying=!representationPlaying;if(!representationPlaying)representationStage=Math.round(representationStage);representationControls();details(); | |
| }); | |
| const trailInput=root.querySelector('[data-representation-trail]'); | |
| if(trailInput){trailInput.checked=representationTrail;trailInput.addEventListener('change',event=>representationTrail=event.target.checked);} | |
| root.querySelector('[data-dimension-axes]')?.addEventListener('change',event=>{ | |
| dimensionAxesEnabled=event.target.checked;hoverDimensionAxis=null;edgeTooltip(null,event);dimensionAxisControls(); | |
| }); | |
| root.querySelector('[data-dimension-opacity]')?.addEventListener('input',event=>dimensionAxisOpacity=Number(event.target.value)); | |
| root.querySelector('[data-dimension-origin]')?.addEventListener('change',event=>{dimensionAxisOrigin=event.target.value;hoverDimensionAxis=null;dimensionAxisControls();}); | |
| root.querySelector('[data-dimension-options]')?.addEventListener('click',()=>{ | |
| const options=root.querySelector('.dimension-axes-options'),button=root.querySelector('[data-dimension-options]'); | |
| options.hidden=!options.hidden;button.setAttribute('aria-expanded',String(!options.hidden));dimensionAxisControls(); | |
| }); | |
| root.querySelector('[data-space-reset]')?.addEventListener('click',resetCamera); | |
| root.querySelector('[data-space-back]')?.addEventListener('click',()=>stepToken(-1)); | |
| root.querySelector('[data-space-forward]')?.addEventListener('click',()=>stepToken(1)); | |
| details(); | |
| } | |
| function receive(){ | |
| mount();const node=document.querySelector('[data-flow-frame]');if(!node)return; | |
| const raw=node.getAttribute('data-flow-frame');if(raw===payload)return; | |
| payload=raw;let data;try{data=JSON.parse(raw);}catch{return;} | |
| running=Boolean(data.running);awaitingGPU=Boolean(data.continue_automatically)&&!data.running&&!data.paused&&!data.ended;ended=Boolean(data.ended);togglePending=false; | |
| if(data.continue_automatically&&!data.running&&!data.paused&&!data.ended){ | |
| const expectedStream=data.stream,expectedRevision=data.revision; | |
| setTimeout(()=>{ | |
| if(stream===expectedStream && JSON.parse(payload).revision===expectedRevision && !running && !paused){ | |
| const host=document.querySelector('#generation-auto'); | |
| const button=host?.tagName?.toLowerCase()==='button'?host:host?.querySelector('button')||host; | |
| button?.click(); | |
| } | |
| },700); | |
| } | |
| if(data.stream!==stream){positionMode='embeddings';const view=root?.querySelector('[data-space-mode]');if(view)view.value=mode;representationPoints.clear();representationMeta=null;representationDimensionAxes=null;representationPlaying=false;representationStage=0;lastRepresentationLayer=-1;layerRows.clear();layerTargets.clear();hiddenLayers.clear();layerCount=0;hoverEdge=null;stream=data.stream;seen=-1;history=[];selected=null;paused=false;textView=null;externalSelected=null;details();} | |
| if(data.dimension_axes)embeddingDimensionAxes=data.dimension_axes; | |
| const now=Date.now(),existing=new Set(history.map(p=>p.n)); | |
| for(const p of data.points||[]){ | |
| if(existing.has(p.n)){const old=history.find(q=>q.n===p.n);if(p.attention){if(!old.attention)old.attentionBorn=now;old.attention=p.attention;}continue;} | |
| if(!Array.isArray(p.xyz)||!p.xyz.every(Number.isFinite))continue; | |
| // Recovered old history must not reappear as freshly generated live points. | |
| history.push({...p,born:p.n<=seen?now-lifetime:now,attentionBorn:p.attention?now:0});seen=Math.max(seen,p.n); | |
| } | |
| if(data.text_view)textView=data.text_view; | |
| if(data.attention_layers){ | |
| layerCount=data.attention_layers.count; | |
| for(const row of data.attention_layers.rows)layerRows.set(row.query,row); | |
| for(const target of data.attention_layers.targets)layerTargets.set(target.n,target); | |
| const first=Math.max(0,seen-512); | |
| for(const query of layerRows.keys())if(query<first)layerRows.delete(query); | |
| for(const n of layerTargets.keys())if(n>=0&&n<seen-4096)layerTargets.delete(n); | |
| } | |
| if(data.representations){ | |
| representationMeta=data.representations; | |
| if(data.representations.dimension_axes)representationDimensionAxes=data.representations.dimension_axes; | |
| if(!data.attention_layers&&data.representations.stages)layerCount=data.representations.stages-1; | |
| for(const point of data.representations.points)representationPoints.set(point.n,point.layers); | |
| for(const n of representationPoints.keys())if(n>=0&&n<seen-128)representationPoints.delete(n); | |
| } | |
| history.sort((a,b)=>a.n-b.n);history=history.slice(-512); | |
| if(Boolean(data.paused)!==paused){ | |
| paused=Boolean(data.paused); | |
| if(paused){previousMode=mode;mode='history';selected=[...history].reverse().find(p=>p.attention)?.n??history.at(-1)?.n??null;connections='attention';} | |
| else{mode=previousMode;positionMode='embeddings';representationPlaying=false;selected=null;externalSelected=null;textView=null;} | |
| const modeInput=root.querySelector('[data-space-mode]');if(modeInput)modeInput.value=positionMode==='representations'?'representations':mode; | |
| const linksInput=root.querySelector('[data-space-links]');if(linksInput)linksInput.value=connections; | |
| } | |
| if(!paused&&mode==='live'&&selected!=null&&!history.some(p=>p.n===selected&&now-p.born<lifetime))selected=null; | |
| representationControls();details();inspectText(); | |
| } | |
| function project(v){ | |
| const[x,y,z]=v.map((a,i)=>a-target[i]),cy=Math.cos(yaw),sy=Math.sin(yaw),rx=x*cy+z*sy,rz=-x*sy+z*cy; | |
| const cp=Math.cos(pitch),sp=Math.sin(pitch),ry=y*cp-rz*sp,depth=y*sp+rz*cp,distance=7/zoom; | |
| const denominator=distance+depth,scale=Math.min(width,height)*.91/Math.max(.08,denominator); | |
| return{x:width/2+panX+rx*scale,y:height*(positionMode==='representations'&&width<=640?.4:.5)+panY+ry*scale,z:depth,scale:Math.min(3,7/Math.max(.08,denominator)),visible:denominator>.08}; | |
| } | |
| function tick(){ | |
| if(disposed)return; | |
| mountGenerationControl();dimensionAxisControls(); | |
| // Remount if Gradio replaced the canvas. Aging uses wall time, never server steps. | |
| mount();const now=Date.now(),dt=Math.min(now-lastTime,100);lastTime=now; | |
| if(!ctx||!width||!height)return; | |
| if(positionMode==='representations'){ | |
| if(representationPlaying&&paused&&representationMeta?.ready){ | |
| representationStage=Math.min(representationMeta.stages-1,representationStage+dt*.002); | |
| if(representationStage>=representationMeta.stages-1)representationPlaying=false; | |
| } | |
| representationControls(); | |
| const stage=Math.round(representationStage); | |
| if(stage!==lastRepresentationLayer){lastRepresentationLayer=stage;details();} | |
| } | |
| if(!paused&&!dragging&&mode==='live'&&!matchMedia('(prefers-reduced-motion: reduce)').matches)yaw+=dt*.000025; | |
| ctx.clearRect(0,0,width,height); | |
| const wash=ctx.createRadialGradient(width*.48,height*.48,0,width*.5,height*.5,width*.6); | |
| wash.addColorStop(0,'#142b34');wash.addColorStop(1,'#080f18');ctx.fillStyle=wash;ctx.fillRect(0,0,width,height); | |
| ctx.lineWidth=1;ctx.strokeStyle='#6b9caa19'; | |
| for(let i=-4;i<=4;i++)for(const pair of [[[-4,2.8,i],[4,2.8,i]],[[i,2.8,-4],[i,2.8,4]]]){ | |
| const a=project(pair[0]),b=project(pair[1]);if(!a.visible||!b.visible)continue; | |
| ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke(); | |
| } | |
| dimensionAxisHits=[]; | |
| const axes=dimensionAxisGeometry(); | |
| if(dimensionAxesEnabled&&axes?.vectors){ | |
| const origin=dimensionAxisOrigin==='raw'?axes.raw_origin:[0,0,0]; | |
| ctx.strokeStyle=`rgba(255,255,255,${dimensionAxisOpacity})`;ctx.lineWidth=.6;ctx.beginPath(); | |
| for(let dimension=0;dimension<axes.vectors.length;dimension++){ | |
| const vector=axes.vectors[dimension]; | |
| let a=origin.map((value,i)=>value-vector[i]),b=origin.map((value,i)=>value+vector[i]); | |
| let pa=project(a),pb=project(b); | |
| const da=7/zoom+pa.z,db=7/zoom+pb.z; | |
| if(da<=.09&&db<=.09)continue; | |
| if(da<=.09){const t=(.09-da)/(db-da);a=a.map((value,i)=>value+(b[i]-value)*t);pa=project(a);} | |
| else if(db<=.09){const t=(.09-db)/(da-db);b=b.map((value,i)=>value+(a[i]-value)*t);pb=project(b);} | |
| if(![pa.x,pa.y,pb.x,pb.y].every(Number.isFinite)||Math.hypot(pa.x-pb.x,pa.y-pb.y)<.2)continue; | |
| ctx.moveTo(pa.x,pa.y);ctx.lineTo(pb.x,pb.y); | |
| dimensionAxisHits.push({type:'dimension-axis',dimension,path:[pa,pb]}); | |
| } | |
| ctx.stroke(); | |
| const highlighted=dimensionAxisHits.find(axis=>axis.dimension===hoverDimensionAxis?.dimension); | |
| if(highlighted){const[a,b]=highlighted.path;ctx.strokeStyle='rgba(255,255,255,.5)';ctx.lineWidth=1.1;ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke();} | |
| ctx.lineWidth=1; | |
| } | |
| const cutoff=paused&&selected!=null?selected:Infinity; | |
| const source=connections==='attention'?sourcePoint():null; | |
| let active=history.filter(p=>p.n<=cutoff&&(mode==='history'||paused||p.n===source?.n||now-p.born<lifetime)); | |
| if(paused&&externalSelected)active.push({...externalSelected,born:now}); | |
| const activeIndices=new Set(active.map(p=>p.n)); | |
| const visibleRows=attentionRows(source); | |
| if(source){ | |
| for(const link of visibleRows.flatMap(row=>row.links)){ | |
| if(activeIndices.has(link.n))continue; | |
| const old=history.find(p=>p.n===link.n); | |
| if(old||Array.isArray(link.xyz)){active.push({...old,n:link.n,id:link.id??old?.id,label:link.label??old?.label??'[context]',xyz:link.xyz??old.xyz,born:now,ghost:true});activeIndices.add(link.n);} | |
| } | |
| } | |
| if(positionMode==='representations')active=active.map(p=>({...p,xyz:displayedPosition(p)})).filter(p=>p.xyz); | |
| const rendered=active.map(p=>({...p,...project(p.xyz),alpha:p.ghost ? .55 : (mode==='history'||paused) ? .7 : Math.pow(Math.max(0,1-(now-Math.max(p.born,p.n===source?.n?(p.attentionBorn??0):0))/lifetime),1.5)})).filter(p=>p.visible); | |
| const byIndex=new Map(rendered.map(p=>[p.n,p])); | |
| function line(a,b,score){ | |
| if(!a||!b)return;const highlight=selected===a.n||selected===b.n; | |
| ctx.strokeStyle=score==null?`rgba(109,207,196,${Math.min(a.alpha,b.alpha)*(highlight?.9:.25)})`:`rgba(244,191,103,${Math.min(a.alpha,b.alpha)*(highlight?1:.12+.4*Math.max(0,score))})`; | |
| ctx.lineWidth=highlight?2:1;ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke(); | |
| } | |
| if(connections==='order')for(const p of rendered)line(byIndex.get(p.n-1),p,null); | |
| if(connections==='similarity')for(const p of rendered)for(const link of p.links||[])line(p,byIndex.get(link.n),link.score); | |
| edgeHits=[]; | |
| if(connections==='attention'){ | |
| const start=source?byIndex.get(source.n):null; | |
| if(start)for(const row of visibleRows)for(const link of row.links){ | |
| const end=byIndex.get(link.n);if(!end)continue; | |
| const focused=legendFocus==null||legendFocus===row.layer; | |
| const offset=layerCount>1?(row.layer/(layerCount-1)-.5)*70:0; | |
| const dx=end.x-start.x,dy=end.y-start.y,length=Math.hypot(dx,dy)||1; | |
| const control={x:(start.x+end.x)/2-dy/length*offset,y:(start.y+end.y)/2+dx/length*offset}; | |
| ctx.strokeStyle=`rgba(${layerRGB(row.layer)},${Math.min(start.alpha,end.alpha)*(.25+.75*link.score)*(focused?1:.08)})`; | |
| ctx.lineWidth=1+8*link.score;ctx.beginPath();ctx.moveTo(start.x,start.y); | |
| const path=[]; | |
| if(start.n===end.n){ | |
| const radius=14+(layerCount>1?row.layer/(layerCount-1)*24:0); | |
| ctx.arc(start.x,start.y,radius,0,Math.PI*2); | |
| for(let i=0;i<=24;i++){const a=i/24*Math.PI*2;path.push({x:start.x+Math.cos(a)*radius,y:start.y+Math.sin(a)*radius});} | |
| }else{ | |
| ctx.quadraticCurveTo(control.x,control.y,end.x,end.y); | |
| for(let i=0;i<=12;i++){const t=i/12,u=1-t;path.push({x:u*u*start.x+2*u*t*control.x+t*t*end.x,y:u*u*start.y+2*u*t*control.y+t*t*end.y});} | |
| } | |
| ctx.stroke();edgeHits.push({layer:row.layer,n:link.n,score:link.score,path}); | |
| if(start.n!==end.n){ | |
| const angle=Math.atan2(end.y-control.y,end.x-control.x),size=6+5*link.score; | |
| ctx.beginPath();ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle-.4),end.y-size*Math.sin(angle-.4)); | |
| ctx.moveTo(end.x,end.y);ctx.lineTo(end.x-size*Math.cos(angle+.4),end.y-size*Math.sin(angle+.4));ctx.stroke(); | |
| } | |
| } | |
| } | |
| if(positionMode==='representations'&&representationTrail&&selected!=null){ | |
| const trajectory=representationPoints.get(selected); | |
| if(trajectory){ | |
| ctx.setLineDash([4,4]);ctx.lineWidth=1.8; | |
| for(let stage=1;stage<trajectory.length;stage++){ | |
| const a=project(trajectory[stage-1]),b=project(trajectory[stage]);if(!a.visible||!b.visible)continue; | |
| ctx.strokeStyle=`rgba(${layerRGB(Math.max(0,stage-1))},.85)`; | |
| ctx.beginPath();ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);ctx.stroke(); | |
| ctx.fillStyle=`rgb(${layerRGB(Math.max(0,stage-1))})`;ctx.beginPath();ctx.arc(b.x,b.y,2,0,Math.PI*2);ctx.fill(); | |
| } | |
| ctx.setLineDash([]); | |
| } | |
| } | |
| rendered.sort((a,b)=>b.z-a.z);hits=rendered; | |
| for(const p of rendered){ | |
| const highlight=p.n===selected,newest=p.n===seen;ctx.globalAlpha=highlight?1:p.alpha; | |
| ctx.fillStyle=p.ghost?'#bba2eb':highlight?'#f4bf67':newest?'#faf0bd':'#83dfd2';ctx.shadowColor=ctx.fillStyle;ctx.shadowBlur=newest||highlight?18:8; | |
| ctx.beginPath();ctx.arc(p.x,p.y,Math.max(2,Math.min(12,(newest||highlight?5:3)*p.scale)),0,Math.PI*2);ctx.fill();ctx.shadowBlur=0; | |
| ctx.font=`${newest||highlight?600:400} ${Math.max(11,Math.min(19,14*p.scale))}px ui-monospace,monospace`; | |
| let label=p.label.replace(/\n/g,'↵').replace(/\t/g,'⇥').replace(/ /g,'·'); | |
| if(!label)label=`[${p.id}]`;if(label.length>32)label=label.slice(0,31)+'…'; | |
| if(p.ghost||mode==='live'||highlight||newest||rendered.length<100)ctx.fillText(label,p.x+9,p.y-8-(p.n%3)*5); | |
| } | |
| ctx.globalAlpha=1;ctx.lineWidth=1; | |
| const counter=root.querySelector('.space-count'),empty=root.querySelector('.space-empty'); | |
| const count=`${active.length} visible · ${seen+1} generated · zoom ${zoom.toFixed(1)}×`; | |
| if(counter&&counter.textContent!==count)counter.textContent=count; | |
| if(empty){const display=seen<0?'flex':'none';if(empty.style.display!==display)empty.style.display=display;} | |
| const back=root.querySelector('[data-space-back]'),forward=root.querySelector('[data-space-forward]'),step=root.querySelector('[data-space-step]'); | |
| const items=(textView?.points||history).filter(p=>positionMode!=='representations'||representationPoints.has(p.n)); | |
| if(back)back.disabled=!paused||selected==null||selected<=items[0]?.n; | |
| if(forward)forward.disabled=!paused||selected==null||selected>=items.at(-1)?.n; | |
| const stepText=paused?`Paused ? inspecting token #${selected==null?'?':selected+1}`:'Live'; | |
| if(step&&step.textContent!==stepText)step.textContent=stepText; | |
| inspectText();syncTextSelection(); | |
| const text=document.querySelector('#page textarea'); | |
| if(text&&text.value!==lastText){ | |
| const following=lastText===''||text.scrollHeight-text.scrollTop-text.clientHeight<80; | |
| if(following&&document.activeElement!==text)text.scrollTop=text.scrollHeight; | |
| lastText=text.value; | |
| } | |
| } | |
| observer=new MutationObserver(receive); | |
| observer.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['data-flow-frame']}); | |
| receive();tick();timer=setInterval(tick,33); | |
| window.__letItFlowSpace=()=>{disposed=true;observer.disconnect();if(resize)resize.disconnect();clearInterval(timer);toggleButton?.removeEventListener?.('click',generationClick);}; | |
| } | |