@double_geste/agent-standup 1.31.0 → 1.33.0

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/public/index.html CHANGED
@@ -41,7 +41,7 @@
41
41
  @media (min-width:1081px) { header .brand { min-width:150px } #pill { flex-shrink:20 } .tok, .ctxp { flex-shrink:0 } } /* wide: a long status gives way before the name and the counters */
42
42
  /* several sessions at once (live): the sessions of the moment as tabs under the header, the one the call is in among them, each with its state; and a visitor from another session that needs you, who takes you there on a click */
43
43
  #tabs { display:none; flex:none; align-items:center; gap:5px; padding:4px 10px; border-bottom:1px solid var(--line); overflow-x:auto; scrollbar-width:none } #tabs::-webkit-scrollbar { display:none } #tabs:not(:empty) { display:flex }
44
- .stab { flex:0 1 auto; min-width:92px; max-width:190px; display:flex; align-items:center; gap:5px; padding:2px 9px; border-radius:99px; border:1px solid var(--line); color:var(--dim); font-size:11.5px; line-height:1.5; white-space:nowrap } .stab span { overflow:hidden; text-overflow:ellipsis } .stab:hover { color:var(--text); border-color:var(--accent) }
44
+ .stab { flex:0 1 auto; min-width:92px; max-width:190px; display:flex; align-items:center; gap:5px; padding:2px 9px; border-radius:99px; border:1px solid var(--line); color:var(--dim); font-size:11.5px; line-height:1.5; white-space:nowrap } .stab span { overflow:hidden; text-overflow:ellipsis } .stab i { flex:none; font-style:normal; font-size:9px; font-weight:700; letter-spacing:.05em; text-transform:uppercase; padding:0 5px; border-radius:99px; border:1px solid currentColor; opacity:.85 } .stab:hover { color:var(--text); border-color:var(--accent) }
45
45
  .stab.on { flex-shrink:0; max-width:min(320px,62vw); background:var(--panel2); color:var(--text); font-weight:600; border-color:var(--accent) } .stab.turn:not(.on) { color:var(--accent) } .stab.blocked:not(.on) { color:#fff; background:#c0392b; border-color:#ff8a80; font-weight:600 } .stab.all { flex:none; min-width:0; padding:2px 8px } /* a narrow panel: the tabs keep a readable width and the row scrolls */
46
46
  #visit { position:absolute; right:12px; bottom:14px; z-index:6; display:none; align-items:flex-end; gap:8px; max-width:min(380px,calc(100% - 24px)); cursor:pointer } #visit.on { display:flex; animation:visit .45s cubic-bezier(.2,1.3,.4,1) } @keyframes visit { from { transform:translateX(120%) } } body.react #visit { bottom:140px }
47
47
  #visit .vsay { position:relative; min-width:0; background:#fff; color:#1b1d27; border-radius:11px 11px 2px 11px; padding:7px 10px; font-size:12.5px; line-height:1.35; box-shadow:0 4px 14px rgba(0,0,0,.4); overflow-wrap:anywhere } #visit .vsay small { display:block; color:#5a6072; font-size:11px; margin-bottom:2px } #visit .vgo { display:inline-block; margin-top:5px; padding:1px 10px; border-radius:99px; background:var(--accent); color:#0b1020; font-weight:600; font-size:11.5px }
@@ -78,7 +78,12 @@
78
78
  .bcard { text-align:left; background:var(--panel2); border:1px solid var(--line); border-radius:12px; padding:11px 13px; display:flex; flex-direction:column; gap:5px; cursor:pointer }
79
79
  .bcard:hover { border-color:var(--accent) } .bcard.blocked { border-color:#ff5252; box-shadow:0 0 0 2px rgba(255,82,82,.25) } .bcard.working { border-color:rgba(240,160,32,.7) } .bcard.waiting { border-color:rgba(110,190,255,.8) } .bcard.idle { opacity:.8 }
80
80
  .bcard .bt { font-weight:600; font-size:13.5px; overflow:hidden; text-overflow:ellipsis; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical } .bcard .bp, .bcard .bm { color:var(--dim); font-size:11.5px }
81
- .bcard .stc { align-self:flex-start }
81
+ .bcard .stc { align-self:flex-start } .bcard .bh { display:flex; align-items:center; gap:6px; min-width:0 } .bcard .bh .stc { overflow:hidden; text-overflow:ellipsis }
82
+ .bcard .bq { font-size:12.5px; color:var(--text); border-left:2px solid #ff5252; padding-left:8px; overflow:hidden; display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical }
83
+ .bsec { margin-bottom:18px } .bhd { display:flex; align-items:center; gap:7px; margin:0 0 9px; font-size:12.5px; font-weight:700; color:var(--dim) } .bhd.blocked { color:#ff8a80 } .bhd.turn { color:var(--text) }
84
+ .bhd .bl { display:inline-block } .bhd .bl::first-letter { text-transform:uppercase } .bhd i { font-style:normal; font-weight:600; font-size:11.5px; padding:0 7px; border-radius:99px; background:var(--panel2); border:1px solid var(--line) }
85
+ .bdone summary { cursor:pointer; list-style:none } .bdone summary::-webkit-details-marker { display:none } .bdone summary::after { content:'▸' } .bdone[open] summary::after { content:'▾' } .bdone .bcard { opacity:.7 }
86
+ .bdo, .bpr { flex:none; font:inherit; font-size:11.5px; line-height:1.5; color:var(--dim); background:none; border:1px solid var(--line); border-radius:99px; padding:0 8px; cursor:pointer } .bh .stc + .bpr, .bh .stc + .bdo { margin-left:auto } .bdo:hover, .bpr:hover, .bdo:focus-visible, .bpr:focus-visible { color:var(--text); border-color:var(--accent) }
82
87
  .stc { font-size:11.5px; padding:2px 9px; border-radius:99px; background:rgba(14,15,24,.6); white-space:nowrap } .stc.working { color:var(--gold) } .stc.waiting { color:#8fd3ff } .stc.blocked { color:#fff; background:#c0392b; font-weight:700 } .stc.stalled { color:#1b1d27; background:#ffb347; font-weight:700 } .stc.done, .stc.turn { color:var(--ok) } .stc.idle { color:var(--dim) }
83
88
  .ctxp { font-size:11px; font-weight:600; padding:3px 9px; border-radius:99px; background:var(--panel2); white-space:nowrap; cursor:default } .ctxp.lo, .cx.lo { color:#7ee2a8 } .ctxp.mid, .cx.mid { color:#ffc857 } .ctxp.hi, .cx.hi { color:#fff; background:#c0392b }
84
89
  .cx:empty { display:none } .tag .cx { font-size:10px }
@@ -117,6 +122,16 @@
117
122
  .pbar .r { background:#ff5f57 } .pbar .y { background:#febc2e } .pbar .g { background:#28c840 } #ptitle { margin:0 0 0 14px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; min-width:0 }
118
123
  #pbody { flex:1; overflow:hidden; padding:10px 14px; font:12.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace; color:#d6dae6 } .pwin.editor #pbody { background:#1a1b26; padding:0 }
119
124
  .pwin.image #pbody { display:flex; gap:8px; align-items:center; justify-content:center; background:#0b0c11; padding:8px } .pwin.image #pbody img { flex:0 1 auto; min-width:0; max-width:100%; max-height:100%; object-fit:contain; border-radius:4px } .pmore { color:#9aa0b4; font-size:12px } .dimg { display:block; max-width:100%; border-radius:6px; margin:4px 0 }
125
+ /* an artifact (a page the session published on claude.ai) on the shared screen: a browser window, with the page in a frame. Shared, it is shown whole and small, as a screen is; pinned (a click on it, or on its name in the line of files) it takes the room and can be read and used */
126
+ .pwin.web { flex-basis:1100px } .pwin.web #pbody { display:flex; flex-direction:column; padding:0; background:#0b0c11; font:12px -apple-system,system-ui,sans-serif }
127
+ .pnav { flex:none; display:flex; align-items:center; gap:6px; padding:5px 8px; background:#161925; border-bottom:1px solid #232637 } .pnn { flex:none; color:#8b95b0; font-size:11px }
128
+ .purl { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; background:#0d1117; border:1px solid #2a2d3d; border-radius:99px; padding:2px 12px; color:#9aa0b4; font-size:11.5px }
129
+ .pnb { flex:none; padding:2px 9px; border-radius:6px; border:1px solid #2a2d3d; background:#1c1f2b; color:#d6dae6; font-size:11.5px; white-space:nowrap } .pnb:hover { border-color:var(--accent) } .pnb.lib { border-color:rgba(240,160,32,.6); color:#ffd24a }
130
+ .pweb { flex:1; min-height:0; position:relative; overflow:hidden; background:#fff } .pweb iframe { position:absolute; left:0; top:0; border:0; width:calc(100% / var(--z,1)); height:calc(100% / var(--z,1)); transform:scale(var(--z,1)); transform-origin:0 0; background:#fff }
131
+ .pzoom { position:absolute; inset:0; width:100%; cursor:zoom-in }
132
+ .pcard { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:7px; padding:14px; text-align:center; background:#0d1117; color:#d6dae6 } .pcard i { font-style:normal; font-size:30px } .pcard b { font-size:16px } .pcard p { margin:0; max-width:520px; color:#9aa0b4; font-size:12.5px } .pcard em { font-style:normal; color:#6b7089; font-size:11.5px }
133
+ #present.pin { height:clamp(240px,74vh,1000px) } #present.pin #pcam, #present.pin #pcap, #present.pin #pbadge { display:none } #present:has(.pwin.web) #pcam { width:110px; height:82px }
134
+ body.narrow #present.pin { height:clamp(220px,70vh,900px) } #present.pin:has(.pcard), body.narrow #present.pin:has(.pcard) { height:clamp(190px,34vh,300px) } /* nothing to read there but a title and a link */
120
135
  .ptab { display:flex; align-items:center; gap:10px; background:#16161e; padding:5px 12px; border-bottom:1px solid #2a2b3d; font:11.5px -apple-system,system-ui,sans-serif } .ptab span { background:#1a1b26; padding:3px 10px; border-radius:6px 6px 0 0; color:#e9eaf0 } .ptab em { color:#6b7089; font-style:normal }
121
136
  .ln { display:flex; gap:10px; padding:0 12px; white-space:pre-wrap; word-break:break-all } .ln b { width:12px; flex:none; color:#7a7f98; font-weight:400 } .ln.add { background:rgba(63,185,80,.16); color:#9be9a8 } .ln.del { background:rgba(248,81,73,.16); color:#ffa198 }
122
137
  .tl { white-space:pre-wrap; word-break:break-word } .tl .ps { color:#7ee787 } .tl.cmd { color:#e6edf3 } .tl.tool { color:#8b95b0 } .dotg { color:#58a6ff }
@@ -188,13 +203,15 @@
188
203
  .ticker.on { display:block } .ticker i { font-style:normal; color:#ffd24a } .ticker.flash { animation:flash .25s } @keyframes flash { from { background:#3b5bdb } }
189
204
  /* character animation: all state-driven from the tile's classes */
190
205
  .fig { transform-origin:50px 76px; animation:bob 4.4s ease-in-out infinite; animation-delay:var(--d,0s) } @keyframes bob { 50% { transform:translateY(-.9px) } }
191
- .tile.speaking .fig { animation:talk .46s ease-in-out infinite } @keyframes talk { 50% { transform:scale(1.025,.985) translateY(-.5px) } }
206
+ .tile.speaking .fig { animation:talk .46s ease-in-out infinite } .tile.speaking .fig.still { animation:bob 4.4s ease-in-out infinite; animation-delay:var(--d,0s) } /* a character with a head of its own: the body does not squash, the head nods */
207
+ .chead { transform-origin:50px 44px } .tile.speaking .chead, #pcam.speaking .chead { animation:nod .6s ease-in-out infinite } @keyframes nod { 35% { transform:rotate(-.25deg) translateY(-.18px) } 75% { transform:rotate(.15deg) } } /* very light: the mouth does the talking */ @keyframes talk { 50% { transform:scale(1.025,.985) translateY(-.5px) } }
192
208
  .tile.vanishing { pointer-events:none; z-index:3; animation:vanish 1.2s cubic-bezier(.45,0,.75,.35) forwards }
193
209
  @keyframes vanish { 0% { filter:none; transform:none; opacity:1 } 16% { filter:brightness(1.7) saturate(1.5); transform:scale(1.05) } 55% { filter:brightness(2.3) blur(1.5px); transform:scale(.88) rotate(-3deg); opacity:.85 } 100% { filter:brightness(3.4) blur(11px); transform:scale(.12) rotate(11deg); opacity:0 } }
194
210
  .tile.vanishing::after { content:''; position:absolute; inset:0; background:radial-gradient(circle,#fff 0,rgba(255,255,255,0) 68%); opacity:0; animation:flash2 .7s ease-out .15s }
195
211
  @keyframes flash2 { 40% { opacity:.9 } }
196
212
  .puff { position:fixed; left:0; top:0; z-index:9; pointer-events:none; border-radius:50% }
197
213
  #toasts { position:absolute; left:12px; bottom:12px; z-index:6; display:flex; flex-direction:column; gap:6px; pointer-events:none }
214
+ .toast.offer { pointer-events:auto; animation:none; display:flex; align-items:center; gap:8px; padding:4px 6px 4px 12px; order:9 } .toast.offer .btn { padding:3px 10px; font-size:12px; white-space:nowrap } .toast.offer .ic { font-size:11px; padding:2px 6px } /* the offer of the real voices: stays until answered, under the passing toasts */
198
215
  .toast { background:rgba(27,29,39,.92); border:1px solid var(--line); border-radius:99px; padding:5px 12px; font-size:12px; animation:toast 3s ease forwards } @keyframes toast { 0% { opacity:0; transform:translateY(6px) } 10%, 80% { opacity:1; transform:none } 100% { opacity:0 } }
199
216
  .eye { transform-box:fill-box; transform-origin:center; animation:blink 4.6s infinite; animation-delay:var(--d,0s) } @keyframes blink { 0%,94%,100% { transform:scaleY(1) } 97% { transform:scaleY(.08) } }
200
217
  .brow { transform-box:fill-box; transform-origin:center; transition:transform .25s } .tile.speaking .brow { animation:brow .7s ease-in-out infinite } @keyframes brow { 50% { transform:translateY(-1.1px) } }
@@ -203,7 +220,9 @@
203
220
  .tile.working .arm { display:none } .tile .laptop, .tile .hands, .tile .sparks, .tile .grin, .tile .eyes-happy, .tile .mouth { display:none }
204
221
  .tile.working .laptop, .tile.working .hands, .tile.done .sparks, .tile.done .eyes-happy { display:inline } .tile.done .eyes-open { display:none }
205
222
  .tile.speaking .mouth { display:inline } .tile.speaking .smile, .tile.speaking .grin { display:none } .tile.done:not(.speaking) .smile { display:none } .tile.done:not(.speaking) .grin { display:inline }
206
- .hand { animation:type .34s ease-in-out infinite } .hand.r { animation-delay:-.17s } @keyframes type { 50% { transform:translateY(-1.3px) } }
223
+ .hand { animation:type .34s ease-in-out infinite } .hand.r { animation-delay:-.17s } .tile.working .chand { animation:type .34s ease-in-out infinite } .tile.working .chand.r { animation-delay:-.17s }
224
+ .claptop { display:none } .claptop.on, .tile.lap .claptop { display:inline } .tile.lap .claptop { animation:lapin .5s cubic-bezier(.2,.8,.3,1) } .tile.lapout .claptop { animation:lapout .45s ease-in forwards } /* a laptop pulled out from under the desk, and put away */
225
+ @keyframes lapin { from { transform:translateY(16px) } } @keyframes lapout { to { transform:translateY(18px) } } @keyframes type { 50% { transform:translateY(-1.3px) } }
207
226
  .tw { animation:tw 3.2s ease-in-out infinite } .pulse { animation:tw 1.7s ease-in-out infinite } @keyframes tw { 50% { opacity:.25 } }
208
227
  .drift { animation:drift 24s ease-in-out infinite alternate } @keyframes drift { to { transform:translateX(9px) } }
209
228
  .steam { animation:steam 2.6s ease-in-out infinite } @keyframes steam { 50% { transform:translateY(-1.4px); opacity:.25 } }
@@ -215,6 +234,7 @@
215
234
  /* ---------- overlays ---------- */
216
235
  #gate, #empty { position:absolute; inset:0; z-index:4; display:none; flex-direction:column; align-items:center; justify-content:center; gap:14px; text-align:center; padding:24px; background:rgba(18,19,26,.82); backdrop-filter:blur(3px) }
217
236
  #gate.on, #empty.on { display:flex } #empty { background:var(--bg) } #empty.on ~ #gate { display:none } /* no session at all: nothing to join, the empty state and its demo button are what there is to see */
237
+ body:has(#gate.on) .toast.offer, body:has(#empty.on) .toast.offer { display:none !important } /* the lines that offer something wait for the call: over the join screen of a small panel they covered its button, and the click fell on theirs */
218
238
  #gate h2, #empty h2 { margin:0; font:800 22px "Comic Sans MS","Chalkboard SE",system-ui,sans-serif } #gate p, #empty p { margin:0; color:var(--dim); max-width:380px } #eP b { color:var(--text) }
219
239
  .cta { background:var(--accent); color:#0b1020; font-weight:700; padding:10px 22px; border-radius:99px; font-size:14px } .cta:hover { filter:brightness(1.1) } .cta:empty { display:none }
220
240
  .btn { background:var(--panel2); border:1px solid var(--line); padding:6px 12px; border-radius:8px } .btn:hover { border-color:var(--accent) }
@@ -239,14 +259,14 @@
239
259
  body.compact #stage .tile .prop { top:2px; left:34px; right:auto; font-size:16px }
240
260
  body.compact #stage .tile .status:empty { display:none }
241
261
  body.compact #stage .tile .tag { order:1 } body.compact #stage .tile .status { order:2 } body.compact #stage .tile .prop { order:3 }
242
- @media (max-width:899px) { #menu .mi[data-t=roster] { display:none } } /* the agents list only exists from 900 px: no switch for it under that */
262
+ @media (max-width:899px) { :is(#menu,#prefs) .mi[data-t=roster] { display:none } } /* the agents list only exists from 900 px: no switch for it under that */
243
263
  body.tiny #present { display:none !important } body.tiny #hl { display:none } body.tiny #gantt { display:none } /* under 300 px: the rows only */
244
- #menu.on { display:block } #menu h4 { margin:8px 10px 4px; font-size:10.5px; letter-spacing:.08em; text-transform:uppercase; color:var(--dim); font-weight:600 }
264
+ #menu.on { display:block } :is(#menu,#prefs) h4 { margin:8px 10px 4px; font-size:10.5px; letter-spacing:.08em; text-transform:uppercase; color:var(--dim); font-weight:600 }
245
265
  .mi { display:flex; align-items:center; justify-content:space-between; gap:10px; width:100%; text-align:left; padding:8px 10px; border-radius:8px } .mi:hover { background:var(--panel2) }
246
266
  .sw { width:30px; height:17px; border-radius:99px; background:#3a3e50; position:relative; flex:none; transition:background .15s } .sw::after { content:''; position:absolute; top:2px; left:2px; width:13px; height:13px; border-radius:50%; background:#fff; transition:transform .15s }
247
267
  .sw.on { background:var(--accent) } .sw.on::after { transform:translateX(13px) }
248
- #menu select { width:100%; background:var(--panel2); border:1px solid var(--line); border-radius:8px; padding:6px 8px; margin:2px 0 6px } #menu .box { padding:0 10px }
249
- #menu .hint { font-size:11.5px; color:#ffb347; padding:0 10px 6px }
268
+ :is(#menu,#prefs) select { width:100%; background:var(--panel2); border:1px solid var(--line); border-radius:8px; padding:6px 8px; margin:2px 0 6px } :is(#menu,#prefs) .box { padding:0 10px }
269
+ :is(#menu,#prefs) .hint { font-size:11.5px; color:#ffb347; padding:0 10px 6px }
250
270
  #card { position:fixed; inset:0; z-index:20; display:none; align-items:center; justify-content:center; text-align:center; background:radial-gradient(circle at 50% 40%,#2a3a66,#05060c); color:#fff }
251
271
  #card.on { display:flex; animation:fadein .4s } @keyframes fadein { from { opacity:0 } }
252
272
  #card h1 { font:900 clamp(34px,8vw,90px)/1 "Comic Sans MS","Chalkboard SE",sans-serif; margin:0; text-shadow:4px 4px 0 #d8372b, 8px 8px 0 #111 } #card p { font-size:clamp(14px,2.2vw,24px); color:#cdd6f4; max-width:70vw; margin:16px auto 0 }
@@ -254,8 +274,20 @@
254
274
  #detail.on { display:flex } #detail .hd { display:flex; justify-content:space-between; align-items:center; padding:10px 14px; border-bottom:1px solid var(--line) }
255
275
  #dbody { overflow:auto; padding:6px 14px 14px } #dbody h3 { margin:14px 0 4px; font-size:10.5px; text-transform:uppercase; letter-spacing:.08em; color:var(--dim) }
256
276
  #dbody pre { white-space:pre-wrap; word-break:break-word; background:var(--bg); padding:8px; border-radius:6px; margin:0; font:11.5px/1.4 ui-monospace,Menlo,monospace }
277
+ #prefs { position:fixed; inset:0; z-index:16; display:none; align-items:flex-start; justify-content:center; padding:7vh 14px 14px; background:rgba(5,6,12,.72) } #prefs.on { display:flex } /* ⚙ → All settings: what is not changed every day */
278
+ #prefs .pbox { width:min(780px,100%); max-height:86vh; overflow:auto; overscroll-behavior:contain; background:var(--panel); border:1px solid var(--line); border-radius:14px; box-shadow:0 20px 60px rgba(0,0,0,.6); padding:14px 12px 16px }
279
+ #prefs .phead { display:flex; align-items:center; justify-content:space-between; gap:10px; padding:2px 10px 6px } #prefs h2 { margin:0; font:900 22px "Comic Sans MS","Chalkboard SE",sans-serif }
280
+ #prefs .pcols { display:grid; grid-template-columns:1fr 1fr; gap:4px 18px } @media (max-width:640px) { #prefs .pcols { grid-template-columns:1fr } }
281
+ #prefs .flash { animation:flash 1.6s ease } @keyframes flash { 0%, 40% { background:rgba(124,156,255,.28) } }
282
+ #prefs .pfoot { display:flex; justify-content:flex-end; padding:12px 10px 0; margin-top:8px; border-top:1px solid var(--line) } #prefsReset.sure { border-color:#ff7a6b; color:#ffb4a8 }
283
+ #menuTip { position:fixed; z-index:13; max-width:260px; padding:10px 12px; border-radius:10px; background:#2b3352; border:1px solid var(--accent); box-shadow:0 10px 30px rgba(0,0,0,.5); font-size:12.5px; line-height:1.45; color:var(--text) } #menuTip::before { content:''; position:absolute; top:-7px; right:var(--ax,14px); width:12px; height:12px; background:#2b3352; border-left:1px solid var(--accent); border-top:1px solid var(--accent); transform:rotate(45deg) } #menuTip .btn { display:block; margin:8px 0 0 auto } /* once, after the menu moved */
284
+ a.artist { color:#f5c04a; text-underline-offset:2px } #menuShop:empty { display:none } #menuShop { margin:2px 0 8px; font-size:12px; line-height:1.5; color:#c3c6d4 } /* the Halloween pack, for those who do not have it */
257
285
  #recap { position:fixed; inset:0; z-index:15; background:rgba(5,6,12,.88); display:none; overflow:auto; padding:28px 16px } #recap.on { display:block }
258
286
  #recap .box { max-width:860px; margin:0 auto; background:var(--panel); border:1px solid var(--line); border-radius:14px; padding:22px 26px }
287
+ .cgrid { display:grid; grid-template-columns:repeat(auto-fill,minmax(160px,1fr)); gap:12px } .ccard { display:block; padding:0; text-align:left; background:var(--bg); border:2px solid var(--line); border-radius:12px; overflow:hidden; color:inherit; font:inherit; cursor:pointer } .ccard:hover { border-color:#4a5070 } .ccard.on { border-color:var(--accent); box-shadow:0 0 0 3px rgba(124,156,255,.18) } /* ⚙ → Characters: the window */
288
+ .ccard .pv { position:relative; display:block; aspect-ratio:4/3; background:#1b1e2a; overflow:hidden } .ccard .pv > svg, .ccard .pv > img { display:block; width:100%; height:100%; object-fit:cover } .ccard .pics { display:flex; height:100%; align-items:flex-end; justify-content:center; gap:4px; padding:10px 10px 6px } .ccard .pics img { height:72%; max-width:33%; object-fit:contain } .ccard .pvx { display:grid; place-items:center; height:100%; font-size:38px }
289
+ .ccard b { display:block; padding:8px 10px 0; font-size:13.5px } .ccard .sub { display:block; padding:2px 10px 10px; font-size:11.5px; color:var(--dim) } .ccard .ptag { position:absolute; top:7px; right:7px; padding:2px 9px; border-radius:999px; background:#f5c04a; color:#10131c; font:700 12px system-ui,sans-serif }
290
+ .cmore { margin-top:12px; font-size:12.5px; line-height:1.55; color:#c3c6d4 } .cmore > img { max-width:440px } .cmore:empty { display:none } .slots { display:grid; gap:8px; margin:10px 0 } .slot { display:flex; flex-wrap:wrap; align-items:center; gap:6px } .slot b { min-width:86px } .mine { display:flex; flex-wrap:wrap; gap:6px } .mine .chip { display:inline-flex; align-items:center; gap:6px; padding:3px 4px; background:var(--panel2); border:1px solid var(--line); border-radius:8px } .mine .chip img { width:26px; height:26px; object-fit:contain } .mine .ic { padding:0 4px }
259
291
  #recap h1 { margin:0 0 14px; font:900 26px "Comic Sans MS","Chalkboard SE",sans-serif; text-shadow:2px 2px 0 #d8372b } #recap h3 { margin:20px 0 6px; font-size:10.5px; text-transform:uppercase; letter-spacing:.08em; color:var(--dim) }
260
292
  .kpis { display:grid; grid-template-columns:repeat(auto-fit,minmax(110px,1fr)); gap:10px } .kpi { background:var(--bg); border-radius:10px; padding:10px 12px } .kpi b { display:block; font-size:22px } .kpi span { color:var(--dim); font-size:11.5px }
261
293
  .coffee { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-top:20px; padding:12px 14px; background:var(--bg); border:1px dashed #4a4f66; border-radius:10px; font-size:13px; color:#c3c6d4 }
@@ -291,37 +323,24 @@
291
323
  <div id="menu">
292
324
  <input id="menuQ" type="search" placeholder="Search settings…" aria-label="Search settings" style="margin:4px 8px 2px;width:calc(100% - 16px)">
293
325
  <div class="hint" id="menuNone" style="display:none;padding-top:6px;color:var(--dim)" data-fr="Aucun réglage trouvé" data-en="No setting found">Aucun réglage trouvé</div>
326
+ <div id="menuFound"></div>
294
327
  <h4 data-fr="Langue" data-en="Language">Langue</h4>
295
328
  <div class="box"><select id="langSel" aria-label="Language"></select></div>
329
+ <button class="mi" data-t="callTr" id="callTrMi" style="display:none"><span data-fr="Appel dans cette langue (traduit avec votre Claude Code)" data-en="Call in this language (translated with your Claude Code)">Appel dans cette langue (traduit avec votre Claude Code)</span><i class="sw"></i></button>
296
330
  <div class="hint" id="trHint" style="display:none"></div>
297
331
  <h4 data-fr="Son" data-en="Sound">Son</h4>
298
332
  <button class="mi" data-t="voice"><span data-fr="Voix des agents" data-en="Agent voices">Voix des agents</span><i class="sw"></i></button>
299
- <button class="mi" data-t="office"><span data-fr="Ambiance de bureau (clavier, café…)" data-en="Office ambience (keys, coffee…)">Ambiance de bureau (clavier, café…)</span><i class="sw"></i></button>
300
- <div class="box" id="officeBox" style="display:none"><input id="officeVol" type="range" min="0.1" max="1" step="0.05" style="width:100%" aria-label="Ambience volume"></div>
301
- <button class="mi" data-t="notify"><span data-fr="Me prévenir quand les agents ont fini" data-en="Notify me when agents finish">Me prévenir quand les agents ont fini</span><i class="sw"></i></button>
302
- <button class="mi" data-t="music"><span data-fr="Musique d’ambiance (radio FIP)" data-en="Office music (FIP radio)">Musique d’ambiance (radio FIP)</span><i class="sw"></i></button>
303
- <div class="box" id="musicBox" style="display:none"><select id="station"></select><input id="musicVol" type="range" min="0" max="1" step="0.05" style="width:100%" aria-label="Music volume"></div>
304
- <div class="box" id="vstyleBox"><label class="lbl" for="vstyle" data-fr="Style des voix" data-en="Voice style">Style des voix</label><select id="vstyle"></select><div class="hint" id="vstyleTip" style="padding:6px 0 0;display:none" data-fr="Pour la meilleure expérience, choisissez les voix très naturelles." data-en="For the best experience, pick the very natural voices.">Pour la meilleure expérience, choisissez les voix très naturelles.</div></div>
333
+ <div class="box" id="vstyleBox"><label class="lbl" for="vstyle" data-fr="Style des voix" data-en="Voice style">Style des voix</label><select id="vstyle"></select><div class="hint" id="vstyleTip" style="padding:6px 0 0;display:none" data-fr="Pour la meilleure expérience, choisissez les voix naturelles." data-en="For the best experience, pick the natural voices.">Pour la meilleure expérience, choisissez les voix naturelles.</div></div>
305
334
  <div class="box" id="kokoroBox" style="display:none"><button class="btn" id="kokoroInstall" style="width:100%"></button><div class="hint" id="kokoroHint" style="padding:2px 0 6px"></div></div>
306
- <h4 data-fr="Affichage" data-en="Display">Affichage</h4>
307
- <button class="mi" data-t="roster"><span data-fr="Liste des agents (à gauche)" data-en="Agents list (left)">Liste des agents (à gauche)</span><i class="sw"></i></button>
308
- <button class="mi" data-t="reactions"><span data-fr="Barre de réactions (👍 👏 ☕)" data-en="Reactions bar (👍 👏 ☕)">Barre de réactions (👍 👏 ☕)</span><i class="sw"></i></button>
309
- <button class="mi" data-t="banter"><span data-fr="Petites répliques et animations" data-en="Little lines & animations">Petites répliques et animations</span><i class="sw"></i></button>
310
- <div class="box"><div class="lbl"><span data-fr="Bavardage entre agents" data-en="Chatter between agents">Bavardage entre agents</span></div><select id="chatSel"><option value="quiet" data-fr="Discret" data-en="Quiet">Discret</option><option value="normal" data-fr="Normal" data-en="Normal">Normal</option><option value="lively" data-fr="Animé" data-en="Lively">Animé</option></select></div>
311
- <button class="mi" data-t="vanish"><span data-fr="Retirer les agents terminés (2 min)" data-en="Remove finished agents (2 min)">Retirer les agents terminés (2 min)</span><i class="sw"></i></button>
312
- <button class="mi" data-t="epi"><span data-fr="Réactions et blagues" data-en="Reactions & jokes">Réactions et blagues</span><i class="sw"></i></button>
313
- <button class="mi" data-t="files"><span data-fr="Fichiers créés pour vous, à la fin d’un tour" data-en="Files made for you, when a turn ends">Fichiers créés pour vous, à la fin d’un tour</span><i class="sw"></i></button>
314
- <button class="mi" data-t="visits"><span data-fr="Un visiteur quand une autre session vous attend" data-en="A visitor when another session needs you">Un visiteur quand une autre session vous attend</span><i class="sw"></i></button>
315
- <button class="mi" data-t="followTab" id="mFollowTab" style="display:none"><span data-fr="Suivre l’onglet Claude Code affiché" data-en="Follow the Claude Code tab I am on">Suivre l’onglet Claude Code affiché</span><i class="sw"></i></button>
335
+ <h4 data-fr="Personnages" data-en="Characters">Personnages</h4>
336
+ <div class="box"><button class="btn" id="charPick" style="width:100%;display:flex;align-items:center;gap:8px;text-align:left"><span id="charNow" style="flex:1;min-width:0"></span><span class="dim" aria-hidden="true">›</span></button></div>
337
+ <div class="box" id="menuShop"></div>
316
338
  <h4 data-fr="Source" data-en="Source">Source</h4>
317
339
  <div class="box"><div class="seg" style="width:100%" id="modeSeg"><button data-m="live" style="flex:1" data-fr="Live" data-en="Live">Live</button><button data-m="replay" style="flex:1" data-fr="Replay" data-en="Replay">Replay</button><button data-m="demo" style="flex:1" data-fr="Démo" data-en="Demo">Demo</button></div>
318
340
  <select id="liveProj" style="display:none;margin-top:6px" title="Project to follow"></select>
319
341
  <select id="sessions" style="display:none"></select></div>
320
- <h4 data-fr="Personnages" data-en="Characters">Personnages</h4>
321
- <div class="box"><select id="charPack" aria-label="Characters"><option value="none" data-fr="Personnages dessinés" data-en="Drawn characters">Personnages dessinés</option><option value="folder" data-fr="Mon dossier" data-en="My folder">Mon dossier</option><option value="cats" data-fr="Pack de chats" data-en="Cat pack">Pack de chats</option></select></div>
322
- <div class="box"><div id="charInfo" class="dim" style="font-size:11.5px;line-height:1.5"></div><div style="display:flex;gap:6px;margin-top:6px"><button class="btn" id="charReload" data-fr="Recharger" data-en="Reload">Recharger</button><button class="btn" id="charOpen" style="display:none" data-fr="Ouvrir le dossier" data-en="Open folder">Ouvrir le dossier</button></div></div>
323
- <button class="mi" data-t="customLaptop"><span data-fr="Ordinateur devant vos personnages" data-en="Laptop in front of your own characters">Ordinateur devant vos personnages</span><i class="sw"></i></button>
324
- <button class="mi" data-t="ownNames"><span data-fr="Garder les noms de mes agents" data-en="Keep my agents’ own names">Garder les noms de mes agents</span><i class="sw"></i></button>
342
+ <h4 data-fr="Plus" data-en="More">Plus</h4>
343
+ <button class="mi" id="mPrefs"><span data-fr="⚙ Tous les réglages (affichage, alertes…)" data-en="⚙ All settings (display, alerts…)">⚙ Tous les réglages (affichage, alertes…)</span><span class="dim" aria-hidden="true">›</span></button>
325
344
  <h4 data-fr="Outils" data-en="Tools">Outils</h4>
326
345
  <button class="mi" id="mCoffee" style="display:none"><span id="mCoffeeT"></span></button>
327
346
  <button class="mi" id="mKeys"><span data-fr="⌨ Raccourcis clavier (?)" data-en="⌨ Keyboard shortcuts (?)">⌨ Raccourcis clavier (?)</span></button>
@@ -329,9 +348,37 @@
329
348
  <button class="mi" id="mExport"><span data-fr="🎞 Exporter la vidéo" data-en="🎞 Export video">🎞 Exporter la vidéo</span></button>
330
349
  <button class="mi" id="mClip"><span data-fr="🎬 Clip à partager (25 s)" data-en="🎬 Clip to share (25 s)">🎬 Clip à partager (25 s)</span></button>
331
350
  <button class="mi" data-t="hideCode"><span data-fr="Masquer code et fichiers dans les vidéos" data-en="Hide code & file names in videos">Masquer code et fichiers dans les vidéos</span><i class="sw"></i></button>
332
- <div class="keys">Space ⏯ · M 🔇 · T tree · R recap · L log · Esc ✕</div>
333
351
  <button class="mi" id="mBrowser" style="display:none"><span data-fr="↗ Ouvrir dans le navigateur" data-en="↗ Open in browser">↗ Ouvrir dans le navigateur</span></button>
352
+ <button class="mi" id="mReport"><span data-fr="🐞 Signaler un problème" data-en="🐞 Report a problem">🐞 Signaler un problème</span></button>
334
353
  </div>
354
+ <div id="menuTip" role="status" style="display:none"><span id="menuTipT"></span><button class="btn" id="menuTipOk"></button></div>
355
+ <div id="prefs" role="dialog" aria-modal="true" aria-labelledby="prefsT"><div class="pbox">
356
+ <div class="phead"><h2 id="prefsT" data-fr="Réglages" data-en="Settings">Réglages</h2><button class="btn" id="prefsX" data-fr="Fermer" data-en="Close">Fermer</button></div>
357
+ <div class="pcols"><div class="pcol">
358
+ <h4 data-fr="Son et alertes" data-en="Sound and alerts">Son et alertes</h4>
359
+ <button class="mi" data-t="office"><span data-fr="Ambiance de bureau (clavier, café…)" data-en="Office ambience (keys, coffee…)">Ambiance de bureau (clavier, café…)</span><i class="sw"></i></button>
360
+ <div class="box" id="officeBox" style="display:none"><input id="officeVol" type="range" min="0.1" max="1" step="0.05" style="width:100%" aria-label="Ambience volume"></div>
361
+ <button class="mi" data-t="music"><span data-fr="Musique d’ambiance (radio FIP)" data-en="Office music (FIP radio)">Musique d’ambiance (radio FIP)</span><i class="sw"></i></button>
362
+ <div class="box" id="musicBox" style="display:none"><select id="station"></select><input id="musicVol" type="range" min="0" max="1" step="0.05" style="width:100%" aria-label="Music volume"></div>
363
+ <button class="mi" data-t="notify"><span data-fr="Me prévenir quand les agents ont fini" data-en="Notify me when agents finish">Me prévenir quand les agents ont fini</span><i class="sw"></i></button>
364
+ <h4 data-fr="Personnages" data-en="Characters">Personnages</h4>
365
+ <button class="mi" data-t="customLaptop"><span data-fr="Ordinateur devant vos personnages" data-en="Laptop in front of your own characters">Ordinateur devant vos personnages</span><i class="sw"></i></button>
366
+ <button class="mi" data-t="ownNames"><span data-fr="Garder les noms de mes agents" data-en="Keep my agents’ own names">Garder les noms de mes agents</span><i class="sw"></i></button>
367
+ </div><div class="pcol">
368
+ <h4 data-fr="Affichage" data-en="Display">Affichage</h4>
369
+ <button class="mi" data-t="roster"><span data-fr="Liste des agents (à gauche)" data-en="Agents list (left)">Liste des agents (à gauche)</span><i class="sw"></i></button>
370
+ <button class="mi" data-t="reactions"><span data-fr="Barre de réactions (👍 👏 ☕)" data-en="Reactions bar (👍 👏 ☕)">Barre de réactions (👍 👏 ☕)</span><i class="sw"></i></button>
371
+ <button class="mi" data-t="banter"><span data-fr="Petites répliques et animations" data-en="Little lines & animations">Petites répliques et animations</span><i class="sw"></i></button>
372
+ <div class="box"><div class="lbl"><span data-fr="Bavardage entre agents" data-en="Chatter between agents">Bavardage entre agents</span></div><select id="chatSel"><option value="quiet" data-fr="Discret" data-en="Quiet">Discret</option><option value="normal" data-fr="Normal" data-en="Normal">Normal</option><option value="lively" data-fr="Animé" data-en="Lively">Animé</option></select></div>
373
+ <button class="mi" data-t="vanish"><span data-fr="Retirer les agents terminés (2 min)" data-en="Remove finished agents (2 min)">Retirer les agents terminés (2 min)</span><i class="sw"></i></button>
374
+ <button class="mi" data-t="epi"><span data-fr="Réactions et blagues" data-en="Reactions & jokes">Réactions et blagues</span><i class="sw"></i></button>
375
+ <button class="mi" data-t="files"><span data-fr="Fichiers créés pour vous, à la fin d’un tour" data-en="Files made for you, when a turn ends">Fichiers créés pour vous, à la fin d’un tour</span><i class="sw"></i></button>
376
+ <button class="mi" data-t="artNet"><span data-fr="Artifacts : charger leurs bibliothèques (depuis Internet)" data-en="Artifacts: load their libraries (from the internet)">Artifacts : charger leurs bibliothèques (depuis Internet)</span><i class="sw"></i></button>
377
+ <button class="mi" data-t="visits"><span data-fr="Un visiteur quand une autre session vous attend" data-en="A visitor when another session needs you">Un visiteur quand une autre session vous attend</span><i class="sw"></i></button>
378
+ <button class="mi" data-t="followTab" id="mFollowTab" style="display:none"><span data-fr="Suivre l’onglet Claude Code affiché" data-en="Follow the Claude Code tab I am on">Suivre l’onglet Claude Code affiché</span><i class="sw"></i></button>
379
+ </div></div>
380
+ <div class="pfoot"><button class="btn" id="prefsReset" data-fr="Réglages par défaut" data-en="Reset to defaults">Réglages par défaut</button></div>
381
+ </div></div>
335
382
 
336
383
  <main>
337
384
  <nav id="roster" aria-label="Agents"></nav>
@@ -342,7 +389,7 @@
342
389
  <div id="files"></div>
343
390
  <div id="hl"></div>
344
391
  <canvas id="gantt" height="90"></canvas>
345
- <div id="toasts" role="status" aria-live="polite"></div><div id="visit" role="status" aria-live="polite"></div>
392
+ <div id="toasts" role="status" aria-live="polite"><div class="toast offer" id="vOffer" style="display:none"><span id="vOfferT"></span><button class="btn" id="vOfferB"></button><button class="ic" id="vOfferX" aria-label="Close">✕</button></div><div class="toast offer" id="packNote" style="display:none"><span id="packNoteT"></span><button class="btn" id="packNoteB"></button><button class="ic" id="packNoteX" aria-label="Close">✕</button></div><div class="toast offer" id="trNote" style="display:none"><span id="trNoteT"></span><button class="btn" id="trNoteOk"></button><button class="btn" id="trNoteOff"></button></div></div><div id="visit" role="status" aria-live="polite"></div>
346
393
  <div id="empty"><h2 id="eT"></h2><p id="eP"></p><button class="cta" id="eDemo"></button></div>
347
394
  <div id="gate"><h2 id="gT"></h2><p id="gP"></p><button class="cta" id="gB"></button></div>
348
395
  <div id="detail"><div class="hd"><b id="dname"></b><button class="ic" id="dclose">✕</button></div><div id="dbody"></div></div>
@@ -361,6 +408,19 @@
361
408
  // =====================================================================
362
409
  // helpers, prefs, i18n
363
410
  // =====================================================================
411
+ // The page's own errors are written to the local log (errors.log beside the settings, see logError in server.js): nothing leaves the computer. ⚙ › Report a problem shows them.
412
+ // Twenty a page at most, each message once; what is not a fault of the app is left out (a sound the browser refuses to play, the server that went away, an interrupted request).
413
+ const ERRS = { n: 0, seen: new Set() };
414
+ function reportError(where, e) {
415
+ try {
416
+ const msg = String((e && e.message) || e || '').slice(0, 500), name = (e && e.name) || '';
417
+ if (!msg || ERRS.n >= 20 || ERRS.seen.has(msg) || /^(AbortError|NotAllowedError|NotSupportedError)$/.test(name) || /^Script error\.?$|ResizeObserver loop|Failed to fetch|NetworkError|Load failed/i.test(msg)) return;
418
+ ERRS.seen.add(msg); ERRS.n++;
419
+ fetch('/api/errors', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ where, msg, stack: String((e && e.stack) || '').slice(0, 4000) }) }).catch(() => {});
420
+ } catch {}
421
+ }
422
+ addEventListener('error', (ev) => { if (ev.error || ev.message) reportError('error', ev.error || { message: ev.message, stack: `at ${ev.filename}:${ev.lineno}:${ev.colno}` }); });
423
+ addEventListener('unhandledrejection', (ev) => reportError('promise', ev.reason));
364
424
  const $ = (s) => document.querySelector(s);
365
425
  const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
366
426
  const hash = (s) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
@@ -370,11 +430,17 @@ const CID = Math.random().toString(36).slice(2, 12); // identifies this window
370
430
  const Q = new URLSearchParams(location.search);
371
431
  const EMBED = Q.get('embed') === '1' || window.parent !== window;
372
432
 
373
- let prefs = { lang: 'en', voice: true, roster: true, banter: true, reactions: false, office: false, officeVol: 0.8, vstyle: 'cartoon', notify: false, epi: false, vanish: true, music: false, station: 'fip', musicVol: 0.35, view: 'call', hideCode: false, ownNames: true, visits: true, followTab: true, files: true };
433
+ let prefs = { lang: 'en', voice: true, roster: true, banter: true, reactions: false, office: false, officeVol: 0.8, vstyle: 'kokoro', notify: false, epi: false, vanish: true, music: false, station: 'fip', musicVol: 0.35, view: 'call', hideCode: false, ownNames: true, visits: true, followTab: true, files: true, callTr: true };
434
+ const PREF_DEFAULTS = { ...prefs }; // for ⚙ → All settings → Reset to defaults
374
435
  { let loc = {}; try { loc = JSON.parse(localStorage.getItem('cc.prefs') || '{}') || {}; } catch {} // the settings file (shared by every window) and this origin's copy: the more recent one wins
375
436
  const sv = window.SAVED_PREFS && typeof window.SAVED_PREFS === 'object' ? window.SAVED_PREFS : {}; Object.assign(prefs, (sv._t || 0) > (loc._t || 0) ? sv : loc); }
437
+ const HAD_PREFS = !!prefs._t; // someone who used the app before this page: shown once where the settings went
376
438
  if (prefs.vstyle === 'babble') prefs.vstyle = 'animal', prefs.vstyleChosen = true;
377
- if (!prefs.vstyleChosen && (prefs.vstyle === 'animal' || prefs.vstyle === 'sims')) prefs.vstyle = 'cartoon'; // the gibberish styles are opt-in: understandable voices by default
439
+ // Two styles since 1.32.0: the natural voices (the model, the default, which babble until they are installed) and the Animal Crossing babble. The cartoon voices, Simlish and the plain system voices are no longer offered:
440
+ // whoever had Simlish is on the other babble, everyone else on the natural voices. The cartoon voices read the words with no install, so the call offers the real ones once more to who had closed that line.
441
+ if (prefs.vstyle === 'cartoon' && prefs.voiceOffer === 'no') delete prefs.voiceOffer;
442
+ if (prefs.vstyle === 'sims' && prefs.vstyleChosen) prefs.vstyle = 'animal';
443
+ if (prefs.vstyle !== 'animal' || !prefs.vstyleChosen) prefs.vstyle = 'kokoro';
378
444
  if (!prefs.notifyChosen) prefs.notify = true; // “tell me when the agents are done” is on unless the person chose otherwise
379
445
  let prefsTimer = null;
380
446
  const savePrefs = () => { prefs._t = Date.now(); try { localStorage.setItem('cc.prefs', JSON.stringify(prefs)); } catch {} clearTimeout(prefsTimer); prefsTimer = setTimeout(() => { fetch('/api/prefs', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(prefs) }).catch(() => {}); }, 400); };
@@ -383,17 +449,35 @@ const savePrefs = () => { prefs._t = Date.now(); try { localStorage.setItem('cc.
383
449
  const LANGS = [['en', 'English', 'en'], ['fr', 'Français', 'fr'], ['zh-TW', '繁體中文', 'zh-Hant-TW'], ['zh-CN', '简体中文', 'zh-Hans-CN'], ['es', 'Español', 'es'], ['de', 'Deutsch', 'de'], ['da', 'Dansk', 'da'], ['pt-BR', 'Português (Brasil)', 'pt-BR'], ['ja', '日本語', 'ja'], ['ko', '한국어', 'ko']];
384
450
  let LOC = {};
385
451
  const FR = () => prefs.lang === 'fr';
386
- const FR_W = /\b(le|la|les|des|une|un|et|est|pour|dans|que|qui|pas|sur|avec|je|tu|nous|vous|ce|cette|ça|du|au|aux|mais|sont|été|fait|plus|ne|ont|il|elle|ils|elles|très|aussi|donc|bien|tout|voici|voilà|merci|oui|non|comme|où|déjà|encore)\b/gi, EN_W = /\b(the|and|is|are|to|of|in|that|with|for|this|it|on|you|we|not|have|has|was|be|will|can|from|your|at|as|but|all|now|also|done|here|there|which|what|then|just|so)\b/gi;
387
- const langOf = (t) => { // 'fr' or 'en' when a line clearly reads as one of them, else null: the voice then follows the interface language
388
- t = String(t || ''); const fr = (t.match(FR_W) || []).length + (t.match(/[éèêàçùâîôûœ]/g) || []).length, en = (t.match(EN_W) || []).length;
389
- return fr >= 2 && fr > en * 1.5 ? 'fr' : en >= 2 && en > fr * 1.5 ? 'en' : null;
452
+ // The language the call is held in: what the agents say is translated into it, the little built-in lines exist in it and its voices are used. A French interface means a French call, as it always did.
453
+ // Spanish and Brazilian Portuguese are one too, unless the person switches it off (⚙ → Language). Translating sends the lines to Anthropic through their own Claude Code and counts on their plan, which
454
+ // nobody who picked one of these two languages before had agreed to: the first call held in one of them says so, once, with the way out (callNote). With any other interface language, or the switch off,
455
+ // the call is the session as it is, with the built-in lines in English.
456
+ const CALL_LANG = { fr: 'fr', es: 'es', 'pt-BR': 'pt' };
457
+ let noTr = false; // no Claude Code and no API key on this computer: nothing can be translated, and a Spanish or Portuguese call is not held (French goes on saying what is missing, as it always did)
458
+ const CALL = () => { const l = CALL_LANG[prefs.lang]; return l && (l === 'fr' || (prefs.callTr && !noTr)) ? l : 'en'; }, TRL = () => CALL() !== 'en';
459
+ const FR_L = 'le|la|les|des|une|un|et|est|pour|dans|que|qui|pas|sur|avec|je|tu|nous|vous|ce|cette|ça|du|au|aux|mais|sont|été|fait|plus|ne|ont|il|elle|ils|elles|très|aussi|donc|bien|tout|voici|voilà|merci|oui|non|comme|où|déjà|encore', FR_W = new RegExp('\\b(' + FR_L + ')\\b', 'gi'), EN_W = /\b(the|and|is|are|to|of|in|that|with|for|this|it|on|you|we|not|have|has|was|be|will|can|from|your|at|as|but|all|now|also|done|here|there|which|what|then|just|so)\b/gi;
460
+ // Spanish and Portuguese: only words that are neither French nor English words, and that the other of the two does not have (para, por, como, este… say nothing). Accents are not ASCII: the edges are spelled out.
461
+ const wordsRe = (w) => new RegExp('(^|[^\\p{L}\\p{N}_])(?:' + w + ')(?![\\p{L}\\p{N}_])', 'giu');
462
+ const ES_W = wordsRe('el|los|las|una|unos|y|es|con|del|al|pero|más|muy|también|ya|hay|están|esto|donde|sí|gracias|aquí|ahora|hecho|listo|ha|han|lo|sus|yo|tú|sin|cuando|puede|hacer|tiene|voy|estoy|tengo|puedo|necesito|quiero|creo|pruebas|archivo|archivos|cambios'),
463
+ PT_W = wordsRe('o|um|uma|uns|e(?!\\.)|é|em|com|não|da|dos|das|na|nas|mas|são|mais|muito|também|já|há|estão|isso|isto|esse|essa|onde|sim|obrigado|aqui|agora|tudo|feito|pronto|você|vocês|eu|meu|minha|seu|sua|foi|tem|vou|fazer|pode|sem|quando|ao|pelo|pela|estou|tenho|posso|preciso|quero|acho|testes|arquivo|arquivos|alterações');
464
+ const FR_S = wordsRe(FR_L); // the French words with the same edges: \b reads "está" as "est" and "quién" as "qui"
465
+ // German, Danish, Japanese, Korean and Chinese are told apart too, though no call is held in them and the model has no voice for them: a line in one of them goes to a system voice of that language, not to an English voice.
466
+ const DE_W = wordsRe('der|die|und|ist|nicht|ich|mit|für|auf|ein|eine|einen|zu|dem|wir|sie|auch|wird|sind|von|noch|aber|oder|wenn|dass|habe|kann|jetzt|hier|nur|schon|mehr|dann|nach|wurde|werden|keine|diese|dieser|datei|dateien|fehler|nein|bitte|danke'),
467
+ DA_W = wordsRe('og|det|jeg|ikke|til|på|har|vi|som|vil|skal|også|eller|fra|så|nu|kun|mere|efter|ved|blev|bliver|ingen|denne|dette|filen|filer|fejl|være|været|hvis|når|af|tak|nej');
468
+ const langOf = (t) => { // the language a line clearly reads as ('fr', 'en', 'es', 'pt', 'de', 'da', 'ja', 'ko', 'zh'), else null: the voice then follows the language of the call
469
+ t = String(t || ''); const n = (re) => (t.match(re) || []).length, kana = n(/[\u3040-\u30ff]/g), hang = n(/[\uac00-\ud7af]/g), han = n(/[\u4e00-\u9fff]/g), cjk = kana + hang + han;
470
+ if (cjk >= 2 && cjk * 3 > n(/[A-Za-z]/g)) return kana || (prefs.lang === 'ja' && !hang) ? 'ja' : hang > han ? 'ko' : 'zh'; // by the script; Japanese without a single kana is rare, and then the interface says
471
+ const fr = n(FR_W) + n(/[éèêàçùâîôûœ]/g), en = n(EN_W), [[lo, top], [, next]] = [['es', n(ES_W) + n(/[ñ¿¡]/g)], ['pt', n(PT_W) + n(/[ãõ]/g)], ['de', n(DE_W) + n(/[äöüß]/g)], ['da', n(DA_W) + n(/[æøå]/g)]].sort((a, b) => b[1] - a[1]);
472
+ if (top >= 2 && top > next * 1.5 && top > n(FR_S) * 1.5 && top > en * 1.5) return lo; // against the French words alone: é, à, ç are Portuguese and Spanish letters too
473
+ return fr >= 2 && fr > en * 1.5 && fr > n(/[áíóúñ¿¡ãõ]/g) * 2 ? 'fr' : en >= 2 && en > fr * 1.5 ? 'en' : null; // á, í, ó, ú, ñ, ã are never French: "está" and "quién" would count as "est" and "qui"
390
474
  };
391
475
  const tr = (en) => (prefs.lang === 'en' || prefs.lang === 'fr' ? en : LOC[en] || en);
392
476
  const L = (fr, en) => (FR() ? fr : tr(en));
393
477
  async function loadLocale(code) { LOC = {}; if (code === 'en' || code === 'fr') return; try { const r = await fetch('/locales/' + encodeURIComponent(code) + '.json'); if (r.ok) LOC = await r.json(); } catch {} }
394
478
  async function setLang(code, save) {
395
479
  if (!LANGS.some((l) => l[0] === code)) code = 'en'; prefs.lang = code; await loadLocale(code); if (save) { prefs.langChosen = true; savePrefs(); }
396
- if (FR()) fetch('/api/warm').catch(() => {}); AUD.stopAll(); synth && synth.cancel(); applyLang(); if (FR()) prefetchTr(S.idx);
480
+ if (TRL()) fetch('/api/warm?lang=' + CALL()).catch(() => {}); AUD.stopAll(); synth && synth.cancel(); applyLang(); if (TRL()) prefetchTr(S.idx); kokoroUI(); voiceOffer(); callNote(); /* its texts, and the offer to add the voices of this language */
397
481
  }
398
482
 
399
483
  // =====================================================================
@@ -411,30 +495,128 @@ const hexRGB = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
411
495
  const mix = (a, b, t) => { const A = hexRGB(a), B = hexRGB(b); return '#' + A.map((v, i) => Math.round(v + (B[i] - v) * t).toString(16).padStart(2, '0')).join(''); };
412
496
  // ---- custom characters: the person's own pixel art (folder served by /api/characters) replaces the drawn figure, scene and desk stay ----
413
497
  let CHARS = { lead: null, you: null, pool: [], dir: '', n: 0 };
498
+ const CHAR_CHOICES = ['none', 'folder', 'cats', 'halloween']; // what ⚙ → Characters offers: the drawn characters, one's own folder, the built-in packs and the packs of the shop
499
+ let SHOP = {}; // the packs of the shop, by name, as the server knows them: how many characters are here (none until it is bought), its price, the code of the purchase
414
500
  const toData = (url) => fetch(url).then((r) => r.blob()).then((b) => new Promise((res) => { const f = new FileReader(); f.onload = () => res(f.result); f.readAsDataURL(b); }));
501
+ const imgSize = (src) => new Promise((res) => { const i = new Image(); i.onload = () => res([i.naturalWidth, i.naturalHeight]); i.onerror = () => res([0, 0]); i.src = src; }), isDrawing = (wh) => Math.max(wh[0], wh[1]) > 128; // a large image is a drawing, shown smooth; pixel art (32 or 64 px) keeps its hard pixels
502
+ const youMode = () => prefs.charYou || (prefs.charPack === 'none' ? 'vampire' : 'cast'); // who you are: the cast's own human, or the vampire of the Halloween pack, everyone's and free (the default with the drawn characters, so that everyone meets the pack)
503
+ let VAMP = null; // the free vampire (examples/vampire), loaded once
504
+ async function charEntry(base, c) { // one character of a folder or a pack, ready to draw: its pictures as data, their sizes, what it may wear
505
+ const e = { name: c.stem, idle: await toData(base + encodeURIComponent(c.file)), talk: c.talk ? await toData(base + encodeURIComponent(c.talk)) : null, bg: c.bg ? await toData(base + encodeURIComponent(c.bg)) : null, desks: await Promise.all((c.desks || []).map((f) => toData(base + encodeURIComponent(f)))), hands: c.hands ? await toData(base + encodeURIComponent(c.hands)) : null, head: c.head ? await toData(base + encodeURIComponent(c.head)) : null };
506
+ const wh = await imgSize(e.idle), rm = e.bg ? await imgSize(e.bg) : [0, 0]; e.smooth = isDrawing(wh); e.bgSmooth = isDrawing(rm);
507
+ e.full = !!(wh[1] && rm[1] && Math.abs(wh[0] / wh[1] - rm[0] / rm[1]) < .01); // a character drawn on a sheet of the same shape as its room is laid over the room as it is: its artist placed it, and it may be wider or taller than the usual place of a character
508
+ e.extras = null; if (c.extras) { e.extras = {}; for (const k of Object.keys(c.extras).sort()) e.extras[k] = await Promise.all(c.extras[k].map((f) => toData(base + encodeURIComponent(f)))); }
509
+ return e;
510
+ }
511
+ const vampEntry = async () => { const c = ((await (await fetch('/api/characters?pack=vampire')).json()).chars || []).find((x) => x.role === 'you'); return c ? charEntry('/packs/vampire/', c) : null; };
415
512
  async function loadChars() {
416
- if (!['none', 'folder', 'cats'].includes(prefs.charPack)) { // drawn characters by default; someone who already had images in their folder keeps them (this is also where a choice of the starter pack, no longer shipped, ends up)
417
- let n = 0; try { n = ((await (await fetch('/api/characters')).json()).chars || []).length; } catch {} prefs.charPack = n ? 'folder' : 'none'; savePrefs(); const sel = $('#charPack'); if (sel) sel.value = prefs.charPack;
513
+ if (!CHAR_CHOICES.includes(prefs.charPack)) { // drawn characters by default; someone who already had images in their folder keeps them (this is also where a choice of the starter pack, no longer shipped, ends up)
514
+ let n = 0; try { n = ((await (await fetch('/api/characters')).json()).chars || []).length; } catch {} prefs.charPack = n ? 'folder' : 'none'; savePrefs();
418
515
  }
419
- const pack = prefs.charPack, next = { lead: null, you: null, pool: [], dir: '', n: 0, pack };
420
- if (pack === 'none') { try { next.dir = (await (await fetch('/api/characters')).json()).dir || ''; } catch {} CHARS = next; return; } // the drawn characters, whatever is in the folder
516
+ const pack = prefs.charPack, next = { lead: null, you: null, pool: [], dir: '', n: 0, pack, youFrom: '', castYou: null }; // castYou: the cast's own human, for the window
517
+ try { SHOP = Object.fromEntries((await (await fetch('/api/packs')).json()).filter((p) => p.shop).map((p) => [p.name, p])); } catch {}
421
518
  try {
422
- const base = pack === 'folder' ? '/characters/' : '/packs/' + pack + '/', d = await (await fetch('/api/characters?pack=' + (pack === 'folder' ? '' : pack))).json(); next.dir = d.dir || '';
423
- for (const c of d.chars || []) { try { const e = { name: c.stem, idle: await toData(base + encodeURIComponent(c.file)), talk: c.talk ? await toData(base + encodeURIComponent(c.talk)) : null };
424
- if (c.role === 'lead') next.lead = e; else if (c.role === 'you') next.you = e; else next.pool.push(e); next.n++; } catch {} }
519
+ const base = pack === 'folder' ? '/characters/' : '/packs/' + pack + '/', d = await (await fetch('/api/characters?pack=' + (pack === 'folder' || pack === 'none' ? '' : pack))).json(); next.dir = d.dir || ''; // with the drawn characters, only where the folder is
520
+ if (pack !== 'none') for (const c of d.chars || []) { try { const e = await charEntry(base, c); if (c.role === 'lead') next.lead = e; else if (c.role === 'you') { next.you = e; next.castYou = e; } else next.pool.push(e); next.n++; } catch {} }
425
521
  } catch {}
522
+ if (youMode() === 'vampire') { try { VAMP = VAMP || (await vampEntry()); if (VAMP) { next.you = VAMP; next.youFrom = 'vampire'; } } catch {} }
426
523
  CHARS = next;
427
524
  }
428
525
  const customFor = (id) => { // sub-agents: the best-hashed image no other agent holds; the whole pool again only once every image is taken
429
526
  if (id === 'main') return CHARS.lead; if (id === 'user') return CHARS.you; if (!CHARS.pool.length) return null;
430
527
  const used = new Set(Object.keys(S.agents).filter((k) => k !== id && S.agents[k].custom).map((k) => S.agents[k].custom.name));
431
- const free = CHARS.pool.filter((c) => !used.has(c.name)), from = free.length ? free : CHARS.pool;
432
- return from.reduce((b, c) => (hash(id + '|' + (c.idle || '')) > hash(id + '|' + (b.idle || '')) ? c : b));
528
+ const free = CHARS.pool.filter((c) => !used.has(c.name)), varied = CHARS.pool.filter((c) => c.extras && Object.keys(c.extras).some((k) => !/^sticker/.test(k))), from = free.length ? free : varied.length ? varied : CHARS.pool; // varied: what the character itself wears (a hat, glasses), not the stickers of its laptop // every image taken: one that has extras (a hat, glasses…) is given again, since it does not look the same twice
529
+ return from.reduce((b, c) => (hash(id + '|' + c.name) > hash(id + '|' + b.name) ? c : b)); // by the character's name, not its picture: a pack drawn again gives each agent the same character
433
530
  };
434
- function renderCharInfo() {
435
- const el = $('#charInfo'); if (!el) return;
436
- el.innerHTML = CHARS.pack === 'none' ? esc(L('Les personnages dessinés par l’application. Choisissez « Mon dossier » pour vos propres images, ou un pack.', 'The characters drawn by the app. Pick “My folder” for your own images, or a pack.')) : CHARS.pack !== 'folder' ? `✓ ${CHARS.n} ${esc(L('personnages du pack', 'characters from the pack'))} · ${esc(L('Pour les modifier, copiez-les dans votre dossier et choisissez « Mon dossier ».', 'To tweak them, copy them into your folder and pick “My folder”.'))}` : CHARS.n ? `✓ ${CHARS.n} ${esc(L('personnage(s) personnalisé(s) chargé(s)', 'custom character(s) loaded'))}` : `${esc(L('Déposez vos images (PNG) dans ce dossier pour remplacer les personnages :', 'Drop your pixel art (PNG) in this folder to replace the characters:'))}<br><code style="word-break:break-all">${esc(CHARS.dir)}</code><br>${esc(L('lead.png = le chef · you.png = vous · les autres = les sous-agents · nom-talk.png = bouche ouverte', 'lead.png = the lead · you.png = you · others = the sub-agents · name-talk.png = open mouth'))}`;
437
- $('#charOpen').style.display = EMBED ? '' : 'none';
531
+ // ---- the shop: a pack that is sold. The page never sees a card: the button asks the app's server for a payment page (Stripe's, through the website), opens it, and then asks for the pack until it is paid
532
+ const shopSay = (t) => { const m = $('#shopMsg'); if (m) m.textContent = t; };
533
+ const shopWhy = (e) => ({ code: L('Ce code n’est pas valide.', 'This code is not valid.'), refunded: L('Cet achat a été remboursé.', 'This purchase was refunded.'), unpaid: L('Ce paiement n’est pas encore terminé.', 'This payment is not complete yet.'), closed: L('La boutique n’est pas encore ouverte.', 'The shop is not open yet.') }[e] || L('La boutique est injoignable. Vérifiez votre connexion et réessayez.', 'The shop cannot be reached. Check your connection and try again.'));
534
+ const shopAsk = async (what, body) => { try { return await (await fetch('/api/packs/' + what, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })).json(); } catch { return { error: 'offline' }; } };
535
+ let shopPoll = 0;
536
+ const shopDone = (name) => { prefs.charPack = name; savePrefs(); reloadChars(); }; // a pack just bought is the cast at once
537
+ function shopWait(name) { // after the payment page was opened: every few seconds for a quarter of an hour, or until it is there
538
+ clearInterval(shopPoll); const until = Date.now() + 15 * 60e3;
539
+ shopPoll = setInterval(async () => { if (Date.now() > until) return clearInterval(shopPoll); const r = await shopAsk('claim', { pack: name }); if (r.ok) { clearInterval(shopPoll); shopDone(name); } }, 4000);
540
+ }
541
+ function renderShop(el, name, shop) {
542
+ el.innerHTML = `<img src="pack-${esc(name)}.jpg" alt="" style="display:block;width:100%;border-radius:8px;margin-bottom:8px">${esc(L('Des personnages d’Halloween dessinés à la main, chacun dans sa pièce.', 'Hand-drawn Halloween characters, each in its own room.'))}<br>${esc(L('Un seul paiement, par carte, sur une page Stripe. Sans compte.', 'One payment, by card, on a Stripe page. No account.'))}<br>${esc(L('2 € minimum : vous pouvez donner plus sur la page de paiement, si vous le souhaitez.', '2 € minimum: you can pay more on the payment page if you like.'))}${shop.artist ? `<br>${esc(L('Dessinés par', 'Drawn by'))} <a href="#" class="artist">${esc(shop.artist)}</a>` : ''}
543
+ <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:8px"><button class="btn" id="shopBuy" style="background:var(--accent);border-color:transparent;color:#10131c;font-weight:600">${esc(L('Acheter', 'Buy'))} · ${esc(shop.price)}</button><button class="btn" id="shopHave">${esc(L('Je l’ai déjà acheté', 'I already bought it'))}</button></div>
544
+ <div id="shopCode" style="display:none;gap:6px;margin-top:8px"><input id="shopKey" aria-label="${esc(L('Code d’achat', 'Purchase code'))}" placeholder="${esc(L('Code d’achat', 'Purchase code'))}" autocomplete="off" spellcheck="false" style="flex:1;min-width:0;font:inherit;color:inherit;background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px 8px"><button class="btn" id="shopGo">${esc(L('Installer', 'Install'))}</button></div>
545
+ <div id="shopMsg" role="status" style="margin-top:8px"></div>`;
546
+ $('#shopBuy').onclick = async () => {
547
+ const w = EMBED ? null : window.open('', '_blank'); // opened in the click itself: a browser blocks a window that opens later, once the shop has answered
548
+ shopSay(L('Ouverture de la page de paiement…', 'Opening the payment page…')); const r = await shopAsk('buy', { pack: name });
549
+ if (!r.url) { if (w) w.close(); return shopSay(shopWhy(r.error)); }
550
+ if (w && !w.closed) { w.opener = null; w.location.href = r.url; } else openExternal(r.url);
551
+ shopSay(L('En attente du paiement. Le pack s’installe tout seul une fois payé.', 'Waiting for the payment. The pack installs by itself once it is paid.')); shopWait(name);
552
+ };
553
+ el.querySelectorAll('.artist').forEach((a) => (a.onclick = (e) => { e.preventDefault(); openExternal(shop.artistUrl); }));
554
+ $('#shopHave').onclick = () => { $('#shopCode').style.display = 'flex'; $('#shopKey').focus(); };
555
+ $('#shopGo').onclick = async () => { const code = $('#shopKey').value.trim(); if (!code) return; shopSay('…'); const r = await shopAsk('claim', { pack: name, code }); if (r.ok) shopDone(name); else shopSay(shopWhy(r.error)); };
556
+ if (shop.waiting && !renderShop.tried) { renderShop.tried = true; shopAsk('claim', { pack: name }).then((r) => { if (r.ok) shopDone(name); }); } // a payment page was opened earlier (the app was closed meanwhile, say): asked once, in case it was paid since
557
+ }
558
+ const packLabel = (name) => ({ none: L('Personnages dessinés', 'Drawn characters'), folder: L('Mon dossier', 'My folder'), cats: L('Pack de chats', 'Cat pack'), halloween: L('Pack Halloween', 'Halloween pack') }[name] || String(name).replace(/^./, (c) => c.toUpperCase()));
559
+ function renderCharInfo() { // the line of ⚙ → Characters, and the window when it is open
560
+ if (!$('#recap.on #chdlg')) renderMenuShop(); const el = $('#charNow'); if (el) el.textContent = packLabel(CHARS.pack || prefs.charPack || 'none') + ' · ' + (youMode() === 'vampire' ? L('Vous : le vampire', 'You: the vampire') : L('Vous : comme l’équipe', 'You: like the cast'));
561
+ return $('#recap.on #chdlg') ? openChars() : Promise.resolve();
562
+ }
563
+ const CHPICK = { more: '' }; // what the window shows under the cast: the folder, a pack, or the shop of a pack not bought yet (by default, the cast chosen)
564
+ async function openChars() { // ⚙ → Characters: the whole cast (drawn, a pack, a pack of the shop, one's own pictures), then who you are
565
+ let packs = [], mine = { chars: [], dir: CHARS.dir }; try { packs = await (await fetch('/api/packs')).json(); } catch {} try { mine = await (await fetch('/api/characters')).json(); } catch {}
566
+ if (!VAMP) { try { VAMP = await vampEntry(); } catch {} }
567
+ const files = {}; for (const p of packs.filter((x) => !x.shop && x.name !== 'vampire')) { try { files[p.name] = ((await (await fetch('/api/characters?pack=' + p.name)).json()).chars || []).map((c) => c.file); } catch { files[p.name] = []; } }
568
+ const cast = CHARS.pack || prefs.charPack, more = CHPICK.more || cast, ym = youMode(); let k = 0;
569
+ const tile = (id, custom) => avatarSVG({ ...persona0({ id, role: '' }), custom: custom || null }, undefined, 'cp' + k++ + '_'); // the very drawing of a tile
570
+ const pics = (base, list, px) => `<span class="pics">${list.slice(0, 3).map((f) => `<img src="${base + encodeURIComponent(f)}" alt=""${px ? ' style="image-rendering:pixelated"' : ''}>`).join('')}</span>`;
571
+ const many = (n) => `${n} ${n === 1 ? L('personnage', 'character') : L('personnages', 'characters')}`;
572
+ const card = (on, pv, title, sub, tag, data) => `<button class="ccard${on ? ' on' : ''}" ${data}><span class="pv">${pv}${tag ? `<i class="ptag">${esc(tag)}</i>` : ''}</span><b>${esc(title)}</b><span class="sub">${esc(sub)}</span></button>`;
573
+ const castCards = [card(cast === 'none', tile('main'), packLabel('none'), L('Ceux de l’app', 'The app’s own'), '', 'data-cast="none"'),
574
+ ...packs.filter((p) => p.shop).map((p) => card(cast === p.name && p.n, `<img src="pack-${esc(p.name)}.jpg" alt="">`, packLabel(p.name), p.n ? `✓ ${L('Le vôtre', 'Yours')} · ${many(p.n)}` : p.artist ? `${L('Dessinés par', 'Drawn by')} ${p.artist}` : L('Dessinés à la main, chacun dans sa pièce', 'Hand-drawn, each in its own room'), p.n ? '' : p.price, `data-cast="${esc(p.name)}"`)),
575
+ ...packs.filter((p) => !p.shop && p.name !== 'vampire').map((p) => card(cast === p.name, pics('/packs/' + p.name + '/', files[p.name], true), packLabel(p.name), `${many(p.n)}`, '', `data-cast="${esc(p.name)}"`)),
576
+ card(cast === 'folder', mine.chars.length ? pics('/characters/', mine.chars.map((c) => c.file)) : '<span class="pvx">🖼️</span>', packLabel('folder'), mine.chars.length ? many(mine.chars.length) : L('Vos propres images', 'Your own pictures'), '', 'data-cast="folder"')];
577
+ const youCards = [card(ym === 'vampire', VAMP ? tile('user', VAMP) : '', L('Le vampire', 'The vampire'), L('Offert, du pack Halloween', 'Free, from the Halloween pack'), '', 'data-you="vampire"'),
578
+ card(ym === 'cast', CHARS.castYou ? tile('user', CHARS.castYou) : tile('user'), L('Comme l’équipe', 'Like the cast'), cast === 'none' || !CHARS.castYou ? L('Le personnage dessiné', 'The drawn character') : packLabel(cast), '', 'data-you="cast"')];
579
+ const box = $('#recap .box'), top = $('#recap').scrollTop; $('#menuShop').innerHTML = '';
580
+ box.innerHTML = `<div id="chdlg"><h1>${esc(L('Personnages', 'Characters'))}</h1>
581
+ <h3>${esc(L('L’équipe', 'The cast'))}</h3><div class="cgrid">${castCards.join('')}</div><div id="castMore" class="cmore"></div>
582
+ <h3>${esc(L('Vous', 'You'))}</h3><div class="cgrid">${youCards.join('')}</div>
583
+ <p style="text-align:right;margin:18px 0 0"><button class="btn" id="recapx">${esc(L('Fermer', 'Close'))}</button></p></div>`;
584
+ box.querySelectorAll('[data-cast]').forEach((b) => (b.onclick = async () => { const v = b.dataset.cast, sp = SHOP[v]; CHPICK.more = v; if (sp && !sp.n) return openChars(); prefs.charPack = v; savePrefs(); await reloadChars(); })); // a pack not bought yet: its shop, and the cast stays as it is
585
+ box.querySelectorAll('[data-you]').forEach((b) => (b.onclick = async () => { prefs.charYou = b.dataset.you; savePrefs(); await reloadChars(); }));
586
+ $('#recapx').onclick = () => $('#recap').classList.remove('on');
587
+ const el = $('#castMore'), sp = SHOP[more];
588
+ if (sp && !sp.n) renderShop(el, more, sp);
589
+ else if (more === 'folder') renderFolder(el, mine);
590
+ else if (more === cast && more === 'none') el.textContent = L('Les personnages dessinés par l’application. Choisissez « Mon dossier » pour vos propres images, ou un pack.', 'The characters drawn by the app. Pick “My folder” for your own images, or a pack.');
591
+ else if (more === cast) {
592
+ el.innerHTML = `✓ ${CHARS.n} ${esc(L('personnages du pack', 'characters from the pack'))} · ${esc(L('Pour les modifier, copiez-les dans votre dossier et choisissez « Mon dossier ».', 'To tweak them, copy them into your folder and pick “My folder”.'))}${sp && sp.artist ? `<br>${esc(L('Dessinés par', 'Drawn by'))} <a href="#" class="artist">${esc(sp.artist)}</a>` : ''}`;
593
+ el.querySelectorAll('.artist').forEach((a) => (a.onclick = (e) => { e.preventDefault(); openExternal(sp.artistUrl); }));
594
+ if (sp && sp.code) { el.innerHTML += `<br>${esc(L('Votre code d’achat, pour installer le pack sur un autre ordinateur :', 'Your purchase code, to install the pack on another computer:'))} <code style="word-break:break-all;user-select:all">${esc(sp.code)}</code><br><button class="btn" id="shopUpdate" style="margin-top:6px">${esc(L('Mettre à jour le pack', 'Update the pack'))}</button> <span id="shopMsg" role="status"></span>`;
595
+ $('#shopUpdate').onclick = async () => { shopSay('…'); const r = await shopAsk('claim', { pack: more }); if (r.ok) reloadChars(); else shopSay(shopWhy(r.error)); }; } // the pack as the shop has it now (characters added since): fetched again with the code kept here, only when asked
596
+ }
597
+ $('#recap').classList.add('on'); $('#recap').scrollTop = top;
598
+ }
599
+ function renderFolder(el, mine) { // one's own pictures: where they are, a button per role to add one, and the ones there, each with a way to take it out (moved aside, never deleted)
600
+ const role = (c) => (c.role === 'lead' ? L('Chef', 'Lead') : c.role === 'you' ? L('Vous', 'You') : L('Sous-agent', 'Sub-agent'));
601
+ el.innerHTML = `${esc(L('Vos images sont dans ce dossier :', 'Your pictures are in this folder:'))} <code style="word-break:break-all">${esc(mine.dir || CHARS.dir || '')}</code>
602
+ <div class="slots">${[['you', L('Vous', 'You')], ['lead', L('Chef', 'Lead')], ['agent', L('Sous-agents', 'Sub-agents')]].map(([r, t]) => `<div class="slot"><b>${esc(t)}</b><button class="btn" data-add="${r}">${esc(r === 'agent' ? L('Ajouter des images', 'Add pictures') : L('Choisir une image', 'Choose a picture'))}</button>${r !== 'agent' ? `<button class="btn" data-add="${r}-talk">${esc(L('Bouche ouverte (facultatif)', 'Open mouth (optional)'))}</button>` : ''}</div>`).join('')}</div>
603
+ <div class="mine">${mine.chars.length ? mine.chars.map((c) => `<span class="chip"><img src="/characters/${encodeURIComponent(c.file)}" alt="">${esc(c.stem)} · ${esc(role(c))}<button class="ic" data-rm="${esc(c.file)}" aria-label="${esc(L('Retirer', 'Remove'))}" title="${esc(L('Retirer', 'Remove'))}">✕</button></span>`).join('') : esc(L('Aucune image pour l’instant.', 'No picture yet.'))}</div>
604
+ <p class="dim" style="margin:8px 0 0;font-size:11.5px">${esc(L('lead.png = le chef · you.png = vous · les autres = les sous-agents · nom-talk.png = bouche ouverte', 'lead.png = the lead · you.png = you · others = the sub-agents · name-talk.png = open mouth'))}</p>
605
+ <div style="display:flex;gap:6px;margin-top:8px"><button class="btn" id="charReload">${esc(L('Recharger', 'Reload'))}</button>${EMBED ? `<button class="btn" id="charOpen">${esc(L('Ouvrir le dossier', 'Open folder'))}</button>` : ''}</div>
606
+ <div id="shopMsg" role="status" style="margin-top:6px"></div><input type="file" id="charFile" accept="image/png,image/gif,image/webp,image/jpeg" hidden>`;
607
+ const inp = $('#charFile'), post = (p, b) => fetch(p, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(b) }).then((r) => r.json()).catch(() => ({ error: 'write' }));
608
+ el.querySelectorAll('[data-add]').forEach((b) => (b.onclick = () => { inp.multiple = b.dataset.add === 'agent'; inp.dataset.role = b.dataset.add; inp.value = ''; inp.click(); }));
609
+ inp.onchange = async () => {
610
+ let bad = 0; for (const f of [...inp.files].slice(0, 20)) { const data = await new Promise((res) => { const r = new FileReader(); r.onload = () => res(String(r.result).split(',')[1] || ''); r.onerror = () => res(''); r.readAsDataURL(f); }); if (!(await post('/api/characters/add', { role: inp.dataset.role, name: f.name, data })).file) bad++; }
611
+ prefs.charPack = 'folder'; if (/^you/.test(inp.dataset.role)) prefs.charYou = 'cast'; savePrefs(); CHPICK.more = 'folder'; await reloadChars(); // a picture added is meant to be seen: the folder becomes the cast, and a picture of you is you
612
+ if (bad) shopSay(L('Image refusée : PNG, GIF, WebP ou JPEG, 300 Ko au plus.', 'This picture could not be added: PNG, GIF, WebP or JPEG, up to 300 KB.'));
613
+ };
614
+ el.querySelectorAll('[data-rm]').forEach((b) => (b.onclick = async () => { await post('/api/characters/remove', { file: b.dataset.rm }); await reloadChars(); }));
615
+ $('#charReload').onclick = () => reloadChars(); if ($('#charOpen')) $('#charOpen').onclick = () => window.parent.postMessage({ agentStandup: 'openCharacters' }, '*');
616
+ }
617
+ function packNote() { // once, to someone who is the vampire without the pack: where the rest of the cast is
618
+ const on = CHARS.youFrom === 'vampire' && !prefs.vampSeen && !Q.get('demo') && !(SHOP.halloween && SHOP.halloween.n), el = $('#packNote'); if (!el) return; el.style.display = on ? '' : 'none'; if (!on) return;
619
+ $('#packNoteT').textContent = L('Pour Halloween, vous êtes le vampire. Le reste de l’équipe est dans le pack Halloween.', 'This Halloween, you are the vampire. The rest of the cast is in the Halloween pack.'); $('#packNoteB').textContent = L('Voir le pack', 'See the pack');
438
620
  }
439
621
  function persona(a) { const p = persona0(a); p.custom = customFor(a.id); return p; }
440
622
  const subName = (a, h) => (a.own && prefs.ownNames ? (nameBook[a.id] = a.own) : a.given || uniqueName(a.id, h)); // own: the name the person gave this agent (see ownName in server.js); otherwise a first name from the list. a.own is tested first: the landing page reuses this section and has no settings
@@ -533,19 +715,30 @@ function avatarSVG(p, o, uid = '') { // uid keeps SVG ids unique per instance:
533
715
  const lapDark = `<rect x="33" y="46" width="34" height="18" rx="2.8" fill="#3b4152"/><rect x="33" y="46" width="34" height="18" rx="2.8" fill="url(#${uid}lg)" opacity=".18"/><circle cx="50" cy="55" r="2.3" fill="${c1}"/><rect x="29.5" y="63.4" width="41" height="3" rx="1.5" fill="#262a36"/>`; // for custom characters: darker, so it still shows under a white or cream sprite
534
716
  const hands = `<circle class="hand l" cx="38" cy="65.6" r="3.1" fill="${c2}"/><circle class="hand r" cx="62" cy="65.6" r="3.1" fill="${c2}"/>`;
535
717
  const sparks = star(22, 28, 3) + star(78, 22, 2.6, '#ff9bb8') + star(70, 40, 1.9, '#9be7ff') + star(30, 46, 1.6, '#ffe58a');
536
- const custFig = (c, talking) => { const base = 'x="20" y="6" width="60" height="58" preserveAspectRatio="xMidYMax meet"', px = 'image-rendering:pixelated;';
537
- return `<image class="cimg" href="${c.idle}" ${base} style="${px}${talking && c.talk ? 'display:none' : ''}"/>` + (c.talk ? `<image class="cimg cimg-talk" href="${c.talk}" ${base} style="${px}${talking ? '' : 'display:none'}"/>` : ''); };
538
- const fig = p.custom ? custFig(p.custom, st && o.m === 2) : `${arm('l')}${bodyShape(p.shape, `url(#${gid})`, c2)}${arm('r')}${face}${acc}`;
718
+ const custFig = (c, talking, who) => { const base = c.full ? 'width="100" height="75" preserveAspectRatio="xMidYMid slice"' : 'x="20" y="6" width="60" height="58" preserveAspectRatio="xMidYMax meet"', px = c.smooth ? '' : 'image-rendering:pixelated;';
719
+ const worn = c.extras ? Object.keys(c.extras).filter((k) => !/^sticker/.test(k)).map((k) => { const n = c.extras[k].length, i = hash(who + '+' + k) % (2 * n); return i < n ? `<image href="${c.extras[k][i]}" ${base} style="${px}"/>` : ''; }).join('') : ''; // one of each kind, or none, half of the time: always the same for a given agent
720
+ const face = c.head || c.idle; // a character drawn with its head apart: the body stays, the head (and what it wears) nods while it speaks, its two mouths swap on it
721
+ const mouths = `<image class="cimg" href="${face}" ${base} style="${px}${talking && c.talk ? 'display:none' : ''}"/>` + (c.talk ? `<image class="cimg cimg-talk" href="${c.talk}" ${base} style="${px}${talking ? '' : 'display:none'}"/>` : '');
722
+ return c.head ? `<image href="${c.idle}" ${base} style="${px}"/><g class="chead">${mouths}${worn}</g>` : mouths + worn; };
723
+ const custFront = (c, hid, who) => { const base = c.full ? 'width="100" height="75" preserveAspectRatio="xMidYMid slice"' : 'x="20" y="6" width="60" height="58" preserveAspectRatio="xMidYMax meet"', px = c.smooth ? '' : 'image-rendering:pixelated;'; // in front of the character, outside its group so that they stay still while it breathes
724
+ const hands = c.hands ? `<clipPath id="${hid}l"><rect width="50" height="75"/></clipPath><clipPath id="${hid}r"><rect x="50" width="50" height="75"/></clipPath><g clip-path="url(#${hid}l)"><image class="chand" href="${c.hands}" ${base} style="${px}"/></g><g clip-path="url(#${hid}r)"><image class="chand r" href="${c.hands}" ${base} style="${px}"/></g>` : '';
725
+ if (!c.desks || !c.desks.length || (st && !prefs.customLaptop)) return hands; // a picture for a video has a laptop only when ⚙ asks for one all the time
726
+ const lid = c.desks[hash(who + '+desk') % c.desks.length], stuck = c.extras ? Object.keys(c.extras).filter((k) => /^sticker/.test(k)).map((k) => { const n = c.extras[k].length, i = hash(who + '+' + k) % (2 * n); return i < n ? `<image href="${c.extras[k][i]}" ${base} style="${px}"/>` : ''; }).join('') : ''; // its laptop, light or dark, and its stickers: one of each design or none, half of the time, always the same for a given agent
727
+ return hands + `<g class="claptop${prefs.customLaptop ? ' on' : ''}"><image href="${lid}" ${base} style="${px}"/>${stuck}</g>`; // over the hands: only the outer fingers show. Hidden unless ⚙ asks for it, or for the few seconds this character pulls it out (see LAP)
728
+ };
729
+ const room = p.custom && p.custom.bg ? uid + 'rm' + p.gid : ''; // a custom character that brings its own room: one picture, desk included; the part below the desk line is drawn again over the character, so it sits behind its desk
730
+ const fig = p.custom ? custFig(p.custom, st && o.m === 2, p.id || p.gid) : `${arm('l')}${bodyShape(p.shape, `url(#${gid})`, c2)}${arm('r')}${face}${acc}`;
539
731
  return `<svg viewBox="0 0 100 75" preserveAspectRatio="xMidYMid slice"${st ? ' xmlns="http://www.w3.org/2000/svg" width="400" height="300"' : ''}>
540
732
  <defs><linearGradient id="${gid}" gradientUnits="userSpaceOnUse" x1="0" y1="12" x2="0" y2="72"><stop offset="0" stop-color="${c1}"/><stop offset="1" stop-color="${c}"/></linearGradient>
541
733
  <linearGradient id="${uid}dk${p.scene}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${sc.desk[0]}"/><stop offset="1" stop-color="${sc.desk[1]}"/></linearGradient>
542
734
  <linearGradient id="${uid}lg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient></defs>
543
- ${sc.svg().replace(/id="(g[a-z]\d)"/g, `id="${uid}$1"`).replace(/url\(#(g[a-z]\d)\)/g, `url(#${uid}$1)`)}
544
- <g class="fig" style="--d:${d0}s">
735
+ ${room ? `<clipPath id="${room}c"><rect y="62" width="100" height="13"/></clipPath><image id="${room}" href="${p.custom.bg}" width="100" height="75" preserveAspectRatio="xMidYMid slice"${p.custom.bgSmooth ? '' : ' style="image-rendering:pixelated"'}/>` : sc.svg().replace(/id="(g[a-z]\d)"/g, `id="${uid}$1"`).replace(/url\(#(g[a-z]\d)\)/g, `url(#${uid}$1)`)}
736
+ <g class="fig${p.custom && p.custom.head ? ' still' : ''}" style="--d:${d0}s">
545
737
  ${fig}
546
738
  </g>
547
- <rect y="62" width="100" height="13" fill="url(#${uid}dk${p.scene})"/><rect y="62" width="100" height="1.3" fill="#fff" opacity=".38"/><rect y="63.3" width="100" height="2.6" fill="#000" opacity=".1"/>
548
- ${prop}${p.custom ? (prefs.customLaptop ? V('laptop', working, lapDark) : '') : V('laptop', working, lap) + V('hands', working, hands)}${V('sparks', done, `<g class="sparks">${sparks}</g>`)}
739
+ ${p.custom ? custFront(p.custom, uid + 'hd' + p.gid, p.id || p.gid) : ''}
740
+ ${room ? `<use href="#${room}" clip-path="url(#${room}c)"/>` : `<rect y="62" width="100" height="13" fill="url(#${uid}dk${p.scene})"/><rect y="62" width="100" height="1.3" fill="#fff" opacity=".38"/><rect y="63.3" width="100" height="2.6" fill="#000" opacity=".1"/>`}
741
+ ${room ? '' : prop}${p.custom ? (prefs.customLaptop && !(p.custom.desks && p.custom.desks.length) ? V('laptop', working, lapDark) : '') : V('laptop', working, lap) + V('hands', working, hands)}${V('sparks', done, `<g class="sparks">${sparks}</g>`)}
549
742
  </svg>`;
550
743
  }
551
744
 
@@ -555,7 +748,7 @@ function avatarSVG(p, o, uid = '') { // uid keeps SVG ids unique per instance:
555
748
  const S = { owner: null, errRun: {}, exQ: [], agents: {}, events: [], idx: 0, playing: false, token: 0, status: {}, tc: {}, cur: null, live: true, userPaused: false, boost: 1, stopAt: 0,
556
749
  speakers: new Set(), say: {}, lastTool: {}, level: {}, detail: null, collapsed: new Set(), title: '', idle: false, locked: true, logTo: 0, trOk: true,
557
750
  clock: 0, doneAt: {}, gone: new Set(), leaving: new Set(), demo: false, hold: false, late: [], byK: new Map(), pos: 0 };
558
- if (Q.get('pin')) S.pin = Q.get('pin'); // a session asked for in the address (the status bar opens the call on one): set here, once S exists (set above it, it stopped the whole page)
751
+ if (Q.get('pin')) S.pick = { proj: Q.get('pproj') || '', id: Q.get('pin') }; // pproj: where that session is kept, when it is not the folder the window follows (a Vibe or Codex session, see openPanel in extension.js). A session asked for in the address (the status bar opens the call on one): set here, once S exists (set above it, it stopped the whole page)
559
752
  const VANISH_MS = 120000; // a finished agent leaves the call after 2 minutes (playback time)
560
753
  // Live: how far the call is behind the real session, and what to do about it (speak faster, say less, skip decoration) so it keeps the rhythm of the real conversation
561
754
  const lagMs = (i = S.idx) => { // how much newer the newest event of the session is than the one being played: 0 when the call is up to date, however long the session has been idle
@@ -618,35 +811,37 @@ const speakable = (t) => t.replace(/https?:\/\/(?:www\.)?([\w-]+(?:\.[\w-]+)*)\S
618
811
  .replace(/\s*[—–]\s*/g, ', ').replace(/\(([^)]{0,40})\)/g, ', $1,').replace(/\s+/g, ' ').trim();
619
812
 
620
813
  // ---------- translation (local claude CLI) ----------
621
- const trMem = new Map(), trPending = new Map();
814
+ const trMaps = {}, trMap = (l = CALL()) => (trMaps[l] = trMaps[l] || new Map()), trPending = new Map();
815
+ const trMem = { has: (t) => trMap().has(t), get: (t) => trMap().get(t), set: (t, v, l) => trMap(l).set(t, v) }; // one memory per language of the call: what was translated into French is not what is said in Spanish
622
816
  const baseText = (ev, max) => short(ev.text, max || (S.live ? (ev.kind === 'order' ? 220 : 180) : (ev.kind === 'order' ? 200 : 230)));
623
817
  function ensureTr(texts) {
624
- texts = [...new Set(texts)].filter((t) => t && !trMem.has(t)).filter((t) => langOf(t) !== 'fr'); // already French: nothing to translate
625
- const waits = texts.filter((t) => trPending.has(t)).map((t) => trPending.get(t)), fresh = texts.filter((t) => !trPending.has(t));
818
+ const lang = CALL(), pk = (t) => lang + '|' + t; if (lang === 'en') return Promise.resolve([]);
819
+ texts = [...new Set(texts)].filter((t) => t && !trMem.has(t)).filter((t) => langOf(t) !== lang); // already in the language of the call: nothing to translate
820
+ const waits = texts.filter((t) => trPending.has(pk(t))).map((t) => trPending.get(pk(t))), fresh = texts.filter((t) => !trPending.has(pk(t)));
626
821
  if (fresh.length) {
627
- const pr = fetch('/api/translate', { method: 'POST', body: JSON.stringify({ texts: fresh }) }).then((r) => r.json()).then((d) => {
628
- (d.texts || []).forEach((fr, i) => trMem.set(fresh[i], fr)); S.trOk = d.ok !== false; if (!S.trOk) loadHealth(); else updateHint();
822
+ const pr = fetch('/api/translate', { method: 'POST', body: JSON.stringify({ texts: fresh, lang }) }).then((r) => r.json()).then((d) => {
823
+ (d.texts || []).forEach((x, i) => trMem.set(fresh[i], x, lang)); S.trOk = d.ok !== false; if (!S.trOk) loadHealth(); else updateHint();
629
824
  clearTimeout(S.relog); S.relog = setTimeout(() => renderLog(true), 500);
630
- }).catch(() => { S.trOk = false; loadHealth(); }).finally(() => fresh.forEach((t) => trPending.delete(t)));
631
- fresh.forEach((t) => trPending.set(t, pr)); waits.push(pr);
825
+ }).catch(() => { S.trOk = false; loadHealth(); }).finally(() => fresh.forEach((t) => trPending.delete(pk(t))));
826
+ fresh.forEach((t) => trPending.set(pk(t), pr)); waits.push(pr);
632
827
  }
633
828
  return Promise.all(waits);
634
829
  }
635
830
  function trNew(from) { // live: start translating every new line the moment it arrives (small parallel calls)
636
- if (!FR()) return; for (let k = from; k < S.events.length; k++) if (!quiet(S.events[k])) ensureTr([baseText(S.events[k])]);
831
+ if (!TRL()) return; for (let k = from; k < S.events.length; k++) if (!quiet(S.events[k])) ensureTr([baseText(S.events[k])]);
637
832
  }
638
833
  function prefetchTr(i) {
639
- if (!FR() || S.live) return; const t = [];
834
+ if (!TRL() || S.live) return; const t = [];
640
835
  for (let k = i; k < Math.min(S.events.length, i + 120) && t.length < 24; k++) if (!quiet(S.events[k])) t.push(baseText(S.events[k]));
641
836
  ensureTr(t);
642
837
  }
643
838
  function spoken(ev) {
644
- let t = baseText(ev); if (FR() && trMem.has(t)) t = trMem.get(t);
839
+ let t = baseText(ev); if (TRL() && trMem.has(t)) t = trMem.get(t);
645
840
  if (ev.kind === 'order') return `${nameOf(ev.to)}, ${t}`;
646
841
  if (ev.kind === 'report') return L('Terminé. ', 'Done. ') + t;
647
842
  return t;
648
843
  }
649
- async function loadHealth() { try { S.health = await (await fetch('/api/health')).json(); } catch {} updateHint(); }
844
+ async function loadHealth() { try { S.health = await (await fetch('/api/health')).json(); noTr = S.health.claude === null && !S.health.apiKey; } catch {} updateHint(); }
650
845
  function trProblem() { // why translation can't work, with what to do about it
651
846
  const h = S.health || {};
652
847
  if (h.claude === null && !h.apiKey) return L('Claude Code est introuvable : installez-le (npm i -g @anthropic-ai/claude-code) ou indiquez son chemin dans le réglage « agentStandup.claudePath ».', 'Claude Code not found: install it (npm i -g @anthropic-ai/claude-code) or set its path in the “agentStandup.claudePath” setting.');
@@ -655,7 +850,7 @@ function trProblem() { // why translation can't work, with what to do about it
655
850
  return L('Traduction indisponible pour l’instant : vérifiez que « claude » fonctionne dans un terminal.', 'Translation unavailable right now: check that “claude” works in a terminal.');
656
851
  }
657
852
  function updateHint() {
658
- const h = $('#trHint'), noFr = FR() && TTS.server && !TTS.pool.fr.length, noTts = prefs.voice && !TTS.server && TTS.platform !== '', noRadio = prefs.music && RADIO.err, other = elsewhere(), bad = (FR() && !S.trOk) || noFr || noTts || noRadio || other;
853
+ const h = $('#trHint'), noFr = FR() && TTS.server && !babbles() && !TTS.pool.fr.length, noTts = prefs.voice && prefs.vstyle === 'cartoon' && !TTS.server && TTS.platform !== '', noRadio = prefs.music && RADIO.err, other = elsewhere(), bad = (TRL() && !S.trOk) || noFr || noTts || noRadio || other;
659
854
  h.style.display = bad ? '' : 'none';
660
855
  h.textContent = other ? L('Le son est joué dans une autre fenêtre Agent Standup. Cliquez sur 🔈 pour le reprendre ici.', 'Sound is playing in another Agent Standup window. Click 🔈 to take it over here.') : noRadio ? L('Radio injoignable : vérifiez votre connexion ou changez de station.', 'Radio unreachable: check your connection or pick another station.') : noFr ? L('Aucune voix française installée (Windows : Paramètres › Heure et langue › Voix).', 'No French voice installed (Windows: Settings › Time & language › Speech).') : noTts ? L('Aucune voix système trouvée : les agents marmonneront.', 'No system voice found: agents will mumble.') : trProblem();
661
856
  }
@@ -792,34 +987,37 @@ const estMs = (text) => Math.min(9000, 900 + text.length * 42) / spd();
792
987
 
793
988
  const NOVELTY = /grandma|grandpa|rocko|bad news|bahh|bells|boing|bubbles|cellos|good news|jester|organ|superstar|trinoids|whisper|wobble|zarvox|albert|fred|junior|kathy|ralph|hysterical|deranged|pipe/i;
794
989
  const ROBOT = /^(eddy|flo|reed|sandy|shelley)\b/i; /* Apple's synthetic voices: understandable, and plainly a machine. Kept for when nothing else is installed */
795
- const GOOD = /premium|enhanced|natural|siri|neural|améli|amelie|thomas|jacques|audrey|aurélie|aurelie|marie|samantha|daniel|karen|moira|serena|oliver|google|hortense|julie|paul|denise|henri|eloise|zira|david|hazel|mark|aria|guy/i;
990
+ const GOOD = /premium|enhanced|natural|siri|neural|améli|amelie|thomas|jacques|audrey|aurélie|aurelie|marie|samantha|daniel|karen|moira|serena|oliver|google|hortense|julie|paul\b|denise|henri|eloise|zira|david|hazel|mark|aria|guy/i;
796
991
  const voiceScore = (n) => (/premium|enhanced|natural|neural|siri/i.test(n) ? 100 : 0) + (GOOD.test(n) ? 30 : 0) - (ROBOT.test(n) ? 50 : 0) - (NOVELTY.test(n) ? 200 : 0);
797
- const frHome = () => [...(navigator.languages || []), navigator.language || ''].map((l) => String(l).replace('-', '_')).find((l) => /^fr_[A-Z]{2}$/.test(l)) || 'fr_FR'; /* French from France unless the computer itself is set to another French */
992
+ const VLANGS = ['fr', 'en', 'es', 'pt', 'de', 'da', 'ja', 'ko', 'zh'], HOME = { fr: 'fr_FR', es: 'es_ES', pt: 'pt_BR', de: 'de_DE', da: 'da_DK', ja: 'ja_JP', ko: 'ko_KR', zh: 'zh_CN' }; /* the languages a line can be said in; where each is from when the computer does not say */
993
+ const noVoices = () => Object.fromEntries(VLANGS.map((l) => [l, []]));
994
+ const homeOf = (lang) => (lang === 'zh' && /^zh-/.test(prefs.lang) ? prefs.lang.replace('-', '_') : null) || [...(navigator.languages || []), navigator.language || ''].map((l) => String(l).replace('-', '_')).find((l) => new RegExp('^' + lang + '_[A-Z]{2}$').test(l)) || HOME[lang]; /* French from France unless the computer itself is set to another French */
798
995
  function rankVoices(list, lang) { // [{ name, locale }] → names, best distinct voices first. The synthetic ones only when fewer than two others exist
799
- const home = lang === 'fr' ? frHome() : '', sc = (v) => voiceScore(v.name) + (home && v.locale === home ? 10 : 0), seen = new Set(), out = [];
996
+ const home = HOME[lang] ? homeOf(lang) : '', sc = (v) => voiceScore(v.name) + (home && v.locale === home ? 10 : 0), seen = new Set(), out = [];
800
997
  [...list].sort((a, b) => sc(b) - sc(a)).forEach((v) => { const base = v.name.replace(/\s*\(.*$/, ''), x = sc(v); if (x > -100 && (x >= 0 || out.length < 2) && !seen.has(base)) { seen.add(base); out.push(v.name); } });
801
998
  return out.slice(0, 5);
802
999
  }
803
1000
  const TTS = {
804
- server: false, engine: 'system', platform: '', pool: { fr: [], en: [] }, sys: { fr: [], en: [] }, kv: new Set(), cache: new Map(), made: new Map(), q: [], busy: false, now: 0,
1001
+ server: false, engine: 'system', platform: '', pool: noVoices(), sys: noVoices(), kv: new Set(), cache: new Map(), made: new Map(), q: [], busy: false, now: 0,
805
1002
  async init() {
806
- this.engine = 'system'; this.server = false; this.pool = { fr: [], en: [] }; this.sys = { fr: [], en: [] }; this.kv = new Set(); this.cache.clear(); this.made.clear(); this.q = [];
1003
+ this.engine = 'system'; this.server = false; this.pool = noVoices(); this.sys = noVoices(); this.kv = new Set(); this.cache.clear(); this.made.clear(); this.q = [];
807
1004
  try {
808
- let k = null; if (prefs.vstyle === 'kokoro') { try { k = await (await fetch('/api/voices?engine=kokoro')).json(); } catch {} if (!k || !k.available || !k.ready) k = null; } // natural voices installed on demand; until they are, the system voices stay in use
1005
+ let k = null; if (prefs.vstyle === 'kokoro') { try { k = await (await fetch('/api/voices?engine=kokoro')).json(); } catch {} if (!k || !k.available || !k.ready) k = null; } // the real voices, installed on demand; until they are ready the agents babble (see babbles)
809
1006
  let d = { available: false, voices: [] }; try { d = await (await fetch('/api/voices')).json(); } catch {}
810
- this.platform = d.platform || (k && k.platform) || ''; const sys = {}; for (const l of ['fr', 'en']) sys[l] = d.available ? rankVoices(d.voices.filter((v) => v.locale.startsWith(l + '_')), l) : [];
811
- if (k) { // Kokoro speaks the languages it has voices for (English); the others are read by the system voices, each character keeping one of its own
1007
+ this.platform = d.platform || (k && k.platform) || ''; const sys = {}, of = (l) => { const all = d.voices.filter((v) => v.locale.startsWith(l + '_')), home = all.filter((v) => v.locale === homeOf(l)); return l === 'zh' && home.length ? home : all; }; /* Chinese: the voices of one place only, a Cantonese voice does not read Mandarin */
1008
+ for (const l of VLANGS) sys[l] = d.available ? rankVoices(of(l), l) : [];
1009
+ if (k) { // Kokoro speaks the languages the server lists voices for (English, and French, Spanish and Portuguese once their phonemizer is installed); a line in another language (German, Japanese…) is read by a system voice of that language, each character keeping one of its own
812
1010
  this.server = true; this.engine = 'kokoro'; this.sys = sys;
813
- for (const l of ['fr', 'en']) { const kv = k.voices.filter((v) => v.locale.startsWith(l + '_')).map((v) => v.name); kv.forEach((v) => this.kv.add(v)); this.pool[l] = kv.length ? kv : sys[l]; }
1011
+ for (const l of VLANGS) { const kv = k.voices.filter((v) => v.locale.startsWith(l + '_')).map((v) => v.name); kv.forEach((v) => this.kv.add(v)); this.pool[l] = kv.length ? kv : sys[l]; }
814
1012
  return;
815
1013
  }
816
1014
  if (!d.available) return; this.server = true; this.pool = sys; } catch {}
817
1015
  },
818
- voiceFor(p, fr = FR()) { const pool = this.pool[fr ? 'fr' : 'en']; return pool.length ? (p.id === 'main' ? pool[0] : pool[(p.vi >>> 2) % pool.length]) : null; },
1016
+ voiceFor(p, lo = CALL()) { const pool = this.pool[lo].length || lo === 'fr' ? this.pool[lo] : this.pool.en; return pool.length ? (p.id === 'main' ? pool[0] : pool[(p.vi >>> 2) % pool.length]) : null; },
819
1017
  rate() { return Math.round(Math.max(120, Math.min(330, 178 * (S.live ? 1.12 * lagFactor() * (S.boost > 1 ? 1.25 : 1) : +$('#speed').value))) / 10) * 10; },
820
1018
  rateAt(k, boost) { const i = S.idx, b = S.boost; S.idx = k; S.boost = boost; const r = this.rate(); S.idx = i; S.boost = b; return r; }, // the rate rate() will give once playback is at event k
821
1019
  buf(text, voice, rate, ahead) { // ahead: made in advance (see warmTTS); otherwise the line is wanted now
822
- const eng = this.kv.has(voice) ? 'kokoro' : 'system', fb = eng === 'kokoro' && this.sys.en.length ? this.sys.en[Math.max(0, this.pool.en.indexOf(voice)) % this.sys.en.length] : ''; /* fb: the system voice that reads the line if Kokoro cannot */
1020
+ const eng = this.kv.has(voice) ? 'kokoro' : 'system', vl = VLANGS.find((l) => this.pool[l].includes(voice)) || 'en', fb = eng === 'kokoro' && this.sys[vl].length ? this.sys[vl][Math.max(0, this.pool[vl].indexOf(voice)) % this.sys[vl].length] : ''; /* fb: the system voice of the same language that reads the line if Kokoro cannot */
823
1021
  const vt = eng + '|' + voice + '|' + text, K = (r) => eng + '|' + voice + '|' + r + '|' + text, key = K(rate), got = this.made.get(vt) || []; // got: the rates at which this text is ready in this voice
824
1022
  if (!ahead && S.live && !got.includes(rate)) { const r = got.find((x) => Math.abs(x - rate) <= rate * 0.2 && this.cache.has(K(x))); if (r) return this.cache.get(K(r)); } // made ahead at the rate of a moment ago (the call fell behind or caught up since): played as it is, a second of silence is worse than a slightly different pace
825
1023
  if (!this.cache.has(key)) {
@@ -835,6 +1033,7 @@ const TTS = {
835
1033
  const end = () => { this.busy = false; this.pump(); }; this.buf(j.text, j.voice, j.rate, true).then(end, end);
836
1034
  },
837
1035
  };
1036
+ const babbles = () => prefs.vstyle !== 'kokoro' || TTS.engine !== 'kokoro'; // babble: by choice (Animal Crossing), or because the real voices are not there yet (not installed, downloading, loading, stopped). A system voice only reads a line of a language the model lacks
838
1037
  // The lines to come are synthesized ahead of time, so that a voice starts with its line and not a second later. What is made must be what will be asked for: the same text (the lead-in, the part
839
1038
  // that is read when the call is behind), the same voice and the same rate. So this follows what run() will do with the next events if nothing else arrives before then: how it groups them
840
1039
  // (sub-agents back to back, orders in a row) and how it sets the pace. Keep the two in step: a difference costs nothing but the benefit (the line is then made when it is said).
@@ -844,7 +1043,7 @@ function paceAt(k) {
844
1043
  return { hurry, pace: Math.min(q > 7 ? 70 : q > 3 ? 130 : 260, lg > 30 ? 70 : lg > 15 ? 130 : lg > 6 ? 200 : 260), boost: hurry || S.events.length - k > 60 ? 3 : 1 };
845
1044
  }
846
1045
  function warmTTS(i) { // called by run() before each line (i is that line) and when new events arrive (i is the first of them)
847
- if (!TTS.server || !AUD.ctx || AUD.off() || !prefs.voice || prefs.vstyle === 'animal' || prefs.vstyle === 'sims') return;
1046
+ if (!TTS.server || !AUD.ctx || AUD.off() || !prefs.voice || babbles()) return;
848
1047
  const fresh = i <= S.idx, from = fresh ? i : S.idx + 1, len = S.events.length, jobs = []; let n = 0; if (!fresh && !S.playing) return; // new events while a line is being read: the lines after it are planned again, they may now be read shorter and faster
849
1048
  for (let k = from; k < Math.min(len, from + 400) && n < 4;) {
850
1049
  const e = S.events[k]; if (quiet(e)) { k++; continue; }
@@ -854,8 +1053,8 @@ function warmTTS(i) { // called by run() before each line (i is that line) and
854
1053
  else if (isSub(e.agent)) { while (j < Math.min(len, k + 28) && group.length < 3) { const e2 = S.events[j]; if (quiet(e2)) j++; else if (e2.kind !== 'order' && isSub(e2.agent) && !group.some((g) => g.agent === e2.agent)) { group.push(e2); j++; } else break; } }
855
1054
  const pl = paceAt(k), many = e.kind === 'order' && group.length > 1, rate = TTS.rateAt(many || !S.live ? k : j - 1, pl.boost);
856
1055
  for (const g of many ? [e] : group) { // orders in a row: only the first is read out
857
- n++; const p = S.agents[g.agent], bt = baseText(g); if ((pl.hurry && g.kind !== 'user') || !p || (FR() && !trMem.has(bt) && langOf(bt) !== 'fr')) continue; // not translated yet: what will be said is not known
858
- const said = clipSpeech(talkLine(g), pl.pace), text = speakable(said), voice = TTS.voiceFor(p, sessFr(said, g)); if (text && voice) jobs.push({ k, text, voice, rate });
1056
+ n++; const p = S.agents[g.agent], bt = baseText(g); if ((pl.hurry && g.kind !== 'user') || !p || (TRL() && !trMem.has(bt) && langOf(bt) !== CALL())) continue; // not translated yet: what will be said is not known
1057
+ const said = clipSpeech(talkLine(g), pl.pace), text = speakable(said), voice = TTS.voiceFor(p, sessVoice(said, g)); if (text && voice) jobs.push({ k, text, voice, rate });
859
1058
  }
860
1059
  k = j;
861
1060
  }
@@ -885,7 +1084,7 @@ const vowelKey = (ch) => ({ à: 'a', â: 'a', ä: 'a', é: 'e', è: 'e', ê: 'e'
885
1084
  async function speakBabble(text, p, gain, token) {
886
1085
  const c = AUD.ctx, sims = prefs.vstyle === 'sims', clean = speakable(text).toLowerCase(), dur = estMs(text) / 1000, noise = OFFICE.noise();
887
1086
  const base = p.lead ? 150 : p.id === 'user' ? 190 : 200 + ((p.vi >>> 2) % 9) * 30, an = c.createAnalyser(); an.fftSize = 256;
888
- const g = c.createGain(); g.gain.value = gain * (sims ? 0.4 : 0.6); an.connect(g); g.connect(AUD.voice);
1087
+ const g = c.createGain(); g.gain.value = gain * (sims ? 0.4 : 0.45 * Math.max(0.7, Math.min(1.25, 300 / base))); an.connect(g); g.connect(AUD.voice); // the blips of a high voice came out twice as loud as those of the lead: evened out
889
1088
  const clauses = clean.match(/[^.!?;:]+[.!?;:]*/g) || [clean], nodes = []; let t = c.currentTime + 0.03; const end = t + dur;
890
1089
  let tail = 0; const track = (o) => { AUD.live.add(o); nodes.push(o); tail = t; }; // tail: when the last sound starts
891
1090
  const vowelGroups = (w) => w.match(new RegExp(`[^${VOW}]*[${VOW}]+(?:[^${VOW}]+(?![${VOW}]))?`, 'g')) || [w];
@@ -901,8 +1100,8 @@ async function speakBabble(text, p, gain, token) {
901
1100
  for (const ch of w) {
902
1101
  const code = ch.charCodeAt(0), f = base * m * 2 ** (((code % 7) * 2 - 4 + (VOW.includes(ch) ? 3 : 0)) / 12), vw = [...'aeiou'][code % 5];
903
1102
  const o = c.createOscillator(), bp = c.createBiquadFilter(), env = c.createGain(); o.type = 'triangle'; o.frequency.setValueAtTime(f, t); o.frequency.linearRampToValueAtTime(f * (1 + ((code % 3) - 1) * 0.07), t + letterStep);
904
- bp.type = 'bandpass'; bp.frequency.value = FORM[vw][0] * 1.3; bp.Q.value = 1.4; env.gain.setValueAtTime(0.0001, t); env.gain.exponentialRampToValueAtTime(1, t + 0.008); env.gain.exponentialRampToValueAtTime(0.0001, t + letterStep * 0.95);
905
- o.connect(bp).connect(env).connect(an); o.start(t); o.stop(t + letterStep); track(o); t += letterStep;
1103
+ bp.type = 'bandpass'; bp.frequency.value = FORM[vw][0] * 1.3; bp.Q.value = 1.4; env.gain.setValueAtTime(0, t); env.gain.linearRampToValueAtTime(1, t + 0.008); env.gain.setTargetAtTime(0, t + 0.008, letterStep * 0.2); // a blip, not a click: it used to jump to full level in 2 ms and be gone 10 ms later, too short for its note to be heard. Same notes, same rhythm, a rounder start and a tail
1104
+ o.connect(bp).connect(env).connect(an); o.start(t); o.stop(t + letterStep * 1.5); track(o); t += letterStep;
906
1105
  }
907
1106
  t += letterStep * 0.8;
908
1107
  } else {
@@ -926,12 +1125,12 @@ async function speakBabble(text, p, gain, token) {
926
1125
  await new Promise((res) => { if (lastN) lastN.onended = res; setTimeout(res, lastN ? (t - c.currentTime) * 1000 + 600 : Math.max(100, (Math.min(t, end) - c.currentTime) * 1000 + 80)); }); // the line ends when its last sound does (a long last word used to go on after it), or when Pause stops it
927
1126
  nodes.forEach((o) => AUD.live.delete(o)); delete S.level[p.id];
928
1127
  }
929
- async function speakServer(text, p, gain, token, fr = FR()) {
930
- const voice = TTS.voiceFor(p, fr); if (!voice) throw new Error('no voice');
1128
+ async function speakServer(text, p, gain, token, lo = CALL()) {
1129
+ const voice = TTS.voiceFor(p, lo); if (!voice) throw new Error('no voice');
931
1130
  const buf = await TTS.buf(speakable(text), voice, TTS.rate()); if (token !== S.token) return;
932
1131
  const c = AUD.ctx, src = c.createBufferSource(); src.buffer = buf;
933
1132
  const an = c.createAnalyser(); an.fftSize = 256; const g = c.createGain(); g.gain.value = gain; let stops = [];
934
- if (prefs.vstyle === 'natural' || prefs.vstyle === 'kokoro') src.connect(an); else { const ch = fxChain(c, src, fxFor(p)); stops = ch.stops; ch.node.connect(an); }
1133
+ if (prefs.vstyle === 'cartoon') { const ch = fxChain(c, src, fxFor(p)); stops = ch.stops; ch.node.connect(an); } else src.connect(an);
935
1134
  an.connect(g); g.connect(AUD.voice);
936
1135
  const data = new Uint8Array(an.fftSize);
937
1136
  S.level[p.id] = () => { an.getByteTimeDomainData(data); let s = 0; for (const v of data) { const x = (v - 128) / 128; s += x * x; } return Math.sqrt(s / data.length); }; // drives the mouth
@@ -940,10 +1139,10 @@ async function speakServer(text, p, gain, token, fr = FR()) {
940
1139
  captionRun(p.id, text, ms); await new Promise((res) => { src.onended = res; setTimeout(res, ms + 1000); src.start(); }); // the line ends when its sound ends (or when Pause stops it); the timer only covers a sound that never starts
941
1140
  try { src.stop(); } catch {} AUD.live.delete(src); delete S.level[p.id]; stops.forEach((o) => { try { o.stop(); } catch {} });
942
1141
  }
943
- function speakBrowser(text, p, token, fr = FR()) { // fallback where no server voice exists (Windows/Linux)
1142
+ function speakBrowser(text, p, token, lo = CALL()) { // the browser's own voice, when the server could not make the line
944
1143
  return new Promise((resolve) => {
945
- const vs = synth.getVoices().filter((v) => v.lang.toLowerCase().startsWith(fr ? 'fr' : 'en')); if (!vs.length) return resolve(false);
946
- const ranked = rankVoices(vs.map((v) => ({ name: v.name, locale: v.lang.replace('-', '_') })), fr ? 'fr' : 'en'), voice = vs.find((v) => v.name === (p.id === 'main' ? ranked[0] : ranked[(p.vi >>> 2) % ranked.length])) || vs[0];
1144
+ const vs = synth.getVoices().filter((v) => v.lang.toLowerCase().startsWith(lo)); if (!vs.length) return resolve(false);
1145
+ const ranked = rankVoices(vs.map((v) => ({ name: v.name, locale: v.lang.replace('-', '_') })), lo), voice = vs.find((v) => v.name === (p.id === 'main' ? ranked[0] : ranked[(p.vi >>> 2) % ranked.length])) || vs[0];
947
1146
  const parts = speakable(text).match(/[^.!?;:]+[.!?;:]*/g) || [text]; synth.cancel(); let i = 0, done = false, started = false, t0 = 0, said = 0; const all = parts.reduce((n, x) => n + x.length, 0);
948
1147
  const fin = (ok) => { if (!done) { done = true; resolve(ok); } };
949
1148
  setTimeout(() => { if (!started && !done) { synth.cancel(); fin(false); } }, 2500); // engine never started (e.g. inside a webview)
@@ -952,7 +1151,7 @@ function speakBrowser(text, p, token, fr = FR()) { // fallback where no server
952
1151
  if (i >= parts.length || done || token !== S.token) return fin(true);
953
1152
  if (t0 && said >= 20) { const el = performance.now() - t0; captionRun(p.id, text, el * all / said, el); } // the length of the audio is not known in advance here: the subtitles are set again on the pace the voice really has, after each sentence
954
1153
  said += parts[i].length; const part = parts[i++].trim(); if (!part) return next();
955
- const u = new SpeechSynthesisUtterance(part); u.lang = fr ? 'fr-FR' : 'en-US'; u.voice = voice; u.pitch = prefs.vstyle === 'natural' ? 0.95 + ((p.vi >>> 5) % 5) * 0.03 : p.id === 'main' ? 0.8 : [1.5, 0.6, 1.2, 1.7, 0.9, 0.5, 1.35][(p.vi >>> 3) % 7]; u.rate = Math.min(1.7, 0.97 * spd());
1154
+ const u = new SpeechSynthesisUtterance(part); u.lang = lo === 'en' ? 'en-US' : homeOf(lo).replace('_', '-'); u.voice = voice; u.pitch = prefs.vstyle !== 'cartoon' ? 0.95 + ((p.vi >>> 5) % 5) * 0.03 : p.id === 'main' ? 0.8 : [1.5, 0.6, 1.2, 1.7, 0.9, 0.5, 1.35][(p.vi >>> 3) % 7]; u.rate = Math.min(1.7, 0.97 * spd());
956
1155
  u.onstart = () => { started = true; if (!t0) { t0 = performance.now(); captionRun(p.id, text, estMs(text)); } }; u.onend = () => setTimeout(next, 120); u.onerror = () => fin(started); synth.speak(u);
957
1156
  };
958
1157
  next();
@@ -982,34 +1181,36 @@ function captionRun(id, text, totalMs, from = 0) { // from: how far into the l
982
1181
  for (const x of ps) { const when = at - from; if (when <= 0) cur = x; else timers.push(setTimeout(() => setCaption(id, x), when)); at += totalMs * x.length / n; }
983
1182
  setCaption(id, cur); capTimers.set(id, timers);
984
1183
  }
985
- const frVoice = (t) => (langOf(t) ?? (FR() ? 'fr' : 'en')) === 'fr'; // a French line gets a French voice whatever the interface language, and the other way round
1184
+ // In a Spanish or Portuguese call every line is meant to be in that language (it was translated into it) unless it is plainly English: Spanish, Portuguese and French share too many short words to be told apart on one line.
1185
+ const inCall = (lo) => { const c = CALL(); return !lo ? c : (c === 'es' || c === 'pt') && lo !== 'en' ? c : lo; };
1186
+ const voiceLang = (t) => inCall(langOf(t)); // a French line gets a French voice whatever the language of the call, and the same for the others
986
1187
  // A line of the session that is too short to tell ("OK.", a file name) does not follow the interface language: in a French session watched in English, the lead would change voice for that
987
1188
  // one line and change back. It follows, in this order: the whole line it is cut from, what the same character said just before (its voice goes on) or says next, the language of the session so far.
988
- // The session's language is counted once per line as the events arrive; in French, a line counts for what is said, i.e. its translation once it is there.
989
- const SL = { ev0: null, ui: null, n: 0, fr: 0, en: 0, pend: [] };
990
- function sessLang() { // 'fr' or 'en': the majority among the lines of the session that langOf can decide; null when there is none
991
- const ev = S.events, ui = FR(), add = (t) => { const lo = langOf(t); if (lo) SL[lo]++; };
992
- if (ev[0] !== SL.ev0 || ui !== SL.ui || ev.length < SL.n) Object.assign(SL, { ev0: ev[0], ui, n: 0, fr: 0, en: 0, pend: [] }); // another session, or another interface language
993
- for (; SL.n < ev.length; SL.n++) { const e = ev[SL.n]; if (quiet(e) || typeof e.text !== 'string') continue; const t = baseText(e); if (!ui) add(t); else if (trMem.has(t)) add(trMem.get(t)); else if (langOf(t) === 'fr') SL.fr++; else SL.pend.push(t); }
1189
+ // The session's language is counted once per line as the events arrive; when the call is translated, a line counts for what is said, i.e. its translation once it is there.
1190
+ const SL = { ev0: null, ui: null, n: 0, c: {}, pend: [] };
1191
+ function sessLang() { // the majority among the lines of the session that langOf can decide; null when there is none
1192
+ const ev = S.events, ui = CALL(), add = (t) => { const lo = langOf(t); if (lo) SL.c[lo] = (SL.c[lo] || 0) + 1; };
1193
+ if (ev[0] !== SL.ev0 || ui !== SL.ui || ev.length < SL.n) Object.assign(SL, { ev0: ev[0], ui, n: 0, c: {}, pend: [] }); // another session, or another language of the call
1194
+ for (; SL.n < ev.length; SL.n++) { const e = ev[SL.n]; if (quiet(e) || typeof e.text !== 'string') continue; const t = baseText(e); if (ui === 'en') add(t); else if (trMem.has(t)) add(trMem.get(t)); else if (langOf(t) === ui) SL.c[ui] = (SL.c[ui] || 0) + 1; else SL.pend.push(t); }
994
1195
  if (SL.pend.length) SL.pend = SL.pend.filter((t) => !trMem.has(t) || add(trMem.get(t))); // translations that have arrived since
995
- return SL.fr > SL.en ? 'fr' : SL.en > SL.fr ? 'en' : null;
1196
+ const top = Object.entries(SL.c).sort((a, b) => b[1] - a[1]); return top.length && (top.length < 2 || top[0][1] > top[1][1]) ? top[0][0] : null;
996
1197
  }
997
- function sessFr(text, ev) { // for the lines that come from the session (ev: the event, when there is one); the little built-in lines keep frVoice, they are written in the interface language
1198
+ function sessVoice(text, ev) { // for the lines that come from the session (ev: the event, when there is one); the little built-in lines keep voiceLang, they are written in the language of the call
998
1199
  let lo = langOf(text);
999
1200
  if (!lo && ev) {
1000
- const now = (e) => { const t = baseText(e); return langOf(FR() && trMem.has(t) ? trMem.get(t) : t); }, at = S.events.indexOf(ev, Math.max(0, S.idx - 60)); lo = now(ev);
1201
+ const now = (e) => { const t = baseText(e); return langOf(TRL() && trMem.has(t) ? trMem.get(t) : t); }, at = S.events.indexOf(ev, Math.max(0, S.idx - 60)); lo = now(ev);
1001
1202
  for (let k = at - 1, n = 0; !lo && k >= 0 && k > at - 5000 && n < 6; k--) { const e = S.events[k]; if (e.agent === ev.agent && !quiet(e) && typeof e.text === 'string') { lo = now(e); n++; } }
1002
1203
  for (let k = at + 1, n = 0; !lo && at >= 0 && k < S.events.length && k < at + 5000 && n < 6; k++) { const e = S.events[k]; if (e.agent === ev.agent && !quiet(e) && typeof e.text === 'string') { lo = now(e); n++; } } // its first words: what it says next, when that is already there
1003
1204
  }
1004
- return (lo ?? sessLang() ?? (FR() ? 'fr' : 'en')) === 'fr';
1205
+ return inCall(lo ?? sessLang());
1005
1206
  }
1006
- async function speakLine(text, p, primary, token, fr = frVoice(text), always = false) { // always: your own lines are voiced even when the call is behind
1207
+ async function speakLine(text, p, primary, token, lo = voiceLang(text), always = false) { // always: your own lines are voiced even when the call is behind
1007
1208
  captionRun(p.id, text, estMs(text));
1008
1209
  if (AUD.off() || !prefs.voice) { if (!AUD.off() && prefs.office) AUD.murmur(0.5 + (p.vi % 5) / 10, estMs(text) / 1000); return sleep(estMs(text)); }
1009
1210
  if (S.hurry && !always) return sleep(estMs(text));
1010
- if ((prefs.vstyle === 'animal' || prefs.vstyle === 'sims') && AUD.ctx) { try { await speakBabble(text, p, primary ? 1 : 0.5, token); return; } catch {} }
1011
- if (TTS.server && AUD.ctx) { try { await speakServer(text, p, primary ? 1 : 0.5, token, fr); return; } catch {} }
1012
- if (primary && synth && !EMBED && (await speakBrowser(text, p, token, fr))) return;
1211
+ const bab = babbles(); if (bab && AUD.ctx) { try { await speakBabble(text, p, primary ? 1 : 0.5, token); return; } catch {} }
1212
+ if (!bab && TTS.server && AUD.ctx) { try { await speakServer(text, p, primary ? 1 : 0.5, token, lo); return; } catch {} }
1213
+ if (!bab && primary && synth && !EMBED && (await speakBrowser(text, p, token, lo))) return;
1013
1214
  if (token !== S.token) return; // paused while a voice was being tried: no mumble after the fact
1014
1215
  const ms = estMs(text), o = AUD.murmur(0.5 + (p.vi % 5) / 10, ms / 1000); captionRun(p.id, text, ms);
1015
1216
  return o ? new Promise((res) => { o.addEventListener('ended', res); setTimeout(res, ms + 500); }) : sleep(ms); // the mumble that stands in for a voice: the line ends with it, also when Pause stops it
@@ -1082,7 +1283,7 @@ const applyStatus = (ev) => {
1082
1283
  if (ev.kind === 'user' || (ev.agent === 'main' && (ev.kind === 'say' || ev.kind === 'tools' || (ev.kind === 'order' && !ev.wf)))) S.turnOver = !!ev.end; // Claude Code marks the message that closes the lead's turn; anything after it opens the next one (not the agents a workflow launches by itself)
1083
1284
  };
1084
1285
  function recomputeStatus(upTo) {
1085
- S.files = new Map(); S.cands = new Map(); S.turnN = 0; S.turnSaid = '';
1286
+ S.files = new Map(); S.cands = new Map(); S.turnN = 0; S.turnSaid = ''; S.arts = new Map(); S.artCalls = new Map();
1086
1287
  S.term = {}; S.todos = {}; S.run = {}; S.act = {}; S.usage = {}; S.errs = {}; S.lastAct = {}; S.waitOn = {}; S.orderTs = {}; S.prevState = {}; S.lastTool = {}; S.mainBusyAt = 0; S.turnOver = false; S.th = {}; S.ctx = {}; S.model = {}; S.cw = {}; S.compacts = {}; S.ctxWarned = {}; S.rep = {}; S.loops = {}; S.recomputing = true; document.querySelectorAll('.tile').forEach((t) => { clearTimeout(t._byeT); t.classList.remove('bye'); }); hidePresent();
1087
1288
  S.status = {}; S.tc = {}; S.doneAt = {}; S.gone.clear(); S.leaving.clear(); document.querySelectorAll('.tile.vanishing').forEach((t) => t.classList.remove('vanishing')); const doneIdx = {}; document.querySelectorAll('.ticker').forEach((x) => { x.classList.remove('on'); x.innerHTML = ''; });
1088
1289
  for (let i = 0; i < upTo; i++) {
@@ -1103,7 +1304,7 @@ function syncUI() {
1103
1304
  // ---------- tool ticker, shared screen, flying messages ----------
1104
1305
  // ---------- what each agent is doing: tool calls with their real outputs ----------
1105
1306
  S.term = {}; S.todos = {}; S.run = {}; S.act = {}; S.usage = {}; S.errs = {}; S.lastAct = {}; S.waitOn = {}; S.orderTs = {}; S.prevState = {}; S.ctx = {}; S.model = {}; S.cw = {}; S.compacts = {}; S.ctxWarned = {}; S.rep = {}; S.loops = {}; S.present = null; S.camFor = null; let presentTimer = null;
1106
- S.files = new Map(); S.cands = new Map(); S.turnN = 0; S.turnSaid = ''; S.fgone = new Set(); S.fmade = new Map(); // files: path → the Write call that created it, in the order they were written · cands: the documents the commands name (see candFile) · turnN: how many orders you gave so far · turnSaid: what you and the lead said in this turn · fgone: the files found missing on a click · fmade: what the server answered about a document a command names
1307
+ S.files = new Map(); S.cands = new Map(); S.turnN = 0; S.turnSaid = ''; S.fgone = new Set(); S.fmade = new Map(); S.arts = new Map(); S.artCalls = new Map(); S.artOk = new Map(); S.artPin = null; // files: path → the Write call that created it, in the order they were written · cands: the documents the commands name (see candFile) · turnN: how many orders you gave so far · turnSaid: what you and the lead said in this turn · fgone: the files found missing on a click · fmade: what the server answered about a document a command names
1107
1308
  const later = (k, fn, ms = 160) => { later.p = later.p || {}; if (later.p[k]) return; later.p[k] = setTimeout(() => { later.p[k] = 0; fn(); }, ms); }; // coalesce bursts of repaints
1108
1309
  const fmtTok = (n) => (n < 1000 ? String(n) : n < 1e6 ? (n / 1000).toFixed(n < 1e4 ? 1 : 0) + 'k' : (n / 1e6).toFixed(n < 1e7 ? 2 : 1) + 'M');
1109
1310
  const tokTotal = (u) => (u ? u.i + u.o + u.w : 0); // headline = input + output + cache writes; cache reads are cheap and shown separately
@@ -1198,11 +1399,12 @@ function fitBoard(force) { // the chips lose their words when they do not all
1198
1399
  }
1199
1400
  addEventListener('resize', () => fitBoard(true)); new ResizeObserver(() => requestAnimationFrame(() => fitBoard(true))).observe($('#board')); /* the room the chips have also changes when the texts beside them do (a title, a longer status) */
1200
1401
  const RORDER = { blocked: 0, stalled: 1, working: 2, waiting: 3, idle: 4, done: 5 };
1402
+ const TOOL = { _codex: 'Codex', _vibe: 'Vibe', _cowork: 'Cowork' }, leadTool = (p) => (p.id === 'main' && S.cur && TOOL[S.cur.proj] ? ' · ' + TOOL[S.cur.proj] : ''); // a session that is not a Claude Code one says which tool runs it: on its tab, and next to its lead, who has the same name in every call
1201
1403
  const rosTok = (id) => { const u = S.usage[id]; return u && tokTotal(u) ? `<span class="rt" title="${esc(tokTip(u))}">⚡${fmtTok(tokTotal(u))}</span>` : ''; };
1202
1404
  function paintRoster(ros) { // a fixed list beside the call: who is doing what, urgent first, readable even with dozens of agents
1203
1405
  const box = $('#roster'); if (!box || !document.body.classList.contains('rost')) return;
1204
1406
  ros.sort((a, b) => (a.p.id === 'main' ? -1 : b.p.id === 'main' ? 1 : (RORDER[a.st.k] - RORDER[b.st.k]) || (S.lastAct[b.p.id] || 0) - (S.lastAct[a.p.id] || 0)));
1205
- const rows = ros.slice(0, 60).map(({ p, st }) => `<div class="rr k-${st.k}${isTurn(p.id, st) ? ' turn' : ''}${S.focus === p.id ? ' sel' : ''}${S.speakers.has(p.id) ? ' speaking' : ''}" data-id="${esc(p.id)}" tabindex="0" role="button" aria-label="${esc(p.name)}, ${esc(st.txt || '')}"><div class="n"><span class="dot" style="background:${p.shirt}"></span><b>${esc(p.name)}</b><span class="ro">${esc(p.role)}</span>${rosTok(p.id)}</div><div class="st">${esc(st.txt || L('en veille', 'standing by'))}${S.loops[p.id] ? ' 🔁' : ''}</div></div>`).join('');
1407
+ const rows = ros.slice(0, 60).map(({ p, st }) => `<div class="rr k-${st.k}${isTurn(p.id, st) ? ' turn' : ''}${S.focus === p.id ? ' sel' : ''}${S.speakers.has(p.id) ? ' speaking' : ''}" data-id="${esc(p.id)}" tabindex="0" role="button" aria-label="${esc(p.name)}, ${esc(st.txt || '')}"><div class="n"><span class="dot" style="background:${p.shirt}"></span><b>${esc(p.name)}</b><span class="ro">${esc(p.role + leadTool(p))}</span>${rosTok(p.id)}</div><div class="st">${esc(st.txt || L('en veille', 'standing by'))}${S.loops[p.id] ? ' 🔁' : ''}</div></div>`).join('');
1206
1408
  const left = Object.values(S.agents).filter((p) => S.gone.has(p.id) && p.id !== 'main' && p.id !== 'user').sort((a, b) => (S.lastAct[b.id] || 0) - (S.lastAct[a.id] || 0)); // a finished agent's tile leaves the stage: its line stays here, with what it used
1207
1409
  const gone = left.slice(0, 40).map((p) => `<div class="rr left" data-id="${esc(p.id)}" tabindex="0" role="button" aria-label="${esc(p.name)}"><div class="n"><span class="dot" style="background:${p.shirt}"></span><b>${esc(p.name)}</b><span class="ro">${esc(p.role)}</span>${rosTok(p.id)}</div></div>`).join('');
1208
1410
  const html = `<h3>${L('Agents', 'Agents')} · ${ros.length}</h3>${rows}${ros.length > 60 ? `<div class="ro" style="padding:4px 8px">+${ros.length - 60}</div>` : ''}${left.length ? `<h3 style="margin-top:8px">${L('terminés', 'done')} · ${left.length}</h3>${gone}` : ''}`;
@@ -1263,6 +1465,7 @@ function activityLabel(t) { // the short "what is on their screen" tag
1263
1465
  case 'grep': return L('Cherche « ', 'Searching “') + String(d.pattern || '').slice(0, 22) + L(' »', '”');
1264
1466
  case 'glob': return L('Liste ', 'Listing ') + String(d.pattern || '').slice(0, 24);
1265
1467
  case 'todo': return L('Met à jour sa todo', 'Updating todo list');
1468
+ case 'artifact': return L('Publie ', 'Publishing ') + (d.title || f).slice(0, 30);
1266
1469
  case 'web': return d.url ? L('Consulte ', 'Fetching ') + d.url.replace(/^https?:\/\//, '').slice(0, 26) : L('Recherche sur le web', 'Web search');
1267
1470
  case 'text': { const w = d.what; if (w === 'question') return L('Pose une question', 'Asking a question'); if (w === 'skill') return L('Utilise ', 'Using skill ') + (d.v || ''); if (w === 'mcp') return d.v || t.name; if (w === 'toolsearch') return L('Cherche un outil', 'Looking for a tool'); return t.name; }
1268
1471
  default: return t.name;
@@ -1277,7 +1480,7 @@ function pushTerm(id, tool) {
1277
1480
  }
1278
1481
  function applyResults(ev, silent) { // the output of a tool call arrives
1279
1482
  const buf = S.term[ev.agent] || []; let last = null;
1280
- for (const it of ev.items) for (let i = buf.length - 1; i >= 0; i--) if (buf[i].id === it.id) { Object.assign(buf[i], { out: it.out, err: it.err, end: ev.ts, img: it.img || 0, picAt: it.img && !silent ? performance.now() : 0 }); last = buf[i]; break; }
1483
+ for (const it of ev.items) for (let i = buf.length - 1; i >= 0; i--) if (buf[i].id === it.id) { Object.assign(buf[i], { out: it.out, err: it.err, end: ev.ts, img: it.img || 0, picAt: it.img && !silent ? performance.now() : 0, art: it.art || null }); last = buf[i]; break; }
1281
1484
  if (S.run[ev.agent] && ev.items.some((it) => it.id === S.run[ev.agent].id)) delete S.run[ev.agent];
1282
1485
  if (silent || !last) return;
1283
1486
  setTicker(ev.agent, last); if (S.present === ev.agent) { renderPresent(); armPresent(); }
@@ -1310,6 +1513,7 @@ const mediaUrl = (agent, tool, n) => `/api/media?proj=${encodeURIComponent(S.cur
1310
1513
  function termModel(id) {
1311
1514
  const buf = S.term[id] || [], last = buf[buf.length - 1], lines = [], more = (n) => ({ c: 'dim', t: `… +${n} ${L('lignes', 'lines')}` });
1312
1515
  const pic = S.cur && buf.slice(-12).reverse().find((e) => e.img), fresh = pic && performance.now() - pic.picAt < (S.live ? 8000 : 2500 / spd()); // a picture a tool returned (screenshot, image file) stays up for a few seconds whatever comes next, then for the next few calls: a screenshot is usually followed by a click or two
1516
+ const web = last && last.k === 'artifact' && last.art ? S.arts.get(last.art.url) : null; if (web) return artModel(web, id); // a page that was just published: the browser window, until the agent does something else
1313
1517
  if (pic && (fresh || (buf.length - buf.indexOf(pic) <= 4 && (pic === last || !/^(edit|write|read)$/.test(last.k))))) return { view: 'image', title: pic.k === 'read' ? base(pic.tool.d.file) : pic.tool.name.split('__').pop(), imgs: Array.from({ length: Math.min(pic.img, 3) }, (_, n) => mediaUrl(id, pic.id, n)), more: pic.img - 3, lines, stat: statOf(last, id) };
1314
1518
  if (last && (last.k === 'edit' || last.k === 'write' || last.k === 'read')) {
1315
1519
  const d = last.tool.d, rows = (txt, c) => String(txt || '').split('\n').slice(0, 14).map((t) => ({ c, t }));
@@ -1335,14 +1539,15 @@ const lineHtml = (l, view) => view === 'editor'
1335
1539
 
1336
1540
  // ---------- screen sharing: a real video-call presentation (window + presenter camera) ----------
1337
1541
  function renderPresent() {
1338
- const id = S.present, p = S.agents[id]; if (!p) return; const m = termModel(id);
1339
- $('#present .pwin').className = 'pwin ' + (m.view === 'term' ? 'term' : m.view); if ($('#present').classList.toggle('pic', m.view === 'image') !== S.picUp) { S.picUp = m.view === 'image'; layout(); } // a picture gets a taller window
1542
+ const id = S.present, p = S.agents[id]; if (!p) return; if (S.artPin && !S.arts.has(S.artPin)) { S.artPin = null; armPresent(); }
1543
+ const pinned = S.artPin ? S.arts.get(S.artPin) : null, m = pinned ? artModel(pinned, id) : termModel(id), shape = m.view === 'web' && pinned ? 'pin' : m.view === 'web' || m.view === 'image' ? 'pic' : '';
1544
+ $('#present .pwin').className = 'pwin ' + (m.view === 'term' ? 'term' : m.view); $('#present').classList.toggle('pic', shape === 'pic'); $('#present').classList.toggle('pin', shape === 'pin'); if (shape !== S.picUp) { S.picUp = shape; layout(); } // a picture or a page gets a taller window, a pinned page the tallest
1340
1545
  $('#ptitle').textContent = m.view === 'term' ? `${p.name} — zsh — 96×24` : m.title;
1341
- const pb = $('#pbody'), shown = m.view === 'image' ? m.imgs.join(' ') : '';
1342
- if (shown) { if (pb.dataset.img !== shown) pb.innerHTML = m.imgs.map((u) => `<img src="${esc(u)}" alt="">`).join('') + (m.more > 0 ? `<span class="pmore">+${m.more}</span>` : ''); } // the same pictures are left in place: redrawing them would make them blink
1546
+ const pb = $('#pbody'), shown = m.view === 'image' ? m.imgs.join(' ') : m.view === 'web' ? m.key : ''; pb.dataset.art = m.view === 'web' ? m.a.url : '';
1547
+ if (shown) { if (pb.dataset.img !== shown) pb.innerHTML = m.view === 'web' ? artHtml(m) : m.imgs.map((u) => `<img src="${esc(u)}" alt="">`).join('') + (m.more > 0 ? `<span class="pmore">+${m.more}</span>` : ''); } // the same pictures are left in place: redrawing them would make them blink
1343
1548
  else pb.innerHTML = (m.view === 'editor' ? `<div class="ptab"><span>${esc(m.tab.file)}</span><em>${esc(m.tab.path)}</em></div>` : '') + m.lines.map((l) => lineHtml(l, m.view)).join('') + (m.view === 'term' ? '<div class="tl"><span class="ps">❯</span> <span class="cursor"></span></div>' : '');
1344
- pb.dataset.img = shown; pb.scrollTop = m.view === 'term' ? pb.scrollHeight : 0; $('#pstat').textContent = m.stat;
1345
- const td = S.todos[id], el = $('#ptodo'), tk = td && td.length ? prefs.lang + '\n' + td.map((x) => x.s + ' ' + x.c).join('\n') : ''; el.style.display = tk ? '' : 'none'; $('#present').classList.toggle('has-todo', !!tk);
1549
+ pb.dataset.img = shown; pb.scrollTop = m.view === 'term' ? pb.scrollHeight : 0; $('#pstat').textContent = m.stat; if (m.view === 'web') fitArt();
1550
+ const td = S.todos[id], el = $('#ptodo'), tk = m.view !== 'web' && td && td.length ? prefs.lang + '\n' + td.map((x) => x.s + ' ' + x.c).join('\n') : ''; el.style.display = tk ? '' : 'none'; $('#present').classList.toggle('has-todo', !!tk);
1346
1551
  if (tk && el.dataset.k !== tk) { // redrawn only when it changes, so it stays where you scrolled it; the task in progress is brought into view
1347
1552
  el.innerHTML = `<h5>${L('Tâches', 'Tasks')} · ${td.filter((x) => x.s === 'completed').length}/${td.length}</h5>` + td.map((x) => `<div class="td ${x.s}"><i>${x.s === 'completed' ? '☑' : x.s === 'in_progress' ? '◐' : '☐'}</i>${esc(x.c)}</div>`).join('');
1348
1553
  const cur = el.querySelector('.in_progress'); el.scrollTop = cur ? Math.max(0, cur.offsetTop - el.clientHeight / 2) : 0;
@@ -1353,18 +1558,62 @@ function renderPresent() {
1353
1558
  camTok();
1354
1559
  $('#pcam').classList.toggle('speaking', S.speakers.has(id));
1355
1560
  }
1356
- function armPresent() { // stays up while a command is still running, then ~4 s after the last action (~9 s when it shows a picture)
1357
- clearTimeout(presentTimer); if (S.hold) return;
1358
- presentTimer = setTimeout(() => { if (S.present && S.run[S.present] && S.playing) armPresent(); else hidePresent(); }, ($('#present').classList.contains('pic') ? 9000 : 4200) / Math.max(1, spd() / 1.2));
1561
+ function armPresent() { // stays up while a command is still running, then ~4 s after the last action (~9 s when it shows a picture, ~20 s for the page of an artifact; a pinned page stays until it is closed)
1562
+ clearTimeout(presentTimer); if (S.hold || S.artPin) return;
1563
+ presentTimer = setTimeout(() => { if (S.present && S.run[S.present] && S.playing) armPresent(); else hidePresent(); }, ($('#present .pwin').classList.contains('web') ? 20000 : $('#present').classList.contains('pic') ? 9000 : 4200) / Math.max(1, spd() / 1.2));
1359
1564
  }
1360
1565
  function showPresent(id) {
1361
- if (S.boost > 1 || (S.speakers.size && !S.speakers.has(id))) return; // catching up, or someone else has the floor
1566
+ if (S.artPin || S.boost > 1 || (S.speakers.size && !S.speakers.has(id))) return; // a page you pinned stays up · catching up, or someone else has the floor
1362
1567
  const first = S.present !== id; S.present = id; $('#present').classList.add('on'); document.body.classList.add('presenting'); document.querySelectorAll('.tile.presenter').forEach((t) => t.classList.remove('presenter')); const pt = $('#t-' + id); if (pt) pt.classList.add('presenter'); renderPresent(); if (first) { layout(); AUD.tone(880, .12, 'sine', .05); }
1363
1568
  armPresent();
1364
1569
  }
1365
1570
  function hidePresent() {
1366
- clearTimeout(presentTimer); if (!S.present) return; S.present = null; $('#present').classList.remove('on'); document.body.classList.remove('presenting'); document.querySelectorAll('.tile.presenter').forEach((t) => t.classList.remove('presenter')); $('#pcap').textContent = ''; layout();
1571
+ clearTimeout(presentTimer); if (!S.present || S.artPin) return; if ($('#pbody').dataset.art) { $('#pbody').innerHTML = ''; $('#pbody').dataset.img = $('#pbody').dataset.art = ''; } /* the page of an artifact does not go on running behind a closed window */
1572
+ S.present = null; $('#present').classList.remove('on'); document.body.classList.remove('presenting'); document.querySelectorAll('.tile.presenter').forEach((t) => t.classList.remove('presenter')); $('#pcap').textContent = ''; layout();
1573
+ }
1574
+ // ---------- artifacts: the pages the session published on claude.ai, shown the way a call shows a browser window someone shares ----------
1575
+ // When a publish succeeds its author shares the page for a moment; afterwards it is in the line of files, and a click there pins it: the window takes the room, stays until you close it (✕, Esc),
1576
+ // follows the next versions and steps through the other artifacts of the session (‹ ›). The page itself comes from the server, which puts it together from the session file (claude.ai lets nobody frame it):
1577
+ // a frame that can reach neither the app nor, unless you ask for the libraries, the network. Where there is no page to show (made from a claude.ai template, or written another way) the window says so and gives the link.
1578
+ const artSrc = (a) => `/api/artifact?proj=${encodeURIComponent(S.cur.proj)}&id=${encodeURIComponent(S.cur.id)}&agent=${encodeURIComponent(a.agent)}&tool=${encodeURIComponent(a.id)}`;
1579
+ function noteArts(ev) { // one entry per artifact, the last publish of it: published again, it is the newest and shows its new version
1580
+ if (ev.kind === 'tools') { for (const t of ev.tools) if (t.d && t.d.kind === 'artifact') S.artCalls.set(t.id, { agent: ev.agent, title: t.d.title || '', note: t.d.note || '' }); return; }
1581
+ if (ev.kind !== 'results') return;
1582
+ for (const it of ev.items) { const c = it.art && S.artCalls.get(it.id); if (!c) continue; const u = it.art.url, was = S.arts.get(u) || {}; S.arts.delete(u); S.arts.set(u, { url: u, title: it.art.title || c.title || was.title || 'Artifact', note: c.note || was.note || '', agent: c.agent, id: it.id, v: it.art.v || 0, typed: !!it.art.typed, turn: S.turnN }); if (S.artPin === u) later('art', renderPresent); }
1583
+ }
1584
+ function askArt(a) { // is there a page to show for that publish? Asked once: null while the answer is on its way
1585
+ if (S.artOk.has(a.id)) return S.artOk.get(a.id); if (a.typed || S.demo || !S.cur) { S.artOk.set(a.id, { ok: false }); return S.artOk.get(a.id); }
1586
+ const cur = S.cur; S.artOk.set(a.id, null);
1587
+ fetch(artSrc(a) + '&check=1').then((r) => r.json()).then((j) => { if (S.cur !== cur) return; S.artOk.set(a.id, { ok: !!j.ok, net: !!j.net }); if (S.present) renderPresent(); }).catch(() => { if (S.cur === cur) S.artOk.delete(a.id); });
1588
+ return null;
1367
1589
  }
1590
+ function artModel(a, id) {
1591
+ const st = askArt(a), all = [...S.arts.keys()], pinned = S.artPin === a.url, buf = S.term[id] || [];
1592
+ return { view: 'web', title: a.title, lines: [], a, st, pinned, n: all.length, i: all.indexOf(a.url), stat: a.note || statOf(buf[buf.length - 1], id), key: [a.url, a.id, st ? (st.ok ? 'ok' : 'no') : '?', st && st.net ? 'n' : '', prefs.artNet ? 'N' : '', pinned ? 'p' + all.indexOf(a.url) + '/' + all.length : '', prefs.lang].join('|') };
1593
+ }
1594
+ function artHtml(m) {
1595
+ const a = m.a, ok = m.st && m.st.ok, libs = ok && m.st.net && !prefs.artNet, open = esc(L('Ouvrir sur claude.ai', 'Open on claude.ai'));
1596
+ const nav = m.pinned && m.n > 1 ? `<button class="pnb" data-go="-1">‹</button><span class="pnn">${m.i + 1}/${m.n}</span><button class="pnb" data-go="1">›</button>` : '';
1597
+ const bar = `<div class="pnav">${nav}<span class="purl">🔒 ${esc(a.url.replace(/^https:\/\//, ''))}</span>${a.v > 1 ? `<span class="pnn">v${a.v}</span>` : ''}${libs ? `<button class="pnb lib" data-lib title="${esc(L('Cette page utilise des bibliothèques hébergées ailleurs : elles ne sont chargées que si vous le demandez', 'This page uses libraries kept on other servers: they are loaded only if you ask'))}">${esc(L('Charger ses bibliothèques', 'Load its libraries'))}</button>` : ''}<button class="pnb" data-open title="${open}" aria-label="${open}">↗</button>${m.pinned ? `<button class="pnb" data-x title="${esc(L('Fermer', 'Close'))}" aria-label="${esc(L('Fermer', 'Close'))}">✕</button>` : ''}</div>`;
1598
+ const page = ok ? `<iframe sandbox="allow-scripts" referrerpolicy="no-referrer" title="${esc(a.title)}" src="${esc(artSrc(a) + (prefs.artNet ? '&net=1' : ''))}"></iframe>` + (m.pinned ? '' : `<button class="pzoom" data-pin title="${esc(L('Cliquer pour agrandir', 'Click to enlarge'))}" aria-label="${esc(L('Cliquer pour agrandir', 'Click to enlarge'))}"></button>`)
1599
+ : `<div class="pcard"><i>🌐</i><b>${esc(a.title)}</b>${a.note ? `<p>${esc(a.note)}</p>` : ''}${m.st ? `<em>${esc(L('Pas d’aperçu ici : la page est sur claude.ai', 'No preview here: the page is on claude.ai'))}</em><button class="pnb" data-open>${open} ↗</button>` : '<span class="spin"></span>'}</div>`;
1600
+ return bar + `<div class="pweb">${page}</div>`;
1601
+ }
1602
+ function fitArt() { const w = $('#pbody .pweb'); if (w) w.style.setProperty('--z', (S.artPin ? 1 : Math.min(1, Math.max(.2, w.clientWidth / 1100))).toFixed(3)); } // shared: the page is laid out 1100 px wide and shown smaller, as a screen is; pinned: at its real size
1603
+ function pinArt(url) {
1604
+ const a = S.arts.get(url); if (!a) return; const id = S.agents[a.agent] ? a.agent : 'main', first = S.present !== id; filesPop(false); clearTimeout(presentTimer); S.artPin = url; S.present = id;
1605
+ $('#present').classList.add('on'); document.body.classList.add('presenting'); document.querySelectorAll('.tile.presenter').forEach((t) => t.classList.remove('presenter')); const pt = $('#t-' + id); if (pt) pt.classList.add('presenter'); renderPresent(); if (first) layout();
1606
+ }
1607
+ function unpinArt() { if (!S.artPin) return; S.artPin = null; hidePresent(); }
1608
+ $('#present').addEventListener('click', (e) => {
1609
+ const b = e.target.closest('[data-open], [data-x], [data-go], [data-lib], [data-pin]'), a = b && S.arts.get($('#pbody').dataset.art || ''); if (!a) return; const d = b.dataset;
1610
+ if ('open' in d) openExternal(a.url); else if ('x' in d) unpinArt(); else if ('pin' in d) pinArt(a.url);
1611
+ else if ('lib' in d) { prefs.artNet = true; savePrefs(); const sw = document.querySelector('#prefs .mi[data-t="artNet"] .sw'); if (sw) sw.classList.add('on'); renderPresent(); }
1612
+ else if ('go' in d) { const all = [...S.arts.keys()]; pinArt(all[(all.indexOf(a.url) + +d.go + all.length) % all.length]); }
1613
+ });
1614
+ addEventListener('keydown', (e) => { if (e.key === 'Escape' && S.artPin) unpinArt(); });
1615
+ new ResizeObserver(() => fitArt()).observe($('#pbody'));
1616
+ const artTip = (a) => `${a.url}\n${a.agent !== 'main' && S.agents[a.agent] ? nameOf(a.agent) + ' · ' : ''}${L('Cliquer pour la présenter dans l’appel', 'Click to present it in the call')}`;
1368
1617
  // ---------- shared files: the files the session created (its Write calls), the way a call shows what was shared in it ----------
1369
1618
  // They show when a turn ends, the moment you would go and look for them: one line under the call, the newest first, a dot on those of the turn that just ended. A click shows the file in its folder
1370
1619
  // (the server opens Finder, Explorer or the file manager, and only for a file this session wrote). Nothing shows while the team works.
@@ -1378,6 +1627,7 @@ const namesFile = (text, name) => { for (let i = name ? text.indexOf(name) : -1;
1378
1627
  const filesForYou = (all) => { const named = new Set(all.filter((f) => f.named).map((f) => f.turn)); return all.filter((f) => f.named || (!named.has(f.turn) && FDOC.test(f.name))); };
1379
1628
  const fileParts = (f) => { const p = String(f || '').split(/[\\/]/), name = p.pop() || ''; return { name, dir: p.slice(-3).join(' › '), icon: (FICON.find(([re]) => re.test(name)) || [0, '📄'])[1] }; };
1380
1629
  function noteFiles(ev) { // a file written twice is one file, of the turn that wrote it last; a write that failed created nothing
1630
+ noteArts(ev);
1381
1631
  if (ev.kind === 'user') { S.turnN++; S.turnSaid = String(ev.text || ''); }
1382
1632
  else if (ev.kind === 'say' && ev.agent === 'main') { const t = String(ev.text || ''); S.turnSaid = (S.turnSaid + '\n' + t).slice(-20000); for (const f of S.files.values()) if (!f.named && namesFile(t, f.name)) f.named = true; for (const c of S.cands.values()) if (namesFile(t, c.name)) c.want = S.turnN; } // named before it is written ("I will put it in plan.md") or after: both count
1383
1633
  else if (ev.kind === 'tools') { for (const t of ev.tools) { const d = t.d || {}, was = S.files.get(d.file); if (d.kind === 'cmd' && d.outs) for (const f of d.outs) candFile(f, t.id, ev.agent); if (d.kind !== 'write' || !d.file || FSKIP.test(d.file) || (was && was.id === t.id)) continue; const name = fileParts(d.file).name; S.files.delete(d.file); S.files.set(d.file, { file: d.file, name, id: t.id, agent: ev.agent, turn: S.turnN, named: !!(was && was.named) || namesFile(S.turnSaid, name), was }); } }
@@ -1399,16 +1649,17 @@ const fileTip = (f) => `${f.file}\n${f.agent !== 'main' && S.agents[f.agent] ? n
1399
1649
  const fileCls = (f) => (f.turn === S.turnN ? ' new' : '') + (S.fgone.has(f.file) ? ' gone' : '');
1400
1650
  function paintFiles() { // called with every repaint of the states: touches the page only when the line would read differently
1401
1651
  if (prefs.files !== false && S.cands.size && turnDone()) for (const c of S.cands.values()) if (c.want != null && !S.files.has(c.file)) askMade(c); // the documents the commands made, among those the lead named
1402
- const el = $('#files'), all = [...S.files.values()].reverse(), mine = prefs.files !== false ? filesForYou(all) : [], on = mine.length > 0 && turnDone(), rest = all.length - Math.min(mine.length, FMAX);
1403
- const key = on ? prefs.lang + '|' + S.turnN + '|' + all.map((f) => f.file + (S.fgone.has(f.file) ? '!' : '')).join('|') + '||' + mine.map((f) => f.file).join('|') : ''; if (el.dataset.k === key) return;
1652
+ if (S.artPin && !S.arts.has(S.artPin)) unpinArt(); // the call went back to before that page was published
1653
+ const el = $('#files'), all = [...S.files.values()].reverse(), mine = prefs.files !== false ? filesForYou(all) : [], arts = prefs.files !== false ? [...S.arts.values()].reverse() : [], on = mine.length + arts.length > 0 && turnDone(), rest = all.length - Math.min(mine.length, FMAX);
1654
+ const key = on ? prefs.lang + '|' + S.turnN + '|' + all.map((f) => f.file + (S.fgone.has(f.file) ? '!' : '')).join('|') + '||' + mine.map((f) => f.file).join('|') + '||' + arts.map((a) => a.id + a.title).join('|') : ''; if (el.dataset.k === key) return;
1404
1655
  const open = on && !!$('#fpop'), ttl = L('Fichiers créés pendant cette session', 'Files created in this session'); el.dataset.k = key; filesPop(false); if (el.classList.contains('on') !== on) { el.classList.toggle('on', on); later('lay', layout); }
1405
- el.innerHTML = !on ? '' : `<button class="sfh" id="fAll" aria-expanded="false" title="${esc(ttl)}">📎 ${esc(L('Fichiers', 'Files'))}</button>` + mine.slice(0, FMAX).map((f) => `<button class="sfc${fileCls(f)}" data-f="${esc(f.file)}" title="${esc(fileTip(f))}"><i>${fileParts(f.file).icon}</i><span>${esc(f.name)}</span></button>`).join('') + (rest > 0 ? `<button class="sfc more" title="${esc(ttl)}" aria-label="${esc(ttl)}">+${rest}</button>` : '');
1656
+ el.innerHTML = !on ? '' : `<button class="sfh" id="fAll" aria-expanded="false" title="${esc(ttl)}">📎 ${esc(L('Fichiers', 'Files'))}</button>` + arts.slice(0, 4).map((a) => `<button class="sfc${a.turn === S.turnN ? ' new' : ''}" data-a="${esc(a.url)}" title="${esc(artTip(a))}"><i>🌐</i><span>${esc(a.title)}</span></button>`).join('') + mine.slice(0, FMAX).map((f) => `<button class="sfc${fileCls(f)}" data-f="${esc(f.file)}" title="${esc(fileTip(f))}"><i>${fileParts(f.file).icon}</i><span>${esc(f.name)}</span></button>`).join('') + (rest > 0 ? `<button class="sfc more" title="${esc(ttl)}" aria-label="${esc(ttl)}">+${rest}</button>` : '');
1406
1657
  el.scrollLeft = 0; if (open) filesPop(true);
1407
1658
  }
1408
1659
  function filesPop(open) { // the whole list, above the line: every file with the folder it is in and who created it
1409
1660
  const old = $('#fpop'), b = $('#fAll'); if (old) old.remove(); if (b) b.setAttribute('aria-expanded', String(!!open)); if (!open) return;
1410
1661
  const all = [...S.files.values()].reverse(), p = document.createElement('div'), ttl = L('Fichiers créés pendant cette session', 'Files created in this session'); p.id = 'fpop'; p.setAttribute('role', 'dialog'); p.setAttribute('aria-label', ttl);
1411
- p.innerHTML = `<h4>${esc(ttl)} · ${all.length}</h4>` + all.map((f) => { const x = fileParts(f.file), who = f.agent !== 'main' && S.agents[f.agent] ? nameOf(f.agent) : ''; return `<button class="sfr${fileCls(f)}" data-f="${esc(f.file)}" title="${esc(fileTip(f))}"><i>${x.icon}</i><b>${esc(x.name)}</b><em>${esc([x.dir, who].filter(Boolean).join(' · '))}</em></button>`; }).join('');
1662
+ p.innerHTML = `<h4>${esc(ttl)} · ${all.length + S.arts.size}</h4>` + [...S.arts.values()].reverse().map((a) => `<button class="sfr${a.turn === S.turnN ? ' new' : ''}" data-a="${esc(a.url)}" title="${esc(artTip(a))}"><i>🌐</i><b>${esc(a.title)}</b><em>${esc(['claude.ai', a.v > 1 ? 'v' + a.v : '', a.agent !== 'main' && S.agents[a.agent] ? nameOf(a.agent) : ''].filter(Boolean).join(' · '))}</em></button>`).join('') + all.map((f) => { const x = fileParts(f.file), who = f.agent !== 'main' && S.agents[f.agent] ? nameOf(f.agent) : ''; return `<button class="sfr${fileCls(f)}" data-f="${esc(f.file)}" title="${esc(fileTip(f))}"><i>${x.icon}</i><b>${esc(x.name)}</b><em>${esc([x.dir, who].filter(Boolean).join(' · '))}</em></button>`; }).join('');
1412
1663
  p.style.bottom = Math.round($('#center').getBoundingClientRect().bottom - $('#files').getBoundingClientRect().top) + 6 + 'px'; p.onclick = filesClick; $('#center').appendChild(p);
1413
1664
  }
1414
1665
  async function revealFile(file) {
@@ -1417,7 +1668,7 @@ async function revealFile(file) {
1417
1668
  if (r && r.ok) { if (S.fgone.delete(file)) paintFiles(); return; }
1418
1669
  if (r && r.status === 410) { S.fgone.add(file); paintFiles(); toast(L('Ce fichier n’existe plus', 'This file is no longer there')); } else toast(L('Impossible d’ouvrir le dossier', 'Could not open the folder'));
1419
1670
  }
1420
- function filesClick(e) { const f = e.target.closest('[data-f]'); if (f) revealFile(f.dataset.f); else if (e.target.closest('.sfh, .more')) filesPop(!$('#fpop')); }
1671
+ function filesClick(e) { const a = e.target.closest('[data-a]'), f = e.target.closest('[data-f]'); if (a) pinArt(a.dataset.a); else if (f) revealFile(f.dataset.f); else if (e.target.closest('.sfh, .more')) filesPop(!$('#fpop')); }
1421
1672
  $('#files').onclick = filesClick;
1422
1673
  addEventListener('click', (e) => { if ($('#fpop') && !e.target.closest('#fpop, #files')) filesPop(false); });
1423
1674
  addEventListener('keydown', (e) => { if (e.key === 'Escape' && $('#fpop')) { filesPop(false); const b = $('#fAll'); if (b) b.focus(); } });
@@ -1448,10 +1699,12 @@ function poof(tile, color) {
1448
1699
  { duration: 650 + Math.random() * 450, easing: 'cubic-bezier(.2,.7,.4,1)', delay: 120 }).onfinish = () => d.remove();
1449
1700
  }
1450
1701
  }
1451
- function toast(msg) { const t = document.createElement('div'); t.className = 'toast'; t.textContent = msg; const c = $('#toasts'); c.appendChild(t); while (c.children.length > 3) c.firstChild.remove(); setTimeout(() => t.remove(), 3100); }
1702
+ function toast(msg) { const t = document.createElement('div'); t.className = 'toast'; t.textContent = msg; const c = $('#toasts'); c.appendChild(t); while (c.querySelectorAll('.toast:not(.offer)').length > 3) c.querySelector('.toast:not(.offer)').remove(); setTimeout(() => t.remove(), 3100); }
1452
1703
  const BYE = { en: ['Bye, everyone!', 'Off I go. 👋', 'Thanks, see you!', 'My work here is done.', 'Catch you later!', 'Logging off, bye!', 'That’s a wrap!', 'Good luck with the rest!', 'Mic drop. 🎤', 'Leaving the call… ☕'],
1453
- fr: ['Salut tout le monde !', 'Je file. 👋', 'Merci, à plus !', 'Ma mission est terminée.', 'À tout à l’heure !', 'Je me déconnecte, ciao !', 'C’est dans la boîte !', 'Bon courage pour la suite !', 'Mic drop. 🎤', 'Je quitte l’appel… ☕'] };
1454
- function byeLine(id) { const P = BYE[FR() ? 'fr' : 'en'], seed = hash(id + String(S.clock | 0)); let l = P[seed % P.length]; if (l === S.lastBye) l = P[(seed + 1) % P.length]; return (S.lastBye = l); }
1704
+ fr: ['Salut tout le monde !', 'Je file. 👋', 'Merci, à plus !', 'Ma mission est terminée.', 'À tout à l’heure !', 'Je me déconnecte, ciao !', 'C’est dans la boîte !', 'Bon courage pour la suite !', 'Mic drop. 🎤', 'Je quitte l’appel… ☕'],
1705
+ es: ['¡Adiós a todos!', 'Me voy. 👋', '¡Gracias, nos vemos!', 'Mi trabajo aquí ha terminado.', '¡Hasta luego!', 'Me desconecto, ¡chao!', '¡Listo, eso es todo!', '¡Suerte con lo que queda!', 'Mic drop. 🎤', 'Salgo de la llamada… ☕'],
1706
+ pt: ['Tchau, pessoal!', 'Estou indo. 👋', 'Valeu, até mais!', 'Meu trabalho aqui está feito.', 'Até logo!', 'Estou saindo, tchau!', 'Pronto, é isso!', 'Boa sorte com o resto!', 'Mic drop. 🎤', 'Saindo da chamada… ☕'] };
1707
+ function byeLine(id) { const P = BYE[CALL()], seed = hash(id + String(S.clock | 0)); let l = P[seed % P.length]; if (l === S.lastBye) l = P[(seed + 1) % P.length]; return (S.lastBye = l); }
1455
1708
  function vanish(id) {
1456
1709
  S.gone.add(id); const t = $('#t-' + id), p = S.agents[id]; if (!t || !p) return;
1457
1710
  toast(`${p.name} ${L('a quitté l’appel', 'left the call')} 👋`);
@@ -1515,9 +1768,13 @@ const THINK = {
1515
1768
  todo: ['One thing at a time: {x}.', '{x}… then the next one.'], next: ['After this: {x}.'], grep: ['Where is “{x}” hiding?', '“{x}”… it has to be somewhere.'], web: ['“{x}”… let’s see what comes up.'], grep0: ['It has to be somewhere in here.', 'Where is that thing hiding?'], task: ['{x}. Stay on it.', '{x}… getting there, I think.'] },
1516
1769
  fr: { run: ['Toujours en cours… {x}.', 'Allez… {x}.', '{x}. Ça arrive.'], err: ['Pourquoi ça a planté ?', 'Encore cette erreur… qu’est-ce que je rate ?', 'Pas ce que j’attendais de « {x} ».'], two: ['{a}, puis {b}… quel est le lien ?', '{a} et {b}. C’est forcément dans l’un des deux.'], one: ['Il y a un truc dans {a} qui ne colle pas.', '{a}… c’était où, déjà ?'], again: ['Retour à {a}. Encore.', '{a}, une fois de plus. Je rate quelque chose.'],
1517
1770
  todo: ['Une chose à la fois : {x}.', '{x}… puis la suite.'], next: ['Après ça : {x}.'], grep: ['Où se cache « {x} » ?', '« {x} »… c’est forcément quelque part.'], web: ['« {x} »… voyons ce que ça donne.'], grep0: ['C’est forcément quelque part là-dedans.', 'Où est-ce que ça se cache ?'], task: ['{x}. On reste dessus.', '{x}… j’y arrive, je crois.'] },
1771
+ es: { run: ['Sigue en marcha… {x}.', 'Vamos… {x}.', '{x}. Ya casi.'], err: ['¿Por qué ha fallado?', 'Otra vez ese error… ¿qué se me escapa?', 'No es lo que esperaba de “{x}”.'], two: ['{a}, luego {b}… ¿qué los une?', '{a} y {b}. Tiene que estar en uno de los dos.'], one: ['Algo en {a} no cuadra.', '{a}… ¿dónde estaba esa parte?'], again: ['De vuelta a {a}. Otra vez.', '{a}, una vez más. Algo se me escapa.'],
1772
+ todo: ['Una cosa a la vez: {x}.', '{x}… y luego lo siguiente.'], next: ['Después de esto: {x}.'], grep: ['¿Dónde se esconde “{x}”?', '“{x}”… tiene que estar en algún sitio.'], web: ['“{x}”… a ver qué sale.'], grep0: ['Tiene que estar por aquí.', '¿Dónde se esconde eso?'], task: ['{x}. Sigo con ello.', '{x}… creo que ya casi.'] },
1773
+ pt: { run: ['Ainda rodando… {x}.', 'Vamos… {x}.', '{x}. Já vai.'], err: ['Por que isso falhou?', 'Esse erro de novo… o que estou deixando passar?', 'Não era o que eu esperava de “{x}”.'], two: ['{a}, depois {b}… qual é a ligação?', '{a} e {b}. Tem que estar em um dos dois.'], one: ['Alguma coisa em {a} não bate.', '{a}… onde ficava essa parte mesmo?'], again: ['De volta a {a}. De novo.', '{a}, mais uma vez. Estou deixando passar alguma coisa.'],
1774
+ todo: ['Uma coisa de cada vez: {x}.', '{x}… depois a próxima.'], next: ['Depois disso: {x}.'], grep: ['Onde “{x}” está se escondendo?', '“{x}”… tem que estar em algum lugar.'], web: ['“{x}”… vamos ver o que aparece.'], grep0: ['Tem que estar em algum lugar aqui.', 'Onde isso está se escondendo?'], task: ['{x}. Sigo nisso.', '{x}… estou chegando lá, acho.'] },
1518
1775
  };
1519
1776
  function thoughtFor(id) {
1520
- const now = Date.now(), W = THINK[FR() ? 'fr' : 'en'], seen = (TH.said[id] = TH.said[id] || []), cut = (x, n) => { x = String(x || '').replace(/\s+/g, ' ').trim(); return (x.length > n ? x.slice(0, n).replace(/\s+\S*$/, '') : x).replace(/[.…,;:\s]+$/, ''); }; // the line it goes into brings its own punctuation
1777
+ const now = Date.now(), W = THINK[CALL()], seen = (TH.said[id] = TH.said[id] || []), cut = (x, n) => { x = String(x || '').replace(/\s+/g, ' ').trim(); return (x.length > n ? x.slice(0, n).replace(/\s+\S*$/, '') : x).replace(/[.…,;:\s]+$/, ''); }; // the line it goes into brings its own punctuation
1521
1778
  const real = realThought(id); if (real) return real; // its own words first, always: the rest is only for when there are none (left)
1522
1779
  const buf = (S.term[id] || []).slice(-8), last = buf[buf.length - 1], r = S.run[id], hot = [], out = [], add = (to, k, v) => { for (const tpl of W[k]) to.push(tpl.replace(/\{(\w+)\}/g, (m, key) => v[key]).replace(/([?!])[.…]+/g, '$1').replace(/([?!]) (\p{Ll})/u, (m, a, b) => a + ' ' + b.toUpperCase())); }; // "Why is it slow?" keeps its own mark, without a full stop after it
1523
1780
  const cmd = (t) => String(t || '').trim().replace(/^(?:cd\s+\S+\s*(?:&&|;)\s*)+/, '').replace(/^(?:[A-Za-z_]\w*=\S*\s+)+/, '').split(/\s+(?:&&|\|\||[|;>])/)[0].split(/\s+/).slice(0, 3).join(' '); // the command itself: not the folder it starts from, nor what it is piped into
@@ -1557,11 +1814,11 @@ const clearThoughts = () => { document.querySelectorAll('.tile.musing').forEach(
1557
1814
  function stopMumble() { const v = TH.voice; if (v) { TH.voice = null; try { v.src.stop(); } catch {} } }
1558
1815
  async function mumble(id, text) { // lips closed: the mouth does not move, the music does not make room, and anyone who starts to speak cuts it
1559
1816
  const p = S.agents[id], t = $('#t-' + id); if (!p || !t || !prefs.voice || AUD.off() || !AUD.ctx || S.speakers.size || TH.voice) return;
1560
- if (!TTS.server || prefs.vstyle === 'animal' || prefs.vstyle === 'sims') { const o = AUD.murmur(0.5 + (p.vi % 5) / 10, Math.min(2.2, estMs(text) / 1000), 0.4); if (o) { TH.voice = { id, src: o }; o.addEventListener('ended', () => { if (TH.voice && TH.voice.src === o) TH.voice = null; }); } return; }
1561
- const voice = TTS.voiceFor(p, frVoice(text)), token = S.token; if (!voice) return; let buf; try { buf = await TTS.buf(speakable(text), voice, TTS.rate(), true); } catch { return; } // made like a line prepared ahead: it never delays a real one
1817
+ if (!TTS.server || babbles()) { const o = AUD.murmur(0.5 + (p.vi % 5) / 10, Math.min(2.2, estMs(text) / 1000), 0.4); if (o) { TH.voice = { id, src: o }; o.addEventListener('ended', () => { if (TH.voice && TH.voice.src === o) TH.voice = null; }); } return; }
1818
+ const voice = TTS.voiceFor(p, voiceLang(text)), token = S.token; if (!voice) return; let buf; try { buf = await TTS.buf(speakable(text), voice, TTS.rate(), true); } catch { return; } // made like a line prepared ahead: it never delays a real one
1562
1819
  if (token !== S.token || S.speakers.size || TH.voice || !t.classList.contains('musing')) return; // someone spoke meanwhile, or the thought is gone
1563
1820
  const c = AUD.ctx, src = c.createBufferSource(), lp = c.createBiquadFilter(), g = c.createGain(); src.buffer = buf; lp.type = 'lowpass'; lp.frequency.value = 1100; g.gain.value = 0.2; let stops = [];
1564
- if (prefs.vstyle === 'natural' || prefs.vstyle === 'kokoro') src.connect(lp); else { const ch = fxChain(c, src, fxFor(p)); stops = ch.stops; ch.node.connect(lp); }
1821
+ if (prefs.vstyle === 'cartoon') { const ch = fxChain(c, src, fxFor(p)); stops = ch.stops; ch.node.connect(lp); } else src.connect(lp);
1565
1822
  lp.connect(g); g.connect(AUD.voice); AUD.live.add(src); TH.voice = { id, src };
1566
1823
  src.onended = () => { AUD.live.delete(src); stops.forEach((o) => { try { o.stop(); } catch {} }); if (TH.voice && TH.voice.src === src) TH.voice = null; }; src.start();
1567
1824
  }
@@ -1603,15 +1860,39 @@ $('#tree').onclick = (e) => {
1603
1860
  };
1604
1861
 
1605
1862
  // ---------- agent detail ----------
1606
- function openDetail(id) { const p = S.agents[id]; if (!p) return; S.detail = id; $('#dname').textContent = `${p.name} · ${p.role}`; renderDetail(); $('#detail').classList.add('on'); }
1863
+ function openDetail(id) { const p = S.agents[id]; if (!p) return; S.detail = id; S.detailOpen = (S.detailOpen || 0) + 1; // detailOpen: the human's made-up day is drawn again at each opening, and stays put while the panel refreshes
1864
+ $('#dname').textContent = `${p.name} · ${p.role}`; renderDetail(); $('#detail').classList.add('on'); }
1865
+ // ---------- the human's panel: nothing to do any more, and proud of it. Drawn at random each time it opens; English and French, the other languages get the English ----------
1866
+ const IDLE = {
1867
+ en: { tools: ['Coffee', 'Approve without reading', 'Refresh the pull request', '“Looks good to me”', 'Stretch', 'Check Slack', 'Rename one variable', 'Explain the plan to the cat', 'Open X “for research”', 'Sigh', 'Snack', 'Water the plant', 'Pretend to review', 'Update LinkedIn', 'Ctrl+C', 'Ctrl+V', 'Close 37 tabs'],
1868
+ acts: [['✓', 'Went for a walk', '34 min', 'around the block, twice', 'Steps: 4,210\nBugs fixed meanwhile by the agents: 3\nBugs fixed by you: 0'], ['✓', 'Drank too much coffee', '2 min', 'fifth cup', 'Heart rate: high\nOutput: unchanged'],
1869
+ ['✓', 'Cloud spotting', '18 min', 'window, left side', 'Found: a dragon, a rabbit, a merge conflict'], ['⠋', 'Looking busy', 'running', 'the terminal, full screen', '$ ls\n$ ls\n$ ls'], ['✗', 'Tried to help the agents', '3 s', 'one line of code', 'Error: the lead had already done it'],
1870
+ ['✓', 'Watered the plant', '1 min', 'the fern', 'The plant is now the most productive member of the team'], ['✓', 'Read the diff', '4 s', 'scrolled straight to the bottom', 'Approved.'], ['✓', 'Long lunch', '1 h 20', 'the good place', 'The agents did not notice'],
1871
+ ['✓', 'Explained the codebase to a rubber duck', '12 min', 'the yellow one', 'The duck now asks for a raise'], ['✗', 'Meeting about the agents', '45 min', '7 people', 'Decision: schedule another meeting'], ['✓', 'Updated LinkedIn', '25 min', 'new title', 'AI Orchestrator · Prompt Whisperer · Coffee Specialist'],
1872
+ ['✓', 'Tidied the desktop icons', '15 min', 'by colour', 'The agents shipped two features meanwhile'], ['✓', 'Learned to juggle', '40 min', 'three balls', 'The agents learned Rust meanwhile'], ['✓', 'Power nap', '20 min', 'the sofa', 'Woke up to 14 merged pull requests'],
1873
+ ['✓', 'Wrote “please” in a prompt', '1 s', 'just in case', 'Being polite to the future overlords'], ['✗', 'Looked for something to do', '9 min', 'the backlog', 'The backlog is empty. The agents emptied it.']] },
1874
+ fr: { tools: ['Café', 'Approuver sans lire', 'Rafraîchir la pull request', '« Ça me va »', 'S’étirer', 'Vérifier Slack', 'Renommer une variable', 'Expliquer le plan au chat', 'Ouvrir X « pour la veille »', 'Soupirer', 'Grignoter', 'Arroser la plante', 'Faire semblant de relire', 'Mettre à jour LinkedIn', 'Ctrl+C', 'Ctrl+V', 'Fermer 37 onglets'],
1875
+ acts: [['✓', 'Partie se promener', '34 min', 'le tour du pâté de maisons, deux fois', 'Pas : 4 210\nBugs corrigés pendant ce temps par les agents : 3\nBugs corrigés par vous : 0'], ['✓', 'Trop de café', '2 min', 'cinquième tasse', 'Rythme cardiaque : élevé\nProduction : inchangée'],
1876
+ ['✓', 'Observation des nuages', '18 min', 'fenêtre de gauche', 'Vus : un dragon, un lapin, un conflit de fusion'], ['⠋', 'Avoir l’air occupé', 'en cours', 'le terminal en plein écran', '$ ls\n$ ls\n$ ls'], ['✗', 'A voulu aider les agents', '3 s', 'une ligne de code', 'Erreur : le chef l’avait déjà fait'],
1877
+ ['✓', 'Arrosé la plante', '1 min', 'la fougère', 'La plante est désormais le membre le plus productif de l’équipe'], ['✓', 'Lu le diff', '4 s', 'descendu tout en bas d’un coup', 'Approuvé.'], ['✓', 'Long déjeuner', '1 h 20', 'la bonne adresse', 'Les agents n’ont rien remarqué'],
1878
+ ['✓', 'Expliqué le code à un canard en plastique', '12 min', 'le jaune', 'Le canard demande une augmentation'], ['✗', 'Réunion sur les agents', '45 min', '7 personnes', 'Décision : prévoir une autre réunion'], ['✓', 'Mis à jour LinkedIn', '25 min', 'nouveau titre', 'Orchestrateur d’IA · Chuchoteur de prompts · Spécialiste café'],
1879
+ ['✓', 'Rangé les icônes du bureau', '15 min', 'par couleur', 'Les agents ont livré deux fonctionnalités pendant ce temps'], ['✓', 'Appris à jongler', '40 min', 'trois balles', 'Les agents ont appris Rust pendant ce temps'], ['✓', 'Sieste éclair', '20 min', 'le canapé', 'Réveil : 14 pull requests fusionnées'],
1880
+ ['✓', 'Écrit « s’il te plaît » dans un prompt', '1 s', 'au cas où', 'Rester poli avec nos futurs maîtres'], ['✗', 'Cherché quelque chose à faire', '9 min', 'le backlog', 'Le backlog est vide. Les agents l’ont vidé.']] },
1881
+ };
1882
+ const shuffle = (a) => { const b = [...a]; for (let i = b.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [b[i], b[j]] = [b[j], b[i]]; } return b; };
1883
+ function idleHtml() { // the human's Tools and Recent activity, made up: 5 to 7 tools, 6 to 8 moments
1884
+ const I = FR() ? IDLE.fr : IDLE.en, tools = shuffle(I.tools).slice(0, 5 + Math.floor(Math.random() * 3)).map((n) => [n, 1 + Math.floor(Math.random() * (/Ctrl|Coffee|Café|Slack|Sigh|Soupirer/.test(n) ? 40 : 9))]);
1885
+ return `<h3>${L('Outils', 'Tools')} (${tools.reduce((a, t) => a + t[1], 0)})</h3><div>${tools.map(([n, c]) => `${esc(n)} ×${c}`).join(' · ')}</div>` +
1886
+ `<h3>${L('Activité récente', 'Recent activity')}</h3>` + shuffle(I.acts).slice(0, 6 + Math.floor(Math.random() * 3)).map(([m, n, d, a, o]) => `<details><summary>${m} ${esc(n)} <span class="dim">${esc(d)}</span> — ${esc(a)}</summary><pre>${esc(o)}</pre></details>`).join('');
1887
+ }
1607
1888
  function renderDetail() {
1608
1889
  if (!S.detail) return; const id = S.detail, evs = S.events.slice(0, S.idx + 1).filter((e) => e.agent === id || e.to === id);
1609
1890
  const order = evs.find((e) => e.kind === 'order' && e.to === id), tools = evs.filter((e) => e.agent === id && e.kind === 'tools').flatMap((e) => e.tools);
1610
1891
  const counts = {}; tools.forEach((t) => (counts[t.name] = (counts[t.name] || 0) + 1));
1611
1892
  const u = S.usage[id], tokHtml = u && tokTotal(u) ? `<h3>${L('Jetons', 'Tokens')} · ⚡ ${fmtTok(tokTotal(u))}</h3><div class="dim">${L('entrée', 'input')} ${fmtTok(u.i)} · ${L('sortie', 'output')} ${fmtTok(u.o)} · ${L('écriture cache', 'cache write')} ${fmtTok(u.w)} · ${L('lecture cache', 'cache read')} ${fmtTok(u.r)}</div>` : '';
1612
1893
  $('#dbody').innerHTML = tokHtml + (order ? `<h3>${L('Consigne de', 'Prompt from')} ${esc(nameOf(order.agent))}</h3><pre>${esc(order.text)}</pre>` : '') +
1613
- `<h3>${L('Outils', 'Tools')} (${tools.length})</h3><div>${Object.entries(counts).map(([n, c]) => `${esc(n)} ×${c}`).join(' · ') || '—'}</div>` +
1614
- `<h3>${L('Activité récente', 'Recent activity')}</h3>` + (S.term[id] || []).slice(-30).reverse().map((e) => `<details><summary>${e.end == null ? '⠋' : e.err ? '✗' : '✓'} ${esc(e.tool.name)} <span class="dim">${e.end != null ? fmtDur(e.end - e.ts) : L('en cours', 'running')}</span> — ${esc((e.tool.arg || '').slice(-60))}</summary><pre>${esc((e.tool.d && e.tool.d.kind === 'cmd' ? '$ ' + e.tool.d.text + '\n' : '') + (e.out || ''))}</pre>${e.img && S.cur ? `<img class="dimg" src="${esc(mediaUrl(id, e.id, 0))}" alt="" loading="lazy">` : ''}</details>`).join('') +
1894
+ (id === 'user' ? (S.idleHtml = (S.idleFor === S.detailOpen && S.idleHtml) || idleHtml(), S.idleFor = S.detailOpen, S.idleHtml) : `<h3>${L('Outils', 'Tools')} (${tools.length})</h3><div>${Object.entries(counts).map(([n, c]) => `${esc(n)} ×${c}`).join(' · ') || '—'}</div>` +
1895
+ `<h3>${L('Activité récente', 'Recent activity')}</h3>` + (S.term[id] || []).slice(-30).reverse().map((e) => `<details><summary>${e.end == null ? '⠋' : e.err ? '✗' : '✓'} ${esc(e.tool.name)} <span class="dim">${e.end != null ? fmtDur(e.end - e.ts) : L('en cours', 'running')}</span> — ${esc((e.tool.arg || '').slice(-60))}</summary><pre>${esc((e.tool.d && e.tool.d.kind === 'cmd' ? '$ ' + e.tool.d.text + '\n' : '') + (e.out || ''))}</pre>${e.img && S.cur ? `<img class="dimg" src="${esc(mediaUrl(id, e.id, 0))}" alt="" loading="lazy">` : ''}</details>`).join('')) +
1615
1896
  evs.filter((e) => e.agent === id && (e.kind === 'say' || e.kind === 'report')).map((e) => `<h3>${e.kind === 'report' ? L('Rapport final', 'Final report') : L('A dit', 'Said')}</h3><pre>${esc(e.text)}</pre>`).join('');
1616
1897
  }
1617
1898
  $('#dclose').onclick = () => { S.detail = null; $('#detail').classList.remove('on'); };
@@ -1719,13 +2000,15 @@ function openRecap() {
1719
2000
  // episode mode: title cards and reactions
1720
2001
  // =====================================================================
1721
2002
  const REACT = { fr: { ack: ['Compris, chef.', 'C’est parti.', 'Encore du boulot…', 'Je m’en occupe.', 'Ok ok ok.'], done: ['Ça compile chez moi.', 'Oh là là, encore des bugs.', 'Qui a écrit ce code ?', 'Super, on a fini.', 'Classique.'] },
1722
- en: { ack: ['Got it, boss.', 'On it.', 'More work, great.', 'I’ll handle it.', 'Okay okay okay.'], done: ['Works on my machine.', 'Oh man, more bugs.', 'Who wrote this code?', 'Nice, we are done.', 'Classic.'] } };
2003
+ en: { ack: ['Got it, boss.', 'On it.', 'More work, great.', 'I’ll handle it.', 'Okay okay okay.'], done: ['Works on my machine.', 'Oh man, more bugs.', 'Who wrote this code?', 'Nice, we are done.', 'Classic.'] },
2004
+ es: { ack: ['Entendido, jefe.', 'Vamos allá.', 'Más trabajo, genial.', 'Yo me encargo.', 'Vale, vale, vale.'], done: ['En mi máquina funciona.', 'Madre mía, más bugs.', '¿Quién escribió este código?', 'Genial, hemos terminado.', 'Un clásico.'] },
2005
+ pt: { ack: ['Entendido, chefe.', 'Vamos lá.', 'Mais trabalho, que ótimo.', 'Deixa comigo.', 'Tá, tá, tá.'], done: ['Na minha máquina funciona.', 'Nossa, mais bugs.', 'Quem escreveu esse código?', 'Boa, terminamos.', 'Clássico.'] } };
1723
2006
  const quipMem = new Map();
1724
2007
  function prefetchQuips(i) {
1725
2008
  if (!prefs.epi) return; const texts = [];
1726
2009
  for (let k = i; k < Math.min(S.events.length, i + 60) && texts.length < 6; k++) if (S.events[k].kind === 'report') texts.push(baseText(S.events[k], 160));
1727
2010
  const need = texts.filter((t) => !quipMem.has(t)); if (!need.length) return; need.forEach((t) => quipMem.set(t, null));
1728
- fetch('/api/quips', { method: 'POST', body: JSON.stringify({ texts: need, lang: FR() ? 'fr' : 'en' }) }).then((r) => r.json()).then((d) => (d.texts || []).forEach((q, i) => d.ok && q && q !== need[i] && quipMem.set(need[i], q))).catch(() => {});
2011
+ fetch('/api/quips', { method: 'POST', body: JSON.stringify({ texts: need, lang: CALL() }) }).then((r) => r.json()).then((d) => (d.texts || []).forEach((q, i) => d.ok && q && q !== need[i] && quipMem.set(need[i], q))).catch(() => {});
1729
2012
  }
1730
2013
 
1731
2014
  // Little lines that make the call feel alive. They never appear in the transcript and never replace real content: they are short, local (no API) and can be turned off in ⚙.
@@ -1736,11 +2019,17 @@ const ACK = {
1736
2019
  fr: { tests: ['Je lance les tests, comme d’hab.', 'Des tests ? Toujours.', 'On va voir ce qui casse.', 'Vert ou rouge, je te dirai.'], review: ['Je mets mes lunettes de relecteur.', 'Je relis tout deux fois.', 'Je serai gentil. Peut-être.', 'Audit en cours, je reviens.'], explore: ['Je pars explorer le code.', 'Je grep comme si c’était la fin du monde.', 'Allez, on creuse.', 'Je vais le trouver.'],
1737
2020
  fix: ['L’heure de la chasse aux bugs.', 'Je sens un bug.', 'Mode débogueur : activé.', 'Qui a cassé ça ?'], docs: ['Je rédige ça.', 'La doc, mon truc préféré.', 'Des mots arrivent.'], ui: ['Pixels, me voilà.', 'On va rendre ça joli.', 'Je regarde la mise en page.'], cleanup: ['Je nettoie ce désordre.', 'Séance de rangement.', 'Je supprime. Prudemment.'],
1738
2021
  perf: ['On va rendre ça rapide.', 'Je profile, un instant.', 'À la chasse aux millisecondes.'], any: ['Je m’en occupe !', 'Compris, chef.', 'Je lis le brief.', 'C’est comme fait. Sûrement.', 'Ok ok ok.', 'Pas un mot de plus.', 'Je suis déjà parti.', 'Reçu cinq sur cinq.', 'D’abord un café. Ensuite ça.'] },
2022
+ es: { tests: ['Lanzo las pruebas, como siempre.', '¿Pruebas? Siempre.', 'A ver qué se rompe.', 'Verde o rojo, te aviso.'], review: ['Me pongo las gafas de revisor.', 'Lo leo todo dos veces.', 'Seré amable. Quizá.', 'Auditando, ahora vuelvo.'], explore: ['Me voy a explorar el código.', 'Haciendo grep como si no hubiera un mañana.', 'Hora de escarbar.', 'Lo encontraré.'],
2023
+ fix: ['Hora de cazar bugs.', 'Huelo un bug.', 'Modo depurador: activado.', '¿Quién ha roto esto?'], docs: ['Lo pongo por escrito.', 'Documentación, mi favorita.', 'Se vienen palabras.'], ui: ['Píxeles, allá voy.', 'Vamos a dejarlo bonito.', 'Déjame ver el diseño.'], cleanup: ['Limpiando el desorden.', 'Hora de ordenar.', 'Borrando cosas. Con cuidado.'],
2024
+ perf: ['Vamos a hacerlo rápido.', 'Perfilando, un momento.', 'A la caza de milisegundos.'], any: ['¡Voy!', 'Entendido, jefe.', 'Leyendo el encargo.', 'Dalo por hecho. Probablemente.', 'Vale, vale, vale.', 'No digas más.', 'Ya estoy en ello.', 'Recibido.', 'Primero un café. Luego esto.'] },
2025
+ pt: { tests: ['Rodando os testes, como sempre.', 'Testes? Sempre.', 'Vamos ver o que quebra.', 'Verde ou vermelho, eu aviso.'], review: ['Colocando meus óculos de revisor.', 'Lendo tudo duas vezes.', 'Vou ser legal. Talvez.', 'Auditando, já volto.'], explore: ['Vou explorar o código.', 'Dando grep como se não houvesse amanhã.', 'Hora de cavar.', 'Eu vou achar.'],
2026
+ fix: ['Hora de caçar bugs.', 'Sinto cheiro de bug.', 'Modo depurador: ligado.', 'Quem quebrou isso?'], docs: ['Vou escrever isso.', 'Documentação, minha favorita.', 'Palavras a caminho.'], ui: ['Pixels, aí vou eu.', 'Vamos deixar bonito.', 'Deixa eu ver o layout.'], cleanup: ['Limpando a bagunça.', 'Hora de arrumar.', 'Apagando coisas. Com cuidado.'],
2027
+ perf: ['Vamos deixar rápido.', 'Fazendo o profiling, um momento.', 'Caçando milissegundos.'], any: ['Deixa comigo!', 'Entendido, chefe.', 'Lendo o briefing.', 'Considere feito. Provavelmente.', 'Tá, tá, tá.', 'Nem precisa dizer mais.', 'Já estou indo.', 'Entendido.', 'Primeiro um café. Depois isso.'] },
1739
2028
  };
1740
2029
  const ACK_RE = [['tests', /test|qa\b|spec|jest|vitest|coverage/], ['review', /review|audit|check|inspect|lint|critique/], ['explore', /explor|search|research|find|investigat|look|map|scan/], ['fix', /fix|bug|debug|error|crash|broken/], ['docs', /\bdoc|readme|write|changelog|spec/], ['ui', /\bui\b|design|css|style|layout|front|page|component/], ['cleanup', /refactor|clean|tidy|dead code/], ['perf', /perf|speed|slow|optimi|latenc|profil/]];
1741
2030
  function ackLine(ev) {
1742
2031
  // classify on role and title only: the prompt text is too noisy
1743
- const R = ACK[FR() ? 'fr' : 'en'], text = `${ev.title || ''} ${(S.agents[ev.to] || {}).role || ''}`.toLowerCase(), cat = (ACK_RE.find(([, re]) => re.test(text)) || [])[0];
2032
+ const R = ACK[CALL()], text = `${ev.title || ''} ${(S.agents[ev.to] || {}).role || ''}`.toLowerCase(), cat = (ACK_RE.find(([, re]) => re.test(text)) || [])[0];
1744
2033
  const pool = cat && hash(String(ev.ts)) % 4 ? R[cat] : R.any, seed = hash(String(ev.ts) + ev.to); let line = pool[seed % pool.length];
1745
2034
  if (line === S.lastAck) line = pool[(seed + 1) % pool.length]; S.lastAck = line; return line;
1746
2035
  }
@@ -1748,8 +2037,9 @@ function ackLine(ev) {
1748
2037
  // conversation: short exchanges between agents at the right moments, built from what really happened in the session
1749
2038
  // =====================================================================
1750
2039
  const CHAT = { quiet: 0.45, normal: 1, lively: 1.8 }, chatMul = () => CHAT[prefs.chat] || 1; // normal unless chosen otherwise
1751
- const EXW = { en: { edit: ['edit', 'edits'], call: ['tool call', 'tool calls'], error: ['error', 'errors'], file: ['file', 'files'] }, fr: { edit: ['modification', 'modifications'], call: ['appel d’outil', 'appels d’outils'], error: ['erreur', 'erreurs'], file: ['fichier', 'fichiers'] } };
1752
- const P = (k, n) => { const w = EXW[FR() ? 'fr' : 'en'][k]; return `${n} ${n === 1 ? w[0] : w[1]}`; };
2040
+ const EXW = { en: { edit: ['edit', 'edits'], call: ['tool call', 'tool calls'], error: ['error', 'errors'], file: ['file', 'files'] }, fr: { edit: ['modification', 'modifications'], call: ['appel d’outil', 'appels d’outils'], error: ['erreur', 'erreurs'], file: ['fichier', 'fichiers'] },
2041
+ es: { edit: ['cambio', 'cambios'], call: ['llamada a herramienta', 'llamadas a herramientas'], error: ['error', 'errores'], file: ['archivo', 'archivos'] }, pt: { edit: ['alteração', 'alterações'], call: ['chamada de ferramenta', 'chamadas de ferramentas'], error: ['erro', 'erros'], file: ['arquivo', 'arquivos'] } };
2042
+ const P = (k, n) => { const w = EXW[CALL()][k]; return `${n} ${n === 1 ? w[0] : w[1]}`; };
1753
2043
  const EXCH = {
1754
2044
  en: { done: ['All done.', 'Finished.', 'Okay, that’s done.', 'Done on my side.', 'That’s wrapped up.'],
1755
2045
  ask: ['Quick question: is that the whole scope?', 'Anything else I should touch?', 'Any constraints I should know about?', 'Should I check with you before big changes?'],
@@ -1771,6 +2061,26 @@ const EXCH = {
1771
2061
  chime: [(b) => `Bon boulot, ${b}.`, () => 'Joli.', (b) => `Super, ${b}.`],
1772
2062
  trouble: [(b) => `${b}, ça va ? Ça fait beaucoup d’erreurs.`, (b) => `${b}, besoin d’un coup de main avec ces erreurs ?`], troubleBack: ['Je m’en occupe.', 'Oui, j’y suis presque.', 'Donne-moi une minute.', 'Je gère, merci.'],
1773
2063
  sync: ['Petit point rapide : où en est-on ?', 'Point d’étape, tout le monde ?', 'On fait un tour de table rapide.'], syncAns: [(a) => `Toujours dessus : ${a}.`, (a) => `${a}, ça avance bien.`, (a) => `En ce moment : ${a}.`] },
2064
+ es: { done: ['Todo hecho.', 'Terminado.', 'Vale, ya está.', 'Listo por mi parte.', 'Eso ya está cerrado.'],
2065
+ ask: ['Una pregunta rápida: ¿eso es todo el alcance?', '¿Algo más que deba tocar?', '¿Alguna restricción que deba conocer?', '¿Te aviso antes de los cambios grandes?'],
2066
+ askBack: ['Solo eso, gracias.', 'No, céntrate en eso.', 'Usa tu criterio.', 'Nada especial, adelante.', 'Eso es todo, gracias.'],
2067
+ ok: [(f) => `Bien, ${f.what} y sin errores.`, (f) => (f.file ? `Bien, ${f.file} tiene buena pinta.` : 'Bien, tiene buena pinta.'), (f, b) => `Perfecto${f.dur ? ', ha llevado ' + f.dur : ''}. Gracias, ${b}.`, (f) => `Genial, ${f.what}. Limpio.`],
2068
+ err: [(f) => `He visto ${P('error', f.errs)} por el camino. ¿Todo bien ahora?`, (f) => `${P('error', f.errs)} por el camino, ¿es sólido?`],
2069
+ errBack: ['Sí, solo eran reintentos.', 'Todo arreglado al final.', 'Sí, algún tropiezo, nada grave.', 'Ahora es sólido.'],
2070
+ slow: [(f) => `Ha llevado ${f.dur}. ¿Algo te bloquea?`, (f) => `${f.dur}, ha sido largo. ¿Todo bien?`], slowBack: ['No, es que era grande.', 'Nada me bloquea, había mucho que leer.', 'Todo bien, era pesado.'],
2071
+ chime: [(b) => `Buen trabajo, ${b}.`, () => 'Muy bien.', (b) => `Genial, ${b}.`],
2072
+ trouble: [(b) => `${b}, ¿todo bien? Son muchos errores.`, (b) => `${b}, ¿te echo una mano con esos errores?`], troubleBack: ['Estoy en ello.', 'Sí, ya casi lo tengo.', 'Dame un minuto.', 'Me encargo, gracias.'],
2073
+ sync: ['Repaso rápido: ¿cómo vamos?', '¿Estado, equipo?', 'Hagamos una ronda rápida.'], syncAns: [(a) => `Sigo con ello: ${a}.`, (a) => `${a}, va bien.`, (a) => `Ahora mismo: ${a}.`] },
2074
+ pt: { done: ['Tudo feito.', 'Terminei.', 'Pronto, está feito.', 'Feito do meu lado.', 'Isso está fechado.'],
2075
+ ask: ['Pergunta rápida: esse é o escopo todo?', 'Mais alguma coisa em que eu deva mexer?', 'Alguma restrição que eu deva saber?', 'Aviso você antes das mudanças grandes?'],
2076
+ askBack: ['Só isso, valeu.', 'Não, mantenha o foco.', 'Use o seu critério.', 'Nada de especial, pode ir.', 'É só isso, valeu.'],
2077
+ ok: [(f) => `Boa, ${f.what} e nenhum erro.`, (f) => (f.file ? `Bom, ${f.file} parece certo.` : 'Bom, parece certo.'), (f, b) => `Perfeito${f.dur ? ', levou ' + f.dur : ''}. Valeu, ${b}.`, (f) => `Ótimo, ${f.what}. Limpo.`],
2078
+ err: [(f) => `Vi ${P('error', f.errs)} pelo caminho. Tudo certo agora?`, (f) => `${P('error', f.errs)} pelo caminho, está firme?`],
2079
+ errBack: ['Sim, eram só novas tentativas.', 'Tudo resolvido no final.', 'Sim, uns tropeços, nada sério.', 'Agora está firme.'],
2080
+ slow: [(f) => `Levou ${f.dur}. Alguma coisa travando você?`, (f) => `${f.dur}, foi demorado. Tudo bem?`], slowBack: ['Não, é que era grande.', 'Nada travando, só tinha muito para ler.', 'Tudo bem, era pesado.'],
2081
+ chime: [(b) => `Bom trabalho, ${b}.`, () => 'Boa.', (b) => `Ótimo, ${b}.`],
2082
+ trouble: [(b) => `${b}, tudo bem? É muito erro.`, (b) => `${b}, precisa de uma mão com esses erros?`], troubleBack: ['Estou cuidando disso.', 'Sim, estou quase lá.', 'Me dá um minuto.', 'Deixa comigo, valeu.'],
2083
+ sync: ['Alinhamento rápido: como estamos?', 'Status, pessoal?', 'Vamos fazer uma rodada rápida.'], syncAns: [(a) => `Sigo nisso: ${a}.`, (a) => `${a}, indo bem.`, (a) => `No momento: ${a}.`] },
1774
2084
  };
1775
2085
  const exPick = (arr, seed, ...args) => { let k = seed % arr.length; if (arr[k] === S.lastX && arr.length > 1) k = (k + 1) % arr.length; S.lastX = arr[k]; return typeof arr[k] === 'function' ? arr[k](...args) : arr[k]; };
1776
2086
  function exchFacts(i, agent) { // what this agent did since it received its order: edits, tool calls, errors, the files it changed, how long it took
@@ -1799,18 +2109,18 @@ function noteTrouble(agent, ok) { // three errors in a row: someone asks if ev
1799
2109
  }
1800
2110
  function pickOther(not, prefer) { const ids = Object.keys(S.agents).filter((id) => id !== 'user' && !not.includes(id) && exVisible(id)); const pr = ids.filter(prefer || (() => false)); const a = pr.length ? pr : ids; return a.length ? a[Math.floor(Math.random() * a.length)] : null; }
1801
2111
  async function handoffX(g, seed, token) { // an order: the new agent asks a question, the lead answers
1802
- const E = EXCH[FR() ? 'fr' : 'en'], b = g.to, a = g.agent; if (!exVisible(a) || !exVisible(b)) return false; exLog('handoff');
2112
+ const E = EXCH[CALL()], b = g.to, a = g.agent; if (!exVisible(a) || !exVisible(b)) return false; exLog('handoff');
1803
2113
  return (await exSay(b, exPick(E.ask, seed), token)) && (await exSay(a, exPick(E.askBack, seed >>> 3), token));
1804
2114
  }
1805
2115
  async function reportX(g, i, seed, token) { // a report: the receiver reacts to what really happened
1806
- const E = EXCH[FR() ? 'fr' : 'en'], b = g.agent, a = g.to; if (a === 'user' || !exVisible(a) || !exVisible(b)) return false; const f = exchFacts(i, b);
2116
+ const E = EXCH[CALL()], b = g.agent, a = g.to; if (a === 'user' || !exVisible(a) || !exVisible(b)) return false; const f = exchFacts(i, b);
1807
2117
  if (f.errs > 0) { exLog('report-errors'); return (await exSay(a, exPick(E.err, seed, f), token)) && (await exSay(b, exPick(E.errBack, seed >>> 3), token)); }
1808
2118
  if (f.ms >= 120000) { exLog('report-slow'); return (await exSay(a, exPick(E.slow, seed, f), token)) && (await exSay(b, exPick(E.slowBack, seed >>> 3), token)); }
1809
2119
  exLog('report-ok'); if (!(await exSay(a, exPick(E.ok, seed, f, nameOf(b)), token))) return false;
1810
2120
  const c = (seed >>> 5) % 100 < 35 ? pickOther([a, b]) : null; if (c) await exSay(c, exPick(E.chime, seed >>> 7, nameOf(b)), token); return true;
1811
2121
  }
1812
2122
  async function troubleX(token) { // someone keeps failing: a colleague checks in
1813
- const E = EXCH[FR() ? 'fr' : 'en']; while (S.exQ && S.exQ.length) {
2123
+ const E = EXCH[CALL()]; while (S.exQ && S.exQ.length) {
1814
2124
  const x = S.exQ.shift(); if (!exVisible(x)) continue; const h = pickOther([x], (id) => id === 'main'); if (!h) continue; const seed = hash('t' + x + Date.now());
1815
2125
  exLog('trouble'); return (await exSay(h, exPick(E.trouble, seed, nameOf(x)), token)) && (await exSay(x, exPick(E.troubleBack, seed >>> 3), token));
1816
2126
  }
@@ -1819,7 +2129,7 @@ async function troubleX(token) { // someone keeps failing: a colleague checks
1819
2129
  async function syncX(g, token) { // every few minutes of the session: the lead asks where everyone is, the busy agents answer
1820
2130
  if (chatMul() < 0.9 || !g.ts || g.ts - (S.syncTs || 0) < 180000 || !exVisible('main')) return false;
1821
2131
  const now = Date.now(), busy = Object.keys(S.agents).filter((id) => id !== 'user' && id !== 'main' && exVisible(id) && agentState(id, now).k === 'working').slice(0, 3); if (busy.length < 2) return false;
1822
- S.syncTs = g.ts; const E = EXCH[FR() ? 'fr' : 'en'], seed = hash('s' + g.ts); exLog('sync');
2132
+ S.syncTs = g.ts; const E = EXCH[CALL()], seed = hash('s' + g.ts); exLog('sync');
1823
2133
  if (!(await exSay('main', exPick(E.sync, seed), token))) return false;
1824
2134
  for (const [n, id] of busy.entries()) { const act = (S.act[id] || '').replace(/^\S+\s/, '') || L('au travail', 'working'); if (!(await exSay(id, exPick(E.syncAns, seed >>> (n + 1), act.charAt(0).toLowerCase() + act.slice(1)), token))) return false; }
1825
2135
  return true;
@@ -1838,12 +2148,12 @@ async function converse(g, token) { // after a line has been said: an exchange
1838
2148
  }
1839
2149
  // What is said out loud for an order or a report: a natural lead-in, then the text
1840
2150
  function talkLine(g) {
1841
- const E = EXCH[FR() ? 'fr' : 'en'], seed = hash('l' + g.ts + g.agent), t = spoken(g);
2151
+ const E = EXCH[CALL()], seed = hash('l' + g.ts + g.agent), t = spoken(g);
1842
2152
  if (g.kind === 'report') return t.replace(/^(Terminé\.|Done\.)\s*/, E.done[seed % E.done.length] + ' ');
1843
2153
  return t;
1844
2154
  }
1845
2155
  async function react(ev, token) {
1846
- if ((!prefs.epi && !prefs.banter) || S.boost > 1 || S.hurry || !nearLive()) return; const seed = hash(String(ev.ts) + ev.agent), R = REACT[FR() ? 'fr' : 'en']; let who, line, thanks = false;
2156
+ if ((!prefs.epi && !prefs.banter) || S.boost > 1 || S.hurry || !nearLive()) return; const seed = hash(String(ev.ts) + ev.agent), R = REACT[CALL()]; let who, line, thanks = false;
1847
2157
  if (ev.kind === 'order') { if (!prefs.banter && seed % 100 > 55) return; who = ev.to; line = prefs.banter ? ackLine(ev) : R.ack[seed % R.ack.length]; }
1848
2158
  else if (ev.kind === 'report') {
1849
2159
  const r = seed % 100, joke = prefs.epi ? 60 : prefs.chat === 'quiet' ? -1 : 35; // a remark from someone else, or (a little less often) a word of thanks from whoever receives the report
@@ -1862,6 +2172,12 @@ const FILL = {
1862
2172
  fr: { share: ['Vous voyez bien mon écran ?', 'Deux secondes, ça charge.', 'Désolé, ma machine rame aujourd’hui.', 'C’est assez gros pour tout le monde ?', 'Une seconde… j’y suis presque.', 'Dites-moi si je vais trop vite.'],
1863
2173
  busy: ['Toujours là, je suis dessus.', 'Pardon, j’étais en muet.', 'Petit point : j’avance.', 'Pas de point bloquant de mon côté.', 'Vous m’entendez ?', 'C’est moi, ou c’est calme ?', 'Je vous fais un retour dans une minute.'],
1864
2174
  wait: ['Vous m’entendez ?', 'Vous êtes toujours là ?', 'Allô ? Je crois que ton micro est coupé.', 'On a perdu quelqu’un ?', 'C’est ma connexion ?', 'On en reparle en off ?', 'On refait un point quand tu veux.', 'Je vous rends une minute.', 'D’autres sujets ?', 'Pardon, vas-y. Non, toi d’abord.'] },
2175
+ es: { share: ['¿Se ve bien mi pantalla?', 'Un momento, está cargando.', 'Perdón, mi máquina va lenta hoy.', '¿Se ve lo bastante grande?', 'Un segundo… ya casi.', 'Avisa si voy demasiado rápido.'],
2176
+ busy: ['Sigo aquí, a lo mío.', 'Perdón, estaba en silencio.', 'Novedades: sigo con ello.', 'Sin bloqueos por mi parte.', '¿Se me oye?', '¿Soy yo, o está todo muy callado?', 'Tendré novedades en un minuto.'],
2177
+ wait: ['¿Se me oye?', '¿Sigue alguien ahí?', '¿Hola? Creo que tienes el micro apagado.', '¿Hemos perdido a alguien?', '¿Es mi conexión?', '¿Lo hablamos fuera de la reunión?', 'Lo retomamos cuando quieras.', 'Un minuto libre para todos.', '¿Algún otro tema?', 'Perdón, sigue. No, tú primero.'] },
2178
+ pt: { share: ['Todo mundo está vendo a minha tela?', 'Só um instante, está carregando.', 'Desculpa, minha máquina está lenta hoje.', 'Está grande o suficiente para todo mundo?', 'Um segundo… quase lá.', 'Me avisem se eu estiver indo rápido demais.'],
2179
+ busy: ['Ainda estou aqui, focando no trabalho.', 'Desculpa, eu estava no mudo.', 'Atualização rápida: sigo nisso.', 'Sem bloqueios do meu lado.', 'Vocês estão me ouvindo?', 'É impressão minha, ou está tudo quieto?', 'Trago novidades em um minuto.'],
2180
+ wait: ['Vocês estão me ouvindo?', 'Vocês ainda estão aí?', 'Alô? Acho que você está no mudo.', 'Perdemos alguém?', 'É a minha conexão?', 'Vamos falar disso depois da reunião?', 'A gente retoma quando você quiser.', 'Devolvo um minuto para todo mundo.', 'Mais algum assunto?', 'Desculpa, pode falar. Não, você primeiro.'] },
1865
2181
  };
1866
2182
  // A little more talk between agents: a word of thanks when a report comes in, a word from whoever has been thinking for a long time.
1867
2183
  const TALK = {
@@ -1869,8 +2185,12 @@ const TALK = {
1869
2185
  think: ['Hmm, let me think.', 'Give me a second, I’m thinking.', 'Interesting… let me think this through.', 'One moment, I’m working it out.', 'Hang on, I want to get this right.', 'Let me double-check something.', 'Still thinking… almost there.', 'That one needs a bit of thought.'] },
1870
2186
  fr: { thanks: ['Merci, ça m’aide.', 'Bien reçu, merci.', 'C’est noté. Je prends la suite.', 'Parfait, c’est ce qu’il me fallait.', 'Merci, bon boulot.', 'Bon à savoir, merci.', 'Compris, merci.', 'Super, un souci de moins.'],
1871
2187
  think: ['Hmm, laissez-moi réfléchir.', 'Une seconde, je réfléchis.', 'Intéressant… je creuse ça.', 'Un instant, je fais le point.', 'Attendez, je veux être sûr.', 'Je vérifie un truc.', 'Je réfléchis encore… j’y suis presque.', 'Ça demande un peu de réflexion.'] },
2188
+ es: { thanks: ['Gracias, eso ayuda.', 'Entendido, gracias.', 'Anotado. Sigo yo desde aquí.', 'Perfecto, es lo que necesitaba.', 'Gracias, buen trabajo.', 'Bueno saberlo, gracias.', 'Comprendido, gracias.', 'Genial, una cosa menos de la que preocuparse.'],
2189
+ think: ['Mmm, déjame pensar.', 'Dame un segundo, estoy pensando.', 'Interesante… déjame pensarlo bien.', 'Un momento, lo estoy resolviendo.', 'Espera, quiero hacerlo bien.', 'Déjame comprobar una cosa.', 'Sigo pensando… ya casi.', 'Esto requiere pensarlo un poco.'] },
2190
+ pt: { thanks: ['Valeu, isso ajuda.', 'Entendi, valeu.', 'Anotado. Eu sigo daqui.', 'Perfeito, era o que eu precisava.', 'Valeu, bom trabalho.', 'Bom saber, valeu.', 'Entendido, agradeço.', 'Ótimo, uma preocupação a menos.'],
2191
+ think: ['Hmm, deixa eu pensar.', 'Me dá um segundo, estou pensando.', 'Interessante… deixa eu pensar melhor.', 'Um momento, estou resolvendo isso.', 'Espera, quero fazer isso direito.', 'Deixa eu conferir uma coisa.', 'Ainda pensando… quase lá.', 'Essa pede um pouco de reflexão.'] },
1872
2192
  };
1873
- function varied(kind, seed) { const P = TALK[FR() ? 'fr' : 'en'][kind]; let line = P[seed % P.length]; if (line === S.lastTalk) line = P[(seed + 1) % P.length]; return (S.lastTalk = line); } // never the same line twice in a row
2193
+ function varied(kind, seed) { const P = TALK[CALL()][kind]; let line = P[seed % P.length]; if (line === S.lastTalk) line = P[(seed + 1) % P.length]; return (S.lastTalk = line); } // never the same line twice in a row
1874
2194
  // Who is thinking once this event has happened: the agent whose tool just answered, the lead after your message or a report, a sub-agent that just got its order. After a line or a tool call, nobody is.
1875
2195
  const thinkerOf = (e) => (e.kind === 'results' ? e.agent : e.kind === 'user' ? 'main' : e.kind === 'report' || e.kind === 'finish' || e.kind === 'order' ? e.to : null);
1876
2196
  const before = (i) => { let k = i - 1; while (k >= 0 && (S.events[k].kind === 'usage' || S.events[k].kind === 'compact')) k--; return S.events[k]; };
@@ -1882,10 +2202,12 @@ async function ponder(i, token) { // replay: an agent that really took a long
1882
2202
  const LEAD = {
1883
2203
  en: { in: ['Got it.', 'Okay.', 'On it.', 'Sure.', 'Right.'], read: 'Let me look at ', edit: 'I’m editing ', write: 'I’m writing ', cmd: 'I’m running ', note: 'I’m running a command: ', grep: 'Let me search the code.', glob: 'Let me see which files we have.', todo: 'Let me lay out a plan.', web: 'Let me check the web.', question: 'I have a question for you.', any: 'Let me get started.', and: ' and ' },
1884
2204
  fr: { in: ['D’accord.', 'Compris.', 'Très bien.', 'Entendu.', 'Ça marche.'], read: 'Je regarde ', edit: 'Je modifie ', write: 'J’écris ', cmd: 'Je lance ', note: 'Je lance une commande : ', grep: 'Je cherche dans le code.', glob: 'Je regarde quels fichiers on a.', todo: 'Je fais mon plan.', web: 'Je vais voir sur le web.', question: 'J’ai une question pour vous.', any: 'Je m’y mets.', and: ' et ' },
2205
+ es: { in: ['Entendido.', 'Vale.', 'Voy.', 'Claro.', 'De acuerdo.'], read: 'Voy a mirar ', edit: 'Estoy editando ', write: 'Estoy escribiendo ', cmd: 'Estoy ejecutando ', note: 'Ejecuto un comando: ', grep: 'Voy a buscar en el código.', glob: 'Voy a ver qué archivos tenemos.', todo: 'Voy a trazar un plan.', web: 'Voy a mirar en la web.', question: 'Tengo una pregunta para ti.', any: 'Me pongo a ello.', and: ' y ' },
2206
+ pt: { in: ['Entendi.', 'Certo.', 'Deixa comigo.', 'Claro.', 'Tá bom.'], read: 'Vou dar uma olhada em ', edit: 'Estou editando ', write: 'Estou escrevendo ', cmd: 'Estou rodando ', note: 'Estou rodando um comando: ', grep: 'Vou procurar no código.', glob: 'Vou ver quais arquivos temos.', todo: 'Vou montar um plano.', web: 'Vou conferir na web.', question: 'Tenho uma pergunta para você.', any: 'Vou começar.', and: ' e ' },
1885
2207
  };
1886
2208
  async function leadAck(ev, token) {
1887
2209
  if (!prefs.banter || !S.agents.main) { S.owed = false; return; } if (S.hurry || S.boost > 1 || !nearLive() || S.speakers.size) return; S.owed = false; // reading your order took a while: the first tool is rarely less than 6 s old; if now is a bad moment, the next tool will do
1888
- const W = LEAD[FR() ? 'fr' : 'en'], d = ev.tools[0].d || {}, k = d.kind === 'text' ? d.what : d.kind; let what = W[k] || W.any;
2210
+ const W = LEAD[CALL()], d = ev.tools[0].d || {}, k = d.kind === 'text' ? d.what : d.kind; let what = W[k] || W.any;
1889
2211
  if (k === 'read' || k === 'edit' || k === 'write') { const files = [...new Set(ev.tools.filter((t) => (t.d || {}).kind === k).map((t) => base(t.d.file)).filter(Boolean))].slice(0, 2); what = files.length ? what + files.join(W.and) + '.' : W.any; }
1890
2212
  else if (k === 'cmd') { const note = (d.note || '').trim().replace(/[.\s]+$/, ''), cmd = String(d.text || '').trim().split(/\s+/).slice(0, 2).join(' ').slice(0, 26); what = note ? W.note + note + '.' : cmd ? what + cmd + '.' : W.any; }
1891
2213
  await sayLine('main', `${W.in[hash('k' + ev.ts) % W.in.length]} ${what}`, '💬', token);
@@ -1896,9 +2218,11 @@ async function leadAck(ev, token) {
1896
2218
  const CLOSE = {
1897
2219
  en: { edit: [(a) => `I changed ${a}.`, (a) => `I updated ${a}.`, (a) => `My changes are in ${a}.`], calls: [(w, d) => `That was ${w}${d ? ' in ' + d : ''}.`, (w, d) => `In total: ${w}${d ? ' in ' + d : ''}.`], said: ['That’s my answer.', 'That’s all from me.', 'Nothing more from me.'], ask: ['I’ll wait for your answer.', 'Your call.', 'Tell me what you prefer.'], you: ['Your turn.', 'Over to you.', 'Back to you.'], step: ['One step done.', 'That part is done.', 'So far so good.'], team: ['The team is back. I’ll go through the reports.', 'All the reports are in. Let me read them.', 'Everyone has reported. I’ll take it from here.'], and: ' and ' },
1898
2220
  fr: { edit: [(a) => `J’ai modifié ${a}.`, (a) => `J’ai mis à jour ${a}.`, (a) => `Mes changements sont dans ${a}.`], calls: [(w, d) => `Ça fait ${w}${d ? ' en ' + d : ''}.`, (w, d) => `Au total : ${w}${d ? ' en ' + d : ''}.`], said: ['Voilà ma réponse.', 'C’est tout pour moi.', 'Rien de plus de mon côté.'], ask: ['J’attends votre réponse.', 'À vous de décider.', 'Dites-moi ce que vous préférez.'], you: ['À vous.', 'C’est à vous.', 'Je vous rends la main.'], step: ['Une étape de faite.', 'Cette partie est faite.', 'Jusqu’ici, tout va bien.'], team: ['L’équipe est de retour. Je parcours les rapports.', 'Tous les rapports sont là. Je les lis.', 'Tout le monde a rendu son rapport. Je prends la suite.'], and: ' et ' },
2221
+ es: { edit: [(a) => `He cambiado ${a}.`, (a) => `He actualizado ${a}.`, (a) => `Mis cambios están en ${a}.`], calls: [(w, d) => `Eso suma ${w}${d ? ' en ' + d : ''}.`, (w, d) => `En total: ${w}${d ? ' en ' + d : ''}.`], said: ['Esa es mi respuesta.', 'Eso es todo por mi parte.', 'Nada más por mi parte.'], ask: ['Espero tu respuesta.', 'Tú decides.', 'Dime qué prefieres.'], you: ['Tu turno.', 'Te toca.', 'Te devuelvo la palabra.'], step: ['Un paso hecho.', 'Esa parte está hecha.', 'Hasta aquí, todo bien.'], team: ['El equipo ha vuelto. Voy a repasar los informes.', 'Ya están todos los informes. Voy a leerlos.', 'Todos han informado. Sigo yo desde aquí.'], and: ' y ' },
2222
+ pt: { edit: [(a) => `Alterei ${a}.`, (a) => `Atualizei ${a}.`, (a) => `Minhas alterações estão em ${a}.`], calls: [(w, d) => `Isso deu ${w}${d ? ' em ' + d : ''}.`, (w, d) => `No total: ${w}${d ? ' em ' + d : ''}.`], said: ['Essa é a minha resposta.', 'Isso é tudo da minha parte.', 'Nada mais da minha parte.'], ask: ['Aguardo sua resposta.', 'Você decide.', 'Me diga o que prefere.'], you: ['Sua vez.', 'É com você.', 'Passo a palavra para você.'], step: ['Uma etapa feita.', 'Essa parte está feita.', 'Até aqui, tudo certo.'], team: ['A equipe voltou. Vou passar pelos relatórios.', 'Todos os relatórios chegaram. Vou ler.', 'Todo mundo entregou. Eu sigo daqui.'], and: ' e ' },
1899
2223
  };
1900
2224
  function closeLine(e, tail) { // e: the message that closed this stretch of work; none when there is no new one, and then the line is only how it ends
1901
- const W = CLOSE[FR() ? 'fr' : 'en'], f = e ? exchFacts(S.pos - 1, 'main') : null, n = f ? f.files.length : 0, ask = tail === 'you' && !!e && /[??]$/.test(plain(e.text)); // it ends on a question: the floor is yours, to answer it
2225
+ const W = CLOSE[CALL()], f = e ? exchFacts(S.pos - 1, 'main') : null, n = f ? f.files.length : 0, ask = tail === 'you' && !!e && /[??]$/.test(plain(e.text)); // it ends on a question: the floor is yours, to answer it
1902
2226
  const make = (s) => { const end = W[tail][(s >>> 3) % W[tail].length]; if (!e) return end; if (ask) return W.ask[s % W.ask.length];
1903
2227
  const did = n ? W.edit[s % W.edit.length](n < 3 ? f.files.join(W.and) : P('file', n)) : f.tools ? W.calls[s % W.calls.length](P('call', f.tools), f.ms >= 20000 ? f.dur : '') : tail === 'you' ? W.said[s % W.said.length] : ''; return (did ? did + ' ' : '') + end; };
1904
2228
  const s = hash('c' + (e ? e.ts : Date.now())); let line = make(s); if (line === S.lastClose) line = make(s + 8); return (S.lastClose = line); // never the same line twice in a row
@@ -1921,7 +2245,7 @@ async function smallTalk(token) {
1921
2245
  const p = before(S.events.length), muser = S.live && !n && !S.mused && p ? thinkerOf(p) : null, think = !!muser && here.includes(muser) && quiet > 6000 && Date.now() - p.ts > 20000 && Date.now() - p.ts < 180000; // live: 20 s without a word from whoever is thinking, once per silence
1922
2246
  if (!think && (quiet < (S.live ? 45000 : 12000 / spd()) * [1, 2.5, 6][n] || (S.live && Date.now() - last.ts > 6e5))) return; // live: a session untouched for ten minutes is a call that is over
1923
2247
  const busy = here.filter((id) => agentState(id, Date.now()).k === 'working'), who = think ? muser : S.present && here.includes(S.present) ? S.present : pick(busy.length ? busy : here); if (!who) return; // whoever shares their screen speaks, so the screen stays up
1924
- const P = FILL[FR() ? 'fr' : 'en'][who === S.present ? 'share' : busy.length ? 'busy' : 'wait']; let line = think ? varied('think', Math.floor(Math.random() * 97)) : pick(P); if (!think && line === S.lastFill) line = P[(P.indexOf(line) + 1) % P.length]; if (!think) S.lastFill = line;
2248
+ const P = FILL[CALL()][who === S.present ? 'share' : busy.length ? 'busy' : 'wait']; let line = think ? varied('think', Math.floor(Math.random() * 97)) : pick(P); if (!think && line === S.lastFill) line = P[(P.indexOf(line) + 1) % P.length]; if (!think) S.lastFill = line;
1925
2249
  startTalk(who, line, think ? '💭' : '💬'); if (think) S.mused = true; else S.fill = n + 1; await speakLine(line, S.agents[who], true, token); stopTalk(who);
1926
2250
  }
1927
2251
  async function card(text, sub, ms = 2500) {
@@ -1964,7 +2288,7 @@ async function run(i) {
1964
2288
  const backlog = S.live ? S.events.length - i : 0, quick = S.live ? Math.min(1, 40 / Math.max(1, backlog)) : 1; // live: hundreds of tool events from parallel sub-agents must not take minutes to scroll past
1965
2289
  if (ev.kind === 'results') { applyResults(ev, S.boost > 1); await sleep((S.boost === 1 && S.present === ev.agent && ev.items.some((it) => it.img) ? (S.live ? 900 : 1800) : S.demo ? 900 : S.live ? 30 * quick : 80) / spd()); i++; continue; } // a picture gets a moment on screen
1966
2290
  if (ev.kind === 'tools') { applyStatus(ev); tickTools(ev); AUD.click(); OFFICE.kick(ev.tools[ev.tools.length - 1].name); paintStatus(); if (S.live && S.owed && ev.agent === 'main') { await leadAck(ev, token); if (token !== S.token) return; } if (quick === 1) await smallTalk(token); await sleep((S.demo ? 1100 : S.live ? 110 * quick : 250) / spd()); i++; continue; }
1967
- const group = [ev]; let j = i + 1; // sub-agents talking back-to-back were running in parallel: they talk over each other
2291
+ const group = [ev]; let j = i + 1; // sub-agents talking back-to-back were running in parallel: their lines are taken together and said one after the other
1968
2292
  if (ev.kind === 'order') { // several orders in a row (a parallel launch): the new agents all appear now, the first order is read, the others are named in one line
1969
2293
  while (j < Math.min(S.events.length, i + 40) && group.length < 8) { const e2 = S.events[j]; if (e2.kind === 'usage' || e2.kind === 'compact') { tally(e2); j++; continue; } if (e2.kind === 'order' && e2.agent === ev.agent) { group.push(e2); j++; } else break; }
1970
2294
  if (group.length > 1) { for (const g of group) applyStatus(g); paintStatus(); }
@@ -1979,7 +2303,7 @@ async function run(i) {
1979
2303
  if (e2.kind !== 'order' && isSub(e2.agent) && !group.some((g) => g.agent === e2.agent)) { group.push(e2); j++; } else break;
1980
2304
  }
1981
2305
  }
1982
- if (FR() && !S.hurry) { prefetchTr(i); await Promise.race([ensureTr(group.map((g) => baseText(g))), sleep(S.live ? 7000 : 14000)]); if (token !== S.token) return; }
2306
+ if (TRL() && !S.hurry) { prefetchTr(i); await Promise.race([ensureTr(group.map((g) => baseText(g))), sleep(S.live ? 7000 : 14000)]); if (token !== S.token) return; }
1983
2307
  prefetchQuips(i); warmTTS(i);
1984
2308
  const playOne = (g) => {
1985
2309
  applyStatus(g); if (g.end) paintStates(); g._as = g.kind; if (g.agent === 'user') S.owed = true; else if (g.agent === 'main') S.owed = false; // your order waits for a word from the lead
@@ -1988,7 +2312,7 @@ async function run(i) {
1988
2312
  if (g.kind === 'order') { S.status[g.to] = 'working'; AUD.join(); setTimeout(() => { paintStatus(); fly(g.agent, g.to, '📨'); popTile(g.to); }, 30); }
1989
2313
  if (g.kind === 'report') { AUD.ding(); setTimeout(() => { fly(g.agent, g.to, '✅'); popTile(g.agent); }, 30); }
1990
2314
  const said = clipSpeech(line, S.pace); if (g.agent === 'main' && g.kind === 'say') { const full = plain(g.text), key = said.replace(/…$/, '').trim().slice(-30), pos = key ? full.indexOf(key) : -1, n = pos >= 0 ? pos + key.length : said.length; S.mainSaid = { ev: g, said: n, full: n >= full.length - 5 }; }
1991
- return speakLine(said, S.agents[g.agent], true, token, sessFr(said, g), g.kind === 'user').then(() => { if (token === S.token) stopTalk(g.agent); });
2315
+ return speakLine(said, S.agents[g.agent], true, token, sessVoice(said, g), g.kind === 'user').then(() => { if (token === S.token) stopTalk(g.agent); });
1992
2316
  };
1993
2317
  let plays;
1994
2318
  if (ev.kind === 'order' && group.length > 1) { // the first order in full, then "Also Remy on X, Iris on Y"
@@ -1996,8 +2320,8 @@ async function run(i) {
1996
2320
  setTimeout(() => rest.forEach((o, k) => setTimeout(() => { fly(o.agent, o.to, '📨'); popTile(o.to); }, k * 120)), 30);
1997
2321
  plays = [playOne(ev).then(() => { if (token !== S.token) return; startTalk(ev.agent, line, ''); return speakLine(clipSpeech(line, S.pace), S.agents[ev.agent], true, token).then(() => { if (token === S.token) stopTalk(ev.agent); }); })];
1998
2322
  }
1999
- else if (S.live) { plays = []; let chain = Promise.resolve(); for (const g of group) { chain = chain.then(() => (token === S.token ? playOne(g) : null)); plays.push(chain); } } else plays = group.map(playOne); // live: one voice at a time so each can be heard; replay keeps the overlapping chatter
2000
- S.idx = j - 1; paintStatus(); await Promise.all(plays); if (token !== S.token) return;
2323
+ else plays = [group.reduce((turn, g) => turn.then(() => { if (token !== S.token) return null; if (!S.live) { S.idx = S.events.indexOf(g); paintStatus(); } return playOne(g); }), Promise.resolve())]; // one voice at a time, live and in replay: each waits for the one before to finish, so every line is heard. In a replay the place follows the one who speaks: paused there, the replay resumes with that line and loses none of the next ones
2324
+ S.idx = j - 1; paintStatus(); await Promise.all(plays); if (token !== S.token) return; S.idx = j - 1;
2001
2325
  for (const g of (ev.kind === 'order' ? group.slice(0, 3) : group)) { await converse(g, token); if (token !== S.token) return; } // a parallel launch: the first three answer, as long as the call keeps up
2002
2326
  i = j;
2003
2327
  }
@@ -2038,24 +2362,24 @@ async function loadSession(proj, id) {
2038
2362
  const data = await (await fetch(`/api/session?proj=${encodeURIComponent(proj)}&id=${id}`)).json();
2039
2363
  if (mine !== S.loadN || data.error) return false;
2040
2364
  S.term = {}; S.camFor = null; S.focus = null; S.agents = {}; for (const k in nameBook) delete nameBook[k]; [{ id: 'user' }, ...data.agents].forEach((a) => (S.agents[a.id] = persona(a)));
2041
- clearThoughts(); Object.assign(TH, { since: {}, next: {}, said: {}, last: 0 }); S.events = data.events; stampT(0); S.byK = new Map(data.events.map((e) => [e.k, e])); S.seq = data.seq || 0; S.ep = data.ep || ''; S.sawEnd = !!data.marks || data.events.some((e) => e.end); S.late = []; S.pos = 0; S.joinAt = Date.now(); S.idx = 0; S.status = {}; S.tc = {}; S.cur = { proj, id }; S.logTo = 0; S.detail = null; $('#detail').classList.remove('on'); S.fgone = new Set(); S.fmade = new Map();
2365
+ clearThoughts(); Object.assign(TH, { since: {}, next: {}, said: {}, last: 0 }); S.events = data.events; stampT(0); S.byK = new Map(data.events.map((e) => [e.k, e])); S.seq = data.seq || 0; S.ep = data.ep || ''; S.sawEnd = !!data.marks || data.events.some((e) => e.end); S.late = []; S.pos = 0; S.joinAt = Date.now(); S.idx = 0; S.status = {}; S.tc = {}; S.cur = { proj, id }; S.logTo = 0; S.detail = null; $('#detail').classList.remove('on'); S.fgone = new Set(); S.fmade = new Map(); S.artOk = new Map(); S.artPin = null;
2042
2366
  const opt = $('#sessions').selectedOptions[0]; S.title = (S.live ? niceProj(proj) : opt && opt.dataset.title) || '';
2043
- if (proj === '_demo') S.events.forEach((e) => { if (e.fr) trMem.set(baseText(e), e.fr); }); // the demo ships its own French
2367
+ if (proj === '_demo') S.events.forEach((e) => { if (e.fr) trMem.set(baseText(e), e.fr, 'fr'); }); // the demo ships its own French
2044
2368
  $('#subtitle').textContent = S.title; recomputeStatus(0); buildStage(); renderHighlights(); setFocus('main'); renderLog(true); computeGantt(); layout(); paintStatus(); prefetchTr(0); return true;
2045
2369
  }
2046
- const niceProj = (p) => (p === '_demo' ? '' : p === '_codex' ? 'Codex' : p === '_vibe' ? 'Mistral Vibe' : String(p).replace(/^-+/, '').replace(/-/g, '/').split('/').slice(-2).join('/'));
2370
+ const niceProj = (p) => (p === '_demo' ? '' : p === '_codex' ? 'Codex' : p === '_vibe' ? 'Mistral Vibe' : p === '_cowork' ? 'Cowork' : String(p).replace(/^-+/, '').replace(/-/g, '/').split('/').slice(-2).join('/'));
2047
2371
  async function fillProjects() { // live view: follow the latest activity anywhere, or pin one project
2048
2372
  const sel = $('#liveProj'); let rows = []; try { rows = await (await fetch('/api/projects')).json(); } catch {}
2049
2373
  sel.innerHTML = `<option value="">${L('Tous les projets (le plus récent)', 'All projects (most recent)')}</option>` + rows.map((r) => `<option value="${esc(r.proj)}">${esc(niceProj(r.proj))}</option>`).join('');
2050
2374
  sel.value = prefs.proj && rows.some((r) => r.proj === prefs.proj) ? prefs.proj : ''; sel.style.display = rows.length > 1 ? '' : 'none';
2051
2375
  }
2052
- $('#liveProj').onchange = () => { Q.delete('proj'); prefs.proj = $('#liveProj').value; S.pin = S.pinProj = ''; S.hold = null; savePrefs(); S.cur = null; followCurrent(); };
2376
+ $('#liveProj').onchange = () => { Q.delete('proj'); prefs.proj = $('#liveProj').value; S.pick = null; savePrefs(); S.cur = null; followCurrent(); };
2053
2377
  async function followCurrent() {
2054
- if (S.hold && (S.pin || Date.now() > S.hold.until)) S.hold = null; const at = S.pin ? { id: S.pin, proj: S.pinProj } : S.hold; // the session the call is kept in: the pinned one, or for a moment the one of the tab you went to (see tabSession)
2055
- const cur = await (await fetch('/api/current?proj=' + encodeURIComponent((at && at.proj) || Q.get('proj') || prefs.proj || '') + (at ? '&id=' + encodeURIComponent(at.id) : '') + (S.cur && !at ? '&sproj=' + encodeURIComponent(S.cur.proj) + '&sid=' + encodeURIComponent(S.cur.id) : ''))).json();
2056
- if ((S.pin || (S.hold && S.hold.id) || '') !== (at ? at.id : '')) return false; // asked before a click or a tab sent the call elsewhere (or let it go): the answer to act on is the one asked since. This one undid the click
2378
+ const at = S.pick, enc = encodeURIComponent, watch = Q.get('proj') || prefs.proj || ''; // at: the session you went to by hand (see goSession). The server says whether the call is still to be kept there: it is, until you type somewhere
2379
+ const cur = await (await fetch('/api/current?proj=' + enc(watch) + (at ? '&pproj=' + enc(at.proj || watch) + '&pid=' + enc(at.id) + (at.since != null ? '&since=' + at.since : '') + (at.pin ? '&pin=1' : '') : '') + (S.cur ? '&sproj=' + enc(S.cur.proj) + '&sid=' + enc(S.cur.id) : ''))).json();
2380
+ if (S.pick !== at) return false; // asked before a click or a tab sent the call elsewhere: the answer to act on is the one asked since. This one undid the click
2381
+ if (!cur.pick) { S.pick = null; S.wide = !!cur.wide; } else if (at.since == null) at.since = cur.asked || 0; /* not kept there any more: you typed somewhere since, or that session is gone · wide: the folder the call follows has no session, the server looked everywhere, and so do the tabs (inWatch). An answer about a session you went to says nothing of that folder · since: the latest order there was when you went there, which a later one is told from */
2057
2382
  if (!cur.id) { $('#empty').classList.add('on'); return false; } $('#empty').classList.remove('on');
2058
- if (at && at === S.hold && cur.id !== at.id) S.hold = null; if (S.pin && cur.id !== S.pin) S.pin = S.pinProj = ''; // the pinned session is gone: follow the latest one instead of staying silently pinned
2059
2383
  if (S.cur && S.cur.id === cur.id && S.cur.proj === cur.proj) return false;
2060
2384
  const key = cur.proj + '/' + cur.id, was = S.lastKey, moved = !!was && was !== key && !S.locked; if (moved) S.left[was] = Date.now(); // what was said of the session the call leaves is not said again when it comes back to it
2061
2385
  if (!(await loadSession(cur.proj, cur.id))) return false;
@@ -2103,10 +2427,10 @@ setInterval(async () => {
2103
2427
  }, 400);
2104
2428
 
2105
2429
 
2106
- window.addEventListener('message', (e) => { // the VS Code status bar asks to follow a given session
2430
+ window.addEventListener('message', (e) => { // VS Code asks for a given session: the one the status bar was clicked for, or the one of the Claude Code tab you went to (the message is named 'pin' on both sides, from when the call was pinned there)
2107
2431
  const d = e.data; if (!EMBED || e.source !== window.parent || !d || d.agentStandup !== 'pin' || typeof d.id !== 'string') return;
2108
- if (d.tab) { if (prefs.followTab !== false && S.live && !S.demo && typeof d.proj === 'string') tabSession(d.proj, d.id); return; } // the Claude Code tab you went to: the call goes with you (see tabSession, and followTab in extension.js)
2109
- prefs.proj = typeof d.proj === 'string' ? d.proj : ''; S.pin = d.id; S.pinProj = prefs.proj; S.cur = null; setView('call'); if (S.live) { fillProjects(); followCurrent(); } else setMode('live');
2432
+ if (d.tab) { if (prefs.followTab !== false && S.live && !S.demo && typeof d.proj === 'string' && !(S.pick && S.pick.pin)) goSession(d.proj, d.id); return; } // the Claude Code tab you went to: the call goes with you (followTab in extension.js; off in ⚙), unless you pinned a call (📌): that one stays while you go through your tabs
2433
+ const dp = typeof d.proj === 'string' ? d.proj : ''; if (!TOOL[dp]) prefs.proj = dp; S.pick = { proj: dp, id: d.id }; S.cur = null; setView('call'); if (S.live) { fillProjects(); followCurrent(); } else setMode('live');
2110
2434
  });
2111
2435
  // ---------- meeting chrome: participants and a clock ----------
2112
2436
  function renderMeet() {
@@ -2129,25 +2453,42 @@ $('#reactBar').onclick = (e) => {
2129
2453
  const BSTATE = { blocked: ['✋', 'needs you?', 'attend vous ?'], working: ['⚙', 'working', 'au travail'], waiting: ['🔗', 'waiting on sub-agents', 'attend ses sous-agents'], turn: ['✓', 'your turn', 'à vous'], idle: ['💤', 'idle', 'inactif'] };
2130
2454
  const BORDER = ['blocked', 'working', 'waiting', 'turn', 'idle'];
2131
2455
  const agoStr = (ms) => (ms < 90e3 ? Math.max(1, Math.round(ms / 1000)) + 's' : ms < 5400e3 ? Math.round(ms / 60e3) + ' min' : Math.round(ms / 3600e3) + ' h');
2132
- let boardBusy = false;
2456
+ const BGROUP = ['blocked', 'turn', 'working', 'waiting', 'idle']; // the board is in sections, what waits for you first
2457
+ let boardBusy = false, boardAll = null, boardDoneOpen = false;
2458
+ const isDone = (r) => !!r.done; // put away by you, until the session moves again: the server says so, to every window
2459
+ function bcard(r, now, done) {
2460
+ const [ic, en, fr] = BSTATE[r.state], extra = r.state === 'blocked' ? ` · ${r.ask ? '' : esc(r.tool) + ' '}${agoStr(r.ageMs)}` : r.state === 'working' && r.tool ? ` · ${esc(r.tool)}` : r.state === 'idle' || r.state === 'turn' ? ` · ${agoStr(now - r.mtime)}` : '';
2461
+ const pr = r.pr ? `<button class="bpr" data-url="${esc(r.pr.url)}" title="${esc(L('Ouvrir la pull request', 'Open the pull request'))}">PR #${+r.pr.n} ↗</button>` : '';
2462
+ const put = done ? `<button class="bdo" data-undo="1" title="${esc(L('Rouvrir', 'Reopen'))}" aria-label="${esc(L('Rouvrir', 'Reopen'))}">↩</button>` : r.state === 'turn' || r.state === 'idle' ? `<button class="bdo" title="${esc(L('Marquer comme traitée', 'Mark as done'))}" aria-label="${esc(L('Marquer comme traitée', 'Mark as done'))}">✓</button>` : '';
2463
+ return `<div class="bcard ${r.state}" tabindex="0" role="button" data-p="${esc(r.proj)}" data-i="${esc(r.id)}"><div class="bh"><span class="stc ${r.state}">${ic} ${L(fr, en)}${extra}</span>${pr}${put}</div><div class="bt">${esc(/^[0-9a-f]{8}-[0-9a-f-]{27}$/.test(r.title) ? L('Session sans titre', 'Untitled session') : r.title)}</div>${r.ask ? `<div class="bq">${esc(r.ask)}</div>` : ''}<div class="bp">${esc(niceProj(r.proj))}</div>${r.subTotal ? `<div class="bm">👥 ${r.subActive}/${r.subTotal} ${L('sous-agents actifs', 'sub-agents active')}</div>` : ''}</div>`;
2464
+ }
2465
+ function paintBoard() {
2466
+ if (!boardAll || !document.body.classList.contains('board')) return; const now = Date.now(), recent = (a, b) => b.mtime - a.mtime;
2467
+ const live = boardAll.filter((r) => !isDone(r)), done = boardAll.filter(isDone).sort(recent), head = (k, label, n) => `${BSTATE[k] ? BSTATE[k][0] : '✓'} <span class="bl">${label}</span><i>${n}</i>`;
2468
+ const secs = BGROUP.map((k) => [k, live.filter((r) => r.state === k).sort(recent)]).filter(([, rs]) => rs.length).map(([k, rs]) => `<section class="bsec"><h3 class="bhd ${k}">${head(k, L(BSTATE[k][2], BSTATE[k][1]), rs.length)}</h3><div class="bgrid">${rs.map((r) => bcard(r, now, false)).join('')}</div></section>`).join('');
2469
+ const put = done.length ? `<details class="bsec bdone"${boardDoneOpen ? ' open' : ''}><summary class="bhd">${head('', L('Traitées', 'Done'), done.length)}</summary><div class="bgrid">${done.map((r) => bcard(r, now, true)).join('')}</div></details>` : '';
2470
+ $('#boardv').innerHTML = secs + put || `<div class="bsum"><span>${L('Aucune session récente', 'No recent session')}</span></div>`;
2471
+ }
2133
2472
  async function renderBoardView() {
2134
2473
  if (!document.body.classList.contains('board') || boardBusy) return; boardBusy = true;
2135
2474
  try {
2136
- const rows = (await (await fetch('/api/board')).json()).sort((a, b) => BORDER.indexOf(a.state) - BORDER.indexOf(b.state) || b.mtime - a.mtime), now = Date.now();
2137
- if (!document.body.classList.contains('board')) return;
2138
- const cnt = {}; rows.forEach((r) => (cnt[r.state] = (cnt[r.state] || 0) + 1));
2139
- const sum = BORDER.filter((k) => cnt[k]).map((k) => `<span class="stc ${k}">${BSTATE[k][0]} ${cnt[k]} ${L(BSTATE[k][2], BSTATE[k][1])}</span>`).join('');
2140
- $('#boardv').innerHTML = `<div class="bsum">${sum || `<span>${L('Aucune session récente', 'No recent session')}</span>`}</div><div class="bgrid">${rows.map((r) => {
2141
- const [ic, en, fr] = BSTATE[r.state], extra = r.state === 'blocked' ? ` · ${esc(r.tool)} ${agoStr(r.ageMs)}` : r.state === 'working' && r.tool ? ` · ${esc(r.tool)}` : r.state === 'idle' || r.state === 'turn' ? ` · ${agoStr(now - r.mtime)}` : '';
2142
- return `<div class="bcard ${r.state}" tabindex="0" role="button" data-p="${esc(r.proj)}" data-i="${esc(r.id)}"><div><span class="stc ${r.state}">${ic} ${L(fr, en)}${extra}</span></div><div class="bt">${esc(/^[0-9a-f]{8}-[0-9a-f-]{27}$/.test(r.title) ? L('Session sans titre', 'Untitled session') : r.title)}</div><div class="bp">${esc(niceProj(r.proj))}</div>${r.subTotal ? `<div class="bm">👥 ${r.subActive}/${r.subTotal} ${L('sous-agents actifs', 'sub-agents active')}</div>` : ''}</div>`; }).join('')}</div>`;
2475
+ boardAll = await (await fetch('/api/board')).json();
2476
+ paintBoard();
2143
2477
  } catch {} finally { boardBusy = false; }
2144
2478
  }
2479
+ $('#boardv').addEventListener('toggle', (e) => { if (e.target.classList && e.target.classList.contains('bdone')) boardDoneOpen = e.target.open; }, true);
2145
2480
  $('#boardv').onkeydown = (e) => { if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('bcard')) { e.preventDefault(); e.target.click(); } };
2146
2481
  async function openSession(proj, id) {
2147
- prefs.proj = proj; S.pin = id; S.pinProj = proj; savePrefs(); setView('call');
2482
+ if (!TOOL[proj]) prefs.proj = proj; S.pick = { proj, id }; savePrefs(); setView('call'); // a Vibe or Codex session is listed under its tool, which is not a folder to follow: kept as the project, it left a window with no folder showing that tool's sessions only, for good
2148
2483
  if (S.live || S.demo) { if (S.demo) await setMode('live'); S.cur = null; fillProjects(); await followCurrent(); } else await setMode('live');
2149
2484
  }
2150
- $('#boardv').onclick = (e) => { const c = e.target.closest('.bcard'); if (c) openSession(c.dataset.p, c.dataset.i); };
2485
+ $('#boardv').onclick = (e) => {
2486
+ const pr = e.target.closest('.bpr'), put = e.target.closest('.bdo'), c = e.target.closest('.bcard'); if (pr) return openExternal(pr.dataset.url); if (!c) return;
2487
+ if (put) { const proj = c.dataset.p, id = c.dataset.i, on = !put.dataset.undo; // shown at once here, and told to the server, which the other windows ask
2488
+ for (const list of [boardAll || [], S.rows]) { const r = list.find((x) => x.proj === proj && x.id === id); if (r) { if (on) r.done = 1; else delete r.done; } }
2489
+ paintBoard(); paintTabs(); fetch('/api/done', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ proj, id, on }) }).catch(() => {}); return; }
2490
+ openSession(c.dataset.p, c.dataset.i);
2491
+ };
2151
2492
  // Cmd/Ctrl+K: jump to any session from any view
2152
2493
  async function openSwitcher() {
2153
2494
  let sw = $('#switcher'); if (sw) { closeSwitcher(); return; }
@@ -2168,45 +2509,43 @@ async function openSwitcher() {
2168
2509
  function closeSwitcher() { const sw = $('#switcher'); if (sw) sw.remove(); }
2169
2510
  setInterval(() => { if (!document.hidden) renderBoardView(); }, 2500);
2170
2511
  // ---------- several sessions at once (live): the sessions of the moment as tabs under the header, and a visitor when another one needs you ----------
2171
- // The row is there only when there is something to tell apart: a second session at work or waiting for you, or a call you pinned. With a single session the header is as it always was.
2172
- // The tabs keep the order in which the sessions showed up, so the one the call is in stays where it was. A click on another tab takes the call there and keeps it there (📌);
2173
- // a click on the call's own tab pins it, or lets the call follow the latest activity again. In VS Code the call also goes to the Claude Code tab you are on, without being pinned there (⚙, see tabSession, and followTab in extension.js).
2174
- S.rows = []; S.tabOrder = []; S.knockAt = {}; S.left = {}; S.visit = S.knock = null; S.hold = null;
2512
+ // The row is there only when there is something to tell apart: a second session at work or waiting for you. With a single session the header is as it always was.
2513
+ // The tabs keep the order in which the sessions showed up, so the one the call is in stays where it was. The call is in the session you last touched: the one you typed in or started,
2514
+ // or the one you went to since (a click on its tab, the visitor, the list; in VS Code, the Claude Code tab you are on: ⚙, and followTab in extension.js). Nothing is pinned and nothing is to be let go:
2515
+ // the next thing you type, wherever it is, takes the call there. The rule itself is in server.js (currentSession).
2516
+ S.rows = []; S.tabOrder = []; S.knockAt = {}; S.left = {}; S.visit = S.knock = null; S.pick = S.pick || null;
2175
2517
  const UNTITLED = /^[0-9a-f]{8}-[0-9a-f-]{27}$/, sessKey = (r) => r.proj + '/' + r.id, tabName = (r) => (r.title && !UNTITLED.test(r.title) ? r.title : r.title ? L('Session sans titre', 'Untitled session') : niceProj(r.proj) || L('Session sans titre', 'Untitled session'));
2176
- const inWatch = (r) => { const k = Q.get('proj') || prefs.proj || ''; return !k || [r.proj, r.dir || ''].some((d) => d === k || d.startsWith(k + '-')); }; // the folder the live view follows, when it follows one
2518
+ const inWatch = (r) => { const k = Q.get('proj') || prefs.proj || ''; return !k || S.wide ? !r.tmp : [r.proj, r.dir || ''].some((d) => d === k || d.startsWith(k + '-')); }; // the folder the live view follows, when it follows one and that folder has sessions (S.wide: it has none, see followCurrent). Looking everywhere, not the sessions started in the temporary folder (tmp, see tmpKey in server.js)
2177
2519
  const rowOf = (c) => (c && S.rows.find((r) => r.proj === c.proj && r.id === c.id)) || null;
2178
2520
  function paintTabs() {
2179
2521
  const el = $('#tabs'), cur = S.cur; if (!S.live || S.demo) { if (paintTabs.html) el.innerHTML = paintTabs.html = ''; if (S.visit) hideVisit(); return; } if (!cur) return; // between two sessions the tabs stay as they are: the row does not come and go
2180
- const ck = sessKey(cur), by = new Map(S.rows.filter((r) => sessKey(r) === ck || (r.state !== 'idle' && inWatch(r))).map((r) => [sessKey(r), r])); if (!by.has(ck)) by.set(ck, { proj: cur.proj, id: cur.id, title: '', state: '' }); // the call's own session always has its tab, also before the list knows it
2181
- S.tabOrder = S.tabOrder.filter((k) => by.has(k)); for (const k of by.keys()) if (!S.tabOrder.includes(k)) S.tabOrder.push(k);
2182
- const ks = S.tabOrder.slice(0, 8); if (!ks.includes(ck)) ks[ks.length - 1] = ck; // the others are in ⋯
2183
- const html = by.size < 2 && !S.pin ? '' : ks.map((k) => { const r = by.get(k), on = k === ck, st = BSTATE[r.state], pinned = on && !!S.pin; // one session and nothing pinned: no row, there is nothing to tell apart
2184
- const tip = tabName(r) + '\n' + niceProj(r.proj) + (st ? ' · ' + L(st[2], st[1]) : '') + (on ? '\n' + (pinned ? L('Épinglée : cliquez pour suivre la session la plus récente', 'Pinned: click to follow the latest session') : L('Cliquez pour rester dans cette session', 'Click to stay in this session')) : '');
2185
- return `<button class="stab ${r.state}${on ? ' on' : ''}" role="tab" aria-selected="${on}" data-k="${esc(k)}" title="${esc(tip)}">${st ? st[0] : ''}<span>${esc(tabName(r))}</span>${pinned ? '📌' : ''}</button>`; }).join('')
2522
+ const ck = sessKey(cur), by = new Map(S.rows.filter((r) => sessKey(r) === ck || (r.state !== 'idle' && !r.done && inWatch(r))).map((r) => [sessKey(r), r])); if (!by.has(ck)) by.set(ck, { proj: cur.proj, id: cur.id, title: '', state: '' }); // the call's own session always has its tab, also before the list knows it
2523
+ for (const k of by.keys()) if (!S.tabOrder.includes(k)) S.tabOrder.push(k); // a session keeps its place while it has no tab: the call now goes by itself to a session that is started, sometimes before the list has the one it leaves, which then came back second
2524
+ const ks = S.tabOrder.filter((k) => by.has(k)).slice(0, 8); if (!ks.includes(ck)) ks[ks.length - 1] = ck; // the others are in ⋯
2525
+ const html = by.size < 2 ? '' : ks.map((k) => { const r = by.get(k), on = k === ck, st = BSTATE[r.state]; // one session: no row, there is nothing to tell apart
2526
+ const pinned = on && !!S.pick && !!S.pick.pin && sessKey(S.pick) === k, tip = tabName(r) + '\n' + niceProj(r.proj) + (st ? ' · ' + L(st[2], st[1]) : '') + (pinned ? '\n' + L('Épinglé : cliquez pour désépingler', 'Pinned: click to unpin') : '');
2527
+ return `<button class="stab ${r.state}${on ? ' on' : ''}" role="tab" aria-selected="${on}" data-k="${esc(k)}" title="${esc(tip)}">${st ? st[0] : ''}${TOOL[r.proj] ? `<i>${TOOL[r.proj]}</i>` : ''}<span>${esc(tabName(r))}</span>${pinned ? '📌' : ''}</button>`; }).join('')
2186
2528
  + `<button class="stab all" title="${esc(L('Aller à une session', 'Go to a session'))} (Cmd / Ctrl + K)" aria-label="${esc(L('Aller à une session', 'Go to a session'))}">⋯</button>`;
2187
2529
  if (html === paintTabs.html) return; if (!html) paintTabs.cur = ''; el.innerHTML = paintTabs.html = html;
2188
2530
  if (paintTabs.cur !== ck) { paintTabs.cur = ck; const on = el.querySelector('.on'); if (on) on.scrollIntoView({ block: 'nearest', inline: 'nearest' }); }
2189
2531
  }
2190
- function goSession(proj, id) { // the call moves to this session and stays in it
2191
- S.pin = id; S.pinProj = proj; if (S.cur && S.cur.proj === proj && S.cur.id === id) { paintTabs(); return; }
2532
+ function goSession(proj, id, pin) { // you go to this session: the call is kept there until you type somewhere (since: filled by the first answer, see followCurrent)
2533
+ // pin: by a click on its tab. The call is pinned there (📌): it stays while you go through the Claude Code tabs of the editor and while you type in it, until you ask something in another session. A click on that tab again unpins it
2534
+ const held = !!pin && !!S.pick && !!S.pick.pin && S.pick.proj === proj && S.pick.id === id; S.pick = pin && !held ? { proj, id, pin: true } : { proj, id };
2535
+ if (S.cur && S.cur.proj === proj && S.cur.id === id) { paintTabs(); return; } // already there: the call no longer leaves it for a session still at work
2192
2536
  hideVisit(); S.cur = null; followCurrent();
2193
2537
  }
2194
- function tabSession(proj, id) { // the Claude Code tab you went to, in VS Code. A tab never pins the call: going to the tab of the session the call is in changes nothing, and a call that is pinned takes its pin along
2195
- if (S.cur && S.cur.proj === proj && S.cur.id === id) return;
2196
- if (S.pin) return goSession(proj, id);
2197
- S.hold = { proj, id, until: Date.now() + 90000 }; hideVisit(); S.cur = null; followCurrent(); // kept here as long as a session that has just written keeps the call (STICK_MS in server.js), then the latest activity is followed again: going to a conversation is not activity, and without this the call would leave at once for a busier session
2198
- }
2199
2538
  $('#tabs').onclick = (e) => {
2200
2539
  const b = e.target.closest('.stab'); if (!b) return; if (b.classList.contains('all')) { openSwitcher(); return; }
2201
- const [p, i] = b.dataset.k.split('/'); if (!b.classList.contains('on')) { goSession(p, i); return; }
2202
- if (S.pin) { S.pin = S.pinProj = ''; toast(L('Suit la session la plus récente', 'Following the latest session')); } else { S.pin = i; S.pinProj = p; toast('📌 ' + tabName(rowOf(S.cur) || { proj: p })); }
2203
- paintTabs();
2540
+ const [p, i] = b.dataset.k.split('/'); goSession(p, i, true);
2204
2541
  };
2205
2542
  // The visitor: another session has just stopped for you (a question, an edit that waits for your go-ahead, or its turn is over). Someone from there leans in at the edge of the call and says so,
2206
2543
  // between two lines and never over one; a click takes the call there. One at a time, a session that needs you before one that is merely done. Off in ⚙; its line exists in English and French, as the other little lines.
2207
2544
  const VISIT = {
2208
2545
  en: { ask: [(t) => `Knock knock. They have a question for you in “${t}”.`, (t) => `Sorry to cut in: “${t}” has a question for you.`], ok: [(t) => `Knock knock. “${t}” is waiting for your go-ahead.`, (t) => `Excuse me, you are wanted in “${t}”: it waits for your approval.`], turn: [(t) => `Just passing by: “${t}” is done, it is your turn over there.`, (t) => `News from “${t}”: they are finished and wait for you.`] },
2209
2546
  fr: { ask: [(t) => `Toc toc. On a une question pour vous dans « ${t} ».`, (t) => `Pardon de vous couper : « ${t} » a une question pour vous.`], ok: [(t) => `Toc toc. « ${t} » attend votre feu vert.`, (t) => `Excusez-moi, on vous demande dans « ${t} » : on y attend votre accord.`], turn: [(t) => `Je ne fais que passer : « ${t} » a fini, c’est à vous là-bas.`, (t) => `Des nouvelles de « ${t} » : ils ont fini et vous attendent.`] },
2547
+ es: { ask: [(t) => `Toc, toc. Tienen una pregunta para ti en “${t}”.`, (t) => `Perdona que interrumpa: “${t}” tiene una pregunta para ti.`], ok: [(t) => `Toc, toc. “${t}” espera tu visto bueno.`, (t) => `Disculpa, te buscan en “${t}”: esperan tu aprobación.`], turn: [(t) => `Solo pasaba por aquí: “${t}” ha terminado, te toca allí.`, (t) => `Noticias de “${t}”: han terminado y te esperan.`] },
2548
+ pt: { ask: [(t) => `Toc, toc. Tem uma pergunta para você em “${t}”.`, (t) => `Desculpe interromper: “${t}” tem uma pergunta para você.`], ok: [(t) => `Toc, toc. “${t}” está esperando o seu sinal verde.`, (t) => `Com licença, estão chamando você em “${t}”: esperam a sua aprovação.`], turn: [(t) => `Só de passagem: “${t}” terminou, é a sua vez lá.`, (t) => `Notícias de “${t}”: terminaram e esperam por você.`] },
2210
2549
  };
2211
2550
  function knocks() {
2212
2551
  const now = Date.now(), first = !knocks.seen, seen = knocks.seen || (knocks.seen = {}), ck = S.cur ? sessKey(S.cur) : ''; let best = null;
@@ -2220,7 +2559,7 @@ function knocks() {
2220
2559
  if (best && prefs.visits !== false && !S.locked && !(S.visit && S.visit.kind !== 'turn' && best.kind === 'turn')) { S.knockAt[best.k] = now; showVisit(best); }
2221
2560
  }
2222
2561
  function showVisit(v) { // the same face and name each time for a given session; with your own characters, one of them
2223
- const h = hash('visit' + v.k), p = persona0({ id: 'visit:' + v.k, name: NAMES[h % NAMES.length], role: '' }), W = VISIT[FR() ? 'fr' : 'en'][v.kind], t = tabName(v.r), el = $('#visit');
2562
+ const h = hash('visit' + v.k), p = persona0({ id: 'visit:' + v.k, name: NAMES[h % NAMES.length], role: '' }), W = VISIT[CALL()][v.kind], t = tabName(v.r), el = $('#visit');
2224
2563
  p.custom = CHARS.pool.length ? CHARS.pool[h % CHARS.pool.length] : null; v.p = p; v.line = W[(h + (showVisit.n = (showVisit.n || 0) + 1)) % W.length](t.length > 46 ? t.slice(0, 44).replace(/\s+\S*$/, '') + '…' : t);
2225
2564
  el.className = 'on ' + (v.kind === 'turn' ? 'turn' : 'blocked');
2226
2565
  el.innerHTML = `<div class="vsay"><button class="vx" aria-label="${esc(L('Fermer', 'Close'))}">✕</button><small>${esc(p.name)} · ${esc(niceProj(v.r.proj))}</small>${esc(v.line)}<br><button class="vgo">${esc(L('Y aller', 'Go there'))} →</button></div><div class="vwho">${avatarSVG(p, undefined, 'v' + p.gid + '_')}</div>`;
@@ -2295,11 +2634,11 @@ function drawFrame(cv, mark = 0) { // mark: 1 = a clip to share (site address
2295
2634
  const x = 20, y = 50, w = W - 40, ed = m.view === 'editor', col = { cmd: '#e6edf3', out: '#aab2c5', err: '#ff7b72', tool: '#8b95b0', dim: '#6b7089', run: '#ffd24a', add: '#9be9a8', del: '#ffa198', ctx: '#d6dae6' };
2296
2635
  c.fillStyle = ed ? '#1a1b26' : '#0d1117'; c.beginPath(); c.roundRect(x, y, w, bh, 12); c.fill(); c.fillStyle = '#1c1f2b'; c.fillRect(x, y, w, 28);
2297
2636
  ['#ff5f57', '#febc2e', '#28c840'].forEach((cl, i) => { c.fillStyle = cl; c.beginPath(); c.arc(x + 16 + i * 18, y + 14, 5, 0, 7); c.fill(); });
2298
- c.font = '13px sans-serif'; c.fillStyle = '#9aa0b4'; c.fillText(ed ? (hide ? m.title.split(' — ').pop() : m.title) : m.view === 'image' ? (hide ? '' : m.title) : S.agents[S.present].name + ' — zsh', x + 90, y + 19); c.font = '14px monospace';
2299
- if (m.view === 'image') { // masked like the code: a picture from the session is replaced by an empty frame
2300
- const im = hide ? null : mediaImg(m.imgs[0]), ax = x + 14, ay = y + 38, aw = w - 238, ah = bh - 82, k = im && im.complete && im.naturalWidth ? Math.min(aw / im.naturalWidth, ah / im.naturalHeight, 1.5) : 0;
2637
+ c.font = '13px sans-serif'; c.fillStyle = '#9aa0b4'; c.fillText(ed ? (hide ? m.title.split(' — ').pop() : m.title) : m.view === 'image' || m.view === 'web' ? (hide ? '' : m.title) : S.agents[S.present].name + ' — zsh', x + 90, y + 19); c.font = '14px monospace';
2638
+ if (m.view === 'image' || m.view === 'web') { // masked like the code: a picture from the session is replaced by an empty frame. The page of an artifact always is: a video cannot draw what is in a frame
2639
+ const im = hide || m.view === 'web' ? null : mediaImg(m.imgs[0]), ax = x + 14, ay = y + 38, aw = w - 238, ah = bh - 82, k = im && im.complete && im.naturalWidth ? Math.min(aw / im.naturalWidth, ah / im.naturalHeight, 1.5) : 0;
2301
2640
  if (k) c.drawImage(im, ax + (aw - im.naturalWidth * k) / 2, ay + (ah - im.naturalHeight * k) / 2, im.naturalWidth * k, im.naturalHeight * k);
2302
- else { c.fillStyle = 'rgba(255,255,255,.07)'; c.beginPath(); c.roundRect(ax + aw / 2 - 170, ay + 10, 340, ah - 20, 10); c.fill(); c.font = '64px sans-serif'; c.textAlign = 'center'; c.fillStyle = '#6b7089'; c.fillText('🖼', ax + aw / 2, ay + ah / 2 + 22); c.textAlign = 'start'; }
2641
+ else { c.fillStyle = 'rgba(255,255,255,.07)'; c.beginPath(); c.roundRect(ax + aw / 2 - 170, ay + 10, 340, ah - 20, 10); c.fill(); c.font = '64px sans-serif'; c.textAlign = 'center'; c.fillStyle = '#6b7089'; c.fillText(m.view === 'web' ? '🌐' : '🖼', ax + aw / 2, ay + ah / 2 + 22); c.textAlign = 'start'; }
2303
2642
  c.font = '14px monospace';
2304
2643
  }
2305
2644
  const rows = ed ? m.lines.slice(0, 13) : m.lines.slice(-13), cw = c.measureText('M').width;
@@ -2346,16 +2685,17 @@ async function exportVideo(from = 0, to = 0, clip = 0) { // clip: length in ms
2346
2685
  // UI wiring
2347
2686
  // =====================================================================
2348
2687
  function applyLang() {
2349
- renderCharInfo();
2688
+ renderCharInfo(); packNote(); menuTip();
2350
2689
  document.documentElement.lang = (LANGS.find((l) => l[0] === prefs.lang) || LANGS[0])[2];
2351
2690
  document.querySelectorAll('[data-fr]').forEach((el) => (el.textContent = FR() ? el.dataset.fr : tr(el.dataset.en)));
2352
2691
  document.querySelectorAll('#viewSeg button').forEach((b) => { b.title = b.textContent; }); // in a narrow window they are icons: the name stays as a tooltip
2692
+ $('#callTrMi').style.display = CALL_LANG[prefs.lang] && !FR() ? '' : 'none';
2353
2693
  const sel = $('#langSel'); if (!sel.options.length) sel.innerHTML = LANGS.map(([c, n]) => `<option value="${c}">${n}</option>`).join(''); sel.value = prefs.lang;
2354
2694
  [['#bPlay', L('Pause / Lecture (espace)', 'Pause / Play (space)')], ['#bLog', 'Transcript'], ['#bMute', L('Son (touche M)', 'Sound (M key)')], ['#bMenu', L('Réglages', 'Settings')], ['#dclose', L('Fermer', 'Close')], ['#officeVol', L('Volume de l’ambiance', 'Ambience volume')], ['#musicVol', L('Volume de la musique', 'Music volume')], ['#liveProj', L('Projet à suivre', 'Project to follow')], ['#reactBar', L('Réactions', 'Reactions')], ['#logQ', L('Rechercher dans la transcription', 'Search the transcript')], ['#roster', L('Agents', 'Agents')]].forEach(([q, t]) => { const el = $(q); if (!el) return; el.title = t; el.setAttribute('aria-label', t); }); $('#logQ').placeholder = L('Rechercher…', 'Search…'); $('#menuQ').placeholder = L('Chercher un réglage…', 'Search settings…'); document.querySelectorAll('#reactBar button').forEach((b) => b.setAttribute('aria-label', b.dataset.e));
2355
2695
  $('#gT').textContent = L('Rejoindre l’appel', 'Join the call'); $('#gP').textContent = L('Cliquez pour activer le son et suivre votre session Claude Code en direct.', 'Click to enable sound and follow your Claude Code session live.'); $('#gB').textContent = L('▶ Rejoindre', '▶ Join');
2356
2696
  $('#eDemo').textContent = L('▶ Voir la démo', '▶ Watch the demo'); $('#eT').textContent = L('En attente d’une session', 'Waiting for a session'); $('#eP').innerHTML = watched() ? esc(L('Lancez Claude Code dans {0} : l’appel démarrera tout seul.', 'Start Claude Code in {0} — the call will start by itself.')).replace('{0}', `<b>${esc(watched())}</b>`) : esc(L('Lancez Claude Code dans ce dossier : l’appel démarrera tout seul.', 'Start Claude Code in this folder — the call will start by itself.'));
2357
2697
  for (const id in S.agents) { const p = persona(S.agents[id]); Object.assign(S.agents[id], { name: p.name, role: p.role }); const t = $('#t-' + id); if (t) { t.querySelector('.tag span').textContent = p.role; t.querySelector('.tag b').textContent = p.name; if (id === 'main' || id === 'user') t.querySelector('.tag span').textContent = p.role; } }
2358
- document.querySelectorAll('#menu .mi[data-t]').forEach((b) => b.querySelector('.sw').classList.toggle('on', !!prefs[b.dataset.t])); renderCoffee(); renderTokens(); updateHint(); renderLog(true); syncUI();
2698
+ document.querySelectorAll('#menu .mi[data-t], #prefs .mi[data-t]').forEach((b) => b.querySelector('.sw').classList.toggle('on', !!prefs[b.dataset.t])); renderCoffee(); renderTokens(); updateHint(); renderLog(true); syncUI();
2359
2699
  }
2360
2700
  const elsewhere = () => !!(S.owner && S.owner !== CID);
2361
2701
  function applyMute() {
@@ -2376,48 +2716,111 @@ function setView(v) { prefs.view = v; savePrefs(); document.body.classList.toggl
2376
2716
 
2377
2717
  $('#viewSeg').onclick = (e) => { const b = e.target.closest('button'); if (b) setView(b.dataset.v); };
2378
2718
  $('#langSel').onchange = () => setLang($('#langSel').value, true);
2379
- $('#charPack').value = ['none', 'folder', 'cats'].includes(prefs.charPack) ? prefs.charPack : 'none'; $('#charPack').onchange = () => { prefs.charPack = $('#charPack').value; savePrefs(); $('#charReload').onclick(); };
2380
- $('#charReload').onclick = async () => { await loadChars(); for (const k in imgCache) delete imgCache[k]; for (const id in S.agents) S.agents[id].custom = null; for (const id in S.agents) S.agents[id].custom = customFor(id); buildStage(); paintStatus(); renderCharInfo(); };
2381
- $('#charOpen').onclick = () => window.parent.postMessage({ agentStandup: 'openCharacters' }, '*');
2719
+ const LAP = { id: '' }; // now and then one character pulls out its laptop for 7 to 14 seconds: one at a time, about every 40 seconds, preferably one at work. ⚙ → Characters → laptop keeps them all out instead
2720
+ setInterval(() => {
2721
+ if (prefs.customLaptop || document.hidden || LAP.id || Math.random() > .13) return;
2722
+ const ids = Object.keys(S.agents).filter((id) => { const c = S.agents[id].custom, t = $('#t-' + id); return c && c.desks && c.desks.length && t && t.style.display !== 'none'; }); if (!ids.length) return;
2723
+ const busy = ids.filter((id) => agentState(id, Date.now()).k === 'working'), from = busy.length ? busy : ids, id = from[Math.floor(Math.random() * from.length)], t = $('#t-' + id);
2724
+ LAP.id = id; t.classList.add('lap'); setTimeout(() => { t.classList.add('lapout'); setTimeout(() => { t.classList.remove('lap', 'lapout'); LAP.id = ''; }, 450); }, 7000 + Math.random() * 7000);
2725
+ }, 5000);
2726
+ async function reloadChars() { await loadChars(); for (const k in imgCache) delete imgCache[k]; for (const id in S.agents) S.agents[id].custom = null; for (const id in S.agents) S.agents[id].custom = customFor(id); buildStage(); paintStatus(); packNote(); await renderCharInfo(); }
2727
+ $('#charPick').onclick = () => { $('#menu').classList.remove('on'); CHPICK.more = ''; openChars(); };
2728
+ $('#packNoteB').onclick = () => { prefs.vampSeen = true; savePrefs(); packNote(); CHPICK.more = 'halloween'; openChars(); };
2729
+ $('#packNoteX').onclick = () => { prefs.vampSeen = true; savePrefs(); packNote(); };
2382
2730
  $('#modeSeg').onclick = (e) => { const b = e.target.closest('button'); if (b) setMode(b.dataset.m); };
2383
2731
  // ⚙ menu: sections that fold (remembered) and a search box
2384
2732
  function menuInit() {
2385
2733
  const m = $('#menu'), secs = []; let cur = null;
2386
2734
  for (const el of [...m.children]) { if (el.tagName === 'H4') { cur = { h: el, items: [] }; secs.push(cur); } else if (cur && !el.classList.contains('keys')) cur.items.push(el); }
2387
- secs.forEach((sc, i) => { sc.h.classList.add('fold'); sc.h.dataset.i = i; sc.h.onclick = () => { const c = !sc.h.classList.contains('closed'); sc.h.classList.toggle('closed', c); sc.items.forEach((e) => e.classList.toggle('mfold', c)); const set = new Set(prefs.menuClosed || []); c ? set.add(i) : set.delete(i); prefs.menuClosed = [...set]; savePrefs(); };
2388
- if ((prefs.menuClosed || []).includes(i)) { sc.h.classList.add('closed'); sc.items.forEach((e) => e.classList.add('mfold')); } });
2735
+ secs.forEach((sc, i) => { sc.h.classList.add('fold'); sc.h.dataset.i = i; sc.h.onclick = () => { const c = !sc.h.classList.contains('closed'); sc.h.classList.toggle('closed', c); sc.items.forEach((e) => e.classList.toggle('mfold', c)); const set = new Set(prefs.menuFold || []); c ? set.add(sc.h.dataset.en) : set.delete(sc.h.dataset.en); prefs.menuFold = [...set]; savePrefs(); }; // by name: the sections moved in 1.33
2736
+ if ((prefs.menuFold || []).includes(sc.h.dataset.en)) { sc.h.classList.add('closed'); sc.items.forEach((e) => e.classList.add('mfold')); } });
2389
2737
  $('#menuQ').oninput = () => {
2390
2738
  const q = $('#menuQ').value.trim().toLowerCase();
2391
2739
  for (const sc of secs) { let any = false;
2392
2740
  for (const e of sc.items) { const hit = !q || e.textContent.toLowerCase().includes(q) || [...e.querySelectorAll('option')].some((o) => o.textContent.toLowerCase().includes(q)); e.classList.toggle('mhide', !hit); if (hit && q) any = true; if (q) e.classList.remove('mfold'); else e.classList.toggle('mfold', sc.h.classList.contains('closed')); }
2393
2741
  sc.h.classList.toggle('mhide', !!q && !any && !sc.h.textContent.toLowerCase().includes(q)); if (q) sc.h.classList.remove('closed'); }
2394
- if (!q) secs.forEach((sc, i) => sc.h.classList.toggle('closed', (prefs.menuClosed || []).includes(i)));
2395
- $('#menuNone').style.display = q && !secs.some((sc) => sc.items.some((e) => !e.classList.contains('mhide'))) ? '' : 'none';
2742
+ if (!q) secs.forEach((sc) => sc.h.classList.toggle('closed', (prefs.menuFold || []).includes(sc.h.dataset.en)));
2743
+ const found = $('#menuFound'), label = (e) => ((e.matches('.mi') ? e.querySelector('span') : e.querySelector('.lbl')) || {}).textContent || ''; found.innerHTML = '';
2744
+ const far = q ? [...document.querySelectorAll('#prefs .mi, #prefs .box')].filter((e) => e.style.display !== 'none' && label(e) && (e.textContent.toLowerCase().includes(q) || [...e.querySelectorAll('option')].some((o) => o.textContent.toLowerCase().includes(q)))) : [];
2745
+ for (const e of far) { const b = document.createElement('button'); b.className = 'mi'; b.innerHTML = `<span>${esc(label(e))}</span><span class="dim" style="font-size:11px">${esc(L('Tous les réglages', 'All settings'))} ›</span>`; b.onclick = (ev) => { ev.stopPropagation(); openPrefs(e); }; found.appendChild(b); } // a setting of the panel, found from the menu
2746
+ $('#menuNone').style.display = q && !far.length && !secs.some((sc) => sc.items.some((e) => !e.classList.contains('mhide'))) ? '' : 'none';
2396
2747
  };
2397
2748
  }
2398
- $('#menu').onclick = (e) => { const b = e.target.closest('.mi[data-t]'); if (!b) return; prefs[b.dataset.t] = !prefs[b.dataset.t]; savePrefs(); if (prefs[b.dataset.t] && ['voice', 'office', 'music', 'notify'].includes(b.dataset.t)) claimAudio(); b.querySelector('.sw').classList.toggle('on', prefs[b.dataset.t]); AUD.apply(); if (b.dataset.t === 'office') $('#officeBox').style.display = prefs.office ? '' : 'none'; if (b.dataset.t === 'customLaptop') { for (const k in imgCache) delete imgCache[k]; buildStage(); paintStatus(); } if (b.dataset.t === 'files') paintFiles(); if (b.dataset.t === 'ownNames') renameAll(); if (b.dataset.t === 'reactions') document.body.classList.toggle('react', prefs.reactions); if (b.dataset.t === 'roster') { document.body.classList.toggle('rost', prefs.roster); paintStates(); } if (b.dataset.t === 'notify') { prefs.notifyChosen = true; savePrefs(); } if (b.dataset.t === 'notify' && prefs.notify) askNotify(); if (b.dataset.t === 'vanish' && !prefs.vanish) { S.gone.clear(); paintStatus(); }
2749
+ const onSwitch = (e) => { const b = e.target.closest('.mi[data-t]'); if (!b) return; prefs[b.dataset.t] = !prefs[b.dataset.t]; savePrefs(); if (prefs[b.dataset.t] && ['voice', 'office', 'music', 'notify'].includes(b.dataset.t)) claimAudio(); b.querySelector('.sw').classList.toggle('on', prefs[b.dataset.t]); AUD.apply(); if (b.dataset.t === 'office') $('#officeBox').style.display = prefs.office ? '' : 'none'; if (b.dataset.t === 'callTr') { prefs.callTrSeen = true; savePrefs(); setLang(prefs.lang); } if (b.dataset.t === 'voice') voiceOffer(); if (b.dataset.t === 'customLaptop') { for (const k in imgCache) delete imgCache[k]; buildStage(); paintStatus(); } if (b.dataset.t === 'files') paintFiles(); if (b.dataset.t === 'artNet' && S.present) renderPresent(); if (b.dataset.t === 'ownNames') renameAll(); if (b.dataset.t === 'reactions') document.body.classList.toggle('react', prefs.reactions); if (b.dataset.t === 'roster') { document.body.classList.toggle('rost', prefs.roster); paintStates(); } if (b.dataset.t === 'notify') { prefs.notifyChosen = true; savePrefs(); } if (b.dataset.t === 'notify' && prefs.notify) askNotify(); if (b.dataset.t === 'vanish' && !prefs.vanish) { S.gone.clear(); paintStatus(); }
2399
2750
  if (b.dataset.t === 'music') { $('#musicBox').style.display = prefs.music ? '' : 'none'; if (prefs.music) { AUD.init(); AUD.apply(); } } };
2751
+ $('#menu').onclick = onSwitch; $('#prefs').onclick = (e) => { if (e.target === $('#prefs')) return closePrefs(); onSwitch(e); setTimeout(syncSwitches); };
2752
+ function openPrefs(target) { // ⚙ → All settings; target: one of its settings, found by the search of the menu, shown and lit up
2753
+ $('#menu').classList.remove('on'); $('#prefs').classList.add('on'); syncSwitches(); document.querySelectorAll('#prefs .mi[data-t]').forEach((b) => b.querySelector('.sw').classList.toggle('on', !!prefs[b.dataset.t]));
2754
+ if (target) { target.scrollIntoView({ block: 'center' }); target.classList.remove('flash'); void target.offsetWidth; target.classList.add('flash'); (target.matches('.mi') ? target : target.querySelector('select, input, button') || target).focus(); } else $('#prefsX').focus();
2755
+ }
2756
+ const PANEL_KEYS = ['office', 'officeVol', 'music', 'station', 'musicVol', 'notify', 'customLaptop', 'ownNames', 'roster', 'reactions', 'banter', 'chat', 'vanish', 'epi', 'files', 'artNet', 'visits', 'followTab']; // what the panel holds, and so what Reset puts back
2757
+ $('#prefsReset').onclick = async () => {
2758
+ const b = $('#prefsReset'); if (!b.classList.contains('sure')) { b.classList.add('sure'); b.textContent = L('Cliquez encore pour tout remettre', 'Click again to reset them all'); setTimeout(() => { b.classList.remove('sure'); b.textContent = L('Réglages par défaut', 'Reset to defaults'); }, 4000); return; } // two clicks: nothing is lost by a stray one
2759
+ for (const k of PANEL_KEYS) { if (k in PREF_DEFAULTS) prefs[k] = PREF_DEFAULTS[k]; else delete prefs[k]; } delete prefs.notifyChosen; // notifyChosen too: the default of notifications is decided at start-up from it
2760
+ prefs._t = Date.now(); try { localStorage.setItem('cc.prefs', JSON.stringify(prefs)); } catch {} try { await fetch('/api/prefs', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(prefs) }); } catch {}
2761
+ location.reload(); // every part of the page starts again from them
2762
+ };
2763
+ function menuTip() { // once, to someone who used the app before: where the settings went. Gone with its button, or as soon as the menu is opened
2764
+ const t = $('#menuTip'); if (!HAD_PREFS || prefs.menuTipSeen || Q.get('demo')) { t.style.display = 'none'; return; }
2765
+ const r = $('#bMenu').getBoundingClientRect(); if (!r.width) return;
2766
+ $('#menuTipT').textContent = L('Vos réglages ont bougé : ceux de tous les jours sont ici, les autres dans « Tous les réglages ».', 'Your settings moved: the everyday ones are here, the rest in “All settings”.'); $('#menuTipOk').textContent = L('Compris', 'Got it');
2767
+ t.style.display = ''; t.style.top = Math.round(r.bottom + 10) + 'px'; t.style.right = Math.max(8, Math.round(innerWidth - r.right - 6)) + 'px'; t.style.setProperty('--ax', Math.max(8, Math.round(r.width / 2 - 2)) + 'px');
2768
+ }
2769
+ const menuTipDone = () => { if (prefs.menuTipSeen) return; prefs.menuTipSeen = true; savePrefs(); $('#menuTip').style.display = 'none'; };
2770
+ $('#menuTipOk').onclick = menuTipDone;
2771
+ function closePrefs() { $('#prefs').classList.remove('on'); $('#bMenu').focus(); }
2772
+ $('#prefsX').onclick = closePrefs; $('#mPrefs').onclick = () => openPrefs();
2773
+ function renderMenuShop() { // in the menu, under Characters: the Halloween pack for those who do not have it. Emptied while the Characters window shows the same panel (one set of ids at a time)
2774
+ const el = $('#menuShop'), sp = SHOP.halloween; if (!el) return; if (!sp || sp.n || $('#recap.on #chdlg')) { el.innerHTML = ''; return; } renderShop(el, 'halloween', sp);
2775
+ }
2400
2776
  $('#station').innerHTML = STATIONS.map((s) => `<option value="${s.id}">📻 ${s.name}</option>`).join('');
2401
2777
  $('#station').value = prefs.station; $('#musicVol').value = prefs.musicVol; $('#musicBox').style.display = prefs.music ? '' : 'none';
2402
2778
  $('#station').onchange = (e) => { prefs.station = e.target.value; savePrefs(); AUD.init(); RADIO.sync(); };
2403
2779
  $('#chatSel').value = ['quiet', 'normal', 'lively'].includes(prefs.chat) ? prefs.chat : 'normal'; $('#chatSel').onchange = () => { prefs.chat = $('#chatSel').value; savePrefs(); };
2404
- $('#vstyle').innerHTML = [['animal', 'Animal Crossing (babillage)', 'Animal Crossing (babble)'], ['sims', 'Simlish (babillage)', 'Simlish (babble)'], ['cartoon', 'Voix cartoon (voix réelle)', 'Cartoon voices (real voice)'], ['natural', 'Voix naturelles', 'Natural voices'], ['kokoro', 'Voix très naturelles (à installer)', 'Very natural voices (installs on demand)']].map(([v, fr, en]) => `<option value="${v}" data-fr="${fr}" data-en="${en}">${L(fr, en)}</option>`).join(''); $('#vstyle').value = prefs.vstyle; $('#vstyle').onchange = () => { prefs.vstyle = $('#vstyle').value; prefs.vstyleChosen = true; savePrefs(); TTS.init().then(kokoroUI); kokoroUI(); };
2780
+ $('#vstyle').innerHTML = [['animal', 'Animal Crossing (babillage)', 'Animal Crossing (babble)'], ['kokoro', 'Voix naturelles (à installer)', 'Natural voices (installs on demand)']].map(([v, fr, en]) => `<option value="${v}" data-fr="${fr}" data-en="${en}">${L(fr, en)}</option>`).join(''); $('#vstyle').value = prefs.vstyle; $('#vstyle').onchange = () => { prefs.vstyle = $('#vstyle').value; prefs.vstyleChosen = true; savePrefs(); TTS.init().then(kokoroUI); kokoroUI(); };
2405
2781
  // ---- ⚙ → very natural voices (Kokoro): install box and status, polled while installing
2406
2782
  let kokoroTimer = null;
2407
2783
  async function kokoroUI() {
2408
2784
  const box = $('#kokoroBox'), on = prefs.vstyle === 'kokoro'; box.style.display = on ? '' : 'none'; $('#vstyleTip').style.display = on ? 'none' : ''; if (!on) { clearInterval(kokoroTimer); kokoroTimer = null; return; }
2409
2785
  let st; try { st = await (await fetch('/api/kokoro')).json(); } catch { return; }
2410
- const b = $('#kokoroInstall'), h = $('#kokoroHint'); b.style.display = st.installed ? 'none' : '';
2411
- b.disabled = st.installing || !st.npm; b.textContent = st.installing ? L('Installation…', 'Installing…') : L(`Installer (${st.sizeMb} Mo)`, `Install (${st.sizeMb} MB)`);
2412
- h.textContent = st.installing ? L('Téléchargement en cours, vous pouvez continuer : les voix du système servent en attendant.', 'Downloading, you can carry on: system voices are used meanwhile.')
2786
+ const b = $('#kokoroInstall'), h = $('#kokoroHint'), addFr = st.installed && !st.g2p && !!CALL_LANG[prefs.lang]; b.style.display = st.installed && !addFr ? 'none' : ''; /* addFr: installed before French, Spanish and Portuguese were added, which is one small package more. Offered where one of them is the interface language: a session in that language is then read by these voices, translated or not */
2787
+ b.disabled = st.installing || !st.npm; b.textContent = st.installing ? L('Installation…', 'Installing…') : addFr ? L('Ajouter les voix françaises', 'Add the voices of this language') + L(` (${st.g2pMb} Mo)`, ` (${st.g2pMb} MB)`) : L(`Installer (${st.sizeMb} Mo)`, `Install (${st.sizeMb} MB)`);
2788
+ h.textContent = st.installing ? L('Téléchargement en cours, vous pouvez continuer : les agents babillent en attendant.', 'Downloading, you can carry on: the agents babble meanwhile.')
2413
2789
  : st.error ? st.error : !st.npm && !st.installed ? L('npm est introuvable : installez Node.js pour activer cette option.', 'npm not found: install Node.js to enable this option.')
2414
- : st.installed ? (st.gaveUp ? L('Le moteur s’est arrêté : les voix du système servent à la place.', 'The engine stopped: system voices are used instead.') : st.ready ? L('Voix prêtes.', 'Voices ready.') : L('Chargement du modèle (téléchargé au premier usage, environ 305 Mo)…', 'Loading the model (downloaded on first use, about 305 MB)…'))
2415
- : L('Voix locales de bonne qualité, en anglais. Gratuit, rien n’est envoyé nulle part.', 'Good-quality local voices, in English. Free, nothing leaves your machine.');
2790
+ : st.installed ? (st.gaveUp ? L('Le moteur s’est arrêté : les agents babillent à la place.', 'The engine stopped: the agents babble instead.') : st.ready ? (addFr ? L('Voix prêtes en anglais. Le français est encore lu par les voix du système.', 'Voices ready in English. This language is still read by the system voices.') : L('Voix prêtes.', 'Voices ready.')) : L('Chargement du modèle (téléchargé au premier usage, environ 305 Mo)…', 'Loading the model (downloaded on first use, about 305 MB)…'))
2791
+ : CALL_LANG[prefs.lang] ? L('Voix locales de bonne qualité, en français et en anglais. Gratuit, rien n’est envoyé nulle part.', 'Good-quality local voices, in this language and in English. Free, nothing leaves your machine.') : L('Voix locales de bonne qualité, en anglais. Gratuit, rien n’est envoyé nulle part.', 'Good-quality local voices, in English. Free, nothing leaves your machine.');
2416
2792
  if ((st.installing || (st.installed && !st.ready && !st.gaveUp)) && !kokoroTimer) kokoroTimer = setInterval(async () => { await kokoroUI(); }, 2500);
2417
- if (!st.installing && (st.ready || st.gaveUp || !st.installed) && kokoroTimer) { clearInterval(kokoroTimer); kokoroTimer = null; if (st.ready && TTS.engine !== 'kokoro') TTS.init(); }
2793
+ if (!st.installing && (st.ready || st.gaveUp || !st.installed) && kokoroTimer) { clearInterval(kokoroTimer); kokoroTimer = null; if (st.ready && (TTS.engine !== 'kokoro' || (st.g2p && !TTS.pool.fr.some((v) => TTS.kv.has(v))))) TTS.init(); } /* also when the voices of the other languages have just been added */
2418
2794
  }
2419
- $('#kokoroInstall').onclick = async () => { try { await fetch('/api/kokoro/install', { method: 'POST' }); } catch {} kokoroUI(); };
2795
+ $('#kokoroInstall').onclick = async () => { try { await fetch('/api/kokoro/install', { method: 'POST' }); } catch {} kokoroUI(); voiceOffer(); };
2420
2796
  kokoroUI();
2797
+ // ---- on the call: one line that says the real voices exist, to whoever does not have them. Nothing outside ⚙ said so, and without them the agents babble. One click installs them (and the style changes
2798
+ // to them once they are ready, not before); ✕ and the line never comes back. Not in the scripted demo (?demo=1), which is what the pictures and videos are made from.
2799
+ let offerTimer = null;
2800
+ async function voiceOffer() {
2801
+ const el = $('#vOffer'), hide = () => { el.style.display = 'none'; clearInterval(offerTimer); offerTimer = null; };
2802
+ if (!prefs.voice || prefs.voiceOffer === 'no' || Q.get('demo')) return hide();
2803
+ let st; try { st = await (await fetch('/api/kokoro')).json(); } catch { return; }
2804
+ const add = st.installed && st.ready && !st.g2p && !!CALL_LANG[prefs.lang] && prefs.vstyle === 'kokoro'; // the voices are there, from before French, Spanish and Portuguese were added: one small package more, said on the call where one of them is the language of the interface (⚙ said it, and nothing else)
2805
+ if (st.ready && prefs.voiceOffer === 'want' && !st.installing && !add) { prefs.voiceOffer = 'no'; prefs.vstyle = 'kokoro'; prefs.vstyleChosen = true; savePrefs(); $('#vstyle').value = 'kokoro'; hide(); await TTS.init(); kokoroUI(); toast(L('Voix prêtes.', 'Voices ready.')); return; }
2806
+ const busy = st.installing || (st.installed && !st.ready && !st.gaveUp && prefs.voiceOffer === 'want');
2807
+ if (busy && !st.installing && !voiceOffer.woke) { voiceOffer.woke = true; fetch('/api/voices?engine=kokoro').catch(() => {}); } // installed in an earlier run, closed before the model was ready: nothing else starts the engine while another style is in use, and the line would say “Downloading” for good
2808
+ if ((st.installed && !busy && !add) || !st.npm) return hide(); // they have them; or cannot have them (no npm), which ⚙ explains
2809
+ $('#vOfferT').textContent = busy ? L('Téléchargement des vraies voix… vous pouvez continuer.', 'Downloading the real voices… you can carry on.') : st.error || (add ? L('Voix prêtes en anglais. Le français est encore lu par les voix du système.', 'Voices ready in English. This language is still read by the system voices.') : L('Vos agents peuvent parler avec de vraies voix.', 'Your agents can speak with real voices.'));
2810
+ $('#vOfferB').style.display = busy ? 'none' : ''; $('#vOfferB').textContent = add ? L('Ajouter les voix françaises', 'Add the voices of this language') + L(` (${st.g2pMb} Mo)`, ` (${st.g2pMb} MB)`) : L('Installer', 'Install') + L(` (${st.sizeMb} Mo)`, ` (${st.sizeMb} MB)`); el.style.display = '';
2811
+ if (busy && !offerTimer) offerTimer = setInterval(voiceOffer, 2500); if (!busy && offerTimer) { clearInterval(offerTimer); offerTimer = null; }
2812
+ }
2813
+ $('#vOfferB').onclick = async () => { prefs.voiceOffer = 'want'; savePrefs(); try { await fetch('/api/kokoro/install', { method: 'POST' }); } catch {} voiceOffer(); kokoroUI(); };
2814
+ $('#vOfferX').onclick = () => { prefs.voiceOffer = 'no'; savePrefs(); voiceOffer(); };
2815
+ voiceOffer();
2816
+ // ---- on the call: the first time one is held in Spanish or Portuguese on this computer, a line says that it is translated, and with what. Nobody asked for it (it follows the interface language, as French
2817
+ // always did), and it sends what the agents say to Anthropic through the person's own Claude Code. Said once; "Turn off" is the switch of ⚙ → Language.
2818
+ function callNote() {
2819
+ const on = TRL() && !FR() && !prefs.callTrSeen && !Q.get('demo'); $('#trNote').style.display = on ? '' : 'none'; if (!on) return;
2820
+ $('#trNoteT').textContent = L('L’appel est maintenant traduit dans cette langue, avec votre Claude Code.', 'The call is now translated into this language, with your Claude Code.'); $('#trNoteOk').textContent = L('Garder', 'Keep'); $('#trNoteOff').textContent = L('Désactiver', 'Turn off');
2821
+ }
2822
+ $('#trNoteOk').onclick = () => { prefs.callTrSeen = true; savePrefs(); callNote(); };
2823
+ $('#trNoteOff').onclick = () => { prefs.callTrSeen = true; prefs.callTr = false; savePrefs(); setLang(prefs.lang); };
2421
2824
  $('#officeVol').value = prefs.officeVol; $('#officeBox').style.display = prefs.office ? '' : 'none';
2422
2825
  $('#officeVol').oninput = (e) => { prefs.officeVol = +e.target.value; savePrefs(); AUD.applyMusic(); };
2423
2826
  $('#musicVol').oninput = (e) => { prefs.musicVol = +e.target.value; savePrefs(); AUD.applyMusic(); };
@@ -2497,15 +2900,16 @@ function focusDoor() { // never taken from a field or a menu the person is in
2497
2900
  if (b && a !== b && (!a || a === document.body || a === $('#gB') || a === $('#eDemo'))) b.focus({ preventScroll: true });
2498
2901
  }
2499
2902
  for (const q of ['#gate', '#empty']) new MutationObserver(focusDoor).observe($(q), { attributes: true, attributeFilter: ['class'] });
2500
- function syncSwitches() { document.querySelectorAll('#menu .mi[data-t]').forEach((b) => { b.setAttribute('role', 'switch'); b.setAttribute('aria-checked', String(!!prefs[b.dataset.t])); }); }
2903
+ function syncSwitches() { document.querySelectorAll('#menu .mi[data-t], #prefs .mi[data-t]').forEach((b) => { b.setAttribute('role', 'switch'); b.setAttribute('aria-checked', String(!!prefs[b.dataset.t])); }); }
2501
2904
  new MutationObserver(() => { // the menu opens under the header and the status line, not over them
2502
2905
  const m = $('#menu'), on = m.classList.contains('on'), h = Math.round($('main').getBoundingClientRect().top); $('#bMenu').setAttribute('aria-expanded', String(on)); if (!on) return;
2503
- syncSwitches(); m.style.top = h + 3 + 'px'; m.style.maxHeight = `calc(100dvh - ${h + 13}px)`;
2906
+ syncSwitches(); menuTipDone(); if (!$('#menuShop').innerHTML) renderMenuShop(); m.style.top = h + 3 + 'px'; m.style.maxHeight = `calc(100dvh - ${h + 13}px)`;
2504
2907
  }).observe($('#menu'), { attributes: true, attributeFilter: ['class'] });
2505
2908
  $('#menu').addEventListener('click', () => setTimeout(syncSwitches)); $('#bMenu').setAttribute('aria-expanded', 'false'); syncSwitches();
2506
2909
  addEventListener('keydown', (e) => { // on the way down: Escape also works from the search box and the selects of the menu, which the shortcuts below ignore
2507
2910
  if (e.key !== 'Escape' || $('#switcher')) return;
2508
- if ($('#menu').classList.contains('on')) { $('#menu').classList.remove('on'); $('#bMenu').focus(); }
2911
+ if ($('#prefs').classList.contains('on')) closePrefs();
2912
+ else if ($('#menu').classList.contains('on')) { $('#menu').classList.remove('on'); $('#bMenu').focus(); }
2509
2913
  else if ($('#detail').classList.contains('on') && !$('#recap').classList.contains('on')) { const t = $('#t-' + S.detail); $('#dclose').click(); if (t && t.offsetParent) t.focus(); }
2510
2914
  }, true);
2511
2915
  // ---------- a bubble that is not whole on screen (last row of tiles, a row of the compact list below the fold) brings the stage to it ----------
@@ -2541,6 +2945,29 @@ function openKeys() {
2541
2945
  $('#recapx').onclick = () => $('#recap').classList.remove('on'); $('#recap').classList.add('on');
2542
2946
  }
2543
2947
  $('#mKeys').onclick = () => { $('#menu').classList.remove('on'); openKeys(); };
2948
+ // ⚙ › Report a problem: the last errors of the local log, shown exactly as they would be sent, and the draft of an issue on GitHub that carries them. Nothing leaves from here:
2949
+ // the person reads the draft on GitHub, says what happened and sends it. The text of the report is in English whatever the language: it is read by the developer.
2950
+ const ISSUES = 'https://github.com/Atoll92/agent-standup/issues/new';
2951
+ async function openReport() {
2952
+ let r = null; try { r = await (await fetch('/api/errors')).json(); } catch {}
2953
+ const str = (x) => (typeof x === 'string' ? x.replace(/```/g, "'''") : ''), whole = (s) => (s.toWellFormed ? s.toWellFormed() : s.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, '').replace(/(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '$1')); // whole: no half of an emoji left by a cut, which a link cannot carry
2954
+ const errs = ((r && Array.isArray(r.errors) && r.errors) || []).filter((e) => e && typeof e === 'object').slice(-5).reverse(), one = (e) => `${str(e.t)} · ${str(e.v)} · ${str(e.where)}\n${str(e.msg)}${str(e.stack) ? '\n' + str(e.stack).split('\n').slice(0, 5).map((l) => ' ' + l.slice(0, 200)).join('\n') : ''}`;
2955
+ const app = r ? [`Agent Standup ${r.version}${r.host ? ' · ' + r.host : ''}`, `${r.platform} · Node ${r.node}${r.electron ? ' · Electron ' + r.electron : ''}`] : ['Agent Standup']; app.push(navigator.userAgent, 'Language: ' + (prefs.lang || ''));
2956
+ const body = (list) => whole('**What happened?**\n\n\n**App**\n' + app.join('\n') + '\n\n**Last errors in the local log**\n' + (list.length ? '```\n' + list.map(one).join('\n\n') + '\n```' : 'none'));
2957
+ let list = errs; while (list.length > 1 && encodeURIComponent(body(list)).length > 5500) list = list.slice(0, -1); // the draft travels in the address: the oldest errors give way
2958
+ let text = body(list); while (encodeURIComponent(text).length > 5500) text = whole(text.slice(0, Math.floor(text.length * 0.8))) + '\n…\n```'; // one error alone that is too long is cut, and its block closed
2959
+ const url = ISSUES + '?title=' + encodeURIComponent(list[0] ? whole(`[${str(r && r.version)}] ${str(list[0].msg).slice(0, 90)}`) : '') + '&body=' + encodeURIComponent(text);
2960
+ $('#recap .box').innerHTML = `<h1>${L('Signaler un problème', 'Report a problem')}</h1>
2961
+ <p>${L('Rien n’est envoyé d’ici. Le bouton ouvre un brouillon sur GitHub avec le texte ci-dessous : relisez-le, dites ce qui s’est passé, puis envoyez-le vous-même.', 'Nothing is sent from here. The button opens a draft on GitHub with the text below: read it, say what happened, then send it yourself.')}</p>
2962
+ <pre id="reportTxt" style="margin:12px 0;padding:12px 14px;max-height:44vh;overflow:auto;white-space:pre-wrap;word-break:break-word;background:var(--bg);border:1px solid var(--line);border-radius:10px;font:12px ui-monospace,Menlo,monospace"></pre>
2963
+ ${r && r.file ? `<p class="dim" style="font-size:12px">${L('Les erreurs de l’app sont gardées dans un fichier sur cet ordinateur :', 'The app’s errors are kept in a file on this computer:')} <span class="f">${esc(r.file)}</span></p>` : ''}
2964
+ <p style="text-align:right;margin:18px 0 0"><button class="btn" id="reportCopy">📋 ${L('Copier', 'Copy')}</button> <button class="btn" id="recapx">${L('Fermer', 'Close')}</button> <button class="cta" id="reportGo">${L('Ouvrir le brouillon sur GitHub', 'Open the draft on GitHub')}</button></p>`;
2965
+ $('#reportTxt').textContent = text;
2966
+ $('#reportCopy').onclick = async () => { let ok = false; try { await navigator.clipboard.writeText(text); ok = true; } catch { try { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;opacity:0'; document.body.appendChild(ta); ta.select(); ok = document.execCommand('copy'); ta.remove(); } catch {} } $('#reportCopy').textContent = ok ? '✓ ' + L('Copié', 'Copied') : L('Copie impossible', 'Copy failed'); setTimeout(() => { if ($('#reportCopy')) $('#reportCopy').textContent = '📋 ' + L('Copier', 'Copy'); }, 2000); };
2967
+ $('#reportGo').onclick = () => openExternal(url);
2968
+ $('#recapx').onclick = () => $('#recap').classList.remove('on'); $('#recap').classList.add('on');
2969
+ }
2970
+ $('#mReport').onclick = () => { $('#menu').classList.remove('on'); openReport(); };
2544
2971
  addEventListener('keydown', (e) => {
2545
2972
  if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openSwitcher(); return; }
2546
2973
  if (/INPUT|SELECT|TEXTAREA/.test(e.target.tagName) || e.metaKey || e.ctrlKey || e.altKey) return; // browser shortcuts (Cmd+R, Ctrl+N…) stay the browser's
@@ -2550,12 +2977,12 @@ addEventListener('keydown', (e) => {
2550
2977
  if (EMBED) $('#mBrowser').style.display = $('#mFollowTab').style.display = '';
2551
2978
 
2552
2979
  (async function init() {
2553
- if (!LANGS.some((l) => l[0] === prefs.lang)) prefs.lang = 'en'; await loadLocale(prefs.lang); await loadChars();
2980
+ if (!LANGS.some((l) => l[0] === prefs.lang)) prefs.lang = 'en'; await loadLocale(prefs.lang); voiceOffer(); kokoroUI(); await loadChars();
2554
2981
  document.body.classList.toggle('rost', prefs.roster !== false); document.body.classList.toggle('react', !!prefs.reactions); setView(prefs.view); menuInit(); addEventListener('click', () => { try { if (prefs.notify && !EMBED && 'Notification' in window && Notification.permission === 'default') Notification.requestPermission(); } catch {} }, { once: true }); applyLang(); applyMute(); TTS.init().then(updateHint);
2555
2982
  loadHealth().then(() => { // French by default only if translation can actually work; otherwise stay in English without a warning
2556
2983
  const h = S.health || {};
2557
2984
  if (!prefs.langChosen && FR() && h.claude === null && !h.apiKey) { prefs.lang = 'en'; applyLang(); }
2558
- if (FR()) fetch('/api/warm').catch(() => {});
2985
+ if (TRL()) { fetch('/api/warm?lang=' + CALL()).catch(() => {}); prefetchTr(S.idx); } callNote();
2559
2986
  });
2560
2987
  if (Q.get('lang')) { await setLang(Q.get('lang'), false); }
2561
2988
  if (Q.get('demo')) {