1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
|
package main
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
)
// sseKeepalive bounds how long the stream may sit silent. Nothing sits between
// the browser and us on loopback, so this is not about proxies timing out; it
// is a liveness probe. A write to a browser that vanished without a FIN (the
// machine slept with the lid closed, X died) fails, which tears the handler
// down and lets the idle timer start.
const sseKeepalive = 25 * time.Second
// round is one batch of variantCount generations. Round 0 is the initial
// captioning; a later round is either a refinement, carrying the instruction
// that produced it, or a regeneration from an edited prompt.
//
// Invariant, which the page relies on to label a round: Instruction is empty
// exactly when the round was generated straight from the prompt, with no
// conversation behind it. So round 0 and every regeneration have none, and
// only a refinement has one.
type round struct {
Number int
Instruction string // empty unless this round is a refinement
Variants map[int]variant
Done bool
}
type server struct {
mu sync.Mutex
// image is the WebP the alt texts were generated from, kept to render the
// thumbnail and to re-send with every refinement.
//
// The clipboard is read exactly once, into here. It cannot be read again
// later: picking a variant replaces the clipboard's contents with that
// text, so by the time a refinement runs there is no image there any more.
image []byte
imageMime string
// prompt is the brief the current conversation was started from, editable
// in the page. It is held here, not only in the browser, so that a page
// which reloads or connects late is shown the prompt its cards actually
// came from rather than the default.
prompt string
// history accumulates the conversation. Each refinement appends the chosen
// text and the instruction, so constraints given in earlier rounds ("no
// mention of the logo") continue to apply to later ones.
//
// A regeneration throws this away and rebuilds it from the image and the
// prompt, which is the difference between the two operations: refining
// carries the past forward, regenerating discards it.
history []content
rounds []*round
// busy serialises rounds. Refinements are strictly one at a time, which is
// what keeps this free of the supersede and stale-publish races that come
// with cancelling work in flight: there is never more than one generation
// batch alive, so nothing needs cancelling.
busy bool
fatal error
subs map[chan sseEvent]struct{}
subsMu sync.Mutex
// idle bookkeeping. See noteSubscriberGone.
idleTimer *time.Timer
idleTimeout time.Duration
shutdown func()
}
type sseEvent struct {
name string
data any
}
func newServer(idleTimeout time.Duration) *server {
return &server{
subs: map[chan sseEvent]struct{}{},
idleTimeout: idleTimeout,
prompt: defaultAltTextPrompt,
}
}
// currentRound returns the newest round, or nil before the first one starts.
// Callers must hold s.mu.
func (s *server) currentRoundLocked() *round {
if len(s.rounds) == 0 {
return nil
}
return s.rounds[len(s.rounds)-1]
}
func (s *server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", s.handleIndex)
mux.HandleFunc("/events", s.handleEvents)
mux.HandleFunc("/pick", s.handlePick)
mux.HandleFunc("/refine", s.handleRefine)
mux.HandleFunc("/regenerate", s.handleRegenerate)
return mux
}
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// The page is generated fresh per run; caching it would serve a stale
// window's content on the next invocation.
w.Header().Set("Cache-Control", "no-store")
fmt.Fprint(w, indexHTML)
}
// broadcast fans an event out to the connected page(s). Slow or dead
// subscribers are skipped rather than blocking the sender; every event is also
// replayed from state on connect, so a dropped event is recovered on reconnect.
func (s *server) broadcast(ev sseEvent) {
s.subsMu.Lock()
defer s.subsMu.Unlock()
for ch := range s.subs {
select {
case ch <- ev:
default:
}
}
}
// snapshot returns the events needed to bring a freshly connected page up to
// date. Because generation runs independently of whether anything is watching,
// a reconnecting page (or one opened late) must be able to catch up.
func (s *server) snapshot() []sseEvent {
s.mu.Lock()
defer s.mu.Unlock()
var evs []sseEvent
if s.fatal != nil {
return []sseEvent{{name: "fatal", data: map[string]string{"error": s.fatal.Error()}}}
}
if s.image != nil {
evs = append(evs, sseEvent{name: "image", data: map[string]string{
"url": "data:image/webp;base64," + base64.StdEncoding.EncodeToString(s.image),
}})
}
// Sent before the round, so the field is filled in before the cards it
// belongs to appear. The default is sent too, so the page's reset link
// does not have to keep its own copy of a string that lives in Go.
evs = append(evs, sseEvent{name: "prompt", data: map[string]string{
"prompt": s.prompt,
"default": defaultAltTextPrompt,
}})
// Only the newest round is replayed, because only the newest round is on
// screen: a refinement replaces the cards rather than adding to them.
if r := s.currentRoundLocked(); r != nil {
evs = append(evs, sseEvent{name: "round", data: map[string]any{
"round": r.Number,
"instruction": r.Instruction,
}})
for i := range variantCount {
if v, ok := r.Variants[i]; ok {
evs = append(evs, sseEvent{name: "variant", data: variantJSON(r.Number, v)})
}
}
if r.Done {
evs = append(evs, sseEvent{name: "done", data: map[string]any{"round": r.Number}})
}
}
return evs
}
// variantJSON tags every variant with its round. A reconnect or a slow response
// can otherwise land after the page has moved on, and an untagged variant would
// paint over a card belonging to a newer round.
func variantJSON(roundNo int, v variant) map[string]any {
m := map[string]any{"round": roundNo, "index": v.Index}
if v.Err != nil {
m["error"] = v.Err.Error()
} else {
m["text"] = v.Text
}
return m
}
func (s *server) setImage(img []byte, mime string) {
s.mu.Lock()
s.image = img
s.imageMime = mime
s.mu.Unlock()
s.broadcast(sseEvent{name: "image", data: map[string]string{
"url": "data:image/webp;base64," + base64.StdEncoding.EncodeToString(img),
}})
}
// startRound registers a new round and announces it, which is the page's cue to
// clear the cards back to skeletons.
func (s *server) startRound(instruction string) *round {
s.mu.Lock()
r := &round{
Number: len(s.rounds),
Instruction: instruction,
Variants: map[int]variant{},
}
s.rounds = append(s.rounds, r)
s.mu.Unlock()
s.broadcast(sseEvent{name: "round", data: map[string]any{
"round": r.Number,
"instruction": r.Instruction,
}})
return r
}
func (s *server) addVariant(r *round, v variant) {
s.mu.Lock()
r.Variants[v.Index] = v
s.mu.Unlock()
s.broadcast(sseEvent{name: "variant", data: variantJSON(r.Number, v)})
}
func (s *server) setDone(r *round) {
s.mu.Lock()
r.Done = true
s.mu.Unlock()
s.broadcast(sseEvent{name: "done", data: map[string]any{"round": r.Number}})
}
// setFatal reports a failure that prevented any generation at all (no image in
// the clipboard, no API key). The page shows it in place of the cards; the
// server stays up so the message is readable, and exits on the idle timer.
func (s *server) setFatal(err error) {
s.mu.Lock()
s.fatal = err
s.mu.Unlock()
logf("fatal: %s", err)
s.broadcast(sseEvent{name: "fatal", data: map[string]string{"error": err.Error()}})
}
func (s *server) handleEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher.Flush()
ch := make(chan sseEvent, 16)
s.subsMu.Lock()
s.subs[ch] = struct{}{}
s.subsMu.Unlock()
s.noteSubscriberArrived()
defer func() {
s.subsMu.Lock()
delete(s.subs, ch)
n := len(s.subs)
s.subsMu.Unlock()
s.noteSubscriberGone(n)
}()
for _, ev := range s.snapshot() {
if err := writeSSE(w, ev); err != nil {
return
}
}
flusher.Flush()
ticker := time.NewTicker(sseKeepalive)
defer ticker.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ticker.C:
if _, err := fmt.Fprint(w, ": keepalive\n\n"); err != nil {
return
}
flusher.Flush()
case ev := <-ch:
if err := writeSSE(w, ev); err != nil {
return
}
flusher.Flush()
}
}
}
func writeSSE(w http.ResponseWriter, ev sseEvent) error {
b, err := json.Marshal(ev.data)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev.name, b)
return err
}
func (s *server) handlePick(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
var req struct {
Index int `json:"index"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
s.mu.Lock()
cur := s.currentRoundLocked()
var v variant
ok := false
if cur != nil {
v, ok = cur.Variants[req.Index]
}
s.mu.Unlock()
if !ok || v.Err != nil {
http.Error(w, "no such variant", http.StatusNotFound)
return
}
if err := copyToSelections(v.Text); err != nil {
logf("pick %d: %s", req.Index, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logf("picked round %d variant %d (%d chars)", cur.Number, req.Index, len(v.Text))
// Deliberately no shutdown here: the window stays open, you may pick a
// different variant, and the server goes away on its own once you close it.
w.WriteHeader(http.StatusNoContent)
}
// handleRefine starts a new round from one of the current variants plus an
// instruction for changing it.
func (s *server) handleRefine(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
var req struct {
Index int `json:"index"`
Instruction string `json:"instruction"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
req.Instruction = strings.TrimSpace(req.Instruction)
if req.Instruction == "" {
http.Error(w, "empty instruction", http.StatusBadRequest)
return
}
s.mu.Lock()
// Checked server-side as well as in the page: a browser that reconnected
// mid-round has stale state and could offer a button it should not.
if s.busy {
s.mu.Unlock()
http.Error(w, "a round is already generating", http.StatusConflict)
return
}
cur := s.currentRoundLocked()
var chosen variant
ok := false
if cur != nil {
chosen, ok = cur.Variants[req.Index]
}
if !ok || chosen.Err != nil {
s.mu.Unlock()
http.Error(w, "no such variant", http.StatusNotFound)
return
}
if s.image == nil {
s.mu.Unlock()
http.Error(w, "no image to refine against", http.StatusConflict)
return
}
s.busy = true
// The chosen text and the instruction are folded into the running
// conversation now, so the next refinement builds on this one too.
s.history = appendTurn(s.history, chosen.Text, req.Instruction)
history := s.history
s.mu.Unlock()
apiKey, err := resolveAPIKey()
if err != nil {
s.mu.Lock()
s.busy = false
s.mu.Unlock()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logf("refining round %d variant %d: %q", cur.Number, req.Index, req.Instruction)
// Detached from the request context on purpose: the round must survive the
// POST returning, and it is the browser closing the *event stream*, not
// this request, that means nobody is watching any more.
go s.runRound(context.Background(), apiKey, history, req.Instruction)
w.WriteHeader(http.StatusAccepted)
}
// handleRegenerate starts a fresh conversation from the image and the prompt
// the page sends, discarding everything that came before.
//
// This is deliberately not a variety of refinement. Refining is a
// conversation: it needs a chosen variant, and it accumulates, so a chain of
// them drifts away from the image. Regenerating throws the conversation away
// and asks the original question again with a different brief, which is why it
// needs no pick, works while nothing has been chosen, and cannot drift.
func (s *server) handleRegenerate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
var req struct {
Prompt string `json:"prompt"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
req.Prompt = strings.TrimSpace(req.Prompt)
// An empty prompt would send the image with no instruction at all, which
// gets a chatty description rather than alt text. Refuse instead of
// silently substituting the default: the field would then disagree with
// what was actually sent.
if req.Prompt == "" {
http.Error(w, "empty prompt", http.StatusBadRequest)
return
}
s.mu.Lock()
if s.busy {
s.mu.Unlock()
http.Error(w, "a round is already generating", http.StatusConflict)
return
}
if s.image == nil {
// Either the clipboard read failed (in which case a fatal is already on
// screen) or the first round has not got that far yet.
s.mu.Unlock()
http.Error(w, "no image to caption", http.StatusConflict)
return
}
s.busy = true
s.prompt = req.Prompt
// The whole point: history is rebuilt rather than extended, so no earlier
// instruction and no earlier wording survives into the new round.
s.history = initialHistory(s.image, s.imageMime, req.Prompt)
history := s.history
s.mu.Unlock()
apiKey, err := resolveAPIKey()
if err != nil {
s.mu.Lock()
s.busy = false
s.mu.Unlock()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logf("regenerating with prompt: %q", req.Prompt)
// Echoed back so that every connected page (and this one, after a reload)
// agrees on the prompt now in force.
s.broadcast(sseEvent{name: "prompt", data: map[string]string{
"prompt": req.Prompt,
"default": defaultAltTextPrompt,
}})
// Detached from the request context for the same reason as a refinement:
// the round outlives the POST.
go s.runRound(context.Background(), apiKey, history, "")
w.WriteHeader(http.StatusAccepted)
}
// noteSubscriberArrived cancels a pending idle shutdown: the window is (still)
// open.
func (s *server) noteSubscriberArrived() {
s.mu.Lock()
defer s.mu.Unlock()
if s.idleTimer != nil {
s.idleTimer.Stop()
s.idleTimer = nil
logf("idle timer cancelled (client connected)")
}
}
// noteSubscriberGone arms the idle shutdown once the last page has gone away.
//
// On suspend: Go timers run on CLOCK_MONOTONIC, which does not advance while
// the machine is suspended. A timer armed before suspend therefore has the same
// remaining time on resume, and cannot fire "during" the sleep. That is what we
// want here — suspending with the window closed keeps the process alive across
// the sleep and it exits a minute after you come back, rather than the timeout
// silently elapsing while the laptop is in a bag. Do not switch this to
// wall-clock deadlines.
func (s *server) noteSubscriberGone(remaining int) {
if remaining > 0 {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.idleTimer != nil {
s.idleTimer.Stop()
}
logf("no clients, exiting in %s unless one reconnects", s.idleTimeout)
s.idleTimer = time.AfterFunc(s.idleTimeout, func() {
logf("idle for %s, shutting down", s.idleTimeout)
s.shutdown()
})
}
// resolveAPIKey prefers the environment and falls back to the password store.
func resolveAPIKey() (string, error) {
if key := os.Getenv("GEMINI_API_KEY"); key != "" {
return key, nil
}
key, err := apiKeyFromPass()
if err != nil {
return "", fmt.Errorf("GEMINI_API_KEY not set and pass failed: %w", err)
}
return key, nil
}
// runRound generates one batch of variants from history and clears the busy
// flag when it is finished. It owns s.busy for its whole lifetime; callers set
// it before starting the goroutine so that two rounds cannot be admitted in the
// gap before this begins.
func (s *server) runRound(ctx context.Context, apiKey string, history []content, instruction string) {
r := s.startRound(instruction)
defer func() {
s.mu.Lock()
s.busy = false
s.mu.Unlock()
}()
t := time.Now()
generateVariants(ctx, apiKey, history, func(v variant) { s.addVariant(r, v) })
logf("round %d complete: %s", r.Number, time.Since(t).Round(time.Millisecond))
s.setDone(r)
}
// run performs the initial work: grab the clipboard image, convert it, and fan
// out the first round. It runs in the background so the page is servable
// immediately and errors can be shown in the browser instead of only landing in
// the journal.
func (s *server) run(ctx context.Context) {
// Releases the flag serve() set on our behalf if we bail out before
// runRound takes over; clearing it twice is harmless.
defer func() {
s.mu.Lock()
s.busy = false
s.mu.Unlock()
}()
apiKey, err := resolveAPIKey()
if err != nil {
s.setFatal(err)
return
}
t0 := time.Now()
imageBytes, mime, err := readImageFromClipboard()
if err != nil {
s.setFatal(err)
return
}
logf("clipboard read: %s (%s, %d KB)", time.Since(t0).Round(time.Millisecond), mime, len(imageBytes)/1024)
t1 := time.Now()
webpBytes, err := convertToWebP(imageBytes)
if err != nil {
s.setFatal(err)
return
}
logf("webp convert: %s (%d KB → %d KB)", time.Since(t1).Round(time.Millisecond), len(imageBytes)/1024, len(webpBytes)/1024)
s.setImage(webpBytes, "image/webp")
s.mu.Lock()
// s.prompt, not the constant. It still holds the default here — the busy
// flag is set for this whole first round, so no regeneration can have
// changed it yet — but reading it keeps one source of truth for "the
// prompt this history was built from" rather than two that agree by
// accident.
s.history = initialHistory(webpBytes, "image/webp", s.prompt)
history := s.history
s.mu.Unlock()
s.runRound(ctx, apiKey, history, "")
logf("first round total: %s", time.Since(t0).Round(time.Millisecond))
}
func serve(addr string, idleTimeout time.Duration) error {
s := newServer(idleTimeout)
ln, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("listen %s: %w", addr, err)
}
logf("listening on http://%s", ln.Addr())
httpSrv := &http.Server{
Handler: s.Handler(),
// No WriteTimeout or IdleTimeout: both would kill a healthy SSE stream,
// which by design stays open and mostly silent for as long as the
// window is up. ReadHeaderTimeout is safe and guards against a stuck
// connection holding a goroutine.
ReadHeaderTimeout: 10 * time.Second,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var once sync.Once
s.shutdown = func() {
once.Do(func() {
cancel()
shutCtx, shutCancel := context.WithTimeout(context.Background(), 3*time.Second)
defer shutCancel()
_ = httpSrv.Shutdown(shutCtx)
})
}
// Publish the port *before* reporting readiness. systemctl restart returns
// on the readiness notification, so this ordering is what lets the launcher
// read the file immediately afterwards and be certain it is this run's.
if err := writePortFile(ln.Addr().String()); err != nil {
return fmt.Errorf("publish port: %w", err)
}
defer os.Remove(portFile())
// systemctl stop sends SIGTERM, which by default kills the process outright
// and skips the deferred cleanup above, leaving a port file pointing at a
// server that is gone. Shut down gracefully instead so it is removed.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigCh
logf("signal received, shutting down")
s.shutdown()
}()
// Tell systemd we are accepting connections. The launcher relies on
// `systemctl restart` having returned before it starts the browser, so
// there is no retry loop on the chromium side.
notifyReady()
// Arm the idle timer up front: if the browser never manages to connect we
// must still go away rather than linger forever.
s.noteSubscriberGone(0)
// Marked busy before the goroutine starts, so a refine arriving during the
// first round is rejected rather than racing it.
s.mu.Lock()
s.busy = true
s.mu.Unlock()
go s.run(ctx)
if err := httpSrv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}
func logf(format string, args ...any) {
log.Printf(format, args...)
}
|