File size: 47,615 Bytes
673a352
 
 
 
 
 
 
17374eb
3e4c0fe
 
4d443ef
9d3e0c7
 
ae55e6a
9d20fe4
 
a02fde5
3ce4754
b07a730
 
3ce4754
b07a730
 
 
 
 
 
 
 
 
 
 
 
 
9d20fe4
b07a730
 
 
9d3e0c7
 
 
 
 
 
 
 
 
 
9d20fe4
 
 
 
 
 
 
b0d4a08
 
 
 
 
 
9d20fe4
9d3e0c7
9d20fe4
 
 
 
 
 
 
 
 
b0d4a08
9d20fe4
 
 
 
 
 
 
 
 
 
 
 
 
b0d4a08
9d20fe4
 
 
 
 
 
 
 
ae55e6a
a02fde5
ae55e6a
 
 
 
a02fde5
 
 
 
 
ae55e6a
9d20fe4
 
a02fde5
 
 
9d20fe4
a02fde5
 
9d20fe4
a02fde5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae55e6a
673a352
 
 
 
 
3e4c0fe
 
 
 
 
 
 
 
 
 
 
9d20fe4
3e4c0fe
9d20fe4
3e4c0fe
 
9d20fe4
 
3e4c0fe
 
 
 
 
 
 
9d3e0c7
 
 
 
3e4c0fe
 
9d3e0c7
3e4c0fe
 
 
673a352
9d20fe4
a02fde5
9d20fe4
 
b0d4a08
9d20fe4
 
571ce7d
9d20fe4
571ce7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d20fe4
571ce7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d20fe4
571ce7d
 
 
 
 
 
 
673a352
 
 
 
 
 
 
 
3e4c0fe
 
9d20fe4
0dae3e0
3e4c0fe
 
0dae3e0
 
 
 
3e4c0fe
 
 
 
 
 
 
 
 
 
 
9d20fe4
3e4c0fe
 
4d443ef
3e4c0fe
4d443ef
 
 
3e4c0fe
 
 
 
 
 
 
 
 
 
 
 
4d443ef
 
 
3e4c0fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dae3e0
3e4c0fe
 
 
0dae3e0
3e4c0fe
 
0dae3e0
 
a02fde5
673a352
0dae3e0
673a352
 
 
 
 
 
 
 
 
4d443ef
 
673a352
 
 
 
 
 
 
3e4c0fe
 
 
 
 
 
 
 
 
9d3e0c7
 
 
 
 
 
 
 
 
 
 
3e4c0fe
673a352
 
 
 
 
9d3e0c7
673a352
 
 
 
 
 
 
 
9d20fe4
673a352
 
9d20fe4
 
 
 
 
 
b0d4a08
9d20fe4
 
 
9d3e0c7
 
 
 
 
 
 
 
 
673a352
ae55e6a
 
673a352
 
 
 
 
 
3ce4754
815acd7
 
 
833b4fb
3ce4754
833b4fb
815acd7
 
 
 
9d3e0c7
 
673a352
 
ae55e6a
673a352
 
ae55e6a
 
a02fde5
3e4c0fe
 
 
 
 
 
 
 
9d20fe4
 
9d3e0c7
b0d4a08
9d20fe4
 
 
ae55e6a
 
 
 
9d20fe4
 
ae55e6a
673a352
ae55e6a
9d20fe4
673a352
 
 
 
 
b0d4a08
673a352
 
 
9d3e0c7
673a352
 
 
9d20fe4
 
 
 
 
 
 
 
 
ae55e6a
673a352
 
 
 
 
 
 
 
9d3e0c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae55e6a
 
9d20fe4
a02fde5
ae55e6a
3e4c0fe
 
 
ae55e6a
 
 
 
 
9d20fe4
ae55e6a
673a352
 
 
a217268
673a352
 
 
 
3e4c0fe
673a352
3e4c0fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673a352
 
 
9d20fe4
 
 
 
 
 
 
 
 
 
 
 
 
673a352
 
 
a217268
673a352
 
 
 
ae55e6a
673a352
 
 
 
 
 
ae55e6a
9d20fe4
a02fde5
 
ae55e6a
 
a02fde5
17374eb
 
 
 
 
 
673a352
 
 
 
b07a730
c339a80
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
() => {
  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);};
}