1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package main

import "strconv"

// Single self-contained page: no external assets, no build step. It is served
// from loopback to one browser window, so there is nothing to optimise for.
//
// The page never closes itself — you close the chromium window when you are
// done, and the server notices the dropped SSE stream and shuts down on its own
// after the idle timeout.

// variantCountJS keeps the page's card count tied to the Go constant, so the
// two cannot drift apart.
var variantCountJS = strconv.Itoa(variantCount)

var indexHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mastodon alt text</title>
<style>
  :root {
    --bg:#f5f5f7; --card:#ffffff; --fg:#1b1b1f; --fg2:#5f6368;
    --accent:#2f6fb0; --accent-h:#245a91; --border:#dcdce0;
    --good:#2e7d32; --bad:#c62828;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg:#161618; --card:#212124; --fg:#e8e8ea; --fg2:#a0a0a6;
      --accent:#5aa3dd; --accent-h:#7bb8e8; --border:#3a3a40;
      --good:#7bc47f; --bad:#e57373;
    }
  }
  *,*::before,*::after { box-sizing:border-box; }
  body { font-family:system-ui,sans-serif; background:var(--bg); color:var(--fg);
    margin:0; padding:0 0 2rem 0; line-height:1.45; }
  .wrap { max-width:900px; margin:0 auto; padding:0 1rem; }
  header.top { position:sticky; top:0; z-index:10; background:var(--card);
    border-bottom:1px solid var(--border); padding:.6rem 0; margin-bottom:1rem; }
  header.top .wrap { display:flex; align-items:center; gap:.75rem; }
  header.top h1 { font-size:1.05rem; margin:0; flex:1; font-weight:600; }
  .status { font-size:.8rem; color:var(--fg2); white-space:nowrap; }
  .status.err { color:var(--bad); }

  .shot { display:block; max-width:100%; max-height:34vh; width:auto;
    border:1px solid var(--border); border-radius:10px; margin:0 auto 1rem; }

  /* Prompt block, directly under the image: it is a property of the picture,
     and it is what the cards below are answers to, so it reads top to bottom. */
  .prompt { background:var(--card); border:1px solid var(--border);
    border-radius:10px; padding:.7rem .8rem; margin-bottom:1rem; }
  .prompt .head { display:flex; align-items:baseline; gap:.5rem;
    font-size:.76rem; color:var(--fg2); margin-bottom:.4rem; }
  .prompt .head .lbl { font-weight:600; color:var(--fg); }
  .prompt .head .spacer { flex:1; }
  .prompt textarea { width:100%; resize:none; overflow:hidden; display:block;
    font:inherit; font-size:.86rem; line-height:1.4; color:var(--fg);
    background:var(--bg); border:1px solid var(--border); border-radius:7px;
    padding:.45rem .55rem; }
  .prompt textarea:focus { outline:2px solid var(--accent); outline-offset:-1px; }
  .prompt .row { display:flex; align-items:center; gap:.5rem; margin-top:.5rem; }
  .prompt .row .why { flex:1; font-size:.76rem; color:var(--fg2); }
  .prompt button:disabled { background:var(--border); color:var(--fg2); cursor:not-allowed; }
  /* A link, not a button: it changes the field, it does not spend a round. */
  .linkbtn { background:none; border:none; padding:0; font:inherit;
    font-size:.76rem; color:var(--accent); cursor:pointer; text-decoration:underline; }
  .linkbtn:hover { color:var(--accent-h); }
  .linkbtn[hidden] { display:none; }

  .card { background:var(--card); border:1px solid var(--border); border-radius:10px;
    padding:.85rem 1rem; margin:.7rem 0; cursor:pointer; position:relative;
    transition:border-color .12s, transform .06s; }
  .card:hover { border-color:var(--accent); }
  .card:active { transform:scale(.995); }
  .card[aria-disabled="true"] { cursor:default; }
  .card[aria-disabled="true"]:hover { border-color:var(--border); }
  .card.copied { border-color:var(--good); }
  .card .text { white-space:pre-wrap; overflow-wrap:anywhere; }
  .card .meta { display:flex; gap:.6rem; align-items:center;
    margin-top:.55rem; font-size:.76rem; color:var(--fg2); }
  .card .badge { font-weight:600; color:var(--good); }
  .card .err { color:var(--bad); white-space:pre-wrap; overflow-wrap:anywhere; }

  /* Skeleton lines shown until a variant arrives. */
  .skel { height:.85rem; border-radius:5px; margin:.42rem 0;
    background:linear-gradient(90deg,var(--border) 25%,var(--bg) 50%,var(--border) 75%);
    background-size:200% 100%; animation:sweep 1.3s linear infinite; }
  .skel:nth-child(2) { width:92%; }
  .skel:nth-child(3) { width:74%; }
  @keyframes sweep { from { background-position:200% 0; } to { background-position:-200% 0; } }
  @media (prefers-reduced-motion:reduce) { .skel { animation:none; } }

  .hint { color:var(--fg2); font-size:.8rem; margin-top:1.2rem; text-align:center; }

  /* Refinement bar. Sticky at the bottom so it stays reachable however long
     the variants are. */
  .refine { position:sticky; bottom:0; background:var(--card); margin-top:1rem;
    border:1px solid var(--border); border-radius:10px; padding:.7rem .8rem; }
  .refine .row { display:flex; gap:.5rem; }
  .refine input { flex:1; }
  .refine button:disabled { background:var(--border); color:var(--fg2); cursor:not-allowed; }
  .refine .why { font-size:.76rem; color:var(--fg2); margin:.45rem .1rem 0; }
  .round-note { font-size:.8rem; color:var(--fg2); margin:.2rem 0 .6rem; }
  .round-note b { color:var(--fg); font-weight:600; }
</style>
</head>
<body>
<header class="top"><div class="wrap">
  <h1>mastodon alt text</h1>
  <span class="status" id="status">reading clipboard…</span>
</div></header>

<div class="wrap">
  <img class="shot" id="shot" alt="" hidden>

  <div class="prompt">
    <div class="head">
      <span class="lbl">Prompt</span>
      <span class="spacer"></span>
      <button type="button" class="linkbtn" id="promptreset" hidden>reset to default</button>
    </div>
    <textarea id="prompt" rows="2" autocomplete="off" spellcheck="false"></textarea>
    <div class="row">
      <span class="why" id="promptwhy"></span>
      <button id="regenbtn" disabled>Regenerate</button>
    </div>
  </div>

  <p class="round-note" id="roundnote" hidden></p>
  <div id="cards"></div>

  <div class="refine">
    <div class="row">
      <input id="instruction" type="text" autocomplete="off"
             placeholder="e.g. shorter, or: don't mention the background">
      <button id="refinebtn" disabled>Refine</button>
    </div>
    <p class="why" id="refinewhy">Pick a variant first — refining works from the one you chose.</p>
  </div>

  <p class="hint">Click a variant to copy it to both selections. Close this window when you are done.</p>
</div>

<script>
(function () {
  var VARIANTS = ` + variantCountJS + `;
  var cards = document.getElementById('cards');
  var statusEl = document.getElementById('status');
  var shot = document.getElementById('shot');
  var roundNote = document.getElementById('roundnote');
  var instruction = document.getElementById('instruction');
  var refineBtn = document.getElementById('refinebtn');
  var refineWhy = document.getElementById('refinewhy');
  var promptEl = document.getElementById('prompt');
  var regenBtn = document.getElementById('regenbtn');
  var promptWhy = document.getElementById('promptwhy');
  var promptReset = document.getElementById('promptreset');

  // Per-round state. currentRound guards against a stale variant from an
  // earlier round arriving after a new one has started and overwriting a card
  // that now belongs to someone else.
  var currentRound = -1;
  var texts = {};
  var picked = null;
  var busy = false;

  // Prompt state.
  //
  // sentPrompt is what the cards on screen were generated from, and is the
  // baseline "changed" is measured against — not the default, so that after a
  // regeneration the edited prompt is the new normal and blurring the field
  // again does not fire a second round.
  //
  // hasImage gates the button: regenerating needs the image, and until the
  // clipboard has been read and converted there is nothing to caption. The
  // server rejects it anyway, but a button that cannot work should look like
  // it cannot work.
  var sentPrompt = null;
  var defaultPrompt = null;
  var hasImage = false;
  // Set once a fatal has been reported, only to tell the two reasons the
  // prompt field is inert apart: still waiting for the clipboard, versus no
  // image is coming at all.
  var dead = false;

  function setStatus(msg, isErr) {
    statusEl.textContent = msg;
    statusEl.classList.toggle('err', !!isErr);
  }

  // Refining needs a chosen variant to work from, and only one round may be in
  // flight at a time; the server enforces both, this only keeps the button
  // honest about it.
  function updateRefine() {
    var ready = picked !== null && !busy;
    refineBtn.disabled = !ready;
    if (busy) {
      refineWhy.textContent = 'Generating…';
    } else if (picked === null) {
      refineWhy.textContent = 'Pick a variant first — refining works from the one you chose.';
    } else {
      refineWhy.textContent = 'Refining variant ' + (picked + 1) + '. It is already on your clipboard.';
    }
  }

  // The textarea grows to fit its content instead of scrolling: the prompt is
  // a couple of lines of prose that you edit as a whole, and a two-line window
  // onto it hides the clause you are about to contradict.
  function autosize() {
    promptEl.style.height = 'auto';
    promptEl.style.height = promptEl.scrollHeight + 'px';
  }

  function promptChanged() {
    return promptEl.value.trim() !== (sentPrompt || '').trim();
  }

  function updatePrompt() {
    // Enabled even when unchanged: the same prompt at this temperature gives
    // three different wordings, so the button doubles as a reroll for when all
    // three were bad rather than the brief being wrong.
    regenBtn.disabled = busy || !hasImage || promptEl.value.trim() === '';
    promptReset.hidden = defaultPrompt === null ||
      promptEl.value.trim() === defaultPrompt.trim();
    if (busy) {
      promptWhy.textContent = 'Generating…';
    } else if (dead) {
      promptWhy.textContent = 'No image — nothing to caption.';
    } else if (!hasImage) {
      promptWhy.textContent = 'Waiting for the image.';
    } else if (promptEl.value.trim() === '') {
      promptWhy.textContent = 'The prompt cannot be empty.';
    } else if (promptChanged()) {
      promptWhy.textContent = 'Changed — regenerating starts over from the image.';
    } else {
      promptWhy.textContent = 'Regenerating discards any refinements.';
    }
  }

  // doRegenerate throws the conversation away and asks again. Unlike Refine it
  // needs no pick: it starts from the image, not from a variant.
  function doRegenerate() {
    var p = promptEl.value.trim();
    if (!p || busy || !hasImage) return;
    busy = true;
    // Optimistic, and load-bearing: the blur handler compares against
    // sentPrompt, so setting it now stops the blur that a click on this button
    // causes from queueing a second, identical round.
    sentPrompt = p;
    updatePrompt();
    updateRefine();
    fetch('/regenerate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt: p })
    }).then(function (r) {
      if (!r.ok) return r.text().then(function (t) { throw new Error(t || ('HTTP ' + r.status)); });
    }).catch(function (e) {
      busy = false;
      updatePrompt();
      updateRefine();
      setStatus('regenerate failed: ' + e.message.trim(), true);
    });
  }

  regenBtn.addEventListener('click', doRegenerate);

  promptEl.addEventListener('input', function () {
    autosize();
    updatePrompt();
  });

  // Ctrl/Cmd+Enter submits; plain Enter inserts a newline, as in any textarea.
  promptEl.addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
      e.preventDefault();
      doRegenerate();
    }
  });

  // Leaving the field having changed it regenerates, which is the "changed"
  // semantics of a native form control. Only on an actual change: blurring a
  // field you merely clicked into must not cost three API calls.
  promptEl.addEventListener('blur', function () {
    if (promptChanged()) doRegenerate();
  });

  // blur fires before click, so a mousedown on this button would first take
  // focus out of an edited textarea and regenerate — the exact round the user
  // is reaching for reset to avoid. Suppressing the default mousedown keeps
  // focus where it is; the click still arrives.
  promptReset.addEventListener('mousedown', function (e) { e.preventDefault(); });

  promptReset.addEventListener('click', function () {
    if (defaultPrompt === null) return;
    promptEl.value = defaultPrompt;
    autosize();
    updatePrompt();
    // Deliberately does not regenerate: this puts the text back so you can
    // edit from it, and spending a round on the way there is rarely wanted.
    promptEl.focus();
  });

  function buildSkeletons() {
    cards.innerHTML = '';
    for (var i = 0; i < VARIANTS; i++) {
      var c = document.createElement('div');
      c.className = 'card';
      c.id = 'card-' + i;
      c.setAttribute('aria-disabled', 'true');
      c.innerHTML = '<div class="skel"></div><div class="skel"></div><div class="skel"></div>';
      c.addEventListener('click', onPick(i));
      cards.appendChild(c);
    }
  }

  // A new round replaces the cards rather than adding to them. Nothing is lost
  // by that: the text a refinement started from was copied to the clipboard
  // when it was picked.
  function startRound(n, instr) {
    currentRound = n;
    texts = {};
    picked = null;
    buildSkeletons();
    if (instr) {
      roundNote.hidden = false;
      roundNote.innerHTML = '';
      roundNote.appendChild(document.createTextNode('Round ' + (n + 1) + ', refining with: '));
      var b = document.createElement('b');
      b.textContent = instr;
      roundNote.appendChild(b);
    } else {
      roundNote.hidden = true;
    }
    updateRefine();
  }

  buildSkeletons();
  updateRefine();
  // The field stays empty and disabled until the server's first prompt event,
  // rather than being prefilled from a copy of the default embedded here.
  // Two copies of the same string drift; and a field that showed a prompt
  // before the server had confirmed one could be edited into disagreeing with
  // the history that was actually built.
  updatePrompt();

  function onPick(i) {
    return function () {
      if (!(i in texts)) return; // still loading, or failed
      fetch('/pick', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ index: i })
      }).then(function (r) {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        markCopied(i);
      }).catch(function (e) {
        setStatus('copy failed: ' + e.message, true);
      });
    };
  }

  function doRefine() {
    var instr = instruction.value.trim();
    if (!instr || picked === null || busy) return;
    busy = true;
    updateRefine();
    fetch('/refine', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ index: picked, instruction: instr })
    }).then(function (r) {
      if (!r.ok) return r.text().then(function (t) { throw new Error(t || ('HTTP ' + r.status)); });
      instruction.value = '';
      // busy stays set until the round's "done" event; the round event that
      // follows is what clears the cards.
    }).catch(function (e) {
      busy = false;
      updateRefine();
      setStatus('refine failed: ' + e.message.trim(), true);
    });
  }

  refineBtn.addEventListener('click', doRefine);
  instruction.addEventListener('keydown', function (e) {
    if (e.key === 'Enter') { e.preventDefault(); doRefine(); }
  });

  function markCopied(i) {
    if (picked !== null) {
      var prev = document.getElementById('card-' + picked);
      if (prev) {
        prev.classList.remove('copied');
        var b = prev.querySelector('.badge');
        if (b) b.remove();
      }
    }
    picked = i;
    var card = document.getElementById('card-' + i);
    card.classList.add('copied');
    var meta = card.querySelector('.meta');
    if (meta && !meta.querySelector('.badge')) {
      var badge = document.createElement('span');
      badge.className = 'badge';
      badge.textContent = 'copied \u2713';
      meta.insertBefore(badge, meta.firstChild);
    }
    setStatus('copied to primary + clipboard');
    updateRefine();
  }

  function renderVariant(v) {
    // Ignore anything belonging to a round that is no longer on screen.
    if (v.round !== currentRound) return;
    var card = document.getElementById('card-' + v.index);
    if (!card) return;
    if (v.error) {
      card.innerHTML = '<div class="err"></div>';
      card.querySelector('.err').textContent = v.error;
      return;
    }
    texts[v.index] = v.text;
    card.removeAttribute('aria-disabled');
    card.innerHTML = '<div class="text"></div><div class="meta"><span class="len"></span></div>';
    card.querySelector('.text').textContent = v.text;
    // Mastodon's alt text limit is 1500; surface it so an over-long variant is
    // visible before you paste it.
    var len = v.text.length;
    card.querySelector('.len').textContent =
      len + ' chars' + (len > 1500 ? ' \u2014 over Mastodon\u2019s 1500 limit' : '');
  }

  var es = new EventSource('/events');

  es.addEventListener('image', function (e) {
    var d = JSON.parse(e.data);
    shot.src = d.url;
    shot.hidden = false;
    hasImage = true;
    updatePrompt();
    setStatus('generating ' + VARIANTS + ' variants…');
  });

  // The server is authoritative for the prompt: it is what actually built the
  // history. Do not overwrite text being typed, though — this event also
  // arrives on every reconnect, and EventSource reconnects on its own.
  es.addEventListener('prompt', function (e) {
    var d = JSON.parse(e.data);
    defaultPrompt = d['default'];
    sentPrompt = d.prompt;
    if (document.activeElement !== promptEl) {
      promptEl.value = d.prompt;
      autosize();
    }
    updatePrompt();
  });

  es.addEventListener('round', function (e) {
    var d = JSON.parse(e.data);
    // Reconnecting mid-round replays this, so treat it as authoritative for
    // both the round number and the fact that something is generating.
    if (d.round !== currentRound) startRound(d.round, d.instruction);
    busy = true;
    updateRefine();
    updatePrompt();
    setStatus('generating ' + VARIANTS + ' variants…');
  });

  es.addEventListener('variant', function (e) {
    renderVariant(JSON.parse(e.data));
  });

  es.addEventListener('done', function (e) {
    var d = JSON.parse(e.data);
    if (d.round !== currentRound) return;
    busy = false;
    updateRefine();
    updatePrompt();
    if (picked === null) setStatus('pick one');
  });

  es.addEventListener('fatal', function (e) {
    setStatus(JSON.parse(e.data).error, true);
    cards.innerHTML = '';
    busy = false;
    refineBtn.disabled = true;
    refineWhy.textContent = 'Nothing to refine.';
    // A fatal means there is no image, so there is nothing to regenerate
    // against either; editing the prompt cannot rescue it.
    hasImage = false;
    dead = true;
    updatePrompt();
  });

  // The server exits once this stream has been gone for the idle timeout, so a
  // reconnect is what keeps it alive while the window is open. EventSource
  // retries on its own; we only surface the gap.
  es.onerror = function () {
    if (es.readyState === EventSource.CLOSED) setStatus('server closed', true);
  };
})();
</script>
</body>
</html>
`