thinkpool-pair 0.7.71 → 0.7.72

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.
Files changed (3) hide show
  1. package/bridge.mjs +77 -5
  2. package/event-id.mjs +20 -0
  3. package/package.json +1 -1
package/bridge.mjs CHANGED
@@ -39,7 +39,7 @@ import { createClient } from '@supabase/supabase-js'
39
39
  import { startClaudeSession } from './claude-session.mjs'
40
40
  import { turnInFlight } from './update-gate.mjs'
41
41
  import { saveSession, flushSession, deleteSession, loadAll, canResume, loadPtyId, savePtyId, loadNames, saveNames } from './session-store.mjs'
42
- import { stampEvent, makeSeqCounter, maxSeq, seqable, capReplayEvents, chunkReplayEvents, boundEventForBroadcast } from './event-id.mjs'
42
+ import { stampEvent, makeSeqCounter, maxSeq, seqable, capReplayEvents, chunkReplayEvents, boundEventForBroadcast, inlineImageBlocks } from './event-id.mjs'
43
43
  import { makeThrottledTrack } from './presence.mjs'
44
44
 
45
45
  // Public client creds (the same anon values the web app ships — safe to embed).
@@ -629,6 +629,64 @@ const ownerOutbox = (kind, id) => path.join(MOCKUP_OUTBOX, kind, id)
629
629
  // back to the old "first live session/terminal" heuristic for it alone.
630
630
  watchOutbox(MOCKUP_OUTBOX, () => [...sessions.keys()][0] || attachedId || [...terms.keys()][0])
631
631
 
632
+ // ── agent image hand-off ───────────────────────────────────────────
633
+ // A screenshot the agent produces arrives as a tool_result whose content carries
634
+ // an inline base64 image (100-600KB+). That overflows Realtime's broadcast frame —
635
+ // it can ride neither a live `code-event` nor a replay (boundEventForBroadcast
636
+ // strips it to a text placeholder so delivery survives). So BEFORE the event is
637
+ // logged/broadcast we lift each image OUT: upload the bytes to Storage (mirrors the
638
+ // mockup path → /api/code-image, service-key write) and rewrite the block to a tiny
639
+ // { type:'image', path } ref. The persisted log + every replay then carry the path,
640
+ // never base64; the web client mints a signed URL on render (structured.jsx, same
641
+ // as the mockup thumbs). Spec: docs/specs/2026-06-26-code-agent-images.md
642
+ async function uploadCodeImage(term, cid, im) {
643
+ const headers = { 'Content-Type': 'application/json' }
644
+ if (codeAuthToken) headers.Authorization = `Bearer ${codeAuthToken}`
645
+ const res = await fetch(`${WEB_BASE}/api/code-image`, {
646
+ method: 'POST',
647
+ headers,
648
+ body: JSON.stringify({ code: room, term, cid, idx: im.idx, mediaType: im.mediaType, b64: im.b64 }),
649
+ })
650
+ if (!res.ok) throw new Error(`code-image ${res.status}`)
651
+ const { path } = await res.json()
652
+ if (!path) throw new Error('code-image: no path')
653
+ return path
654
+ }
655
+ // Defer an image-bearing tool_result behind a per-session upload chain (preserves
656
+ // arrival order among images), then log + broadcast the URL-only event through the
657
+ // normal path. pushLog is the single seq-assignment point, so the deferred event
658
+ // still gets a contiguous seq at chain-resolution time; its ts was stamped at
659
+ // arrival, so it sorts into place. On upload failure the block degrades to the same
660
+ // render-safe text placeholder — base64 is NEVER logged, broadcast, or persisted.
661
+ function deferImageEvent(entry, id, evt, imgs, emitTail) {
662
+ entry.imageChain = (entry.imageChain || Promise.resolve()).then(async () => {
663
+ for (const im of imgs) {
664
+ try {
665
+ const path = await uploadCodeImage(id, evt.cid, im)
666
+ evt.content[im.idx] = { type: 'image', path, mediaType: im.mediaType }
667
+ } catch (e) {
668
+ process.stderr.write(`\n ◇ screenshot upload failed (${e?.message || e}).\n`)
669
+ evt.content[im.idx] = { type: 'text', text: '[screenshot omitted — upload failed]' }
670
+ }
671
+ }
672
+ emitTail(evt)
673
+ }).catch(() => {})
674
+ }
675
+ // Fire-and-forget: drop a closed term's screenshots from Storage so they don't
676
+ // outlive the room (COGS). Per-term scope — never touches a sibling term's images.
677
+ function fireImageCleanup(term) {
678
+ if (!term) return
679
+ try {
680
+ const headers = { 'Content-Type': 'application/json' }
681
+ if (codeAuthToken) headers.Authorization = `Bearer ${codeAuthToken}`
682
+ fetch(`${WEB_BASE}/api/code-image-cleanup`, {
683
+ method: 'POST',
684
+ headers,
685
+ body: JSON.stringify({ code: room, term }),
686
+ }).catch(() => { /* best-effort — the TTL sweep mops up orphans */ })
687
+ } catch { /* noop */ }
688
+ }
689
+
632
690
  // ── shared-PTY geometry ───────────────────────────────────────────
633
691
  // The attached PTY is CAPPED at 120×32, never pinned (2026-06-11).
634
692
  // Mangling physics: a PTY *wider/taller* than the host's window forces
@@ -851,10 +909,23 @@ function openStructured({ id, model, resume, log, commands, mode }) {
851
909
  entry.compacting = false
852
910
  bcast('code-event', { term: id, evt: { kind: 'compact', status: 'done', ts: Date.now() } })
853
911
  }
854
- if (!chrome) pushLog(entry, evt)
855
- bcast('code-event', { term: id, evt })
856
- printLocal(evt)
857
- if (!chrome) persist()
912
+ // Single tail: stamp into the log (transcript kinds only), broadcast live,
913
+ // print locally, persist. Shared so a deferred image event re-enters it once
914
+ // its base64 has been lifted to a Storage path (see deferImageEvent).
915
+ const emitTail = (e) => {
916
+ if (!chrome) pushLog(entry, e)
917
+ bcast('code-event', { term: id, evt: e })
918
+ printLocal(e)
919
+ if (!chrome) persist()
920
+ }
921
+ // A tool_result carrying an inline base64 image can't ride a broadcast frame
922
+ // (live OR replay). Lift it to Storage FIRST, then emit the URL-only event —
923
+ // so the persisted log + replay carry a path, never base64. Order/seq stay
924
+ // intact: pushLog (inside emitTail) is the single seq point, called when the
925
+ // upload resolves. Other kinds emit synchronously, unchanged.
926
+ const imgs = inlineImageBlocks(evt)
927
+ if (imgs.length) { deferImageEvent(entry, id, evt, imgs, emitTail); return }
928
+ emitTail(evt)
858
929
  },
859
930
  requestPermission: (req) => new Promise((resolve) => {
860
931
  // Keep the broadcast payload with the resolver so a reconnect can re-send it
@@ -902,6 +973,7 @@ function endStructured(id) {
902
973
  try { s.mockupWatcher?.close() } catch { /* noop */ }
903
974
  sessions.delete(id)
904
975
  bcast('term-exit', { id })
976
+ fireImageCleanup(id) // drop this term's screenshots from Storage (COGS)
905
977
  }
906
978
  deleteSession(room, id) // remove <id>.json so loadAll() won't bring it back
907
979
  if (s) announce()
package/event-id.mjs CHANGED
@@ -157,3 +157,23 @@ export function boundEventForBroadcast(evt, cap = PER_EVENT_CAP) {
157
157
  out._bounded = true
158
158
  return out
159
159
  }
160
+
161
+ // Detect inline base64 IMAGE blocks on a tool_result event (a screenshot the agent
162
+ // produced — content:[{type:'image', source:{type:'base64', media_type, data}}]).
163
+ // Returns [{ idx, b64, mediaType }] per base64 image block, or [] when none. Pure +
164
+ // import-safe so bridge/test-seq.mjs can exercise it. The bridge uses this to lift
165
+ // images OUT of the event (upload to Storage, swap to a {type:'image', path} ref)
166
+ // BEFORE the base64 ever enters the persisted log or a broadcast frame — so a
167
+ // screenshot renders live AND in replay instead of being stripped to a placeholder
168
+ // by boundEventForBroadcast (which stays the fallback for any block we don't lift).
169
+ export function inlineImageBlocks(evt) {
170
+ if (!evt || evt.kind !== 'tool_result' || !Array.isArray(evt.content)) return []
171
+ const out = []
172
+ evt.content.forEach((b, idx) => {
173
+ if (b && b.type === 'image' && b.source && b.source.type === 'base64' &&
174
+ typeof b.source.data === 'string' && b.source.data.length) {
175
+ out.push({ idx, b64: b.source.data, mediaType: b.source.media_type || 'image/png' })
176
+ }
177
+ })
178
+ return out
179
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "thinkpool-pair",
3
- "version": "0.7.71",
3
+ "version": "0.7.72",
4
4
  "description": "Share a local coding-agent CLI (Claude Code, Codex, Gemini, Aider, …) into a ThinkPool Code room, live.",
5
5
  "type": "module",
6
6
  "bin": {