screw-bugs 0.1.5 → 0.1.7

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.
@@ -1,22 +1,23 @@
1
1
  import { Layer } from 'effect';
2
2
  import { ReportRenderer, SESSION_NOTE } from '../core/index.js';
3
- import { isWebUrl, runFiles } from '../schema/index.js';
3
+ import { isWebUrl, judgedLedger, runFiles, } from '../schema/index.js';
4
4
  import { assetsOf, contentPolicy } from './assets.js';
5
5
  import { favicon, generatorMeta, html, icon, Markup, promptBlock, safeRelative, statusIcon, textParts, webFonts, } from './markup.js';
6
- import { controlsBlock, PLAYER_JS, playableSessions, playerWindow, shapeStyle, share, toggleButton, } from './player.js';
6
+ import { controlsBlock, PLAYER_JS, playableSessions, playerWindow, shapeStyle, share, toggleButton, videoFixPrompt, } from './player.js';
7
7
  import { CHROME_LOGO } from './logos.js';
8
8
  import { topBar } from './menu-bar.js';
9
9
  import { cspHash } from './sha256.js';
10
10
  import { cardShot, viewerShot } from './shots.js';
11
11
  import { styles } from './styles.js';
12
- import { cardShots, caseShots, caseSpans, caseViews, countsOf, countWords, browserWords, deviceWords, durationOf, evaluationOf, formatBytes, formatClock, formatTime, formatTimecode, fragmentSeconds, reportHeading, runMs, severityLabel, statusLabel, statuses, stepParts, uploadNotes, urlAt, urlTimeline, verdictOf, waitNote, } from './view.js';
12
+ import { cardShots, caseShots, caseSpans, caseViews, checksNote, countsOf, countWords, browserWords, deviceWords, durationOf, evaluationOf, formatBytes, formatClock, formatTime, formatTimecode, fragmentSeconds, reportHeading, runMs, severityLabel, statusLabel, statuses, stepParts, uploadNotes, urlAt, urlTimeline, verdictOf, waitNote, } from './view.js';
13
13
  import { renderWalkthrough } from './walkthrough.js';
14
14
  /*
15
15
  * The report: one page, one player. At the top, the run in a line and what was asked; then the
16
16
  * player on one side and, on the other, the evaluation and one card per case. Scrolling the cases
17
17
  * drives the player: the case at the reading line is the current one, and the player plays it (in
18
- * a loop, unless the reader turns that off). Statuses come only from the ledger; the agent's
19
- * write-up fills its own slots and is labelled as its own.
18
+ * a loop, unless the reader turns that off). Statuses come from the ledger, except that the agent's
19
+ * write-up may mark a case failed (`judgedCase`), which the card labels as the agent's verdict
20
+ * beside the code's result; the write-up fills its own slots and is labelled as its own.
20
21
  */
21
22
  /**
22
23
  * The page's one script, allowed by its hash in the Content Security Policy. On top of the shared
@@ -239,6 +240,9 @@ const reportStyles = /* css */ `
239
240
  .eq i:nth-child(2) { animation-delay: -.3s; } .eq i:nth-child(3) { animation-delay: -.6s; }
240
241
  @keyframes eq { 0%, 100% { transform: scaleY(.3); } 50% { transform: scaleY(1); } }
241
242
  .eq i { transform-origin: bottom; }
243
+ .agent-verdict { margin: 8px 0 0 34px; color: var(--st); font: var(--t-control); overflow-wrap: anywhere; }
244
+ .agent-verdict .k { font: var(--t-small-strong); margin-right: 6px; }
245
+ .agent-verdict .checked { display: block; margin-top: 2px; color: var(--muted); font: var(--t-small); }
242
246
  .reason { margin: 8px 0 0 34px; color: var(--st); font: var(--t-control); white-space: pre-wrap; overflow-wrap: anywhere; }
243
247
  .thumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 12px 0 0 34px; }
244
248
  .thumb { margin: 0; width: 92px; }
@@ -333,6 +337,10 @@ a.tc:hover { background: var(--accent); color: var(--on-accent); }
333
337
  .rp-head h1 { font-size: 24px; line-height: 30px; }
334
338
  .filters button { height: 44px; }
335
339
  .rp-main { grid-template-columns: minmax(0, 1fr); gap: 0; padding: 18px 0 0; }
340
+ /* The player no wider than on a phone, centered: in a window wider than a phone, a full-width
341
+ player would be pinned so tall that little room is left to read the cases under it. Its strip
342
+ stays full width, so the cases still scroll out of sight under it. */
343
+ .rp-sticky { max-width: 416px; margin: 0 auto; }
336
344
  /* The player is pinned under the top bar; the cases fade out under it instead. */
337
345
  .rp-left { position: sticky; top: var(--bar); z-index: 2; background: var(--bg); padding: 8px 12px 10px; }
338
346
  .rp-left::after { content: ""; position: absolute; top: 100%; left: 0; right: 0; height: var(--fade); background: linear-gradient(var(--bg), transparent); pointer-events: none; }
@@ -347,10 +355,15 @@ a.tc:hover { background: var(--accent); color: var(--on-accent); }
347
355
  .nowplaying .np-chip { display: none; }
348
356
  .video-notes { display: none; }
349
357
  .rp-right { padding: 0 16px; }
350
- .reason, .thumbs, .case-more { margin-left: 0; }
358
+ .reason, .agent-verdict, .thumbs, .case-more { margin-left: 0; }
351
359
  .play, .full { width: 44px; height: 44px; }
352
360
  .speed button { height: 38px; }
353
361
  }
362
+ /* Between a small window and the two columns, the cases as wide as the player, so their lines do
363
+ not run across the whole window; narrower windows give them all of their width. */
364
+ @media (min-width: 641px) and (max-width: 900px) {
365
+ .rp-right { max-width: 440px; margin: 0 auto; }
366
+ }
354
367
  `;
355
368
  const caseAnchor = (id) => `case-${id}`;
356
369
  /** A timecode: a link that opens the video at that time, which the page's script turns into a
@@ -393,7 +406,7 @@ const stepRow = (view, step, sessions) => {
393
406
  const wait = waitNote(step.step, step.state === 'done' || step.state === 'decided');
394
407
  const decided = step.state === 'decided';
395
408
  return html `<li
396
- class="step st-${step.state}${decided ? ` s-${view.entry.status}` : ''}"
409
+ class="step st-${step.state}${decided ? ` s-${view.checkStatus}` : ''}"
397
410
  ${decided ? html ` aria-current="step"` : ''}
398
411
  >
399
412
  <span class="step-n">${step.index}</span>
@@ -518,6 +531,12 @@ const caseCard = (view, position, span, sessions, assets) => {
518
531
  </h3>
519
532
  ${timeChip(span)}
520
533
  </div>
534
+ ${view.agentFailed !== undefined
535
+ ? html `<p class="agent-verdict">
536
+ <span class="k">Agent's verdict</span>${view.agentFailed}
537
+ <span class="checked">${checksNote(view.checkStatus)}</span>
538
+ </p>`
539
+ : ''}
521
540
  ${entry.reason ? html `<p class="reason">${entry.reason}</p>` : ''}
522
541
  ${shown.length > 0
523
542
  ? html `<div
@@ -566,7 +585,7 @@ const evaluationBlock = (bundle, views) => {
566
585
  </p>
567
586
  <p class="by">
568
587
  ${evaluation.byAgent ? "Verdict and issues: the agent's write-up. " : ''}Statuses: decided by
569
- code in a real browser.
588
+ code in a real browser${agentFailedNote(views)}.
570
589
  </p>
571
590
  ${evaluation.issues.length > 0
572
591
  ? html `<ul class="issues">
@@ -605,8 +624,13 @@ const evaluationBlock = (bundle, views) => {
605
624
  : ''}
606
625
  </section>`;
607
626
  };
627
+ /** `; 2 marked failed by the agent's review`, when its findings mark any case failed. */
628
+ const agentFailedNote = (views) => {
629
+ const n = views.filter((v) => v.agentFailed !== undefined).length;
630
+ return n === 0 ? '' : `; ${n} marked failed by the agent's review`;
631
+ };
608
632
  const filterBlock = (bundle) => {
609
- const counts = countsOf(bundle.ledger.cases);
633
+ const counts = countsOf(judgedLedger(bundle.ledger, bundle.findings).cases);
610
634
  const order = [...statuses.filter((s) => s !== 'passed'), 'passed'];
611
635
  return html `<div class="filters" role="group" aria-label="Show cases">
612
636
  <button type="button" class="all" data-filter="all" aria-pressed="true">
@@ -620,7 +644,7 @@ const filterBlock = (bundle) => {
620
644
  </div>`;
621
645
  };
622
646
  /** The player, its controls with one segment per case, and the case playing now. */
623
- const playerBlock = (bundle, views, spans, playable) => {
647
+ const playerBlock = (bundle, views, spans, playable, hosted) => {
624
648
  const sessions = new Map(playable.map((p) => [p.number, p.src]));
625
649
  const firstCase = views.find((v) => {
626
650
  const span = spans.get(v.entry.id);
@@ -655,6 +679,7 @@ const playerBlock = (bundle, views, spans, playable) => {
655
679
  initialUrl: urlAt(urls, first.number, startMs),
656
680
  none: html `<strong>This case has no video</strong>, so it cannot be played. Its result and
657
681
  screenshots are in its card.`,
682
+ ...(hosted ? {} : { fixPrompt: videoFixPrompt(bundle.jobId) }),
658
683
  })}
659
684
  ${controlsBlock({
660
685
  prefix: 'rp',
@@ -833,7 +858,9 @@ export const renderHtmlReport = (bundle, options) => {
833
858
  </div>`}
834
859
  <main class="rp-main">
835
860
  <div class="rp-left">
836
- <div class="rp-sticky">${playerBlock(bundle, views, spans, playable)}</div>
861
+ <div class="rp-sticky">
862
+ ${playerBlock(bundle, views, spans, playable, options?.assetBaseUrl !== undefined)}
863
+ </div>
837
864
  </div>
838
865
  <div class="rp-right">
839
866
  ${evaluationBlock(bundle, views)}
@@ -24,7 +24,7 @@ export const SHARE_START_PATH = '/.screw-bugs/share/start';
24
24
  export const shareButton = (jobId) => html `<a
25
25
  class="share-btn"
26
26
  href="${`${SHARE_START_PATH}?run=${encodeURIComponent(jobId)}`}"
27
- title="Share this report on screw-bugs Cloud: a link anyone can open for 7 days"
27
+ title="Share this report on Screw Bugs Cloud: a link anyone can open for 7 days"
28
28
  hidden
29
29
  >${icon('share', { size: 16 })}<span class="share-word">Share</span></a
30
30
  >`;
@@ -18,6 +18,13 @@ export declare const recordingShape: (bundle: ReportBundle) => number | undefine
18
18
  export declare const shapeOf: (bundle: ReportBundle) => number;
19
19
  /** The recording's shape as CSS custom properties: `--ar` for `aspect-ratio`, `--arw` a number. */
20
20
  export declare const shapeStyle: (bundle: ReportBundle) => string;
21
+ /**
22
+ * The prompt the "Copy a prompt for your coding agent" button under a video that does not load
23
+ * copies, for the person to paste into their own coding agent. The page's script fills in what
24
+ * only the browser knows: `{video}` (the file that failed, relative to the run folder), `{page}`
25
+ * (the page's address), `{browser}` (its user agent) and `{error}` (what the video element said).
26
+ */
27
+ export declare const videoFixPrompt: (jobId: string) => string;
21
28
  /**
22
29
  * The player: the window with its URL field and the video (with a big play button over it, which
23
30
  * the script shows until the video first plays, by any control, and never again), the note for a video that does not
@@ -38,6 +45,11 @@ export declare const playerWindow: (options: {
38
45
  readonly below?: Value;
39
46
  /** What the player says in the video's place while what is chosen has no video (`none`). */
40
47
  readonly none?: Value;
48
+ /**
49
+ * The prompt (`videoFixPrompt`) the note for a video that does not load offers to copy; none on a
50
+ * page hosted elsewhere, whose reader has no run folder to fix.
51
+ */
52
+ readonly fixPrompt?: string;
41
53
  readonly extraClass?: string;
42
54
  }) => import("./markup.js").Markup;
43
55
  /** A switch: a button whose state is `aria-pressed`. */
@@ -75,7 +87,11 @@ export declare const share: (ms: number, of: number | undefined) => string;
75
87
  * video or its big play button first lays it out that way and plays),
76
88
  * the URL field (the last address recorded by the time shown), session videos (switched with
77
89
  * `load`, moving on to the next session when one ends) and a video that does not load (its note
78
- * takes the player's place, naming the file, while other sessions still play). `none` stops the
90
+ * takes the player's place, naming the file, while other sessions still play; its button copies
91
+ * `videoFixPrompt` filled in with the file, the page's address, the browser and the error that file's video gave,
92
+ * through the Clipboard API where the page is a secure context, else by selecting it in a text box
93
+ * it shows, which also stays for the reader to copy by hand when the browser would not, until the note shows
94
+ * for another file; a copy still pending then says nothing). `none` stops the
79
95
  * player for something chosen that has no video: the video pauses and the `-none` note takes its
80
96
  * place until the next `load`. While either note shows, `playing` says whether the video was
81
97
  * playing before, so what is chosen next plays on. A video that failed before the script ran is
@@ -83,4 +99,4 @@ export declare const share: (ms: number, of: number | undefined) => string;
83
99
  * hooks use. The big play button over the video shows from the start until the video first plays
84
100
  * (by whatever control), and never after. Plain ES2020; no backslashes, so it reads the same in the TypeScript source.
85
101
  */
86
- export declare const PLAYER_JS = "const d=document,r=d.documentElement,K='screw-bugs-theme';\nconst still=()=>matchMedia('(prefers-reduced-motion: reduce)').matches;\nconst topEdge=()=>{const b=d.querySelector('.menubar');return b?Math.max(0,b.getBoundingClientRect().bottom):0};\nconst pad=n=>String(n).padStart(2,'0');\nconst clock=s=>{s=Math.max(0,Math.floor(s||0));const h=Math.floor(s/3600),m=Math.floor(s%3600/60);return(h?h+':'+pad(m):String(m))+':'+pad(s%60)};\nlet theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.theme=theme;\nconst themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\nconst chrome=()=>{\n d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});\n if(location.protocol==='http:'&&(location.hostname==='127.0.0.1'||location.hostname==='localhost'))d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});\n d.querySelectorAll('time.when[datetime]').forEach(e=>{\n const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};\n try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});\n const y=d.createElement('span');y.className='year';y.textContent=', '+p.year;\n e.replaceChildren(p.month+' '+p.day,y,' '+String.fromCharCode(183)+' '+p.hour+':'+p.minute);\n e.title=new Intl.DateTimeFormat('en-US',{dateStyle:'full',timeStyle:'long'}).format(t)}catch(x){}\n });\n d.querySelectorAll('.prompt').forEach(p=>{\n const t=p.querySelector('.prompt-text'),b=p.querySelector('.prompt-more');if(!t||!b)return;\n const fits=()=>{if(!p.classList.contains('open'))b.hidden=t.scrollHeight<=t.clientHeight+1};\n fits();if(window.ResizeObserver)new ResizeObserver(fits).observe(t);if(d.fonts&&d.fonts.ready)d.fonts.ready.then(fits);\n b.addEventListener('click',()=>{const o=p.classList.toggle('open');b.textContent=o?'Show less':'Show full prompt';b.setAttribute('aria-expanded',String(o));fits()});\n });\n};\nconst bare=u=>{const i=u.indexOf('://');return i<0?u:u.slice(i+3)};\nconst player=(p,o)=>{\n const v=d.getElementById(p+'-video'),fig=v.closest('.player'),note=d.getElementById(p+'-unloaded'),c=d.getElementById(p+'-controls'),url=d.getElementById(p+'-url');\n const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));\n const order=[...srcs.keys()];\n const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));\n const dead=new Set(),empty=d.getElementById(p+'-none');let cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;\n const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];\n v.removeAttribute('controls');c.hidden=false;\n const big=d.getElementById(p+'-start');\n if(big){big.hidden=false;big.addEventListener('click',()=>{grow();v.play().catch(()=>{})});v.addEventListener('play',()=>big.remove(),{once:true})}\n const track=()=>tracks.find(t=>t.dataset.s===cur);\n const len=()=>{const t=track(),n=t?Number(t.dataset.total):0;return n>0?n:(isFinite(v.duration)?v.duration:0)};\n const paint=()=>{\n const L=len(),t=v.currentTime,f=L?Math.min(1,t/L):0,k=track();\n tracks.forEach(x=>{x.hidden=x!==k});head.style.left=(f*100)+'%';\n const done=k&&k.querySelector('.done');if(done)done.style.width=(f*100)+'%';\n now.textContent=clock(t);total.textContent=clock(L);\n bar.setAttribute('aria-valuemax',String(Math.round(L)));bar.setAttribute('aria-valuenow',String(Math.round(t)));bar.setAttribute('aria-valuetext',clock(t)+' of '+clock(L));\n play.classList.toggle('playing',!v.paused);play.setAttribute('aria-label',v.paused?'Play':'Pause');\n if(url){let u='';if(down!=='')for(const x of urls){if(x.s===cur&&x.t<=t+0.02)u=x.u}url.textContent=bare(u);url.parentElement.title=u}\n };\n const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};\n const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};\n const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}}if(o.broken)o.broken()};\n const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};\n const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};\n const playing=()=>down===null?!v.paused:held;\n const next=s=>order.slice(order.indexOf(s)+1).find(n=>!dead.has(n));\n const load=(s,t,go,a)=>{\n const my=++ask;auto=!!a;if(dead.has(s))return show(s);\n if(s!==cur||!v.currentSrc||v.error){cur=s;v.dataset.session=s;v.src=srcs.get(s);v.load()}\n const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};\n if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});\n };\n const bad=()=>{if(!v.error)return;dead.add(cur);if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};\n ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));\n v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});\n addEventListener('resize',update);\n v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);\n v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});\n play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});\n v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});\n c.querySelectorAll('[data-rate]').forEach(b=>b.addEventListener('click',()=>{rate=Number(b.dataset.rate);v.playbackRate=rate;v.defaultPlaybackRate=rate;c.querySelectorAll('[data-rate]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));\n const seek=t=>{const L=len();t=Math.max(0,L?Math.min(L,t):t);v.currentTime=t;if(o.seek)o.seek(t);update()};\n const at=e=>{const b=bar.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-b.left)/b.width))*len()};\n bar.addEventListener('pointerdown',e=>{if(e.button>0||down!==null)return;drag=true;bar.setPointerCapture(e.pointerId);seek(at(e))});\n bar.addEventListener('pointermove',e=>{if(drag)seek(at(e))});\n ['pointerup','pointercancel'].forEach(n=>bar.addEventListener(n,()=>{drag=false}));\n bar.addEventListener('keydown',e=>{\n const k=e.key,t=v.currentTime,by={ArrowLeft:-1,ArrowDown:-1,ArrowRight:1,ArrowUp:1,PageDown:-10,PageUp:10}[k];\n const to=by!==undefined?t+by:k==='Home'?0:k==='End'?len():null;if(to===null)return;e.preventDefault();seek(to);\n });\n const full=c.querySelector('.full'),screen=o.full||fig.querySelector('.screen');\n const api=!!(d.fullscreenEnabled&&screen.requestFullscreen),inPage=()=>!!o.inPage&&(o.inPage()||!api);\n const mark=()=>{const f=d.fullscreenElement===screen||screen.classList.contains('focus');full.classList.toggle('out',f);full.setAttribute('aria-label',f?'Exit fullscreen':'Fullscreen');update()};\n let back=0;const focus=on=>{if(on)back=scrollY;screen.classList.toggle('focus',on);scrollTo({top:on?0:back,behavior:'auto'});mark()};\n const grow=()=>{if(!o.expand||!o.inPage||!o.inPage()||d.fullscreenElement||screen.classList.contains('focus'))return false;focus(true);return true};\n if(!api&&!o.inPage)full.hidden=true;\n else{full.addEventListener('click',()=>{const f=screen.classList.contains('focus');if(d.fullscreenElement){d.exitFullscreen().catch(()=>{});if(f)focus(false)}else if(f)focus(false);else if(inPage())focus(true);else screen.requestFullscreen().catch(()=>{})});\n d.addEventListener('fullscreenchange',mark);\n d.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&screen.classList.contains('focus')&&!d.querySelector('dialog[open]')){e.preventDefault();focus(false)}})}\n d.addEventListener('keydown',e=>{if(e.key!==' '||down!==null||e.defaultPrevented||d.querySelector('dialog[open]')||e.target.closest('button,a,input,textarea,select,summary,[role=slider]'))return;e.preventDefault();play.click()});\n return {v,load,none,playing,update,len,cur:()=>cur,down:()=>down,has:s=>srcs.has(s)};\n};\n";
102
+ export declare const PLAYER_JS = "const d=document,r=d.documentElement,K='screw-bugs-theme';\nconst still=()=>matchMedia('(prefers-reduced-motion: reduce)').matches;\nconst topEdge=()=>{const b=d.querySelector('.menubar');return b?Math.max(0,b.getBoundingClientRect().bottom):0};\nconst pad=n=>String(n).padStart(2,'0');\nconst clock=s=>{s=Math.max(0,Math.floor(s||0));const h=Math.floor(s/3600),m=Math.floor(s%3600/60);return(h?h+':'+pad(m):String(m))+':'+pad(s%60)};\nlet theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.theme=theme;\nconst themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\nconst chrome=()=>{\n d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});\n if(location.protocol==='http:'&&(location.hostname==='127.0.0.1'||location.hostname==='localhost'))d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});\n d.querySelectorAll('time.when[datetime]').forEach(e=>{\n const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};\n try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});\n const y=d.createElement('span');y.className='year';y.textContent=', '+p.year;\n e.replaceChildren(p.month+' '+p.day,y,' '+String.fromCharCode(183)+' '+p.hour+':'+p.minute);\n e.title=new Intl.DateTimeFormat('en-US',{dateStyle:'full',timeStyle:'long'}).format(t)}catch(x){}\n });\n d.querySelectorAll('.prompt').forEach(p=>{\n const t=p.querySelector('.prompt-text'),b=p.querySelector('.prompt-more');if(!t||!b)return;\n const fits=()=>{if(!p.classList.contains('open'))b.hidden=t.scrollHeight<=t.clientHeight+1};\n fits();if(window.ResizeObserver)new ResizeObserver(fits).observe(t);if(d.fonts&&d.fonts.ready)d.fonts.ready.then(fits);\n b.addEventListener('click',()=>{const o=p.classList.toggle('open');b.textContent=o?'Show less':'Show full prompt';b.setAttribute('aria-expanded',String(o));fits()});\n });\n};\nconst bare=u=>{const i=u.indexOf('://');return i<0?u:u.slice(i+3)};\nconst player=(p,o)=>{\n const v=d.getElementById(p+'-video'),fig=v.closest('.player'),note=d.getElementById(p+'-unloaded'),c=d.getElementById(p+'-controls'),url=d.getElementById(p+'-url');\n const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));\n const order=[...srcs.keys()];\n const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));\n const dead=new Set(),errs=new Map(),empty=d.getElementById(p+'-none');let shown=0,cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;\n const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];\n v.removeAttribute('controls');c.hidden=false;\n const big=d.getElementById(p+'-start');\n if(big){big.hidden=false;big.addEventListener('click',()=>{grow();v.play().catch(()=>{})});v.addEventListener('play',()=>big.remove(),{once:true})}\n const track=()=>tracks.find(t=>t.dataset.s===cur);\n const len=()=>{const t=track(),n=t?Number(t.dataset.total):0;return n>0?n:(isFinite(v.duration)?v.duration:0)};\n const paint=()=>{\n const L=len(),t=v.currentTime,f=L?Math.min(1,t/L):0,k=track();\n tracks.forEach(x=>{x.hidden=x!==k});head.style.left=(f*100)+'%';\n const done=k&&k.querySelector('.done');if(done)done.style.width=(f*100)+'%';\n now.textContent=clock(t);total.textContent=clock(L);\n bar.setAttribute('aria-valuemax',String(Math.round(L)));bar.setAttribute('aria-valuenow',String(Math.round(t)));bar.setAttribute('aria-valuetext',clock(t)+' of '+clock(L));\n play.classList.toggle('playing',!v.paused);play.setAttribute('aria-label',v.paused?'Play':'Pause');\n if(url){let u='';if(down!=='')for(const x of urls){if(x.s===cur&&x.t<=t+0.02)u=x.u}url.textContent=bare(u);url.parentElement.title=u}\n };\n const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};\n const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};\n const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){++shown;note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}const ft=note.querySelector('.fix-text'),fd=note.querySelector('.fix-done');if(ft){ft.hidden=true;ft.value=''}if(fd)fd.textContent=''}if(o.broken)o.broken()};\n const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};\n const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};\n const playing=()=>down===null?!v.paused:held;\n const next=s=>order.slice(order.indexOf(s)+1).find(n=>!dead.has(n));\n const load=(s,t,go,a)=>{\n const my=++ask;auto=!!a;if(dead.has(s))return show(s);\n if(s!==cur||!v.currentSrc||v.error){cur=s;v.dataset.session=s;v.src=srcs.get(s);v.load()}\n const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};\n if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});\n };\n const bad=()=>{const e=v.error;if(!e)return;dead.add(cur);errs.set(cur,'error code '+e.code+(e.message?': '+e.message:''));if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};\n ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));\n v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});\n addEventListener('resize',update);\n v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);\n const fix=d.getElementById(p+'-fix');\n if(fix){const box=fix.parentElement,ta=box.querySelector('.fix-text'),said=box.querySelector('.fix-done');\n fix.addEventListener('click',()=>{\n let t=ta.dataset.template||'';\n [['video',down?srcs.get(down)||'':''],['page',location.href],['browser',navigator.userAgent],['error',errs.get(down)||'nothing']].forEach(([k,x])=>{t=t.split('{'+k+'}').join(x)});\n const g=shown;ta.value=t;const ok=()=>{if(g!==shown)return;said.textContent='Copied. Paste it into your coding agent.'};\n const by=()=>{if(g!==shown)return;ta.hidden=false;ta.focus();ta.setSelectionRange(0,t.length);ta.scrollTop=0;let c=false;try{c=d.execCommand('copy')}catch(x){}if(c)ok();else said.textContent='Copy the prompt below.'};\n if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(t).then(ok,by);else by();\n })}\n v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});\n play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});\n v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});\n c.querySelectorAll('[data-rate]').forEach(b=>b.addEventListener('click',()=>{rate=Number(b.dataset.rate);v.playbackRate=rate;v.defaultPlaybackRate=rate;c.querySelectorAll('[data-rate]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));\n const seek=t=>{const L=len();t=Math.max(0,L?Math.min(L,t):t);v.currentTime=t;if(o.seek)o.seek(t);update()};\n const at=e=>{const b=bar.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-b.left)/b.width))*len()};\n bar.addEventListener('pointerdown',e=>{if(e.button>0||down!==null)return;drag=true;bar.setPointerCapture(e.pointerId);seek(at(e))});\n bar.addEventListener('pointermove',e=>{if(drag)seek(at(e))});\n ['pointerup','pointercancel'].forEach(n=>bar.addEventListener(n,()=>{drag=false}));\n bar.addEventListener('keydown',e=>{\n const k=e.key,t=v.currentTime,by={ArrowLeft:-1,ArrowDown:-1,ArrowRight:1,ArrowUp:1,PageDown:-10,PageUp:10}[k];\n const to=by!==undefined?t+by:k==='Home'?0:k==='End'?len():null;if(to===null)return;e.preventDefault();seek(to);\n });\n const full=c.querySelector('.full'),screen=o.full||fig.querySelector('.screen');\n const api=!!(d.fullscreenEnabled&&screen.requestFullscreen),inPage=()=>!!o.inPage&&(o.inPage()||!api);\n const mark=()=>{const f=d.fullscreenElement===screen||screen.classList.contains('focus');full.classList.toggle('out',f);full.setAttribute('aria-label',f?'Exit fullscreen':'Fullscreen');update()};\n let back=0;const focus=on=>{if(on)back=scrollY;screen.classList.toggle('focus',on);scrollTo({top:on?0:back,behavior:'auto'});mark()};\n const grow=()=>{if(!o.expand||!o.inPage||!o.inPage()||d.fullscreenElement||screen.classList.contains('focus'))return false;focus(true);return true};\n if(!api&&!o.inPage)full.hidden=true;\n else{full.addEventListener('click',()=>{const f=screen.classList.contains('focus');if(d.fullscreenElement){d.exitFullscreen().catch(()=>{});if(f)focus(false)}else if(f)focus(false);else if(inPage())focus(true);else screen.requestFullscreen().catch(()=>{})});\n d.addEventListener('fullscreenchange',mark);\n d.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&screen.classList.contains('focus')&&!d.querySelector('dialog[open]')){e.preventDefault();focus(false)}})}\n d.addEventListener('keydown',e=>{if(e.key!==' '||down!==null||e.defaultPrevented||d.querySelector('dialog[open]')||e.target.closest('button,a,input,textarea,select,summary,[role=slider]'))return;e.preventDefault();play.click()});\n return {v,load,none,playing,update,len,cur:()=>cur,down:()=>down,has:s=>srcs.has(s)};\n};\n";
@@ -25,6 +25,27 @@ export const recordingShape = (bundle) => {
25
25
  export const shapeOf = (bundle) => Math.round((recordingShape(bundle) ?? (bundle.device.kind === 'mobile' ? 9 / 19.5 : 16 / 10)) * 10_000) / 10_000;
26
26
  /** The recording's shape as CSS custom properties: `--ar` for `aspect-ratio`, `--arw` a number. */
27
27
  export const shapeStyle = (bundle) => `--ar:${shapeOf(bundle)} / 1;--arw:${shapeOf(bundle)}`;
28
+ /**
29
+ * The prompt the "Copy a prompt for your coding agent" button under a video that does not load
30
+ * copies, for the person to paste into their own coding agent. The page's script fills in what
31
+ * only the browser knows: `{video}` (the file that failed, relative to the run folder), `{page}`
32
+ * (the page's address), `{browser}` (its user agent) and `{error}` (what the video element said).
33
+ */
34
+ export const videoFixPrompt = (jobId) => [
35
+ `The screw-bugs video of run ${jobId} does not play in my browser. Please find out why and help me watch it.`,
36
+ '',
37
+ `- Video: .screw-bugs/runs/${jobId}/{video}`,
38
+ '- Page I opened: {page}',
39
+ '- Browser: {browser}',
40
+ '- What the browser said: {error}',
41
+ '',
42
+ 'Check, in this order:',
43
+ "1. Does the video file exist, and is it more than a few KB? If it is missing or empty, run `npx screw-bugs doctor`, fix what it reports (Playwright's ffmpeg records the video), then run the job again.",
44
+ '2. Can this browser play WebM (VP8)? Safari on iPhone and iPad often cannot. If so, tell me which browser to open it in.',
45
+ `3. Was the page opened as a file, or from a server that does not serve the video? Run \`npx screw-bugs report ${jobId}\` and give me the report URL it prints; that server serves the video. It listens on 127.0.0.1 only, so if I am on another device, tell me how to reach it.`,
46
+ '',
47
+ 'Do not change or delete anything in the run folder.',
48
+ ].join('\n');
28
49
  /** What the URL field says at `ms`: the address without its scheme. */
29
50
  const urlText = (url) => (url === undefined ? '' : displayUrl(url, 120));
30
51
  /**
@@ -67,7 +88,22 @@ export const playerWindow = (options) => {
67
88
  </div>
68
89
  <p class="unloaded-video" id="${`${prefix}-unloaded`}" hidden>
69
90
  <strong>Video didn't load:</strong> <a href="${first.src}">${first.src}</a>. Open this page
70
- from its run folder in a browser, or open the file directly.
91
+ from its run folder in a browser, or open the file
92
+ directly.${options.fixPrompt === undefined
93
+ ? ''
94
+ : html `<span class="fix-video"
95
+ ><button type="button" class="fix-copy" id="${`${prefix}-fix`}">
96
+ Copy a prompt for your coding agent</button
97
+ ><span class="fix-done" role="status"></span
98
+ ><textarea
99
+ class="fix-text"
100
+ readonly
101
+ rows="8"
102
+ aria-label="Prompt for your coding agent"
103
+ data-template="${options.fixPrompt}"
104
+ hidden
105
+ ></textarea>
106
+ </span>`}
71
107
  </p>
72
108
  ${options.none === undefined
73
109
  ? ''
@@ -166,7 +202,11 @@ export const share = (ms, of) => of === undefined || of <= 0
166
202
  * video or its big play button first lays it out that way and plays),
167
203
  * the URL field (the last address recorded by the time shown), session videos (switched with
168
204
  * `load`, moving on to the next session when one ends) and a video that does not load (its note
169
- * takes the player's place, naming the file, while other sessions still play). `none` stops the
205
+ * takes the player's place, naming the file, while other sessions still play; its button copies
206
+ * `videoFixPrompt` filled in with the file, the page's address, the browser and the error that file's video gave,
207
+ * through the Clipboard API where the page is a secure context, else by selecting it in a text box
208
+ * it shows, which also stays for the reader to copy by hand when the browser would not, until the note shows
209
+ * for another file; a copy still pending then says nothing). `none` stops the
170
210
  * player for something chosen that has no video: the video pauses and the `-none` note takes its
171
211
  * place until the next `load`. While either note shows, `playing` says whether the video was
172
212
  * playing before, so what is chosen next plays on. A video that failed before the script ran is
@@ -204,7 +244,7 @@ const player=(p,o)=>{
204
244
  const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));
205
245
  const order=[...srcs.keys()];
206
246
  const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));
207
- const dead=new Set(),empty=d.getElementById(p+'-none');let cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;
247
+ const dead=new Set(),errs=new Map(),empty=d.getElementById(p+'-none');let shown=0,cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;
208
248
  const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];
209
249
  v.removeAttribute('controls');c.hidden=false;
210
250
  const big=d.getElementById(p+'-start');
@@ -222,7 +262,7 @@ const player=(p,o)=>{
222
262
  };
223
263
  const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};
224
264
  const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};
225
- const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}}if(o.broken)o.broken()};
265
+ const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){++shown;note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}const ft=note.querySelector('.fix-text'),fd=note.querySelector('.fix-done');if(ft){ft.hidden=true;ft.value=''}if(fd)fd.textContent=''}if(o.broken)o.broken()};
226
266
  const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};
227
267
  const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};
228
268
  const playing=()=>down===null?!v.paused:held;
@@ -233,11 +273,20 @@ const player=(p,o)=>{
233
273
  const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};
234
274
  if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});
235
275
  };
236
- const bad=()=>{if(!v.error)return;dead.add(cur);if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};
276
+ const bad=()=>{const e=v.error;if(!e)return;dead.add(cur);errs.set(cur,'error code '+e.code+(e.message?': '+e.message:''));if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};
237
277
  ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));
238
278
  v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});
239
279
  addEventListener('resize',update);
240
280
  v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);
281
+ const fix=d.getElementById(p+'-fix');
282
+ if(fix){const box=fix.parentElement,ta=box.querySelector('.fix-text'),said=box.querySelector('.fix-done');
283
+ fix.addEventListener('click',()=>{
284
+ let t=ta.dataset.template||'';
285
+ [['video',down?srcs.get(down)||'':''],['page',location.href],['browser',navigator.userAgent],['error',errs.get(down)||'nothing']].forEach(([k,x])=>{t=t.split('{'+k+'}').join(x)});
286
+ const g=shown;ta.value=t;const ok=()=>{if(g!==shown)return;said.textContent='Copied. Paste it into your coding agent.'};
287
+ const by=()=>{if(g!==shown)return;ta.hidden=false;ta.focus();ta.setSelectionRange(0,t.length);ta.scrollTop=0;let c=false;try{c=d.execCommand('copy')}catch(x){}if(c)ok();else said.textContent='Copy the prompt below.'};
288
+ if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(t).then(ok,by);else by();
289
+ })}
241
290
  v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});
242
291
  play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});
243
292
  v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});
@@ -1,4 +1,4 @@
1
- import type { ReportBundle } from '../schema/index.js';
1
+ import { type ReportBundle } from '../schema/index.js';
2
2
  /**
3
3
  * A short GitHub-flavored Markdown summary of a run, to paste into (or post on) a pull request:
4
4
  * the headline (the agent's, when it wrote one up, else the code's verdict), the counts, what to
@@ -1,4 +1,5 @@
1
- import { countsOf, fixesOf, formatTimecode, notTestedCount, severityLabel, statuses, statusLabel, videoOf, } from './view.js';
1
+ import { judgedLedger, } from '../schema/index.js';
2
+ import { checksNote, countsOf, fixesOf, formatTimecode, notTestedCount, severityLabel, statuses, statusLabel, videoOf, } from './view.js';
2
3
  const mark = {
3
4
  passed: '✅',
4
5
  failed: '❌',
@@ -24,7 +25,10 @@ const code = (path) => `\`${path.replaceAll('`', '')}\``;
24
25
  * relative to the project root; `reportPath` defaults to the report's.
25
26
  */
26
27
  export const renderPrSummary = (bundle, options = {}) => {
27
- const { ledger, findings } = bundle;
28
+ const { findings } = bundle;
29
+ // Statuses as results show them: a case the agent's findings mark failed counts as failed.
30
+ const ledger = judgedLedger(bundle.ledger, findings);
31
+ const byAgent = ledger.cases.filter((c) => c.agentFailed !== undefined).length;
28
32
  const counts = countsOf(ledger.cases);
29
33
  const total = ledger.cases.length;
30
34
  const ended = ledger.state === 'finished' || ledger.state === 'errored';
@@ -58,7 +62,7 @@ export const renderPrSummary = (bundle, options = {}) => {
58
62
  '',
59
63
  ...(findings
60
64
  ? [
61
- `**Code decided:** ${verdict}. _The ${notTested.length > 0 ? 'headline, fixes and what was not tested' : 'headline and fixes'} are the agent's write-up._`,
65
+ `**${byAgent > 0 ? 'Code and agent decided' : 'Code decided'}:** ${verdict}${byAgent > 0 ? ` (${byAgent} marked failed by the agent's review)` : ''}. _The ${notTested.length > 0 ? 'headline, fixes and what was not tested' : 'headline and fixes'} are the agent's write-up._`,
62
66
  '',
63
67
  ]
64
68
  : []),
@@ -88,7 +92,12 @@ export const renderPrSummary = (bundle, options = {}) => {
88
92
  '',
89
93
  '| Case | Status | Reason | Video at |',
90
94
  '| --- | --- | --- | --- |',
91
- ...notPassing.map((c) => `| ${inline(c.title)} | ${mark[c.status]} ${statusLabel[c.status]} | ${c.reason ? inline(c.reason) : '—'} | ${at(c)} |`),
95
+ ...notPassing.map((c) => `| ${inline(c.title)} | ${mark[c.status]} ${statusLabel[c.status]} | ${c.agentFailed !== undefined
96
+ ? `Agent's verdict: ${inline(c.agentFailed)} (${checksNote(c.checkStatus)})` +
97
+ (c.reason ? `; ${inline(c.reason)}` : '')
98
+ : c.reason
99
+ ? inline(c.reason)
100
+ : '—'} | ${at(c)} |`),
92
101
  ]
93
102
  : []),
94
103
  '',
@@ -16,7 +16,7 @@ export declare const SIGN_IN_ANIMATION = "https://static.screwbugs.dev/animation
16
16
  * hash is fixed. Frames come by long polling `frame?after=<seq>`; inputs go out in order, one
17
17
  * request at a time, mouse moves merged. `410` from any route means the sign-in ended.
18
18
  */
19
- export declare const SIGN_IN_SCRIPT = "(() => {\n 'use strict';\n const RIVE = 'https://cdn.jsdelivr.net/npm/@rive-app/canvas-lite@2.48.0/', RIVE_JS_SRI = 'sha384-KKLeoe6TCJ0x8AYfmSeeOfpT6u1rpxnG6clu8dKuLNqMImJV40kWrCVhTU7lmcNg', ANIMATION = 'https://static.screwbugs.dev/animations/auth-required.riv';\n // The animation's state while the bug waits by the lock (its `kick` trigger works only then),\n // and how long after the kick the bug has run off, when the browser shows (at most\n // `KICK_WAIT_MAX` after the person started, however long the bug took to reach the lock).\n const WAITING = 'Wait (idle)', KICK_MS = 2300, KICK_WAIT_MAX = 6000;\n const base = location.pathname.replace(/\\/+$/, '');\n const $ = (id) => document.getElementById(id);\n const img = $('screen'), stage = $('stage'), kb = $('keys'), addr = $('addr'), note = $('note');\n let seq = 0, fw = 1280, fh = 800, over = false, saving = false;\n const sleep = (ms) => new Promise((r) => setTimeout(r, ms));\n\n const end = (text) => {\n over = true;\n document.body.classList.add('over');\n note.textContent = text;\n $('ended').textContent = text;\n };\n const GONE = 'This sign-in has ended (it closes after 15 minutes without use), so nothing was saved. Ask your coding agent to start its job again for a new link.';\n\n const queue = [];\n // Inputs per request: under the server's limit (100, and 256 KB with text of up to 2000).\n const BATCH = 50;\n let sending = false;\n // Whether an input may not have reached the browser: Save then asks to check the page first.\n let lost = false;\n const flush = async () => {\n if (sending || over || queue.length === 0) return;\n sending = true;\n const batch = queue.splice(0, BATCH);\n try {\n const r = await fetch(base + '/input', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(batch),\n });\n if (r.status === 410) end('This sign-in has ended. You can close this tab.');\n else if (!r.ok) lost = true;\n } catch {\n // It may or may not have been played; sending it again could type twice.\n lost = true;\n await sleep(500);\n }\n if (lost && !over) note.textContent = 'Some input may not have reached the browser; check the page shows what you expect.';\n sending = false;\n flush();\n };\n const send = (input) => {\n // Nothing more goes in once Save was pressed: the session is what the inputs before it made.\n if (saving || over) return;\n const last = queue[queue.length - 1];\n if (input.type === 'mouse' && input.kind === 'move' && last && last.type === 'mouse' && last.kind === 'move') queue[queue.length - 1] = input;\n else queue.push(input);\n flush();\n };\n\n const frames = async () => {\n let failures = 0;\n while (!over) {\n try {\n const r = await fetch(base + '/frame?after=' + seq, { cache: 'no-store' });\n failures = 0;\n if (r.status === 410) return end('This sign-in has ended. You can close this tab.');\n if (r.status === 200) {\n const f = await r.json();\n seq = f.seq; fw = f.width; fh = f.height;\n img.src = 'data:image/jpeg;base64,' + f.jpeg;\n addr.textContent = f.url;\n } else if (r.status !== 204) await sleep(1000);\n } catch {\n // Its server is gone (it ended, or the agent's process stopped): say so rather than wait.\n if (++failures >= 3) return end(GONE);\n await sleep(1000);\n }\n }\n };\n\n let sized;\n const resize = () => {\n clearTimeout(sized);\n sized = setTimeout(() => send({ type: 'viewport', width: Math.round(stage.clientWidth), height: Math.round(stage.clientHeight) }), 250);\n };\n addEventListener('resize', resize);\n\n const at = (e) => {\n const r = img.getBoundingClientRect();\n return {\n x: Math.round(((e.clientX - r.left) * fw) / Math.max(1, r.width)),\n y: Math.round(((e.clientY - r.top) * fh) / Math.max(1, r.height)),\n };\n };\n const button = (b) => (b === 1 ? 'middle' : b === 2 ? 'right' : 'left');\n let touch;\n img.addEventListener('contextmenu', (e) => e.preventDefault());\n img.addEventListener('pointerdown', (e) => {\n e.preventDefault();\n kb.focus({ preventScroll: true });\n img.setPointerCapture(e.pointerId);\n const p = at(e);\n if (e.pointerType === 'mouse') send({ type: 'mouse', kind: 'down', ...p, button: button(e.button), clickCount: Math.min(3, Math.max(1, e.detail || 1)) });\n else touch = { x: e.clientX, y: e.clientY, moved: false };\n });\n img.addEventListener('pointermove', (e) => {\n const p = at(e);\n if (e.pointerType === 'mouse') return send({ type: 'mouse', kind: 'move', ...p });\n if (!touch) return;\n const dx = e.clientX - touch.x, dy = e.clientY - touch.y;\n if (!touch.moved && Math.hypot(dx, dy) < 8) return;\n touch.moved = true;\n const scale = fw / Math.max(1, img.getBoundingClientRect().width);\n send({ type: 'wheel', ...p, dx: Math.round(-dx * scale), dy: Math.round(-dy * scale) });\n touch.x = e.clientX; touch.y = e.clientY;\n });\n img.addEventListener('pointerup', (e) => {\n const p = at(e);\n if (e.pointerType === 'mouse') return send({ type: 'mouse', kind: 'up', ...p, button: button(e.button), clickCount: Math.min(3, Math.max(1, e.detail || 1)) });\n if (touch && !touch.moved) {\n send({ type: 'mouse', kind: 'move', ...p });\n send({ type: 'mouse', kind: 'down', ...p, button: 'left', clickCount: 1 });\n send({ type: 'mouse', kind: 'up', ...p, button: 'left', clickCount: 1 });\n }\n touch = undefined;\n });\n img.addEventListener('pointercancel', () => { touch = undefined; });\n img.addEventListener('wheel', (e) => {\n e.preventDefault();\n const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? fh : 1;\n send({ type: 'wheel', ...at(e), dx: Math.round(e.deltaX * unit), dy: Math.round(e.deltaY * unit) });\n }, { passive: false });\n\n const ignored = new Set(['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'Unidentified', 'Dead', 'Process', 'Compose']);\n let composing = false;\n kb.addEventListener('compositionstart', () => { composing = true; });\n kb.addEventListener('compositionend', () => { composing = false; typed(); });\n kb.addEventListener('keydown', (e) => {\n if (e.isComposing || e.keyCode === 229 || ignored.has(e.key)) return;\n // A character typed with AltGr (an @ on many European keyboards, where it also reports Ctrl\n // and Alt) or with Option on a Mac is text, not a shortcut: the box gets it as input.\n const altGraph = e.getModifierState && e.getModifierState('AltGraph');\n if (e.key.length === 1 && (altGraph || (e.altKey && !e.ctrlKey && !e.metaKey))) return;\n const command = e.ctrlKey || e.metaKey || e.altKey;\n // Pasting goes in as text, from the paste itself.\n if (command && e.key.toLowerCase() === 'v') return;\n if (e.key.length === 1 && !command) return;\n e.preventDefault();\n const modifiers = [e.altKey && 'Alt', e.ctrlKey && 'Control', e.metaKey && 'Meta', e.shiftKey && 'Shift'].filter(Boolean);\n send({ type: 'key', key: e.key, modifiers });\n });\n // The box always holds one invisible character, so a phone keyboard's Backspace (often only\n // keyCode 229 or 'Unidentified' on keydown) has something to delete, which shows below.\n const MARK = '\u200B';\n const reset = () => {\n kb.value = MARK;\n kb.setSelectionRange(1, 1);\n };\n const typed = () => {\n if (composing) return;\n const value = kb.value;\n const text = value.split(MARK).join('');\n if (!value.includes(MARK) && !text) send({ type: 'key', key: 'Backspace', modifiers: [] });\n if (text) send({ type: 'text', text: text.slice(0, 2000) });\n reset();\n };\n kb.addEventListener('beforeinput', (e) => {\n // Deleting, as keyboards that send no key for it say it: played as the key itself.\n const key = e.inputType === 'deleteContentBackward' ? 'Backspace' : e.inputType === 'deleteContentForward' ? 'Delete' : undefined;\n if (key === undefined || !e.cancelable) return;\n e.preventDefault();\n send({ type: 'key', key, modifiers: [] });\n });\n kb.addEventListener('input', typed);\n kb.addEventListener('focus', reset);\n reset();\n\n $('back').addEventListener('click', () => send({ type: 'nav', kind: 'back' }));\n $('reload').addEventListener('click', () => send({ type: 'nav', kind: 'reload' }));\n const post = async (route) => {\n const r = await fetch(base + '/' + route, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });\n return r;\n };\n /** Until every input already given has been played (or the sign-in ended). */\n const drained = async () => {\n while (!over && (sending || queue.length > 0)) await sleep(50);\n };\n $('save').addEventListener('click', async () => {\n if (saving || over) return;\n saving = true;\n document.body.classList.add('saving');\n note.textContent = 'Saving\u2026';\n try {\n await drained();\n if (over) return;\n if (lost) {\n lost = false;\n saving = false;\n document.body.classList.remove('saving');\n note.textContent = 'Some input did not reach the browser, so nothing was saved yet. Check the page shows you signed in, then press Save sign-in again.';\n return;\n }\n const r = await post('save');\n if (r.ok) return end('Saved. You can close this tab; your coding agent can start the run again.');\n if (r.status === 410) return end('This sign-in has ended. You can close this tab.');\n note.textContent = 'Could not save: ' + (await r.text());\n } catch {\n note.textContent = 'Could not reach screw-bugs to save. Try again.';\n }\n saving = false;\n document.body.classList.remove('saving');\n });\n $('cancel').addEventListener('click', async () => {\n try { await post('cancel'); } catch {}\n end('Cancelled. Nothing was saved. You can close this tab.');\n });\n\n // The theme: light, dark or the system's, in turn, as on screw-bugs Cloud's menu bar (the\n // reports' tokens follow `data-theme`). Not kept: each sign-in is a new origin.\n const themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\n themeCycle(document.querySelector('.menubar .theme'));\n\n // The animation: the bug waits by a lock, and kicks it open when the person starts. It plays\n // with Rive's runtime from its CDN (taken only with the hash it was published with) and the file\n // from screw-bugs' CDN. Without either, or where the person prefers less motion, the page is the\n // same without it.\n const art = $('art');\n // `instance` from when it is made, `rive` once its file loaded; `stopped` once the art is gone\n // for good (it failed, or the person started), so nothing that loads later plays.\n let instance, rive, observer, stopped = false, waiting = false, onWaiting;\n const noArt = () => {\n stopped = true;\n if (art) art.hidden = true;\n if (observer) observer.disconnect();\n try {\n if (instance) instance.cleanup();\n } catch {}\n instance = rive = observer = undefined;\n };\n if (art && !matchMedia('(prefers-reduced-motion: reduce)').matches) {\n const runtime = document.createElement('script');\n runtime.src = RIVE + 'rive.js';\n runtime.integrity = RIVE_JS_SRI;\n runtime.crossOrigin = 'anonymous';\n runtime.onerror = noArt;\n runtime.onload = () => {\n if (stopped) return;\n try {\n const R = window.rive;\n // The runtime is pinned, so the state changes it still gives are what this relies on.\n R.Rive.suppressDeprecationWarnings = ['state-change-events'];\n R.RuntimeLoader.setWasmUrl(RIVE + 'rive.wasm');\n R.RuntimeLoader.setWasmFallbackUrl(RIVE + 'rive_fallback.wasm');\n const canvas = art.querySelector('canvas');\n const r = new R.Rive({\n src: ANIMATION,\n canvas,\n autoplay: true,\n stateMachine: 'Main',\n // Binds the file's view model, whose `kick` trigger starts the kick.\n autoBind: true,\n layout: new R.Layout({ fit: R.Fit.Contain, alignment: R.Alignment.Center }),\n onLoad: () => {\n if (stopped) return;\n r.resizeDrawingSurfaceToCanvas();\n rive = r;\n },\n onLoadError: noArt,\n onStateChange: (e) => {\n for (const name of [].concat(e.data || [])) {\n if (name === WAITING) waiting = true;\n else if (name === 'Arrive' || name === 'Kick') waiting = false;\n }\n if (waiting && onWaiting) onWaiting();\n },\n });\n instance = r;\n observer = new ResizeObserver(() => rive && rive.resizeDrawingSurfaceToCanvas());\n observer.observe(canvas);\n } catch {\n noArt();\n }\n };\n document.head.appendChild(runtime);\n } else noArt();\n /** Plays the kick (once the bug waits by the lock), resolving when the bug has run off. */\n const kick = () =>\n new Promise((done) => {\n if (!rive) return done();\n const cap = setTimeout(done, KICK_WAIT_MAX);\n onWaiting = () => {\n onWaiting = undefined;\n try {\n rive.viewModelInstance.trigger('kick').trigger();\n } catch {\n clearTimeout(cap);\n return done();\n }\n setTimeout(() => {\n clearTimeout(cap);\n done();\n }, KICK_MS);\n };\n if (waiting) onWaiting();\n });\n\n // The explainer comes first; the browser shows (and its frames start) once the person starts.\n let starting = false;\n $('start').addEventListener('click', async () => {\n if (starting || over) return;\n starting = true;\n $('start').setAttribute('aria-disabled', 'true');\n // Reading this takes no requests, so the sign-in may have ended meanwhile.\n try {\n const r = await fetch(base + '/status', { cache: 'no-store' });\n if (!r.ok) return end(GONE);\n } catch {\n return end(GONE);\n }\n await kick();\n noArt();\n if (over) return;\n document.body.classList.remove('intro');\n resize();\n frames();\n });\n})();";
19
+ export declare const SIGN_IN_SCRIPT = "(() => {\n 'use strict';\n const RIVE = 'https://cdn.jsdelivr.net/npm/@rive-app/canvas-lite@2.48.0/', RIVE_JS_SRI = 'sha384-KKLeoe6TCJ0x8AYfmSeeOfpT6u1rpxnG6clu8dKuLNqMImJV40kWrCVhTU7lmcNg', ANIMATION = 'https://static.screwbugs.dev/animations/auth-required.riv';\n // The animation's state while the bug waits by the lock (its `kick` trigger works only then),\n // and how long after the kick the bug has run off, when the browser shows (at most\n // `KICK_WAIT_MAX` after the person started, however long the bug took to reach the lock).\n const WAITING = 'Wait (idle)', KICK_MS = 2300, KICK_WAIT_MAX = 6000;\n const base = location.pathname.replace(/\\/+$/, '');\n const $ = (id) => document.getElementById(id);\n const img = $('screen'), stage = $('stage'), kb = $('keys'), addr = $('addr'), note = $('note');\n let seq = 0, fw = 1280, fh = 800, over = false, saving = false;\n const sleep = (ms) => new Promise((r) => setTimeout(r, ms));\n\n const end = (text) => {\n over = true;\n document.body.classList.add('over');\n note.textContent = text;\n $('ended').textContent = text;\n };\n const GONE = 'This sign-in has ended (it closes after 15 minutes without use), so nothing was saved. Ask your coding agent to start its job again for a new link.';\n\n const queue = [];\n // Inputs per request: under the server's limit (100, and 256 KB with text of up to 2000).\n const BATCH = 50;\n let sending = false;\n // Whether an input may not have reached the browser: Save then asks to check the page first.\n let lost = false;\n const flush = async () => {\n if (sending || over || queue.length === 0) return;\n sending = true;\n const batch = queue.splice(0, BATCH);\n try {\n const r = await fetch(base + '/input', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(batch),\n });\n if (r.status === 410) end('This sign-in has ended. You can close this tab.');\n else if (!r.ok) lost = true;\n } catch {\n // It may or may not have been played; sending it again could type twice.\n lost = true;\n await sleep(500);\n }\n if (lost && !over) note.textContent = 'Some input may not have reached the browser; check the page shows what you expect.';\n sending = false;\n flush();\n };\n const send = (input) => {\n // Nothing more goes in once Save was pressed: the session is what the inputs before it made.\n if (saving || over) return;\n const last = queue[queue.length - 1];\n if (input.type === 'mouse' && input.kind === 'move' && last && last.type === 'mouse' && last.kind === 'move') queue[queue.length - 1] = input;\n else queue.push(input);\n flush();\n };\n\n const frames = async () => {\n let failures = 0;\n while (!over) {\n try {\n const r = await fetch(base + '/frame?after=' + seq, { cache: 'no-store' });\n failures = 0;\n if (r.status === 410) return end('This sign-in has ended. You can close this tab.');\n if (r.status === 200) {\n const f = await r.json();\n seq = f.seq; fw = f.width; fh = f.height;\n img.src = 'data:image/jpeg;base64,' + f.jpeg;\n addr.textContent = f.url;\n } else if (r.status !== 204) await sleep(1000);\n } catch {\n // Its server is gone (it ended, or the agent's process stopped): say so rather than wait.\n if (++failures >= 3) return end(GONE);\n await sleep(1000);\n }\n }\n };\n\n let sized;\n const resize = () => {\n clearTimeout(sized);\n sized = setTimeout(() => send({ type: 'viewport', width: Math.round(stage.clientWidth), height: Math.round(stage.clientHeight) }), 250);\n };\n addEventListener('resize', resize);\n\n const at = (e) => {\n const r = img.getBoundingClientRect();\n return {\n x: Math.round(((e.clientX - r.left) * fw) / Math.max(1, r.width)),\n y: Math.round(((e.clientY - r.top) * fh) / Math.max(1, r.height)),\n };\n };\n const button = (b) => (b === 1 ? 'middle' : b === 2 ? 'right' : 'left');\n let touch;\n img.addEventListener('contextmenu', (e) => e.preventDefault());\n img.addEventListener('pointerdown', (e) => {\n e.preventDefault();\n kb.focus({ preventScroll: true });\n img.setPointerCapture(e.pointerId);\n const p = at(e);\n if (e.pointerType === 'mouse') send({ type: 'mouse', kind: 'down', ...p, button: button(e.button), clickCount: Math.min(3, Math.max(1, e.detail || 1)) });\n else touch = { x: e.clientX, y: e.clientY, moved: false };\n });\n img.addEventListener('pointermove', (e) => {\n const p = at(e);\n if (e.pointerType === 'mouse') return send({ type: 'mouse', kind: 'move', ...p });\n if (!touch) return;\n const dx = e.clientX - touch.x, dy = e.clientY - touch.y;\n if (!touch.moved && Math.hypot(dx, dy) < 8) return;\n touch.moved = true;\n const scale = fw / Math.max(1, img.getBoundingClientRect().width);\n send({ type: 'wheel', ...p, dx: Math.round(-dx * scale), dy: Math.round(-dy * scale) });\n touch.x = e.clientX; touch.y = e.clientY;\n });\n img.addEventListener('pointerup', (e) => {\n const p = at(e);\n if (e.pointerType === 'mouse') return send({ type: 'mouse', kind: 'up', ...p, button: button(e.button), clickCount: Math.min(3, Math.max(1, e.detail || 1)) });\n if (touch && !touch.moved) {\n send({ type: 'mouse', kind: 'move', ...p });\n send({ type: 'mouse', kind: 'down', ...p, button: 'left', clickCount: 1 });\n send({ type: 'mouse', kind: 'up', ...p, button: 'left', clickCount: 1 });\n }\n touch = undefined;\n });\n img.addEventListener('pointercancel', () => { touch = undefined; });\n img.addEventListener('wheel', (e) => {\n e.preventDefault();\n const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? fh : 1;\n send({ type: 'wheel', ...at(e), dx: Math.round(e.deltaX * unit), dy: Math.round(e.deltaY * unit) });\n }, { passive: false });\n\n const ignored = new Set(['Shift', 'Control', 'Alt', 'Meta', 'CapsLock', 'Unidentified', 'Dead', 'Process', 'Compose']);\n let composing = false;\n kb.addEventListener('compositionstart', () => { composing = true; });\n kb.addEventListener('compositionend', () => { composing = false; typed(); });\n kb.addEventListener('keydown', (e) => {\n if (e.isComposing || e.keyCode === 229 || ignored.has(e.key)) return;\n // A character typed with AltGr (an @ on many European keyboards, where it also reports Ctrl\n // and Alt) or with Option on a Mac is text, not a shortcut: the box gets it as input.\n const altGraph = e.getModifierState && e.getModifierState('AltGraph');\n if (e.key.length === 1 && (altGraph || (e.altKey && !e.ctrlKey && !e.metaKey))) return;\n const command = e.ctrlKey || e.metaKey || e.altKey;\n // Pasting goes in as text, from the paste itself.\n if (command && e.key.toLowerCase() === 'v') return;\n if (e.key.length === 1 && !command) return;\n e.preventDefault();\n const modifiers = [e.altKey && 'Alt', e.ctrlKey && 'Control', e.metaKey && 'Meta', e.shiftKey && 'Shift'].filter(Boolean);\n send({ type: 'key', key: e.key, modifiers });\n });\n // The box always holds one invisible character, so a phone keyboard's Backspace (often only\n // keyCode 229 or 'Unidentified' on keydown) has something to delete, which shows below.\n const MARK = '\u200B';\n const reset = () => {\n kb.value = MARK;\n kb.setSelectionRange(1, 1);\n };\n const typed = () => {\n if (composing) return;\n const value = kb.value;\n const text = value.split(MARK).join('');\n if (!value.includes(MARK) && !text) send({ type: 'key', key: 'Backspace', modifiers: [] });\n if (text) send({ type: 'text', text: text.slice(0, 2000) });\n reset();\n };\n kb.addEventListener('beforeinput', (e) => {\n // Deleting, as keyboards that send no key for it say it: played as the key itself.\n const key = e.inputType === 'deleteContentBackward' ? 'Backspace' : e.inputType === 'deleteContentForward' ? 'Delete' : undefined;\n if (key === undefined || !e.cancelable) return;\n e.preventDefault();\n send({ type: 'key', key, modifiers: [] });\n });\n kb.addEventListener('input', typed);\n kb.addEventListener('focus', reset);\n reset();\n\n $('back').addEventListener('click', () => send({ type: 'nav', kind: 'back' }));\n $('reload').addEventListener('click', () => send({ type: 'nav', kind: 'reload' }));\n const post = async (route) => {\n const r = await fetch(base + '/' + route, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });\n return r;\n };\n /** Until every input already given has been played (or the sign-in ended). */\n const drained = async () => {\n while (!over && (sending || queue.length > 0)) await sleep(50);\n };\n $('save').addEventListener('click', async () => {\n if (saving || over) return;\n saving = true;\n document.body.classList.add('saving');\n note.textContent = 'Saving\u2026';\n try {\n await drained();\n if (over) return;\n if (lost) {\n lost = false;\n saving = false;\n document.body.classList.remove('saving');\n note.textContent = 'Some input did not reach the browser, so nothing was saved yet. Check the page shows you signed in, then press Save sign-in again.';\n return;\n }\n const r = await post('save');\n if (r.ok) return end('Saved. You can close this tab; your coding agent can start the run again.');\n if (r.status === 410) return end('This sign-in has ended. You can close this tab.');\n note.textContent = 'Could not save: ' + (await r.text());\n } catch {\n note.textContent = 'Could not reach screw-bugs to save. Try again.';\n }\n saving = false;\n document.body.classList.remove('saving');\n });\n $('cancel').addEventListener('click', async () => {\n try { await post('cancel'); } catch {}\n end('Cancelled. Nothing was saved. You can close this tab.');\n });\n\n // The theme: light, dark or the system's, in turn, as on screw-bugs Cloud's menu bar (the\n // reports' tokens follow `data-theme`). Not kept: each sign-in is a new origin.\n const themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\n themeCycle(document.querySelector('.menubar .theme'));\n\n // The animation: the bug waits by a lock, and kicks it open when the person starts. It plays\n // with Rive's runtime from its CDN (taken only with the hash it was published with) and the file\n // from screw-bugs' CDN. Without either, or where the person prefers less motion, the page is the\n // same without it.\n const art = $('art');\n // `instance` from when it is made, `rive` once its file loaded; `stopped` once the art is gone\n // for good (it failed, or the person started), so nothing that loads later plays.\n let instance, rive, observer, stopped = false, waiting = false, onWaiting;\n const noArt = () => {\n stopped = true;\n if (art) art.hidden = true;\n if (observer) observer.disconnect();\n try {\n if (instance) instance.cleanup();\n } catch {}\n instance = rive = observer = undefined;\n };\n if (art && !matchMedia('(prefers-reduced-motion: reduce)').matches) {\n const runtime = document.createElement('script');\n runtime.src = RIVE + 'rive.js';\n runtime.integrity = RIVE_JS_SRI;\n runtime.crossOrigin = 'anonymous';\n runtime.onerror = noArt;\n runtime.onload = () => {\n if (stopped) return;\n try {\n const R = window.rive;\n // The runtime is pinned, so the state changes it still gives are what this relies on.\n R.Rive.suppressDeprecationWarnings = ['state-change-events'];\n R.RuntimeLoader.setWasmUrl(RIVE + 'rive.wasm');\n R.RuntimeLoader.setWasmFallbackUrl(RIVE + 'rive_fallback.wasm');\n const canvas = art.querySelector('canvas');\n const r = new R.Rive({\n src: ANIMATION,\n canvas,\n autoplay: true,\n stateMachine: 'Main',\n // Binds the file's view model, whose `kick` trigger starts the kick.\n autoBind: true,\n layout: new R.Layout({ fit: R.Fit.Contain, alignment: R.Alignment.Center }),\n onLoad: () => {\n if (stopped) return;\n r.resizeDrawingSurfaceToCanvas();\n rive = r;\n },\n onLoadError: noArt,\n onStateChange: (e) => {\n for (const name of [].concat(e.data || [])) {\n if (name === WAITING) waiting = true;\n else if (name === 'Arrive' || name === 'Kick') waiting = false;\n }\n if (waiting && onWaiting) onWaiting();\n },\n });\n instance = r;\n observer = new ResizeObserver(() => rive && rive.resizeDrawingSurfaceToCanvas());\n observer.observe(canvas);\n } catch {\n noArt();\n }\n };\n document.head.appendChild(runtime);\n } else noArt();\n /** Plays the kick (once the bug waits by the lock), resolving when the bug has run off. */\n const kick = () =>\n new Promise((done) => {\n if (!rive) return done();\n const cap = setTimeout(done, KICK_WAIT_MAX);\n onWaiting = () => {\n onWaiting = undefined;\n try {\n rive.viewModelInstance.trigger('kick').trigger();\n } catch {\n clearTimeout(cap);\n return done();\n }\n setTimeout(() => {\n clearTimeout(cap);\n done();\n }, KICK_MS);\n };\n if (waiting) onWaiting();\n });\n\n // The explainer comes first; the browser shows (and its frames start) once the person starts.\n // Start shows a spinner and takes no more clicks from the click until the browser shows; a\n // failed check gives it back.\n const start = $('start'), startError = $('start-error');\n let starting = false;\n const busy = (on) => {\n starting = on;\n start.disabled = on;\n start.classList.toggle('loading', on);\n if (on) start.setAttribute('aria-busy', 'true');\n else start.removeAttribute('aria-busy');\n };\n start.addEventListener('click', async () => {\n if (starting || over) return;\n busy(true);\n startError.textContent = '';\n // Reading this takes no requests, so the sign-in may have ended meanwhile.\n try {\n const r = await fetch(base + '/status', { cache: 'no-store' });\n if (!r.ok) {\n busy(false);\n return end(GONE);\n }\n } catch {\n // Not reached at all: screw-bugs may have stopped, or the network dropped for a moment.\n busy(false);\n startError.textContent = 'Could not reach screw-bugs. Check that your coding agent is still running, then try again.';\n return;\n }\n await kick();\n noArt();\n if (over) return;\n document.body.classList.remove('intro');\n resize();\n frames();\n });\n})();";
20
20
  /**
21
21
  * The live view's Content-Security-Policy: its own script, frames and icons as data URLs, its own
22
22
  * routes, Google Fonts as the reports load them (`webFonts`), Rive's runtime from its exact folder
@@ -333,17 +333,33 @@ export const SIGN_IN_SCRIPT = /* js */ `(() => {
333
333
  });
334
334
 
335
335
  // The explainer comes first; the browser shows (and its frames start) once the person starts.
336
+ // Start shows a spinner and takes no more clicks from the click until the browser shows; a
337
+ // failed check gives it back.
338
+ const start = $('start'), startError = $('start-error');
336
339
  let starting = false;
337
- $('start').addEventListener('click', async () => {
340
+ const busy = (on) => {
341
+ starting = on;
342
+ start.disabled = on;
343
+ start.classList.toggle('loading', on);
344
+ if (on) start.setAttribute('aria-busy', 'true');
345
+ else start.removeAttribute('aria-busy');
346
+ };
347
+ start.addEventListener('click', async () => {
338
348
  if (starting || over) return;
339
- starting = true;
340
- $('start').setAttribute('aria-disabled', 'true');
349
+ busy(true);
350
+ startError.textContent = '';
341
351
  // Reading this takes no requests, so the sign-in may have ended meanwhile.
342
352
  try {
343
353
  const r = await fetch(base + '/status', { cache: 'no-store' });
344
- if (!r.ok) return end(GONE);
354
+ if (!r.ok) {
355
+ busy(false);
356
+ return end(GONE);
357
+ }
345
358
  } catch {
346
- return end(GONE);
359
+ // Not reached at all: screw-bugs may have stopped, or the network dropped for a moment.
360
+ busy(false);
361
+ startError.textContent = 'Could not reach screw-bugs. Check that your coding agent is still running, then try again.';
362
+ return;
347
363
  }
348
364
  await kick();
349
365
  noArt();
@@ -396,9 +412,18 @@ body { display: flex; flex-direction: column; background: var(--bg); }
396
412
  .card .app-title { margin: 6px 0 0; font: var(--t-small); color: var(--muted); overflow-wrap: anywhere; }
397
413
  .card .go { display: flex; justify-content: center; margin-top: 36px; }
398
414
  #start { height: 40px; padding: 0 20px 0 24px; gap: 10px; font: var(--t-body-lg); font-weight: 500; }
399
- #start[aria-disabled="true"] { cursor: default; filter: none; }
415
+ #start:disabled { cursor: default; filter: none; }
416
+ /* While it starts, a spinner in place of the arrow. It keeps turning (slower) where the person
417
+ prefers less motion: it says something is happening, which a still ring does not. */
418
+ #start .spin { display: none; box-sizing: border-box; width: 18px; height: 18px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: start-spin 700ms linear infinite; }
419
+ #start.loading .spin { display: block; }
420
+ #start.loading svg { display: none; }
421
+ @keyframes start-spin { to { transform: rotate(360deg); } }
422
+ @media (prefers-reduced-motion: reduce) { #start .spin { animation: start-spin 1400ms linear infinite !important; } }
423
+ #start-error { margin: 16px 0 0; font: var(--t-small); color: var(--muted); text-align: center; }
424
+ #start-error:empty { display: none; }
400
425
  #ended { display: none; margin: 36px 0 0; font: var(--t-body); color: var(--text); text-align: center; }
401
- .intro.over .card .go { display: none; }
426
+ .intro.over .card .go, .intro.over #start-error { display: none; }
402
427
  .intro.over #ended { display: block; }
403
428
  body:not(.intro) .intro-only { display: none; }
404
429
  /* The card's entrance, once per page: it rises in, then what it says follows in reading order.
@@ -497,9 +522,13 @@ export const renderSignInPage = (account) => {
497
522
  </div>
498
523
  <div class="go">
499
524
  <button id="start" type="button" class="pill primary">
500
- Sign in with a test user ${icon_('arrow-right', { size: 18 })}
525
+ Sign in with a test user ${icon_('arrow-right', { size: 18 })}<span
526
+ class="spin"
527
+ aria-hidden="true"
528
+ ></span>
501
529
  </button>
502
530
  </div>
531
+ <p id="start-error" role="alert"></p>
503
532
  <p id="ended" role="status"></p>
504
533
  </section>
505
534
  </main>
@@ -145,6 +145,14 @@ figure { margin: 0; }
145
145
  .screen:fullscreen { aspect-ratio: auto; border-radius: 0; }
146
146
  .unloaded-video { margin: 0; padding: 28px 20px; background: var(--panel); text-align: center; overflow-wrap: anywhere; font: var(--t-body); }
147
147
  .player.broken .screen { display: none; }
148
+ /* Under the note for a video that does not load: a button that copies a prompt for the reader's
149
+ coding agent, what it did, and the prompt in a box when the browser would not copy it. */
150
+ .fix-video { display: flex; flex-direction: column; align-items: center; gap: 8px; margin-top: 16px; }
151
+ .fix-copy { padding: 8px 16px; border: 1px solid var(--border-strong); border-radius: 999px; background: var(--bg-2); cursor: pointer; }
152
+ .fix-copy:hover { background: var(--panel); }
153
+ .fix-done:empty { display: none; }
154
+ .fix-done { color: var(--muted); }
155
+ .fix-text:not([hidden]) { display: block; width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid var(--border-strong); border-radius: 8px; background: var(--bg-2); color: inherit; font: 400 12px/18px var(--mono); text-align: left; resize: vertical; }
148
156
  /* The big play button over a video that has not played yet: the whole screen is its target, the
149
157
  circle in the middle shows it. It is over the video, so its colors are the same in both themes. */
150
158
  .big-play { position: absolute; inset: 0; z-index: 6; display: grid; place-items: center; padding: 0; border: 0; border-radius: inherit; background: rgba(0, 0, 0, .18); color: #fff; cursor: pointer; }