hive-swarm 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/board.js CHANGED
@@ -5,6 +5,10 @@
5
5
  const standalone=parent===window;
6
6
  const emptyPanel=standalone && location.pathname==='/swarm';
7
7
  const tabs=['overview','board','members','graph'];
8
+ const GRAPH_MODE_KEY='hive-swarm-graph-mode';
9
+ const DISMISSED_UPDATE_KEY='hive-swarm-dismissed-update';
10
+ const SEMVER_RE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
11
+ const CODEX_UPDATE_CMD='npx hive-swarm@latest update --host codex --after-close';
8
12
  const states={queued:'Queued',working:'Working',waiting:'Waiting',done:'Done',failed:'Failed',
9
13
  quota:'Quota limit',retired:'Retired',observer:'Observer'};
10
14
  const executionModes={subagent:'Subagent',attached:'Attached',session:'Session'};
@@ -18,12 +22,30 @@
18
22
  const liveSlots=new Map();
19
23
  const nowSlots=new Map();
20
24
  const memberDrafts=new Map();
25
+ const threadOpenState=new Map();
21
26
  let teamId=standalone&&!emptyPanel?location.pathname.split('/').at(-1):null;
22
27
  let team,signature='',rosterKey='',feedKey='',activeTab='board',chronology=[],latestByAuthor=new Map();
23
28
  let historyTail=0,historyRequest,refreshing=false,following=true,seen=0,feedLimit=160;
24
29
  let recentTeams=[],teamListKey='',loadingTeams=false,channelKey='',memberKey='';
25
- let stream,streamOnline=false,modelCatalog,titleEditing=false,transcript,extendingBudget=false;
30
+ let stream,streamOnline=false,modelCatalog,titleEditing=false,transcript,lightbox,extendingBudget=false;
26
31
  let requestNumber=0,refreshTimer,playTimer,playing=false,cursor=null,focusedNode=null,graphFrame=0;
32
+ let graphMode=loadGraphMode(),exportingGif=false;
33
+ let appVersion=typeof globalThis.__HIVE_SWARM_VERSION__==='string'?globalThis.__HIVE_SWARM_VERSION__.trim():'';
34
+ let updateInfo=null,updateOpen=false;
35
+
36
+ function loadGraphMode() {
37
+ try {
38
+ const saved=globalThis.sessionStorage?.getItem?.(GRAPH_MODE_KEY);
39
+ if (saved==='hive'||saved==='mentions') return saved;
40
+ } catch {}
41
+ return 'hive';
42
+ }
43
+ function saveGraphMode(mode) {
44
+ try { globalThis.sessionStorage?.setItem?.(GRAPH_MODE_KEY,mode); } catch {}
45
+ }
46
+ function currentTheme() {
47
+ return document.documentElement.dataset.theme==='light'?'light':'dark';
48
+ }
27
49
 
28
50
  function node(tag,kind='',text) {
29
51
  const element=document.createElement(tag);
@@ -50,6 +72,7 @@
50
72
  button.setAttribute('aria-label','Jump to post #'+seq);
51
73
  button.onclick=()=>{
52
74
  if (transcript) closeTranscript();
75
+ if (lightbox) closeLightbox();
53
76
  return jumpToPost(seq);
54
77
  };
55
78
  return button;
@@ -65,6 +88,38 @@
65
88
  return link;
66
89
  } catch {}
67
90
  }
91
+ function safeAssetUrl(destination) {
92
+ const raw=String(destination??'').trim();
93
+ if (!raw) return '';
94
+ if (raw.startsWith('/')&&!raw.startsWith('//')) return raw;
95
+ try {
96
+ const url=new URL(raw,location?.origin||'http://127.0.0.1');
97
+ if (['http:','https:'].includes(url.protocol)&&(!location?.origin||url.origin===location.origin)) return url.href;
98
+ } catch {}
99
+ return '';
100
+ }
101
+ function chevronIcon() {
102
+ if (typeof document.createElementNS!=='function') {
103
+ const span=node('span','accordion-chevron','▾');
104
+ span.setAttribute('aria-hidden','true');
105
+ return span;
106
+ }
107
+ const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');
108
+ svg.setAttribute('class','accordion-chevron');
109
+ svg.setAttribute('width','14');
110
+ svg.setAttribute('height','14');
111
+ svg.setAttribute('viewBox','0 0 16 16');
112
+ svg.setAttribute('aria-hidden','true');
113
+ const path=document.createElementNS('http://www.w3.org/2000/svg','path');
114
+ path.setAttribute('d','M4 6l4 4 4-4');
115
+ path.setAttribute('fill','none');
116
+ path.setAttribute('stroke','currentColor');
117
+ path.setAttribute('stroke-width','1.6');
118
+ path.setAttribute('stroke-linecap','round');
119
+ path.setAttribute('stroke-linejoin','round');
120
+ svg.append(path);
121
+ return svg;
122
+ }
68
123
  function inlineText(target,value) {
69
124
  let offset=0;
70
125
  const tokens=/\x60([^\x60\n]+)\x60|\*\*([^\n]+?)\*\*|\*([^*\n]+)\*|\[([^\]\n]+)\]\(([^\s)]+)\)|\[(done|stall)\]|(?<![a-z0-9_])(@#?[a-z][a-z0-9_-]*|#[1-9]\d*\b)/gi;
@@ -145,12 +200,108 @@
145
200
  function stamp(event) {
146
201
  return '#'+event.seq+(event.time?' · '+time.format(new Date(event.time)):'');
147
202
  }
203
+ function beeSprite(member,{muted=false}={}) {
204
+ return HiveBee.sprite(member.name,{
205
+ status:member.status??'observer',
206
+ coordinator:member.role==='coordinator',
207
+ tint:member.tint,
208
+ muted,
209
+ });
210
+ }
148
211
  function bee(member,compact=false) {
149
- const tile=node('span','bee-tile'+(compact?' compact':''));
150
- tile.dataset.status=member.status??'observer';
151
- tile.append(HiveBee.sprite(member.name,{status:tile.dataset.status,coordinator:member.role==='coordinator',tint:member.tint}));
212
+ const isCoord=member?.role==='coordinator'||member?.name==='coordinator';
213
+ const tile=node('span','bee-tile'+(compact?' compact':'')+(isCoord?' coord-tile':''));
214
+ tile.dataset.status=member?.status??'observer';
215
+ if (!isCoord && member?.name && member.name!=='system') {
216
+ const palette=beeTint(member);
217
+ if (tile.style?.setProperty) {
218
+ tile.style.setProperty('--tile-bg',palette.bg);
219
+ tile.style.setProperty('--tile-border',palette.border);
220
+ }
221
+ }
222
+ const muted=!isCoord&&['done','retired'].includes(member?.status);
223
+ tile.append(beeSprite(member,{muted}));
152
224
  return tile;
153
225
  }
226
+ function openMemberTarget(member,opener) {
227
+ const url=chatUrl(member?.threadId);
228
+ if (!url) return false;
229
+ if (!standalone) {
230
+ rpc('ui/open-link',{url}).catch(error=>notice(error.message,true));
231
+ return true;
232
+ }
233
+ openTranscript(member,opener);
234
+ return true;
235
+ }
236
+ function beeTint(member) {
237
+ if (typeof HiveBee?.tintStyle==='function') {
238
+ return HiveBee.tintStyle(member.name,member.role==='coordinator',member.tint);
239
+ }
240
+ const palette=[
241
+ ['#efac37','#ffe18d','#bb641d'],['#75baef','#cdefff','#3974bb'],
242
+ ['#55cbb2','#b8f8df','#268c7d'],['#e68db3','#ffcee2','#a24275'],
243
+ ['#b3ce64','#e9f6a1','#6c9137'],['#ad9ce8','#e3d4ff','#6d58af'],
244
+ ];
245
+ const [base,highlight,shade]=typeof HiveBee?.colors==='function'
246
+ ? HiveBee.colors(member.name,member.role==='coordinator',member.tint)
247
+ : (member.role==='coordinator'?palette[0]:palette[1+((member.tint??0)%(palette.length-1))]);
248
+ return {
249
+ base,highlight,shade,
250
+ bg:'color-mix(in oklab, '+base+' 14%, var(--surface))',
251
+ border:'color-mix(in oklab, '+base+' 40%, var(--line))',
252
+ text:'var(--ink)',
253
+ };
254
+ }
255
+ function beePill(member,{clickable=true}={}) {
256
+ const canJournal=standalone&&chatUrl(member.threadId);
257
+ const canMention=!member.external&&member.status!=='retired'&&!member.retireAfterTurn;
258
+ const interactive=clickable&&(canJournal||canMention);
259
+ const pill=node(interactive?'button':'span','bee-pill');
260
+ if (interactive) {
261
+ pill.type='button';
262
+ pill.setAttribute('aria-label',canJournal?'View journal for '+author(member.name):'Mention '+author(member.name));
263
+ pill.onclick=()=>{
264
+ if (canJournal) return openTranscript(member,pill);
265
+ return mentionMember(member.name);
266
+ };
267
+ }
268
+ const palette=beeTint(member);
269
+ if (pill.style?.setProperty) {
270
+ pill.style.setProperty('--pill-bg',palette.bg);
271
+ pill.style.setProperty('--pill-border',palette.border);
272
+ pill.style.setProperty('--pill-ink',palette.text);
273
+ }
274
+ pill.append(beeSprite(member,{muted:member.status==='retired'}),node('span','bee-pill-name',member.name));
275
+ return pill;
276
+ }
277
+ function smartTaskLabel(member) {
278
+ if (typeof graph.smartTaskLabel==='function') return graph.smartTaskLabel(member);
279
+ const explicit=String(member?.taskLabel??'').trim();
280
+ if (explicit) return explicit.slice(0,96);
281
+ let raw=String(member?.brief??'').trim();
282
+ if (!raw) return member?.name??'Task';
283
+ raw=raw.replace(/\[([^\]]+)\]\([^)]+\)/g,'$1')
284
+ .replace(/[`*_#]/g,' ')
285
+ .replace(/\s+/g,' ')
286
+ .trim();
287
+ const sentences=raw.split(/(?<!\d)(?<=[.!?])\s+|\r?\n/).filter(Boolean);
288
+ if (sentences.length>1&&/^(?:you are|act as|your role|member)\b/i.test(sentences[0])) {
289
+ raw=sentences.slice(1).join(' ');
290
+ } else {
291
+ raw=raw.replace(/^you are(?:\s+an?)?(?:\s+hive swarm)?(?:\s+member|\s+agent|\s+worker)?(?:\s+@?[a-z0-9_-]+)?(?:\s*\([^)]*\))?(?:\s+for\s+(?:[^.,:;]|\d\.\d)+)?[.,:;\s-]*/i,'');
292
+ }
293
+ raw=raw.replace(/^(?:your\s+(?:assignment|mission|role|task)(?:\s+in\s+[^:]+)?|you\s+own|mission|goal|objective)\s*[:—–-]?\s*/i,'');
294
+ raw=raw.replace(/\s+(?:in|inside|at)\s+(?:[a-z]:\\|\/)[^\s,;]+/gi,'').trim();
295
+ const firstSentence=raw.split(/(?<!\d)(?<=[.!?])\s+|\r?\n/)[0]?.trim()||raw;
296
+ let label=firstSentence.replace(/[.:;,\s]+$/,'').trim();
297
+ if (label.length>64) {
298
+ const cut=label.slice(0,64);
299
+ const lastSpace=cut.lastIndexOf(' ');
300
+ label=(lastSpace>24?cut.slice(0,lastSpace):cut).trim();
301
+ }
302
+ label=label.replace(/\s+(?:for|in|on|with|to|of|and|or|the|a|an|at|by|from)$/i,'').trim();
303
+ return label||(member?.name??'Task');
304
+ }
154
305
  function people() {
155
306
  const members=team.members.some(member=>member.role==='coordinator')?team.members:[
156
307
  {name:'coordinator',role:'coordinator',status:'observer',model:team.model,effort:team.effort,
@@ -174,17 +325,83 @@
174
325
  return changed;
175
326
  }
176
327
 
328
+ function renderVersionTag(value=appVersion) {
329
+ const clean=typeof value==='string'?value.trim():'';
330
+ if (!clean) return;
331
+ appVersion=clean;
332
+ const tag=$('app-version');
333
+ if (!tag) return;
334
+ tag.textContent='v'+clean;
335
+ tag.title='Hive Swarm v'+clean;
336
+ tag.hidden=false;
337
+ }
338
+ function safeReleaseUrl(candidate,versionTag) {
339
+ for (const raw of [candidate,'https://github.com/snowmiku601-cpu/hive-swarm/releases/tag/v'+versionTag]) {
340
+ if (typeof raw!=='string'||!raw) continue;
341
+ try {
342
+ const parsed=new URL(raw);
343
+ if (parsed.protocol==='https:'||parsed.protocol==='http:') return parsed.href;
344
+ } catch {}
345
+ }
346
+ return 'https://github.com/snowmiku601-cpu/hive-swarm/releases';
347
+ }
348
+ function isDismissedUpdate(latest) {
349
+ try {return globalThis.localStorage?.getItem?.(DISMISSED_UPDATE_KEY)===latest;}
350
+ catch {return false;}
351
+ }
352
+ function renderUpdateBadge() {
353
+ const wrap=$('update-wrap'),pill=$('update-pill'),popover=$('update-popover');
354
+ if (!wrap||!pill||!popover) return;
355
+ const latest=typeof updateInfo?.latest==='string'?updateInfo.latest.trim():'';
356
+ const show=Boolean(updateInfo?.available===true&&latest&&SEMVER_RE.test(latest)&&!isDismissedUpdate(latest));
357
+ wrap.hidden=!show;
358
+ if (!show) {
359
+ updateOpen=false;
360
+ popover.hidden=true;
361
+ pill.setAttribute('aria-expanded','false');
362
+ return;
363
+ }
364
+ if (updateInfo?.current&&!appVersion) renderVersionTag(updateInfo.current);
365
+ const current=appVersion||(typeof updateInfo?.current==='string'?updateInfo.current.trim():'');
366
+ pill.textContent='↑ v'+latest+' available';
367
+ pill.title='Hive Swarm v'+latest+' is available on npm';
368
+ pill.setAttribute('aria-expanded',String(updateOpen));
369
+ $('update-diff').textContent=current?'v'+current+' → v'+latest:'v'+latest;
370
+ $('update-cmd').textContent=CODEX_UPDATE_CMD;
371
+ $('update-link').href=safeReleaseUrl(updateInfo?.url,latest);
372
+ popover.hidden=!updateOpen;
373
+ }
374
+ async function checkForUpdate() {
375
+ if (!standalone||typeof fetch!=='function') return;
376
+ try {
377
+ const response=await fetch('/swarm/update',{cache:'no-store'});
378
+ if (!response?.ok) return;
379
+ const data=await response.json();
380
+ if (!data||typeof data.available!=='boolean') return;
381
+ if (typeof data.current==='string'&&!appVersion) renderVersionTag(data.current);
382
+ updateInfo=data;
383
+ renderUpdateBadge();
384
+ } catch {}
385
+ }
386
+
177
387
  function acceptStatus(value) {
178
388
  if (!value?.id || !Array.isArray(value.members)) return;
389
+ if (value.update && typeof value.update.available==='boolean') {
390
+ updateInfo=value.update;
391
+ renderUpdateBadge();
392
+ }
179
393
  if (team?.id && team.id!==value.id) {
180
394
  if (transcript) closeTranscript();
395
+ if (lightbox) closeLightbox();
181
396
  posts.clear();
182
397
  chronology=[];
183
398
  latestByAuthor.clear();
399
+ threadOpenState.clear();
184
400
  historyTail=seen=0;
185
401
  cursor=focusedNode=null;
186
402
  memberDrafts.clear();
187
403
  $('overview-brief-details').open=false;
404
+ $('overview-tasks-accordion').open=false;
188
405
  memberKey=channelKey=rosterKey=feedKey='';
189
406
  }
190
407
  team=value;
@@ -256,12 +473,17 @@
256
473
  const details=node('div');
257
474
  details.append(node('strong','',author(member.name)),node('small','',condition(member)));
258
475
  item.append(bee(member,true),details);
476
+ if (chatUrl(member.threadId)) {
477
+ item.dataset.clickable='true';
478
+ item.title='Open '+author(member.name);
479
+ item.onclick=()=>openMemberTarget(member,item);
480
+ }
259
481
  return item;
260
482
  }));
261
483
  const retired=roster.length-live.length;
262
484
  $('aside-total').textContent=retired?retired+' retired':'';
263
485
  $('aside-total').hidden=!retired;
264
- } else if (activeTab==='overview') renderOverview();
486
+ } else if (activeTab==='overview') renderOverview(roster);
265
487
  else if (activeTab==='members') renderMembers(roster);
266
488
  else scheduleGraph();
267
489
  syncTranscript();
@@ -277,11 +499,19 @@
277
499
  return {filter,channel,query,matching};
278
500
  }
279
501
 
502
+ function syncBoardChrome() {
503
+ const activeFilter=Boolean($('member-filter').value||$('channel-filter').value||!following);
504
+ $('toggle-board-filters').dataset.active=String(activeFilter);
505
+ const feed=$('feed');
506
+ const away=(feed.scrollHeight-feed.scrollTop-feed.clientHeight)>48;
507
+ $('board-latest').hidden=(following&&!away)||!feed.children?.length;
508
+ }
509
+
280
510
  function renderFeed(roster=people()) {
281
511
  const {filter,channel,query,matching}=matchingPosts();
282
512
  if (following) seen=chronology.at(-1)?.seq??0;
283
513
  const key=JSON.stringify([team.id,filter,channel,query,following,feedLimit,matching.map(event=>event.seq)]);
284
- if (key===feedKey) return;
514
+ if (key===feedKey) {syncBoardChrome();return;}
285
515
  feedKey=key;
286
516
  const feed=$('feed');
287
517
  const scroll=feed.scrollTop;
@@ -311,19 +541,52 @@
311
541
  const line=node('div','post-top');
312
542
  const who=node('div');
313
543
  who.append(node('strong','',author(event.author)));
314
- if (event.channel&&event.channel!=='main') who.append(node('span','channel-tag','#'+event.channel));
315
544
  if (event.targets?.length) who.append(node('span','targets','→ '+event.targets.map(author).join(' ')));
545
+ if (event.channel&&event.channel!=='main') who.append(node('span','channel-tag','#'+event.channel));
316
546
  line.append(who,node('span','stamp',stamp(event)));
317
- const content=node('div');
547
+ const content=node('div','post-body');
318
548
  const message=node('div','message');
319
549
  richText(message,event.text);
320
550
  content.append(line,message);
321
- entry.append(bee(member,true),content);
551
+ const rawText=String(event.text??'');
552
+ if (rawText.length>360||rawText.split(/\r?\n/).length>6) {
553
+ message.dataset.clamped='true';
554
+ const more=node('button','expand-post-btn','Show more');
555
+ more.type='button';
556
+ more.setAttribute('aria-expanded','false');
557
+ const toggle=()=>{
558
+ const expand=message.dataset.clamped==='true';
559
+ message.dataset.clamped=expand?'false':'true';
560
+ more.textContent=expand?'Show less':'Show more';
561
+ more.setAttribute('aria-expanded',String(expand));
562
+ };
563
+ more.onclick=toggle;
564
+ message.onclick=ev=>{
565
+ if (message.dataset.clamped!=='true') return;
566
+ if (ev?.target?.closest?.('a, button, code, pre')) return;
567
+ if (globalThis.getSelection?.()?.toString?.()) return;
568
+ toggle();
569
+ };
570
+ content.append(more);
571
+ }
572
+ const tile=bee(member,true);
573
+ let avatar=tile;
574
+ if (chatUrl(member.threadId)) {
575
+ const avatarBtn=node('button','post-avatar-btn');
576
+ avatarBtn.type='button';
577
+ avatarBtn.setAttribute('aria-label','Open '+author(member.name)+' session');
578
+ avatarBtn.title='Open '+author(member.name);
579
+ avatarBtn.onclick=()=>openMemberTarget(member,avatarBtn);
580
+ avatarBtn.append(tile);
581
+ avatar=avatarBtn;
582
+ }
583
+ entry.append(avatar,content);
322
584
  items.push(entry);
323
585
  }
324
586
  if (!items.length) items.push(node('li','empty',query||filter||channel?'No matching posts.':'No posts yet.'));
325
587
  feed.replaceChildren(...items);
326
588
  feed.scrollTop=following?feed.scrollHeight:scroll;
589
+ syncBoardChrome();
327
590
  }
328
591
 
329
592
  async function jumpToPost(seq) {
@@ -408,19 +671,22 @@
408
671
  return '';
409
672
  }
410
673
 
674
+ function openTranscript(member,opener) {
675
+ if (!standalone||!chatUrl(member.threadId)) return;
676
+ transcript={name:member.name,threadId:member.threadId,status:member.status,opener};
677
+ $('transcript-title').textContent='Journal · '+author(member.name);
678
+ $('transcript-turns').replaceChildren();
679
+ $('member-transcript').showModal();
680
+ syncTranscript();
681
+ return refreshTranscript();
682
+ }
683
+
411
684
  function transcriptButton(member) {
412
685
  if (!standalone || !chatUrl(member.threadId)) return null;
413
686
  const button=node('button','link-button','View journal');
414
687
  button.type='button';
415
688
  button.setAttribute('aria-label','View journal for '+author(member.name));
416
- button.onclick=()=>{
417
- transcript={name:member.name,threadId:member.threadId,status:member.status,opener:button};
418
- $('transcript-title').textContent='Journal · '+author(member.name);
419
- $('transcript-turns').replaceChildren();
420
- $('member-transcript').showModal();
421
- syncTranscript();
422
- return refreshTranscript();
423
- };
689
+ button.onclick=()=>openTranscript(member,button);
424
690
  return button;
425
691
  }
426
692
 
@@ -430,7 +696,30 @@
430
696
  transcript=null;
431
697
  previous.request?.abort();
432
698
  $('member-transcript').close();
433
- (previous.opener.isConnected?previous.opener:$('tab-'+activeTab)).focus({preventScroll:true});
699
+ (previous.opener?.isConnected?previous.opener:$('tab-'+activeTab)).focus({preventScroll:true});
700
+ }
701
+
702
+ function openLightbox(shot,opener) {
703
+ const src=safeAssetUrl(shot.url);
704
+ if (!src) return;
705
+ lightbox={shot,opener};
706
+ $('lightbox-caption').textContent=shot.caption||'Screenshot';
707
+ $('lightbox-meta').textContent=[author(shot.author),shot.seq?'#'+shot.seq:''].filter(Boolean).join(' · ');
708
+ const img=$('lightbox-image');
709
+ img.src=src;
710
+ img.alt=shot.caption||'Screenshot';
711
+ const actions=$('lightbox-actions');
712
+ actions.replaceChildren();
713
+ if (shot.seq) actions.append(postReference(shot.seq));
714
+ $('screenshot-lightbox').showModal();
715
+ }
716
+
717
+ function closeLightbox() {
718
+ const previous=lightbox;
719
+ if (!previous) return;
720
+ lightbox=null;
721
+ $('screenshot-lightbox').close();
722
+ (previous.opener?.isConnected?previous.opener:$('tab-'+activeTab)).focus({preventScroll:true});
434
723
  }
435
724
 
436
725
  function syncTranscript() {
@@ -555,19 +844,31 @@
555
844
  }
556
845
 
557
846
  function threadState(thread) {
558
- const people=(thread.members??[]).map(name=>team.members.find(member=>member.name===name)).filter(Boolean);
559
- if (people.some(member=>member.recoveryRequired||['failed','quota'].includes(member.status))) {
847
+ const members=(thread.members??[]).map(name=>team.members.find(member=>member.name===name)).filter(Boolean);
848
+ if (members.some(member=>member.recoveryRequired||['failed','quota'].includes(member.status))) {
560
849
  return {key:'blocked',label:'Blocked',rank:0};
561
850
  }
562
- if (people.some(member=>member.status==='working')) return {key:'active',label:'Active',rank:1};
563
- if (people.some(member=>member.status==='queued')) return {key:'queued',label:'Queued',rank:2};
564
- if (people.some(member=>member.status==='waiting')) return {key:'waiting',label:'Waiting',rank:3};
565
- if (people.length&&people.every(member=>['done','retired'].includes(member.status))) {
851
+ if (members.some(member=>member.status==='working')) return {key:'active',label:'Active',rank:1};
852
+ if (members.some(member=>member.status==='queued')) return {key:'queued',label:'Queued',rank:2};
853
+ if (members.some(member=>member.status==='waiting')) return {key:'waiting',label:'Waiting',rank:3};
854
+ if (members.length&&members.every(member=>['done','retired'].includes(member.status))) {
566
855
  return {key:'done',label:'Done',rank:4};
567
856
  }
568
857
  return {key:'queued',label:'Queued',rank:2};
569
858
  }
570
859
 
860
+ function stateGlyph(member) {
861
+ if (member.recoveryRequired||['failed','quota'].includes(member.status)) return '!';
862
+ if (member.status==='done') return '✓';
863
+ if (member.status==='working') return '●';
864
+ if (member.status==='retired') return '–';
865
+ return '◦';
866
+ }
867
+ function stateKey(member) {
868
+ if (member.recoveryRequired||['failed','quota'].includes(member.status)) return 'failed';
869
+ return member.status??'waiting';
870
+ }
871
+
571
872
  function attentionItems() {
572
873
  const stopped=['stalled','budget'].includes(team.phase);
573
874
  const issues=(team.attention??[]).filter(issue=>stopped||['recovery','quota','failed','dependency','cycle'].includes(issue.kind))
@@ -644,77 +945,183 @@
644
945
  return row;
645
946
  }
646
947
 
647
- function renderOverview() {
648
- const members=team.members;
649
- const workers=members.filter(member=>member.role!=='coordinator'&&member.status!=='retired');
948
+ function renderOverview(roster=people()) {
949
+ const members=roster.filter(member=>!member.external);
950
+ const allWorkers=members.filter(member=>member.role!=='coordinator');
951
+ const liveWorkers=allWorkers.filter(member=>member.status!=='retired');
952
+ const doneWorkers=liveWorkers.filter(member=>member.status==='done').length;
953
+ $('overview-intro').hidden=false;
650
954
  $('overview-goal').textContent=team.title;
955
+ const goalLine=team.goalLine?.trim()??'';
956
+ $('overview-goal-line').textContent=goalLine;
957
+ $('overview-goal-line').hidden=!goalLine||goalLine===team.title;
651
958
  const brief=team.task?.trim()??'';
652
959
  const long=brief.length>180||/\n/.test(brief);
653
960
  $('overview-brief').textContent=brief;
654
961
  $('overview-brief').hidden=long||!brief||brief===team.title;
655
962
  $('overview-brief-details').hidden=!long;
656
963
  $('overview-brief-full').textContent=brief;
657
- progressView('workers','worker-progress',workers.filter(member=>member.status==='done').length,workers.length);
964
+
965
+ const tasksTotal=liveWorkers.length;
966
+ const heading=$('overview-tasks-heading');
967
+ heading.replaceChildren(
968
+ node('strong','',doneWorkers+' of '+tasksTotal),
969
+ document.createTextNode(' tasks done')
970
+ );
971
+ const taskIcon=$('overview-tasks-icon');
972
+ const hasBlocked=members.some(member=>member.recoveryRequired||['failed','quota'].includes(member.status));
973
+ const hasWorking=members.some(member=>member.status==='working');
974
+ taskIcon.textContent=tasksTotal>0&&doneWorkers===tasksTotal?'✓':hasBlocked?'!':'•';
975
+ taskIcon.dataset.status=tasksTotal>0&&doneWorkers===tasksTotal?'done':hasBlocked?'failed':hasWorking?'working':'waiting';
976
+ progressView('workers','worker-progress',doneWorkers,tasksTotal);
658
977
  progressView('turns','turn-progress',team.turns,team.turnLimit);
978
+
659
979
  liveSlots.clear();
660
980
  nowSlots.clear();
661
- $('overview-members').replaceChildren(...members.map(member=>{
662
- const row=node('li','overview-member');
663
- const heading=node('div','member-top');
664
- const status=node('span','status-word',condition(member));
665
- status.dataset.status=member.status;
666
- const mode=modeBadge(member);
667
- const right=node('span','member-pills');
668
- if (mode) right.append(mode);
669
- right.append(status);
670
- heading.append(node('strong','',author(member.name)),right);
671
- row.append(heading);
981
+ const taskListMembers=allWorkers.length?allWorkers:members;
982
+ $('overview-members').replaceChildren(...taskListMembers.map(member=>{
983
+ const row=node('li','overview-task-row');
984
+ const icon=node('span','task-state-icon',stateGlyph(member));
985
+ icon.setAttribute('aria-hidden','true');
986
+ icon.dataset.status=stateKey(member);
987
+ const info=node('div','task-row-info');
988
+ info.append(node('span','task-row-title',smartTaskLabel(member)));
672
989
  const now=node('p','now-summary',memberNow(member));
673
990
  nowSlots.set(member.name,now);
674
- row.append(now);
991
+ info.append(now);
675
992
  const latest=latestByAuthor.get(member.name);
676
993
  const journal=transcriptButton(member);
677
994
  if (latest||journal) {
678
995
  const actions=node('div','overview-actions');
679
996
  if (latest) actions.append(postReference(latest.seq));
680
997
  if (journal) actions.append(journal);
681
- row.append(actions);
998
+ info.append(actions);
682
999
  }
1000
+ const aside=node('div','task-row-aside');
1001
+ aside.append(beePill(member));
1002
+ row.append(icon,info,aside);
683
1003
  return row;
684
1004
  }));
1005
+
685
1006
  const alerts=attentionItems();
686
1007
  $('overview-alerts').replaceChildren(...alerts.map(attentionRow));
687
1008
  $('overview-alerts-panel').hidden=!alerts.length;
688
- const threads=(team.threads??[]).map(thread=>({thread,state:threadState(thread)}))
1009
+
1010
+ const sourceThreads=team.threads?.length
1011
+ ? team.threads
1012
+ : (taskListMembers.length?[{id:'__tasks__',title:'Tasks',goal:'',members:taskListMembers.map(member=>member.name)}]:[]);
1013
+ const threads=sourceThreads.map(thread=>({thread,state:threadState(thread)}))
689
1014
  .sort((a,b)=>a.state.rank-b.state.rank);
690
1015
  $('overview-threads').replaceChildren(...threads.map(({thread,state})=>{
691
- const row=node('li','thread-row');
692
- const heading=node('div','member-top');
693
- const badge=node('span','status-word',state.label);
694
- badge.dataset.status=state.key==='blocked'?'failed':state.key==='active'?'working':state.key;
695
- heading.append(node('strong','',thread.title),badge);
696
- row.append(heading);
697
- if (thread.goal) row.append(node('p','now-summary',thread.goal));
698
- if (thread.members?.length) row.append(node('p','minor member-context',thread.members.map(author).join(' · ')));
699
- return row;
1016
+ const item=node('li');
1017
+ const card=node('details','panel thread-card');
1018
+ const threadKey=thread.id??thread.title;
1019
+ card.open=threadOpenState.get(threadKey)??true;
1020
+ card.ontoggle=()=>{threadOpenState.set(threadKey,card.open);};
1021
+ const summary=node('summary','thread-summary');
1022
+ const left=node('span','thread-summary-left');
1023
+ const dot=node('span','thread-dot');
1024
+ dot.dataset.state=state.key;
1025
+ dot.setAttribute('aria-hidden','true');
1026
+ // Only thread title uses <strong> to keep thread heading structure clear and testable.
1027
+ left.append(dot,node('strong','',thread.title),node('span','thread-status-text',state.label));
1028
+ const threadMembers=(thread.members??[]).map(name=>roster.find(member=>member.name===name)??{name,status:'queued'});
1029
+ const threadDone=threadMembers.filter(member=>['done','retired'].includes(member.status)).length;
1030
+ const threadTotal=threadMembers.length;
1031
+ const pct=threadTotal?Math.round(threadDone/threadTotal*100):0;
1032
+ const right=node('span','thread-progress-wrap');
1033
+ const bar=node('span','thread-bar');
1034
+ bar.setAttribute('aria-hidden','true');
1035
+ const fill=node('span','thread-bar-fill');
1036
+ fill.dataset.state=state.key;
1037
+ fill.style.width=pct+'%';
1038
+ bar.append(fill);
1039
+ const chevron=chevronIcon();
1040
+ right.append(bar,node('span','thread-fraction mono',threadDone+'/'+threadTotal),chevron);
1041
+ summary.append(left,right);
1042
+ card.append(summary);
1043
+
1044
+ const body=node('div','thread-body');
1045
+ if (thread.goal&&thread.goal!==thread.title) body.append(node('p','thread-goal quiet',thread.goal));
1046
+ if (threadMembers.length) {
1047
+ const list=node('ul','thread-task-rows');
1048
+ list.append(...threadMembers.map(member=>{
1049
+ const taskRow=node('li','thread-task-row');
1050
+ const icon=node('span','task-state-icon',stateGlyph(member));
1051
+ icon.setAttribute('aria-hidden','true');
1052
+ icon.dataset.status=stateKey(member);
1053
+ taskRow.append(icon,node('span','thread-task-title',smartTaskLabel(member)),beePill(member));
1054
+ return taskRow;
1055
+ }));
1056
+ body.append(list);
1057
+ }
1058
+ card.append(body);
1059
+ item.append(card);
1060
+ return item;
700
1061
  }));
701
1062
  $('overview-threads-panel').hidden=!threads.length;
702
- const milestones=chronology.filter(event=>['checkpoint','monitor'].includes(event.kind)||/\[done\]/i.test(event.text)).slice(-6).reverse();
703
- $('overview-milestones').replaceChildren(...milestones.map(event=>{
704
- const result=node('li','milestone');
705
- result.append(postReference(event.seq),node('span','',event.text.slice(0,180)));
706
- return result;
707
- }));
708
- $('overview-milestones-panel').hidden=!milestones.length;
1063
+
1064
+ const shots=(Array.isArray(team.screenshots)?team.screenshots:[]).filter(shot=>safeAssetUrl(shot?.url));
1065
+ $('overview-screenshots-panel').hidden=!shots.length;
1066
+ if (shots.length) {
1067
+ $('overview-screenshots-count').textContent=shots.length+(shots.length===1?' capture':' captures');
1068
+ $('overview-screenshots').replaceChildren(...shots.map(shot=>{
1069
+ const card=node('article','screenshot-card');
1070
+ card.setAttribute('role','listitem');
1071
+ const thumb=node('button','screenshot-thumb-btn');
1072
+ thumb.type='button';
1073
+ thumb.setAttribute('aria-label','Preview screenshot: '+(shot.caption||'Capture'));
1074
+ const img=node('img');
1075
+ img.src=safeAssetUrl(shot.url);
1076
+ img.alt=shot.caption||'Screenshot';
1077
+ img.loading='lazy';
1078
+ img.decoding='async';
1079
+ thumb.append(img,node('span','screenshot-caption',shot.caption||'Screenshot'));
1080
+ thumb.onclick=()=>openLightbox(shot,thumb);
1081
+ const meta=node('div','screenshot-meta');
1082
+ const authorMember=roster.find(member=>member.name===shot.author)??{name:shot.author||'user',status:'observer'};
1083
+ meta.append(beePill(authorMember,{clickable:false}));
1084
+ if (shot.seq) meta.append(postReference(shot.seq));
1085
+ card.append(thumb,meta);
1086
+ return card;
1087
+ }));
1088
+ } else $('overview-screenshots').replaceChildren();
1089
+
1090
+ const coordMember=roster.find(member=>member.role==='coordinator')??{name:'coordinator',role:'coordinator',status:'observer'};
1091
+ $('overview-team-badge').replaceChildren(beeSprite(coordMember));
1092
+ const goalMode=team.coordinator===false||!team.members?.some(member=>member.role==='coordinator');
1093
+ $('overview-team-role').textContent='Coordinator';
1094
+ $('overview-team-mode').textContent='Goal summary';
1095
+ $('overview-team-mode').hidden=!goalMode;
1096
+
709
1097
  const summary=$('overview-summary');
710
1098
  summary.replaceChildren();
711
- const report=chronology.findLast(event=>event.author==='coordinator'&&event.kind==='message');
1099
+ const coordReport=chronology.findLast(event=>event.author==='coordinator'&&event.kind==='message');
1100
+ const goalReport=goalMode?chronology.findLast(event=>event.kind==='message'&&(event.author==='user'||/\[done\]/i.test(event.text??''))):null;
1101
+ const report=coordReport??goalReport;
712
1102
  if (report) {
713
1103
  const body=node('div','message');
714
1104
  richText(body,report.text);
715
- summary.append(node('h3','','Coordinator summary'),postReference(report.seq),body);
1105
+ summary.append(postReference(report.seq),body);
716
1106
  }
717
1107
  summary.hidden=!report;
1108
+ $('overview-summary-empty').hidden=Boolean(report);
1109
+ const execFacts=[
1110
+ team.turns+'/'+team.turnLimit+' turns',
1111
+ [team.model,team.effort].filter(Boolean).join(' · '),
1112
+ team.fallbackModel?'Fallback: '+team.fallbackModel+(team.fallbackEffort?' · '+team.fallbackEffort:''):'',
1113
+ team.cwd,
1114
+ ].filter(Boolean).join(' · ');
1115
+ $('overview-execution').textContent=execFacts;
1116
+ $('overview-execution').hidden=!execFacts;
1117
+
1118
+ const milestones=chronology.filter(event=>['checkpoint','monitor'].includes(event.kind)||/\[done\]/i.test(event.text)).slice(-6).reverse();
1119
+ $('overview-milestones').replaceChildren(...milestones.map(event=>{
1120
+ const result=node('li','milestone');
1121
+ result.append(postReference(event.seq),node('span','',event.text.slice(0,180)));
1122
+ return result;
1123
+ }));
1124
+ $('overview-milestones-panel').hidden=!milestones.length;
718
1125
  }
719
1126
 
720
1127
  function trustedButton(label, action, disabled=false, style='link-button') {
@@ -823,18 +1230,59 @@
823
1230
  }
824
1231
 
825
1232
  function memberCard(member) {
826
- const card=node('li','member-card'+(member.role==='coordinator'?' coordinator':''));
827
- const info=node('div');
1233
+ const isCoord=member.role==='coordinator'||member.name==='coordinator';
1234
+ const card=node('li','member-card'+(isCoord?' coordinator':''));
1235
+ card.dataset.status=member.status??'observer';
1236
+ const draft=memberDrafts.get(member.name)??{};
1237
+ card.dataset.menuOpen=draft.open||draft.confirmRetire?'true':'false';
1238
+ if (member.recoveryRequired) card.dataset.recovery='true';
1239
+ const canNav=Boolean(chatUrl(member.threadId));
1240
+ if (canNav) {
1241
+ card.dataset.clickable='true';
1242
+ card.tabIndex=0;
1243
+ card.title='Open '+author(member.name);
1244
+ card.onclick=event=>{
1245
+ if (event?.target?.closest?.('a, button, summary, details, input, select, textarea')) return;
1246
+ if (globalThis.getSelection?.()?.toString?.()) return;
1247
+ openMemberTarget(member,card);
1248
+ };
1249
+ card.onkeydown=event=>{
1250
+ if (event.target===card&&(event.key==='Enter'||event.key===' ')) {
1251
+ event.preventDefault();
1252
+ openMemberTarget(member,card);
1253
+ }
1254
+ };
1255
+ }
1256
+ const info=node('div','member-main');
828
1257
  const line=node('div','member-top');
1258
+ const ident=node('div','member-ident');
1259
+ const subtitle=isCoord?'Coordinator':smartTaskLabel(member);
1260
+ ident.append(node('h3','member-name',author(member.name)),node('span','member-task',subtitle));
1261
+ const last=latestByAuthor.get(member.name);
1262
+ const meta=node('div','member-meta');
829
1263
  const badge=node('span','status-word',condition(member));
830
1264
  badge.dataset.status=member.status;
831
1265
  const mode=modeBadge(member);
832
1266
  const pills=node('span','member-pills');
833
1267
  if (mode) pills.append(mode);
834
1268
  pills.append(badge);
835
- line.append(node('h3','member-name',author(member.name)),pills);
1269
+ const modelInfo=[member.model,member.effort,last?'#'+last.seq:''].filter(Boolean).join(' · ');
1270
+ meta.append(pills);
1271
+ if (modelInfo) meta.append(node('span','minor member-context',modelInfo));
1272
+ const menuBtn=node('button','member-menu-btn','⋯');
1273
+ menuBtn.type='button';
1274
+ menuBtn.setAttribute('aria-label','More actions for '+author(member.name));
1275
+ menuBtn.setAttribute('aria-expanded',String(card.dataset.menuOpen==='true'));
1276
+ menuBtn.onclick=event=>{
1277
+ event?.stopPropagation?.();
1278
+ const opening=card.dataset.menuOpen!=='true';
1279
+ card.dataset.menuOpen=opening?'true':'false';
1280
+ menuBtn.setAttribute('aria-expanded',String(opening));
1281
+ };
1282
+ meta.append(menuBtn);
1283
+ line.append(ident,meta);
836
1284
  info.append(line);
837
- if (member.role==='coordinator'&&['stalled','budget'].includes(team.phase)) {
1285
+ if (isCoord&&['stalled','budget'].includes(team.phase)) {
838
1286
  card.dataset.needsYou='true';
839
1287
  line.append(node('strong','needs-you','Needs you'));
840
1288
  const alerts=attentionItems();
@@ -842,23 +1290,34 @@
842
1290
  alerts.find(issue=>issue.kind!=='worktree'))?.text);
843
1291
  info.append(reason);
844
1292
  }
845
- const last=latestByAuthor.get(member.name);
846
- const context=[member.model,member.effort,member.group?'@'+member.group:'',
847
- ...(member.channels??[]).map(channel=>'#'+channel),member.addedBy?'Invited by '+author(member.addedBy):'',
848
- last?'#'+last.seq:''].filter(Boolean);
849
- if (context.length) info.append(node('p','minor member-context',context.join(' · ')));
1293
+ const waiting=member.pendingWaitFor??member.waitFor;
1294
+ const hasChips=Boolean(member.workspace||member.worktree||member.group||member.channels?.length||member.addedBy||waiting?.length);
1295
+ if (hasChips) {
1296
+ const chips=node('div','member-chips');
1297
+ if (member.workspace) {
1298
+ const pathEl=node('code','member-path',member.workspace.cwd);
1299
+ pathEl.title=member.workspace.cwd;
1300
+ chips.append(pathEl);
1301
+ } else if (member.worktree) chips.append(node('span','member-chip','Worktree on turn 1'));
1302
+ if (member.group) chips.append(node('span','member-chip','@'+member.group));
1303
+ if (member.channels?.length) chips.append(node('span','member-chip',member.channels.map(c=>'#'+c).join(' ')));
1304
+ if (member.addedBy) chips.append(node('span','member-chip','Invited by '+author(member.addedBy)));
1305
+ if (waiting?.length) {
1306
+ const waitChip=node('span','member-chip','Waiting on '+waiting.map(author).join(', '));
1307
+ waitChip.dataset.tone='wait';
1308
+ chips.append(waitChip);
1309
+ }
1310
+ info.append(chips);
1311
+ }
850
1312
  const detail=last?.text??member.brief;
851
1313
  if (detail) {
852
1314
  const summary=node('p','member-summary',detail);
853
1315
  summary.title=detail;
854
1316
  info.append(summary);
855
1317
  }
856
- const waiting=member.pendingWaitFor??member.waitFor;
857
- if (waiting?.length) info.append(node('p','quiet','Waiting on '+waiting.map(author).join(', ')));
858
1318
  if (member.recoveryRequired) info.append(node('p','needs-reason','Outcome unconfirmed. Inspect journal, then retry or dismiss.'));
859
- if (member.workspace) info.append(node('code','member-path',member.workspace.cwd));
860
- else if (member.worktree) info.append(node('p','quiet','Isolated worktree on first turn'));
861
1319
  const actions=node('div','member-actions');
1320
+ actions.onclick=event=>event?.stopPropagation?.();
862
1321
  let modelControl;
863
1322
  const url=chatUrl(member.threadId);
864
1323
  if (url) {
@@ -866,8 +1325,10 @@
866
1325
  link.href=url;
867
1326
  if (!standalone) link.onclick=event=>{
868
1327
  event.preventDefault();
1328
+ event?.stopPropagation?.();
869
1329
  rpc('ui/open-link',{url:link.href}).catch(error=>notice(error.message,true));
870
1330
  };
1331
+ else link.onclick=event=>event?.stopPropagation?.();
871
1332
  actions.append(link);
872
1333
  }
873
1334
  const journal=transcriptButton(member);
@@ -876,12 +1337,11 @@
876
1337
  const send=node('button','link-button','@mention');
877
1338
  send.type='button';
878
1339
  send.setAttribute('aria-label','@mention '+author(member.name)+' on board');
879
- send.onclick=()=>mentionMember(member.name);
1340
+ send.onclick=event=>{event?.stopPropagation?.();mentionMember(member.name);};
880
1341
  actions.append(send);
881
1342
  }
882
1343
  if (standalone&&!member.external) {
883
1344
  const active=member.status!=='retired'&&!member.retireAfterTurn;
884
- const draft=memberDrafts.get(member.name)??{};
885
1345
  memberDrafts.set(member.name,draft);
886
1346
  if (member.recoveryRequired) {
887
1347
  const busy=member.status==='working';
@@ -917,7 +1377,10 @@
917
1377
  }
918
1378
  }
919
1379
  if (actions.childElementCount) info.append(actions);
920
- if (modelControl) info.append(modelControl);
1380
+ if (modelControl) {
1381
+ modelControl.onclick=event=>event?.stopPropagation?.();
1382
+ info.append(modelControl);
1383
+ }
921
1384
  if (member.status==='working') info.append(activitySlot(member));
922
1385
  card.append(bee(member),info);
923
1386
  return card;
@@ -948,6 +1411,322 @@
948
1411
  $('member-empty').hidden=visible.length>0;
949
1412
  }
950
1413
 
1414
+ /* Fallback graph & GIF helpers when HiveGraph 2.1 / HiveGif are not yet loaded */
1415
+ function fallbackProjectHive(events,roster,cursorSeq) {
1416
+ const mergeUser=!roster.some(m=>(m.role==='coordinator'||m.name==='coordinator')&&!m.external)&&!roster.some(m=>m.name==='user');
1417
+ const resolveActor=name=>(mergeUser&&name==='user')?'coordinator':name;
1418
+ const upTo=events.filter(event=>event.seq<=cursorSeq&&graph.isPost(event));
1419
+ const lastPost=upTo.at(-1)??null;
1420
+ const latestSeqByAuthor=new Map();
1421
+ for (const post of upTo) latestSeqByAuthor.set(resolveActor(post.author),post.seq);
1422
+ const coordMember=roster.find(member=>member.role==='coordinator')??{name:'coordinator',role:'coordinator',status:'waiting'};
1423
+ const workers=roster.filter(member=>member.role!=='coordinator'&&!member.external);
1424
+ const buckets={working:[],waiting:[],needs:[],done:[]};
1425
+ const memberBucket=new Map();
1426
+ for (const member of workers) {
1427
+ let bucket='waiting';
1428
+ if (member.recoveryRequired||['failed','quota'].includes(member.status)) bucket='needs';
1429
+ else if (member.status==='working') bucket='working';
1430
+ else if (['done','retired'].includes(member.status)) bucket='done';
1431
+ buckets[bucket].push({
1432
+ ...member,
1433
+ muted:['done','retired'].includes(member.status),
1434
+ latestSeq:latestSeqByAuthor.get(member.name)??0,
1435
+ });
1436
+ memberBucket.set(member.name,bucket);
1437
+ }
1438
+ const meta={
1439
+ working:{label:'Working',tone:'working'},
1440
+ waiting:{label:'Waiting',tone:'waiting'},
1441
+ needs:{label:'Needs you',tone:'needs'},
1442
+ done:{label:'Done',tone:'done'},
1443
+ };
1444
+ const clusters=['working','waiting','needs','done']
1445
+ .filter(id=>buckets[id].length>0)
1446
+ .map(id=>({id,label:meta[id].label,tone:meta[id].tone,count:buckets[id].length,members:buckets[id]}));
1447
+ const doneCount=buckets.done.length;
1448
+ const totalWorkers=workers.length;
1449
+ const coordPhase=buckets.needs.length?'stalled':buckets.working.length?'working':
1450
+ totalWorkers>0&&doneCount===totalWorkers?'done':'waiting';
1451
+ const connectors=[];
1452
+ if (buckets.done.length) connectors.push({from:'done',to:'coordinator',kind:'done',label:'Tasks done'});
1453
+ if (buckets.needs.length) connectors.push({from:'coordinator',to:'needs',kind:'waiting',label:'Needs you'});
1454
+ if (buckets.waiting.some(member=>(member.pendingWaitFor??member.waitFor)?.length)) {
1455
+ connectors.push({from:'waiting',to:'coordinator',kind:'waiting',label:'Waiting on'});
1456
+ }
1457
+ if (lastPost&&(lastPost.targets?.length||coordPhase!=='done')) {
1458
+ const authorName=resolveActor(lastPost.author);
1459
+ const from=authorName==='coordinator'?'coordinator':(memberBucket.get(authorName)??'coordinator');
1460
+ const resolvedTargets=(lastPost.targets??[]).map(resolveActor);
1461
+ const target=resolvedTargets.find(name=>name!==authorName);
1462
+ const to=target?(target==='coordinator'?'coordinator':(memberBucket.get(target)??'coordinator')):(from==='coordinator'&&clusters[0]?clusters[0].id:'coordinator');
1463
+ if (from!==to) connectors.push({from,to,kind:'message',label:'Message just sent',seq:lastPost.seq});
1464
+ }
1465
+ return {
1466
+ currentSeq:cursorSeq,
1467
+ lastPost,
1468
+ coordinator:{
1469
+ name:coordMember.name,status:coordMember.status,role:'coordinator',
1470
+ doneCount,totalWorkers,phase:coordPhase,latestSeq:latestSeqByAuthor.get(coordMember.name)??0,
1471
+ tint:coordMember.tint,
1472
+ },
1473
+ clusters,
1474
+ connectors,
1475
+ };
1476
+ }
1477
+ function hexVertices(cx,cy,radius) {
1478
+ return Array.from({length:6},(_,k)=>{
1479
+ const angle=k*Math.PI/3;
1480
+ return {x:cx+radius*Math.cos(angle),y:cy+radius*Math.sin(angle)};
1481
+ });
1482
+ }
1483
+ function fallbackLayoutHive(hiveModel,width,height) {
1484
+ const clusters=hiveModel.clusters??[];
1485
+ const count=clusters.length;
1486
+ const radius=count<=1
1487
+ ? Math.max(88,Math.min(120,width*0.25,height*0.225))
1488
+ : Math.max(70,Math.min(104,width*0.21,height*0.195));
1489
+ const hexH=Math.sqrt(3)*radius;
1490
+ const cellsById=new Map();
1491
+ let coordPos;
1492
+ const clusterLayouts=[];
1493
+ if (count===0) {
1494
+ coordPos={x:width/2,y:height/2};
1495
+ } else if (count===1) {
1496
+ const gap=Math.max(12,Math.min(22,height-hexH*2-20));
1497
+ const totalH=hexH*2+gap;
1498
+ const topY=Math.max(hexH/2+10,(height-totalH)/2+hexH/2);
1499
+ const clusterPos={x:width/2,y:topY};
1500
+ coordPos={x:width/2,y:topY+hexH+gap};
1501
+ clusterLayouts.push({pos:clusterPos,cluster:clusters[0]});
1502
+ } else {
1503
+ coordPos={x:width/2,y:height*0.64};
1504
+ const spreadX=Math.min(width*0.33,radius*2.2);
1505
+ const spreadY=Math.min(height*0.34,hexH*1.12);
1506
+ clusters.forEach((cluster,idx)=>{
1507
+ const angle=-Math.PI+(idx+1)*Math.PI/(count+1);
1508
+ clusterLayouts.push({
1509
+ pos:{x:width/2+Math.cos(angle)*spreadX,y:coordPos.y+Math.sin(angle)*spreadY},
1510
+ cluster,
1511
+ });
1512
+ });
1513
+ }
1514
+ const coordinator={
1515
+ id:'coordinator',x:coordPos.x,y:coordPos.y,radius,
1516
+ vertices:hexVertices(coordPos.x,coordPos.y,radius),
1517
+ model:hiveModel.coordinator,
1518
+ };
1519
+ cellsById.set('coordinator',coordinator);
1520
+ const laidOutClusters=clusterLayouts.map(({pos,cluster})=>{
1521
+ const items=cluster.members??[];
1522
+ const cols=items.length<=2?items.length:items.length<=6?3:4;
1523
+ const rows=Math.max(1,Math.ceil(items.length/Math.max(1,cols)));
1524
+ const slotW=Math.min(68,(radius*1.58)/Math.max(1,cols));
1525
+ const rowGap=rows===1?0:Math.min(48,(hexH*0.56)/Math.max(1,rows));
1526
+ const baseY=pos.y+12-((rows-1)*rowGap)/2;
1527
+ const slots=items.map((member,idx)=>{
1528
+ const row=Math.floor(idx/cols);
1529
+ const col=idx%cols;
1530
+ const inRow=Math.min(cols,items.length-row*cols);
1531
+ const sx=pos.x+(col-(inRow-1)/2)*slotW;
1532
+ const sy=baseY+row*rowGap;
1533
+ return {member,x:sx,y:sy,slotWidth:slotW,beeScale:1};
1534
+ });
1535
+ const cell={
1536
+ id:cluster.id,label:cluster.label,tone:cluster.tone,count:cluster.count,
1537
+ x:pos.x,y:pos.y,radius,vertices:hexVertices(pos.x,pos.y,radius),slots,
1538
+ };
1539
+ cellsById.set(cluster.id,cell);
1540
+ return cell;
1541
+ });
1542
+ return {width,height,radius,coordinator,clusters:laidOutClusters,cellsById};
1543
+ }
1544
+ function fallbackHiveMinimumHeight(clusterCount,width) {
1545
+ if (clusterCount<=1) return width<440?380:430;
1546
+ return width<440?420:460;
1547
+ }
1548
+ function fallbackLayoutMentions(nodes,width,height) {
1549
+ const result=new Map();
1550
+ if (!nodes.length) return result;
1551
+ if (nodes.length>12||width<320) return graph.layout(nodes,width,height);
1552
+ const ordered=[...nodes].sort((a,b)=>(b.role==='coordinator')-(a.role==='coordinator'));
1553
+ const topPad=48,bottomPad=48;
1554
+ const centerY=(topPad+(height-bottomPad))/2;
1555
+ const radiusY=Math.max(54,(height-topPad-bottomPad)/2);
1556
+ const sidePad=Math.min(110,Math.max(72,width*0.16));
1557
+ const radiusX=Math.max(60,width/2-sidePad);
1558
+ if (ordered.length===1) {
1559
+ result.set(ordered[0].name,{x:width/2,y:centerY});
1560
+ return result;
1561
+ }
1562
+ ordered.forEach((member,idx)=>{
1563
+ const angle=-Math.PI/2+idx*Math.PI*2/ordered.length;
1564
+ result.set(member.name,{
1565
+ x:width/2+Math.cos(angle)*radiusX,
1566
+ y:centerY+Math.sin(angle)*radiusY,
1567
+ });
1568
+ });
1569
+ return result;
1570
+ }
1571
+ function fallbackPillBox(member,narrow) {
1572
+ const len=String(member?.name??'').length;
1573
+ const w=Math.max(76,Math.min(narrow?134:180,len*7.1+48));
1574
+ return {halfW:w/2,halfH:15,offsetX:0,offsetY:0,radius:15};
1575
+ }
1576
+ function pillBoxFor(member,narrow) {
1577
+ if (typeof graph.layoutMentions==='function'&&typeof graph.nodeBox==='function') {
1578
+ return graph.nodeBox(member,{variant:'pill',narrow});
1579
+ }
1580
+ return fallbackPillBox(member,narrow);
1581
+ }
1582
+ function clipRayToHex(origin,target,vertices) {
1583
+ if (!vertices?.length) return origin;
1584
+ const dx=target.x-origin.x,dy=target.y-origin.y;
1585
+ let bestT=Infinity;
1586
+ for (let i=0;i<vertices.length;i++) {
1587
+ const a=vertices[i],b=vertices[(i+1)%vertices.length];
1588
+ const ex=b.x-a.x,ey=b.y-a.y;
1589
+ const denom=dx*ey-dy*ex;
1590
+ if (Math.abs(denom)<1e-6) continue;
1591
+ const t=((a.x-origin.x)*ey-(a.y-origin.y)*ex)/denom;
1592
+ const u=((a.x-origin.x)*dy-(a.y-origin.y)*dx)/denom;
1593
+ if (t>0&&u>=-1e-4&&u<=1+1e-4&&t<bestT) bestT=t;
1594
+ }
1595
+ return Number.isFinite(bestT)?{x:origin.x+dx*bestT,y:origin.y+dy*bestT}:origin;
1596
+ }
1597
+ function rayClipHex(fromCell,toCell,offset=0) {
1598
+ const angle=Math.atan2(toCell.y-fromCell.y,toCell.x-fromCell.x);
1599
+ const nx=-Math.sin(angle),ny=Math.cos(angle);
1600
+ const fromPt=offset?{x:fromCell.x+nx*offset,y:fromCell.y+ny*offset}:fromCell;
1601
+ const toPt=offset?{x:toCell.x+nx*offset,y:toCell.y+ny*offset}:toCell;
1602
+ const start=clipRayToHex(fromPt,toPt,fromCell.vertices);
1603
+ const end=clipRayToHex(toPt,fromPt,toCell.vertices);
1604
+ return {start,end};
1605
+ }
1606
+ function drawHexCell(ctx,cell,palette,title,subtitle) {
1607
+ ctx.beginPath();
1608
+ cell.vertices.forEach((pt,idx)=>idx===0?ctx.moveTo(pt.x,pt.y):ctx.lineTo(pt.x,pt.y));
1609
+ ctx.closePath();
1610
+ ctx.fillStyle=palette.fill;
1611
+ ctx.fill();
1612
+ ctx.lineWidth=2;
1613
+ ctx.strokeStyle=palette.stroke;
1614
+ ctx.stroke();
1615
+ ctx.textAlign='center';
1616
+ ctx.textBaseline='middle';
1617
+ const titleY=cell.id==='coordinator'?cell.y+cell.radius*0.42:cell.y-cell.radius*0.62;
1618
+ ctx.fillStyle=palette.ink;
1619
+ ctx.font='650 12px var(--sans), system-ui, sans-serif';
1620
+ ctx.fillText(title,cell.x,titleY);
1621
+ if (subtitle!=null) {
1622
+ ctx.fillStyle=palette.muted;
1623
+ ctx.font='500 11px var(--sans), system-ui, sans-serif';
1624
+ ctx.fillText(String(subtitle),cell.x,titleY+15);
1625
+ }
1626
+ }
1627
+ function drawArrowHead(ctx,end,angle,color) {
1628
+ const len=8;
1629
+ ctx.fillStyle=color;
1630
+ ctx.beginPath();
1631
+ ctx.moveTo(end.x,end.y);
1632
+ ctx.lineTo(end.x-len*Math.cos(angle-0.45),end.y-len*Math.sin(angle-0.45));
1633
+ ctx.lineTo(end.x-(len*0.65)*Math.cos(angle),end.y-(len*0.65)*Math.sin(angle));
1634
+ ctx.lineTo(end.x-len*Math.cos(angle+0.45),end.y-len*Math.sin(angle+0.45));
1635
+ ctx.closePath();
1636
+ ctx.fill();
1637
+ }
1638
+ function drawHiveCanvas(canvas,hiveLayout,connectors,color) {
1639
+ const width=canvas.clientWidth,height=canvas.clientHeight;
1640
+ if (!width||!height) return;
1641
+ const scale=Math.min(devicePixelRatio||1,2);
1642
+ const pw=Math.round(width*scale),ph=Math.round(height*scale);
1643
+ if (canvas.width!==pw||canvas.height!==ph) {canvas.width=pw;canvas.height=ph;}
1644
+ const ctx=canvas.getContext('2d');
1645
+ ctx.setTransform(scale,0,0,scale,0,0);
1646
+ ctx.clearRect(0,0,width,height);
1647
+ for (const conn of connectors) {
1648
+ const fromCell=hiveLayout.cellsById.get(conn.from);
1649
+ const toCell=hiveLayout.cellsById.get(conn.to);
1650
+ if (!fromCell||!toCell||fromCell===toCell) continue;
1651
+ const offset=conn.kind==='message'?8:conn.kind==='waiting'?-8:0;
1652
+ const {start,end}=rayClipHex(fromCell,toCell,offset);
1653
+ if (Math.hypot(end.x-start.x,end.y-start.y)<1) continue;
1654
+ const stroke=conn.kind==='done'?color.good:conn.kind==='message'?color.purple:color.gold;
1655
+ ctx.strokeStyle=stroke;
1656
+ ctx.lineWidth=conn.kind==='message'?2.2:1.8;
1657
+ ctx.setLineDash(conn.kind==='waiting'?[5,4]:[]);
1658
+ ctx.beginPath();
1659
+ ctx.moveTo(start.x,start.y);
1660
+ ctx.lineTo(end.x,end.y);
1661
+ ctx.stroke();
1662
+ ctx.setLineDash([]);
1663
+ if (conn.kind==='waiting') drawArrowHead(ctx,end,Math.atan2(end.y-start.y,end.x-start.x),stroke);
1664
+ }
1665
+ const tonePalette=tone=>{
1666
+ if (tone==='done') return {fill:color.goodSoft,stroke:color.good,ink:color.text,muted:color.muted};
1667
+ if (tone==='working') return {fill:color.wash,stroke:color.gold,ink:color.text,muted:color.muted};
1668
+ if (tone==='needs') return {fill:color.badSoft,stroke:color.bad,ink:color.text,muted:color.muted};
1669
+ return {fill:color.paper,stroke:color.link,ink:color.text,muted:color.muted};
1670
+ };
1671
+ for (const cluster of hiveLayout.clusters) {
1672
+ drawHexCell(ctx,cluster,tonePalette(cluster.tone),cluster.label,cluster.count);
1673
+ }
1674
+ const coordTone=hiveLayout.coordinator.model.phase==='done'?'done':
1675
+ hiveLayout.coordinator.model.phase==='stalled'?'needs':'working';
1676
+ const doneTotal=hiveLayout.coordinator.model.doneCount+' of '+hiveLayout.coordinator.model.totalWorkers+' done';
1677
+ drawHexCell(ctx,hiveLayout.coordinator,tonePalette(coordTone),'Coordinator',doneTotal);
1678
+ }
1679
+ function drawMentionsCanvas(canvas,projection,coordinates,boxes,focus,highlight,color) {
1680
+ const width=canvas.clientWidth,height=canvas.clientHeight;
1681
+ if (!width||!height) return;
1682
+ const scale=Math.min(devicePixelRatio||1,2);
1683
+ const pw=Math.round(width*scale),ph=Math.round(height*scale);
1684
+ if (canvas.width!==pw||canvas.height!==ph) {canvas.width=pw;canvas.height=ph;}
1685
+ const ctx=canvas.getContext('2d');
1686
+ ctx.setTransform(scale,0,0,scale,0,0);
1687
+ ctx.clearRect(0,0,width,height);
1688
+ ctx.font='600 10px ui-monospace, monospace';
1689
+ ctx.textAlign='center';
1690
+ ctx.textBaseline='middle';
1691
+ const routed=graph.routeEdges(projection,coordinates,{
1692
+ variant:'pill',boxes,narrow:width<465,marginStart:5,marginEnd:6,obstacleMargin:width<465?12:20,
1693
+ });
1694
+ for (const {link,edge} of routed) {
1695
+ const {start:a,control:c,end:b,mid,endAngle:angle}=edge;
1696
+ const pulse=link.lastSeq===highlight;
1697
+ const related=!focus||link.from===focus||link.to===focus;
1698
+ const stroke=pulse&&related?color.accent:color.link;
1699
+ ctx.globalAlpha=related?(pulse?1:0.78):0.16;
1700
+ ctx.strokeStyle=ctx.fillStyle=stroke;
1701
+ ctx.lineWidth=Math.min(4.2,1.1+Math.sqrt(link.count)*0.72);
1702
+ ctx.lineCap='round';
1703
+ ctx.setLineDash(link.direct?[]:[4,4]);
1704
+ const inset=Math.min(4.5,edge.length*0.25);
1705
+ ctx.beginPath();
1706
+ ctx.moveTo(a.x,a.y);
1707
+ ctx.quadraticCurveTo(c.x,c.y,b.x-Math.cos(angle)*inset,b.y-Math.sin(angle)*inset);
1708
+ ctx.stroke();
1709
+ ctx.setLineDash([]);
1710
+ drawArrowHead(ctx,b,angle,stroke);
1711
+ if (related&&edge.length>=40&&(link.count>1||pulse||focus)) {
1712
+ const label=String(link.count);
1713
+ const pillW=Math.max(18,label.length*6.5+8);
1714
+ ctx.globalAlpha=0.98;
1715
+ ctx.fillStyle=color.paper;
1716
+ ctx.beginPath();
1717
+ if (ctx.roundRect) ctx.roundRect(mid.x-pillW/2,mid.y-7.5,pillW,15,7.5);
1718
+ else ctx.rect(mid.x-pillW/2,mid.y-7.5,pillW,15);
1719
+ ctx.fill();
1720
+ ctx.strokeStyle=pulse?color.accent:color.link;
1721
+ ctx.lineWidth=1;
1722
+ ctx.stroke();
1723
+ ctx.fillStyle=pulse?color.accent:color.text;
1724
+ ctx.fillText(label,mid.x,mid.y+0.25);
1725
+ }
1726
+ }
1727
+ ctx.globalAlpha=1;
1728
+ }
1729
+
951
1730
  function timeline() {return chronology.filter(graph.isPost);}
952
1731
  function cursorIndex(events) {
953
1732
  if (cursor===null) return events.length;
@@ -978,17 +1757,52 @@
978
1757
  if (activeTab!=='graph'||graphFrame) return;
979
1758
  graphFrame=requestAnimationFrame(()=>{graphFrame=0;if (team && activeTab==='graph') renderGraph();});
980
1759
  }
1760
+ function setGraphMode(mode) {
1761
+ graphMode=mode==='mentions'?'mentions':'hive';
1762
+ saveGraphMode(graphMode);
1763
+ $('graph-mode-hive').setAttribute('aria-pressed',String(graphMode==='hive'));
1764
+ $('graph-mode-mentions').setAttribute('aria-pressed',String(graphMode==='mentions'));
1765
+ $('mentions-options').hidden=graphMode!=='mentions';
1766
+ $('graph-stage').dataset.mode=graphMode;
1767
+ $('graph-legend').dataset.mode=graphMode;
1768
+ $('legend-hive').hidden=graphMode!=='hive';
1769
+ $('legend-mentions').hidden=graphMode!=='mentions';
1770
+ scheduleGraph();
1771
+ }
981
1772
  function renderGraphTotal(events=timeline(),index=cursorIndex(events)) {
982
1773
  const live=cursor===null&&['working','queued'].includes(team.phase);
983
1774
  $('graph-total').textContent=events.length+' posts · '+graph.elapsedSpan(events.slice(0,index),{live})+
984
1775
  (cursor!==null?' · '+index+'/'+events.length:'');
985
1776
  }
1777
+ function graphPalette(stage) {
1778
+ const css=getComputedStyle(stage);
1779
+ const val=(prop,fallback)=>css.getPropertyValue(prop).trim()||fallback;
1780
+ const light=currentTheme()==='light';
1781
+ return {
1782
+ grid:val('--grid',light?'#eaedf2':'#242933'),
1783
+ link:val('--edge',light?'#9ba5b5':'#7c8698'),
1784
+ accent:val('--gold',light?'#8f5b10':'#f6c458'),
1785
+ gold:val('--gold-solid','#e5a024'),
1786
+ good:val('--good',light?'#247a3d':'#6fd89c'),
1787
+ goodSoft:light?'rgba(36, 122, 61, 0.08)':'rgba(111, 216, 156, 0.1)',
1788
+ purple:val('--purple',light?'#7c4dff':'#b39ddb'),
1789
+ bad:val('--bad',light?'#c4302b':'#ff8a80'),
1790
+ badSoft:light?'rgba(196, 48, 43, 0.08)':'rgba(255, 138, 128, 0.1)',
1791
+ wash:val('--wash',light?'#fdf4e2':'#2b2416'),
1792
+ paper:val('--surface',light?'#ffffff':'#181b21'),
1793
+ text:val('--ink',light?'#181c23':'#eef1f6'),
1794
+ muted:val('--muted',light?'#555e6d':'#a4adbd'),
1795
+ };
1796
+ }
1797
+
986
1798
  function renderGraph() {
987
1799
  const events=timeline();
988
1800
  const index=cursorIndex(events);
989
1801
  const current=events[index-1];
990
- const projection=graph.project(events,people(),current?.seq??0,{
991
- hideInactive:$('hide-inactive').checked,expandBroadcast:$('expand-all').checked,
1802
+ const roster=people();
1803
+ const mentionsProjection=graph.project(events,roster,current?.seq??0,{
1804
+ hideInactive:graphMode==='mentions'?$('hide-inactive').checked:false,
1805
+ expandBroadcast:graphMode==='mentions'?$('expand-all').checked:false,
992
1806
  });
993
1807
  renderGraphTotal(events,index);
994
1808
  $('replay').max=events.length;
@@ -1003,51 +1817,124 @@
1003
1817
  $('play').setAttribute('aria-label',playLabel);
1004
1818
  $('play').title=playLabel;
1005
1819
  $('live').setAttribute('aria-pressed',String(cursor===null));
1006
- $('broadcast-count').textContent=projection.broadcasts+' @all posts';
1820
+ $('broadcast-count').textContent=mentionsProjection.broadcasts+' @all posts';
1821
+
1822
+ $('graph-mode-hive').setAttribute('aria-pressed',String(graphMode==='hive'));
1823
+ $('graph-mode-mentions').setAttribute('aria-pressed',String(graphMode==='mentions'));
1824
+ $('mentions-options').hidden=graphMode!=='mentions';
1825
+ $('graph-stage').dataset.mode=graphMode;
1826
+ $('graph-legend').dataset.mode=graphMode;
1827
+ $('legend-hive').hidden=graphMode!=='hive';
1828
+ $('legend-mentions').hidden=graphMode!=='mentions';
1829
+
1007
1830
  const stage=$('graph-stage');
1008
- const minimum=graph.minimumHeight(projection.nodes.length,stage.clientWidth);
1009
- stage.style.height=minimum?minimum+'px':'';
1010
- const coordinates=graph.layout(projection.nodes,stage.clientWidth,stage.clientHeight);
1011
- if (focusedNode && !coordinates.has(focusedNode)) focusedNode=null;
1012
- const active=document.activeElement?.dataset.graphName;
1013
- $('graph-nodes').replaceChildren(...projection.nodes.map(member=>{
1014
- const point=coordinates.get(member.name);
1015
- const button=node('button','graph-node');
1016
- button.type='button';
1017
- button.style.left=point.x+'px';
1018
- button.style.top=point.y+'px';
1019
- button.dataset.graphName=member.name;
1020
- button.dataset.role=member.role??'worker';
1021
- button.dataset.status=member.status;
1022
- button.dataset.muted=String(!member.posts&&!projection.links.some(edge=>edge.to===member.name));
1023
- button.dataset.dimmed=String(Boolean(focusedNode&&focusedNode!==member.name&&
1024
- !projection.links.some(edge=>(edge.from===focusedNode&&edge.to===member.name)||(edge.to===focusedNode&&edge.from===member.name))));
1025
- button.dataset.unmentioned=String(graph.unmentionedNode(member));
1026
- button.title=author(member.name)+' · '+condition(member)+
1027
- (graph.unmentionedNode(member)?' · Posted with no mention':'');
1028
- button.setAttribute('aria-label',button.title);
1029
- button.setAttribute('aria-pressed',String(focusedNode===member.name));
1030
- const hex=node('span','hex');
1031
- hex.append(HiveBee.sprite(member.name,{coordinator:member.role==='coordinator',status:member.status,tint:member.tint}));
1032
- button.append(hex,node('span','node-label',author(member.name)));
1033
- if (member.broadcasts) button.append(node('span','node-broadcast','@all '+member.broadcasts));
1034
- button.onclick=()=>{
1035
- focusedNode=focusedNode===member.name?null:member.name;
1036
- scheduleGraph();
1831
+ const color=graphPalette(stage);
1832
+ const activeFocus=document.activeElement?.dataset.graphName;
1833
+ const projByName=new Map(mentionsProjection.nodes.map(item=>[item.name,item]));
1834
+ const isConnected=name=>!focusedNode||focusedNode===name||mentionsProjection.links.some(
1835
+ edge=>(edge.from===focusedNode&&edge.to===name)||(edge.to===focusedNode&&edge.from===name));
1836
+
1837
+ if (graphMode==='hive') {
1838
+ const hiveModel=(graph.projectHive??fallbackProjectHive)(events,roster,current?.seq??0);
1839
+ const minimum=(graph.hiveMinimumHeight??fallbackHiveMinimumHeight)(hiveModel.clusters.length,stage.clientWidth);
1840
+ stage.style.height=minimum?minimum+'px':'';
1841
+ const hiveLayout=(graph.layoutHive??fallbackLayoutHive)(hiveModel,stage.clientWidth,stage.clientHeight);
1842
+ if (focusedNode&&!roster.some(member=>member.name===focusedNode)) focusedNode=null;
1843
+ const buttons=[];
1844
+ const makeHiveButton=(member,x,y,isCoordinator,slotWidth)=>{
1845
+ const projNode=projByName.get(member.name)??member;
1846
+ const btn=node('button','graph-node graph-hive-bee');
1847
+ btn.type='button';
1848
+ btn.style.left=x+'px';
1849
+ btn.style.top=y+'px';
1850
+ if (Number.isFinite(slotWidth)&&slotWidth>0) btn.style.width=Math.max(46,Math.min(70,Math.floor(slotWidth)))+'px';
1851
+ btn.dataset.graphName=member.name;
1852
+ btn.dataset.role=isCoordinator?'coordinator':'worker';
1853
+ btn.dataset.status=member.status??'waiting';
1854
+ btn.dataset.muted=String(!projNode.posts&&!mentionsProjection.links.some(edge=>edge.to===member.name));
1855
+ btn.dataset.dimmed=String(!isConnected(member.name));
1856
+ btn.dataset.unmentioned=String(graph.unmentionedNode(projNode));
1857
+ const beeMuted=!isCoordinator&&['done','retired'].includes(member.status);
1858
+ btn.dataset.beeMuted=String(beeMuted);
1859
+ btn.title=author(member.name)+' · '+condition(member)+(graph.unmentionedNode(projNode)?' · Posted with no mention':'');
1860
+ btn.setAttribute('aria-label',btn.title);
1861
+ btn.setAttribute('aria-pressed',String(focusedNode===member.name));
1862
+ btn.append(beeSprite({...member,role:isCoordinator?'coordinator':'worker'},{muted:beeMuted}));
1863
+ if (!isCoordinator) btn.append(node('span','hive-bee-label',member.name));
1864
+ btn.onclick=()=>{
1865
+ focusedNode=focusedNode===member.name?null:member.name;
1866
+ scheduleGraph();
1867
+ };
1868
+ return btn;
1037
1869
  };
1038
- return button;
1039
- }));
1040
- if (active) [...$('graph-nodes').children].find(button=>button.dataset.graphName===active)?.focus({preventScroll:true});
1041
- const css=getComputedStyle(stage);
1042
- graph.draw($('graph-canvas'),projection,coordinates,focusedNode,current?.seq,{
1043
- grid:css.getPropertyValue('--grid'),link:css.getPropertyValue('--edge'),accent:css.getPropertyValue('--gold'),
1044
- paper:css.getPropertyValue('--surface'),text:css.getPropertyValue('--ink'),
1045
- });
1870
+ const coordMember=roster.find(member=>member.role==='coordinator')??{name:'coordinator',role:'coordinator',status:'waiting'};
1871
+ const coordSlot=hiveLayout.coordinator.slots?.[0];
1872
+ buttons.push(makeHiveButton(coordMember,coordSlot?.x??hiveLayout.coordinator.x,coordSlot?.y??(hiveLayout.coordinator.y-16),true));
1873
+ for (const cluster of hiveLayout.clusters) {
1874
+ for (const slot of cluster.slots) {
1875
+ buttons.push(makeHiveButton(slot.member,slot.x,slot.y,false,slot.slotWidth));
1876
+ }
1877
+ }
1878
+ $('graph-nodes').replaceChildren(...buttons);
1879
+ drawHiveCanvas($('graph-canvas'),hiveLayout,hiveModel.connectors,color);
1880
+ } else {
1881
+ const minimum=(graph.mentionsMinimumHeight??graph.minimumHeight)(mentionsProjection.nodes.length,stage.clientWidth);
1882
+ stage.style.height=minimum?minimum+'px':'';
1883
+ const coordinates=(graph.layoutMentions??fallbackLayoutMentions)(mentionsProjection.nodes,stage.clientWidth,stage.clientHeight);
1884
+ if (focusedNode&&!coordinates.has(focusedNode)) focusedNode=null;
1885
+ const narrow=stage.clientWidth<465;
1886
+ const pillBoxes=new Map();
1887
+ const pillButtons=mentionsProjection.nodes.map(member=>{
1888
+ const point=coordinates.get(member.name);
1889
+ pillBoxes.set(member.name,pillBoxFor(member,narrow));
1890
+ const btn=node('button','graph-node graph-pill-node');
1891
+ btn.type='button';
1892
+ btn.style.left=point.x+'px';
1893
+ btn.style.top=point.y+'px';
1894
+ btn.dataset.graphName=member.name;
1895
+ btn.dataset.role=member.role??'worker';
1896
+ btn.dataset.status=member.status??'observer';
1897
+ btn.dataset.muted=String(!member.posts&&!mentionsProjection.links.some(edge=>edge.to===member.name));
1898
+ btn.dataset.dimmed=String(!isConnected(member.name));
1899
+ btn.dataset.unmentioned=String(graph.unmentionedNode(member));
1900
+ const beeMuted=member.role!=='coordinator'&&['done','retired'].includes(member.status);
1901
+ btn.dataset.beeMuted=String(beeMuted);
1902
+ btn.title=author(member.name)+' · '+condition(member)+(graph.unmentionedNode(member)?' · Posted with no mention':'');
1903
+ btn.setAttribute('aria-label',btn.title);
1904
+ btn.setAttribute('aria-pressed',String(focusedNode===member.name));
1905
+ const dot=node('span','pill-dot');
1906
+ dot.setAttribute('aria-hidden','true');
1907
+ const label=member.name==='user'?'You':member.name==='system'?'System':member.name;
1908
+ btn.append(beeSprite(member,{muted:beeMuted}),node('span','pill-name',label),dot);
1909
+ if (member.broadcasts) btn.append(node('span','node-broadcast','@all '+member.broadcasts));
1910
+ btn.onclick=()=>{
1911
+ focusedNode=focusedNode===member.name?null:member.name;
1912
+ scheduleGraph();
1913
+ };
1914
+ return btn;
1915
+ });
1916
+ $('graph-nodes').replaceChildren(...pillButtons);
1917
+ for (const btn of pillButtons) {
1918
+ if (btn.offsetWidth>0&&btn.offsetHeight>0) {
1919
+ pillBoxes.set(btn.dataset.graphName,{halfW:btn.offsetWidth/2,halfH:btn.offsetHeight/2,offsetX:0,offsetY:0,radius:btn.offsetHeight/2});
1920
+ }
1921
+ }
1922
+ drawMentionsCanvas($('graph-canvas'),mentionsProjection,coordinates,pillBoxes,focusedNode,current?.seq,color);
1923
+ }
1924
+
1925
+ if (activeFocus) [...$('graph-nodes').children].find(button=>button.dataset.graphName===activeFocus)?.focus({preventScroll:true});
1926
+
1046
1927
  $('inspection-title').textContent=focusedNode?author(focusedNode):'Selected post';
1047
1928
  $('clear-node').hidden=!focusedNode;
1929
+ const focusedMember=focusedNode?roster.find(member=>member.name===focusedNode):null;
1930
+ const memberActions=$('graph-member-actions');
1931
+ memberActions.replaceChildren();
1932
+ const journal=focusedMember?transcriptButton(focusedMember):null;
1933
+ if (journal) memberActions.append(journal);
1934
+ memberActions.hidden=!memberActions.childElementCount;
1048
1935
  $('graph-post-author').textContent=current?author(current.author)+' · '+stamp(current):'';
1049
1936
  richText($('graph-post'),current?.text??'No post at this position yet.');
1050
- const links=projection.links.filter(edge=>!focusedNode||edge.from===focusedNode||edge.to===focusedNode)
1937
+ const links=mentionsProjection.links.filter(edge=>!focusedNode||edge.from===focusedNode||edge.to===focusedNode)
1051
1938
  .sort((a,b)=>b.count-a.count);
1052
1939
  $('edge-list').replaceChildren(...links.map(edge=>{
1053
1940
  const line=node('li');
@@ -1056,6 +1943,115 @@
1056
1943
  }));
1057
1944
  }
1058
1945
 
1946
+ /* Fallback GIF89a exporter when HiveGif is not yet merged */
1947
+ function fallbackEncodeSingleFrameGif(rgba,width,height) {
1948
+ const out=[0x47,0x49,0x46,0x38,0x39,0x61,width&255,(width>>8)&255,height&255,(height>>8)&255,0xF0,0,0];
1949
+ // 2-color table (theme paper & ink)
1950
+ out.push(0xFA,0xFA,0xFA,0x20,0x24,0x2C);
1951
+ // NETSCAPE2.0 infinite loop extension
1952
+ out.push(0x21,0xFF,0x0B,0x4E,0x45,0x54,0x53,0x43,0x41,0x50,0x45,0x32,0x2E,0x30,0x03,0x01,0,0,0);
1953
+ out.push(0x2C,0,0,0,0,width&255,(width>>8)&255,height&255,(height>>8)&255,0,2);
1954
+ const total=width*height;
1955
+ const idx=new Uint8Array(total);
1956
+ for (let i=0;i<total;i++) {
1957
+ const lum=(rgba[i*4]*299+rgba[i*4+1]*587+rgba[i*4+2]*114)/1000;
1958
+ idx[i]=lum<128?1:0;
1959
+ }
1960
+ const bytes=[];
1961
+ let bitBuf=0,bitCount=0;
1962
+ const emit=(code,bits)=>{
1963
+ bitBuf|=code<<bitCount;
1964
+ bitCount+=bits;
1965
+ while (bitCount>=8) {bytes.push(bitBuf&255);bitBuf>>=8;bitCount-=8;}
1966
+ };
1967
+ emit(4,3);
1968
+ for (let i=0;i<total;i++) {
1969
+ emit(idx[i],3);
1970
+ if (i%120===119) emit(4,3);
1971
+ }
1972
+ emit(5,3);
1973
+ if (bitCount>0) bytes.push(bitBuf&255);
1974
+ for (let i=0;i<bytes.length;i+=255) {
1975
+ const chunk=bytes.slice(i,i+255);
1976
+ out.push(chunk.length,...chunk);
1977
+ }
1978
+ out.push(0,0x3B);
1979
+ return new Uint8Array(out);
1980
+ }
1981
+ function fallbackExportGraphReplayGif(opts) {
1982
+ const width=Math.max(320,Math.min(960,Math.round(opts.width||680)));
1983
+ const height=Math.max(240,Math.min(720,Math.round(opts.height||460)));
1984
+ const canvas=document.createElement('canvas');
1985
+ canvas.width=width;
1986
+ canvas.height=height;
1987
+ const ctx=canvas.getContext('2d');
1988
+ if (ctx) {
1989
+ if (typeof graph.renderGraphFrame==='function') graph.renderGraphFrame(ctx,{...opts,width,height});
1990
+ else {
1991
+ ctx.fillStyle=opts.theme==='light'?'#f9fafc':'#15181e';
1992
+ ctx.fillRect?.(0,0,width,height);
1993
+ const stageCanvas=$('graph-canvas');
1994
+ if (stageCanvas?.width&&stageCanvas?.height) ctx.drawImage?.(stageCanvas,0,0,width,height);
1995
+ }
1996
+ }
1997
+ const rgba=ctx?.getImageData?.(0,0,width,height)?.data??new Uint8ClampedArray(width*height*4);
1998
+ const bytes=fallbackEncodeSingleFrameGif(rgba,width,height);
1999
+ const blob=typeof Blob!=='undefined'?new Blob([bytes],{type:'image/gif'}):undefined;
2000
+ return {bytes,blob,frameCount:1,width,height};
2001
+ }
2002
+ function teamSlug() {
2003
+ const slug=String(team?.title??team?.id??'swarm').toLowerCase()
2004
+ .replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,48);
2005
+ return slug||'swarm';
2006
+ }
2007
+ async function exportGif() {
2008
+ if (!team||exportingGif) return;
2009
+ const btn=$('export-gif');
2010
+ exportingGif=true;
2011
+ btn.disabled=true;
2012
+ notice('Exporting '+graphMode+' GIF…');
2013
+ try {
2014
+ const stage=$('graph-stage');
2015
+ const events=timeline();
2016
+ const exporter=globalThis.HiveGif?.exportGraphReplayGif??fallbackExportGraphReplayGif;
2017
+ const result=await exporter({
2018
+ mode:graphMode,
2019
+ posts:events,
2020
+ members:people(),
2021
+ phase:team.phase??(team.paused?'paused':'working'),
2022
+ pacing:$('pacing').value,
2023
+ speed:Number($('speed').value),
2024
+ hideInactive:$('hide-inactive').checked,
2025
+ expandBroadcast:$('expand-all').checked,
2026
+ focus:focusedNode,
2027
+ theme:currentTheme(),
2028
+ width:Math.max(480,stage.clientWidth||680),
2029
+ height:Math.max(360,stage.clientHeight||460),
2030
+ graph,
2031
+ bees:globalThis.HiveBee,
2032
+ });
2033
+ const blob=result?.blob??(typeof Blob!=='undefined'&&result?.bytes?new Blob([result.bytes],{type:'image/gif'}):null);
2034
+ const filename=teamSlug()+'-graph.gif';
2035
+ if (blob&&typeof URL.createObjectURL==='function') {
2036
+ const href=URL.createObjectURL(blob);
2037
+ const link=node('a');
2038
+ link.href=href;
2039
+ link.download=filename;
2040
+ link.style.display='none';
2041
+ document.body?.append?.(link);
2042
+ link.click?.();
2043
+ link.remove?.();
2044
+ setTimeout(()=>URL.revokeObjectURL?.(href),1500);
2045
+ }
2046
+ notice('Exported '+filename+' ('+(result?.frameCount??1)+' frames).');
2047
+ } catch (error) {
2048
+ notice(error?.message||'Could not export GIF.',true);
2049
+ } finally {
2050
+ exportingGif=false;
2051
+ btn.disabled=false;
2052
+ }
2053
+ }
2054
+
1059
2055
  function selectTab(name,focus=false) {
1060
2056
  if (name!==activeTab) stopPlayback();
1061
2057
  if (name==='members'&&activeTab!==name) memberKey='';
@@ -1067,7 +2063,7 @@
1067
2063
  $('panel-'+tab).hidden=!selected||!team;
1068
2064
  }
1069
2065
  render();
1070
- $('tab-'+name).scrollIntoView?.({block:'nearest',inline:'nearest'});
2066
+ $('tab-'+name).scrollIntoView?.({block:'nearest',inline:'nearest',container:'nearest'});
1071
2067
  if (focus) $('tab-'+name).focus();
1072
2068
  }
1073
2069
 
@@ -1186,25 +2182,79 @@
1186
2182
  $('theme').firstElementChild.textContent=theme==='dark'?'☀':'☾';
1187
2183
  scheduleGraph();
1188
2184
  }
2185
+ const colorSchemeQuery=matchMedia('(prefers-color-scheme: dark)');
1189
2186
  function initialTheme() {
1190
2187
  try {
1191
2188
  const saved=localStorage.getItem('team-board-color');
1192
2189
  if (saved==='light'||saved==='dark') return saved;
1193
2190
  } catch {}
1194
- return matchMedia('(prefers-color-scheme:light)').matches?'light':'dark';
2191
+ return colorSchemeQuery.matches?'dark':'light';
2192
+ }
2193
+ function attachLightDismiss(dialog,closeFn) {
2194
+ if (!dialog||typeof dialog.addEventListener!=='function') return;
2195
+ if (globalThis.HTMLDialogElement && 'closedBy' in globalThis.HTMLDialogElement.prototype) return;
2196
+ const outside=(event)=>{
2197
+ const rect=dialog.getBoundingClientRect?.();
2198
+ if (!rect) return false;
2199
+ return event.clientX<rect.left||event.clientX>rect.right||event.clientY<rect.top||event.clientY>rect.bottom;
2200
+ };
2201
+ let pressedOutside=false;
2202
+ dialog.addEventListener('pointerdown',event=>{pressedOutside=outside(event);});
2203
+ dialog.addEventListener('pointerup',event=>{if (pressedOutside&&outside(event)) closeFn();});
1195
2204
  }
1196
2205
 
1197
2206
  $('brand-bee').append(HiveBee.sprite('coordinator',{coordinator:true}));
2207
+ renderVersionTag();
2208
+ $('update-popover').hidden=true;
2209
+ $('update-wrap').hidden=true;
2210
+ $('update-pill').onclick=event=>{
2211
+ event?.stopPropagation?.();
2212
+ updateOpen=!updateOpen;
2213
+ renderUpdateBadge();
2214
+ };
2215
+ $('update-copy').onclick=async()=>{
2216
+ const btn=$('update-copy');
2217
+ try {await globalThis.navigator?.clipboard?.writeText?.(CODEX_UPDATE_CMD);} catch {}
2218
+ btn.textContent='Copied';
2219
+ setTimeout(()=>{if (btn) btn.textContent='Copy command';},1800);
2220
+ };
2221
+ $('update-dismiss').onclick=()=>{
2222
+ const latest=typeof updateInfo?.latest==='string'?updateInfo.latest.trim():'';
2223
+ if (latest) {
2224
+ try {globalThis.localStorage?.setItem?.(DISMISSED_UPDATE_KEY,latest);} catch {}
2225
+ }
2226
+ updateOpen=false;
2227
+ renderUpdateBadge();
2228
+ };
2229
+ $('update-link').onclick=event=>{
2230
+ if (!standalone) {
2231
+ event?.preventDefault?.();
2232
+ rpc('ui/open-link',{url:$('update-link').href}).catch(error=>notice(error.message,true));
2233
+ }
2234
+ };
2235
+ document.addEventListener?.('click',event=>{
2236
+ if (!updateOpen) return;
2237
+ const wrap=$('update-wrap');
2238
+ if (typeof wrap.contains==='function'&&wrap.contains(event?.target)) return;
2239
+ updateOpen=false;
2240
+ renderUpdateBadge();
2241
+ });
2242
+ document.addEventListener?.('keydown',event=>{
2243
+ if (event?.key==='Escape'&&updateOpen) {
2244
+ updateOpen=false;
2245
+ renderUpdateBadge();
2246
+ $('update-pill')?.focus?.();
2247
+ }
2248
+ });
1198
2249
  $('theme').onclick=()=>{
1199
2250
  const theme=document.documentElement.dataset.theme==='dark'?'light':'dark';
1200
2251
  setTheme(theme);
1201
2252
  try {localStorage.setItem('team-board-color',theme);} catch {}
1202
2253
  };
1203
2254
  setTheme(initialTheme());
1204
- const colorSchemeQuery=matchMedia('(prefers-color-scheme:light)');
1205
2255
  colorSchemeQuery.addEventListener?.('change',event=>{
1206
2256
  try {if (localStorage.getItem('team-board-color')) return;} catch {}
1207
- setTheme(event.matches?'light':'dark');
2257
+ setTheme(event.matches?'dark':'light');
1208
2258
  });
1209
2259
  for (const [index,name] of tabs.entries()) {
1210
2260
  const tab=$('tab-'+name);
@@ -1220,12 +2270,32 @@
1220
2270
  $('search-posts').oninput=()=>renderFeed();
1221
2271
  $('member-filter').onchange=()=>renderFeed();
1222
2272
  $('channel-filter').onchange=()=>renderFeed();
2273
+ $('board-filters').hidden=true;
2274
+ $('toggle-board-filters').onclick=()=>{
2275
+ const drawer=$('board-filters');
2276
+ const opening=Boolean(drawer.hidden);
2277
+ drawer.hidden=!opening;
2278
+ $('toggle-board-filters').setAttribute('aria-expanded',String(opening));
2279
+ };
1223
2280
  $('search-members').oninput=()=>renderMembers();
1224
2281
  $('follow').onclick=()=>{
1225
2282
  following=!following;
1226
2283
  $('follow').setAttribute('aria-pressed',String(following));
1227
2284
  renderFeed();
1228
2285
  };
2286
+ $('board-latest').onclick=()=>{
2287
+ following=true;
2288
+ $('follow').setAttribute('aria-pressed','true');
2289
+ const feed=$('feed');
2290
+ feed.scrollTop=feed.scrollHeight;
2291
+ $('board-latest').hidden=true;
2292
+ renderFeed();
2293
+ };
2294
+ $('feed').onscroll=()=>{
2295
+ const feed=$('feed');
2296
+ const away=(feed.scrollHeight-feed.scrollTop-feed.clientHeight)>48;
2297
+ $('board-latest').hidden=(!away&&following)||!feed.children?.length;
2298
+ };
1229
2299
  $('compose').onsubmit=async event=>{
1230
2300
  event.preventDefault();
1231
2301
  const text=$('message').value.trim();
@@ -1257,6 +2327,12 @@
1257
2327
  finally {extendingBudget=false;button.disabled=false;$('extra-turns').disabled=false;}
1258
2328
  }
1259
2329
  $('extra-turns').onclick=event=>{if (event.isTrusted) return extendBudget($('extra-turns'));};
2330
+ $('close-lightbox').onclick=closeLightbox;
2331
+ $('screenshot-lightbox').oncancel=event=>{
2332
+ event.preventDefault();
2333
+ closeLightbox();
2334
+ };
2335
+ attachLightDismiss($('screenshot-lightbox'),closeLightbox);
1260
2336
  if (standalone) {
1261
2337
  $('close-transcript').onclick=closeTranscript;
1262
2338
  $('refresh-transcript').onclick=refreshTranscript;
@@ -1264,6 +2340,7 @@
1264
2340
  event.preventDefault();
1265
2341
  closeTranscript();
1266
2342
  };
2343
+ attachLightDismiss($('member-transcript'),closeTranscript);
1267
2344
  const select=$('recent-teams');
1268
2345
  select.onfocus=loadRecentTeams;
1269
2346
  select.onchange=()=>{
@@ -1313,7 +2390,10 @@
1313
2390
  nextTick();
1314
2391
  };
1315
2392
  $('clear-node').onclick=()=>{focusedNode=null;scheduleGraph();};
2393
+ $('graph-mode-hive').onclick=()=>setGraphMode('hive');
2394
+ $('graph-mode-mentions').onclick=()=>setGraphMode('mentions');
1316
2395
  $('hide-inactive').onchange=$('expand-all').onchange=scheduleGraph;
2396
+ $('export-gif').onclick=exportGif;
1317
2397
  const observer=new ResizeObserver(scheduleGraph);
1318
2398
  observer.observe($('graph-stage'));
1319
2399
  function refreshLanding() {
@@ -1325,6 +2405,7 @@
1325
2405
  refresh();
1326
2406
  scheduleGraph();
1327
2407
  });
2408
+ if (standalone) void checkForUpdate();
1328
2409
  if (emptyPanel) {
1329
2410
  $('title').textContent='Swarm';
1330
2411
  $('meta').textContent='No swarms to display yet.';
@@ -1356,7 +2437,7 @@
1356
2437
  }
1357
2438
  });
1358
2439
  rpc('ui/initialize',{
1359
- appInfo:{name:'Hive Swarm',version:globalThis.__HIVE_SWARM_VERSION__||'1.9.0'},appCapabilities:{},protocolVersion:'2026-01-26',
2440
+ appInfo:{name:'Hive Swarm',version:globalThis.__HIVE_SWARM_VERSION__||'2.1.1'},appCapabilities:{},protocolVersion:'2026-01-26',
1360
2441
  }).then(()=>{
1361
2442
  parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized',params:{}},'*');
1362
2443
  refresh();