Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

Sync: handle relay refusal frames — break the doomed-op resend loop

nyblnet3dd876c27349
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index afb72e37..bab1cb07 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -106,6 +106,10 @@ export class Editor {
}
known = now
})
+ // the relay refused something (too big, room full, throttled) — the user
+ // needs to know, because for the permanent codes their change stays in
+ // this copy and never reaches anyone else
+ session.onNotice((n) => this.toast(syncNoticeText(n)))
this.canvas.onTextEditChange = (elId) => session.setEditing(elId)
this.store.on('current', () => this.canvas.setRemotePeers(session.peers()))
// a document that carries collab config joins its relay session — at
@@ -2162,6 +2166,27 @@ export class Editor {
}
}
+/**
+ * Turn a relay refusal into a sentence. Honest about the consequence: for the
+ * permanent codes the change lives on in THIS copy only — collaborators will
+ * never receive it, and no later sync repairs that. Built at display time
+ * because t() must never be frozen into a module-level const.
+ */
+function syncNoticeText(n: import('../sync/session').SyncNotice): string {
+ switch (n.code) {
+ case 'too-large':
+ return n.media
+ ? t('That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.')
+ : t('That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.')
+ case 'room-full':
+ return t('This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.')
+ case 'storage-failed':
+ return t('The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.')
+ case 'rate-limited':
+ return t('Too many changes at once — live sync is catching up.')
+ }
+}
+
/** Deep-clone an element with a fresh id (same-slide duplicates must not share ids). */
function cloneElement(el: SlideElement): SlideElement {
return { ...JSON.parse(JSON.stringify(el)), id: uid(el.type[0]), x: el.x + 24, y: el.y + 24 }
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 099de056..273543ad 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const de: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Dieses Bild ist zu groß für die Live-Freigabe (max. etwa 1 MB). Es ist in deiner Kopie gespeichert, aber Mitarbeitende sehen es nicht.",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Diese Änderung ist zu groß für die Live-Freigabe (max. etwa 1 MB). Sie ist in deiner Kopie gespeichert, aber Mitarbeitende sehen sie nicht.",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "Diese Live-Sitzung hat keinen Platz mehr. Deine Änderung ist in deiner Kopie gespeichert, aber Mitarbeitende sehen sie nicht.",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "Die Live-Sitzung konnte diese Änderung nicht speichern. Sie ist in deiner Kopie gespeichert, aber Mitarbeitende sehen sie nicht.",
+ "Too many changes at once — live sync is catching up.": "Zu viele Änderungen auf einmal — die Live-Synchronisierung holt auf.",
"Backdrop": "Hintergrund",
"Blend": "Mischmodus",
"Outline": "Kontur",
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index b17d22a0..3ca94e88 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const es: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Esa imagen es demasiado grande para compartirla en vivo (máx. 1 MB aprox.). Se guarda en tu copia, pero los colaboradores no la verán.",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Ese cambio es demasiado grande para compartirlo en vivo (máx. 1 MB aprox.). Se guarda en tu copia, pero los colaboradores no lo verán.",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "Esta sesión en vivo se ha quedado sin espacio. Tu cambio se guarda en tu copia, pero los colaboradores no lo verán.",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "La sesión en vivo no pudo guardar ese cambio. Se guarda en tu copia, pero los colaboradores no lo verán.",
+ "Too many changes at once — live sync is catching up.": "Demasiados cambios a la vez — la sincronización en vivo se está poniendo al día.",
"Backdrop": "Fondo",
"Blend": "Fusión",
"Outline": "Contorno",
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index 9ee9f26c..e40cca02 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const fr: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Cette image est trop volumineuse pour le partage en direct (environ 1 Mo max). Elle est enregistrée dans votre copie, mais les collaborateurs ne la verront pas.",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Cette modification est trop volumineuse pour le partage en direct (environ 1 Mo max). Elle est enregistrée dans votre copie, mais les collaborateurs ne la verront pas.",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "Cette session en direct n’a plus de place. Votre modification est enregistrée dans votre copie, mais les collaborateurs ne la verront pas.",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "La session en direct n’a pas pu enregistrer cette modification. Elle est enregistrée dans votre copie, mais les collaborateurs ne la verront pas.",
+ "Too many changes at once — live sync is catching up.": "Trop de modifications à la fois — la synchronisation en direct rattrape son retard.",
"Backdrop": "Arrière-plan",
"Blend": "Fusion",
"Outline": "Contour",
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index a8e42a7c..c54299cc 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const it: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Questa immagine è troppo grande per la condivisione dal vivo (circa 1 MB max). È salvata nella tua copia, ma i collaboratori non la vedranno.",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "Questa modifica è troppo grande per la condivisione dal vivo (circa 1 MB max). È salvata nella tua copia, ma i collaboratori non la vedranno.",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "Questa sessione dal vivo ha esaurito lo spazio. La tua modifica è salvata nella tua copia, ma i collaboratori non la vedranno.",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "La sessione dal vivo non è riuscita a salvare questa modifica. È salvata nella tua copia, ma i collaboratori non la vedranno.",
+ "Too many changes at once — live sync is catching up.": "Troppe modifiche insieme — la sincronizzazione dal vivo sta recuperando.",
"Backdrop": "Sfondo",
"Blend": "Fusione",
"Outline": "Contorno",
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index ca617c9d..09443646 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const ja: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "この画像はライブ共有には大きすぎます(上限は約 1 MB)。自分のコピーには保存されますが、共同編集者には表示されません。",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "この変更はライブ共有には大きすぎます(上限は約 1 MB)。自分のコピーには保存されますが、共同編集者には表示されません。",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "このライブセッションの容量がいっぱいです。変更は自分のコピーに保存されますが、共同編集者には表示されません。",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "ライブセッションがこの変更を保存できませんでした。自分のコピーには保存されますが、共同編集者には表示されません。",
+ "Too many changes at once — live sync is catching up.": "変更が多すぎます — ライブ同期が追いついています。",
"Backdrop": "背景ぼかし",
"Blend": "描画モード",
"Outline": "縁取り",
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index 59ba00a8..d577cee8 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const zhHans: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "该图片过大,无法实时共享(上限约 1 MB)。它已保存在你的副本中,但协作者不会看到。",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "该更改过大,无法实时共享(上限约 1 MB)。它已保存在你的副本中,但协作者不会看到。",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "此实时会话空间已满。你的更改已保存在你的副本中,但协作者不会看到。",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "实时会话无法保存该更改。它已保存在你的副本中,但协作者不会看到。",
+ "Too many changes at once — live sync is catching up.": "更改过多 — 实时同步正在追赶。",
"Backdrop": "背景模糊",
"Blend": "混合模式",
"Outline": "描边",
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index 1d51a687..3e27c65c 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -4,6 +4,11 @@
import type { Catalog } from '../i18n'
export const zhHant: Catalog = {
+ "That image is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "此圖片太大,無法即時共用(上限約 1 MB)。它已儲存在你的副本中,但協作者不會看到。",
+ "That change is too large to share live (about 1 MB max). It’s saved in your copy, but collaborators won’t see it.": "此變更太大,無法即時共用(上限約 1 MB)。它已儲存在你的副本中,但協作者不會看到。",
+ "This live session has run out of room. Your change is saved in your copy, but collaborators won’t see it.": "此即時工作階段空間已滿。你的變更已儲存在你的副本中,但協作者不會看到。",
+ "The live session couldn’t store that change. It’s saved in your copy, but collaborators won’t see it.": "即時工作階段無法儲存此變更。它已儲存在你的副本中,但協作者不會看到。",
+ "Too many changes at once — live sync is catching up.": "變更太多 — 即時同步正在追趕。",
"Backdrop": "背景模糊",
"Blend": "混合模式",
"Outline": "外框",
diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.ts
index 0057f725..5fbff1e2 100644
--- a/slides/src/sync/online.ts
+++ b/slides/src/sync/online.ts
@@ -12,8 +12,8 @@
import type { Store } from '../store'
import type { BentoDoc } from '../model'
-import type { SyncStateJSON } from './crdt'
-import type { Frame, SyncSession, Transport } from './session'
+import type { Op, SyncStateJSON } from './crdt'
+import type { Frame, RefusalCode, SyncSession, Transport } from './session'
import { offlineEnabled } from '../update'
export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'
@@ -150,6 +150,24 @@ export function syncHost(): string {
export type OnlineStatus = 'connecting' | 'open' | 'closed'
+/** A frame written to (or parked for) the relay. `ops` is set for persisted op
+ * batches — the only frames the relay acks, and the only ones whose refusal
+ * has to reach the session (an unsendable op must leave the resend log). */
+type Outbound = { text: string; ops: Op[] | null; bytes: number; tries: number }
+
+/** `{ctl:'refused'}` from the relay. No frame id: the sizes are the only
+ * evidence of WHICH frame it names (see matchRefused). */
+type RefusedEnv = {
+ code?: string
+ /** too-large: the relay's ceiling and the frame length it measured */
+ max?: number
+ got?: number
+ /** storage-failed: i.length + d.length of the frame it tried to store */
+ bytes?: number
+ /** rate-limited: how long until the socket's byte window rolls over */
+ retryInMs?: number
+}
+
export class OnlineTransport implements Transport {
readonly kind = 'online'
status: OnlineStatus = 'connecting'
@@ -158,7 +176,19 @@ export class OnlineTransport implements Transport {
private key: CryptoKey | null = null
/** writer signing key — null for readers (they can decrypt but not author). */
private signKey: CryptoKey | null = null
- private queue: string[] = []
+ private queue: Outbound[] = []
+ /** persisted frames written but not yet acked. The relay handles one
+ * socket's frames in order and acks every stored one, so the head of this
+ * list is the frame a `refused` reply is talking about. Purely a
+ * correlation window — delivery is still guaranteed by the log + `need`. */
+ private awaitingAck: Outbound[] = []
+ /** rate-limit backoff deadline: sending into a refusing relay only burns the
+ * next window too, so frames park until it passes */
+ private paused = false
+ private pauseTimer: ReturnType<typeof setTimeout> | null = null
+ private lastLimitNotice = 0
+ private static readonly ACK_WINDOW = 64
+ private static readonly MAX_RETRIES = 4
private closed = false
private backoff = 800
private url = ''
@@ -190,6 +220,9 @@ export class OnlineTransport implements Transport {
onOpen: () => void
/** replay done: (actor,seq) pairs the room holds; return true to upload a snapshot */
onReady: (seen: Set<string>, seq: number) => boolean
+ /** the relay refused a frame; `ops` are the ones it will never accept
+ * (null when the refusal couldn't be pinned to a frame we sent) */
+ onRefused?: (code: RefusalCode, ops: Op[] | null) => void
},
private auth?: AuthSpec,
) {
@@ -262,8 +295,12 @@ export class OnlineTransport implements Transport {
this.backoff = 800
this.inReplay = true
this.replaySeen = new Set()
+ // acks don't survive the socket: whatever was un-acked is unknowable now,
+ // and a stale entry would mis-name a later refusal. Delivery of those ops
+ // is the log's job anyway (session.onRelayReady re-sends what the room lacks).
+ this.awaitingAck = []
this.setStatus('open')
- for (const text of this.queue.splice(0)) ws.send(text)
+ for (const out of this.queue.splice(0)) this.write(out)
this.startHeartbeat(ws)
this.hooks.onOpen()
}
@@ -310,8 +347,105 @@ export class OnlineTransport implements Transport {
this.backoff = Math.min(this.backoff * 1.8, 30000)
}
+ // --- refusals -------------------------------------------------------------
+
+ /**
+ * The relay refused a frame. Handling this is not optional politeness: when
+ * the relay dropped oversize/over-quota frames SILENTLY, the sender got no
+ * ack, the peer stayed behind, its `need`/vv catch-up asked for the very
+ * same op, and the sender re-sent the identical doomed frame forever.
+ *
+ * 'rate-limited' is transient — back off and retry. Everything else is
+ * permanent for that frame: it goes up to the session, which forgets the ops
+ * so the loop cannot restart, and tells the user what they just lost.
+ */
+ private handleRefusal(env: RefusedEnv) {
+ if (env.code === 'rate-limited') {
+ this.throttle(typeof env.retryInMs === 'number' ? env.retryInMs : 10_000)
+ return
+ }
+ if (env.code !== 'too-large' && env.code !== 'storage-failed' && env.code !== 'room-full') {
+ // a code from a newer relay: no recovery we can invent is better than
+ // leaving the op in the log, where `need` will retry it honestly
+ console.warn('[bento-sync] relay refused a frame:', env.code)
+ return
+ }
+ const culprit = this.matchRefused(env)
+ if (culprit) this.awaitingAck = this.awaitingAck.filter((o) => o !== culprit)
+ console.warn(`[bento-sync] relay refused a frame (${env.code})`, env)
+ this.hooks.onRefused?.(env.code, culprit?.ops ?? null)
+ }
+
+ /**
+ * Which frame does this refusal name? The relay quotes no id, so: head of
+ * the ack queue by protocol order, CONFIRMED against the size it reported.
+ * A mismatch means the refusal was for a frame we don't track — snapshots
+ * are never acked, so they never enter the queue — and we must not hand the
+ * session somebody else's ops to drop on a guess. Ambiguity → null → the
+ * ops stay in the log (retried, at worst refused again and reported again),
+ * because a wrong drop is silent permanent data divergence.
+ */
+ private matchRefused(env: RefusedEnv): Outbound | null {
+ // too-large measures the whole envelope; storage-failed measures i+d only
+ const byText = typeof env.got === 'number'
+ const want = byText ? env.got! : typeof env.bytes === 'number' ? env.bytes : null
+ const size = (o: Outbound) => (byText ? o.text.length : o.bytes)
+ const head = this.awaitingAck[0] ?? null
+ if (want === null) return head // room-full carries no size — order is all we have
+ if (head && size(head) === want) return head
+ return this.awaitingAck.find((o) => size(o) === want) ?? null
+ }
+
+ /** Rate limited: hold everything for the window, then replay what we sent
+ * into it. Un-acked frames may or may not have landed — re-sending is safe
+ * (the CRDT dedups by actor:seq) and losing them silently is not. */
+ private throttle(ms: number) {
+ const wait = Math.min(Math.max(ms, 1000), 60_000)
+ const retryable = this.awaitingAck.filter((o) => ++o.tries <= OnlineTransport.MAX_RETRIES)
+ // past the retry cap we stop re-sending, but the op is NOT dropped: it
+ // stays in the session log for the next `need`/reconnect to carry.
+ this.awaitingAck = []
+ this.queue = [...retryable, ...this.queue]
+ if (this.pauseTimer) clearTimeout(this.pauseTimer)
+ this.paused = true
+ this.pauseTimer = setTimeout(() => {
+ this.pauseTimer = null
+ this.paused = false
+ for (const out of this.queue.splice(0)) this.write(out)
+ }, wait)
+ // transient and self-healing, so say it at most once a minute
+ const now = Date.now()
+ if (now - this.lastLimitNotice > 60_000) {
+ this.lastLimitNotice = now
+ this.hooks.onRefused?.('rate-limited', null)
+ }
+ }
+
+ /** write now, or park it (disconnected, or inside a rate-limit backoff) */
+ private write(out: Outbound) {
+ if (!this.paused && this.ws && this.ws.readyState === WebSocket.OPEN) {
+ try {
+ this.ws.send(out.text)
+ } catch {
+ this.park(out) // send threw → onclose will reconnect and flush
+ return
+ }
+ if (out.ops) {
+ this.awaitingAck.push(out)
+ if (this.awaitingAck.length > OnlineTransport.ACK_WINDOW) this.awaitingAck.shift()
+ }
+ return
+ }
+ this.park(out)
+ }
+
+ private park(out: Outbound) {
+ this.queue.push(out)
+ if (this.queue.length > 500) this.queue.shift()
+ }
+
private async onEnvelope(text: string) {
- let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string; p?: string }
+ let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string; p?: string } & RefusedEnv
try {
env = JSON.parse(text)
} catch {
@@ -326,7 +460,15 @@ export class OnlineTransport implements Transport {
}
return
}
+ // the relay would not take a frame and said so (v1.0.9 relay and later;
+ // older relays never send this, which is why every path here is additive)
+ if (env.ctl === 'refused') {
+ this.handleRefusal(env)
+ return
+ }
if (env.ctl === 'ack' || env.ctl === 'ready') {
+ // one ack = the oldest un-acked persisted frame landed
+ if (env.ctl === 'ack') this.awaitingAck.shift()
if (typeof env.q === 'number') {
this.saveSeq(env.q)
this.maybeSnapshot(env.q)
@@ -410,22 +552,21 @@ export class OnlineTransport implements Transport {
const enc = await this.encrypt(JSON.stringify(frame))
if (!enc) return
let env: Record<string, unknown> = enc
+ let ops: Op[] | null = null
if (frame.t === 'ops') {
env = { p: 1, ...enc }
// sign the ciphertext so the relay verifies authorship while blind.
if (this.signKey) env.g = await signFrame(this.signKey, enc.i, enc.d)
+ ops = frame.ops
}
- const text = JSON.stringify(env)
- if (this.ws && this.ws.readyState === WebSocket.OPEN) this.ws.send(text)
- else {
- this.queue.push(text)
- if (this.queue.length > 500) this.queue.shift()
- }
+ // remember what rode in the frame: a refusal names it only by size
+ this.write({ text: JSON.stringify(env), ops, bytes: enc.i.length + enc.d.length, tries: 0 })
})()
}
close() {
this.closed = true
+ if (this.pauseTimer) { clearTimeout(this.pauseTimer); this.pauseTimer = null }
this.stopHeartbeat()
this.ws?.close()
this.ws = null
@@ -497,6 +638,7 @@ export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport
getSnapshot: () => session.snapshot(),
onOpen: () => session.hello(),
onReady: (seen) => session.onRelayReady(seen),
+ onRefused: (code, ops) => session.refused(code, ops),
}, auth)
return active
})
diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.ts
index 9e5308c1..807e8b6a 100644
--- a/slides/src/sync/session.ts
+++ b/slides/src/sync/session.ts
@@ -68,6 +68,28 @@ export interface Transport {
close(): void
}
+/**
+ * Why the relay refused a frame (`{ctl:'refused', code, …}` — see
+ * server/sync-worker). Everything but 'rate-limited' is PERMANENT for the
+ * frame that drew it: retrying can only reproduce the refusal.
+ */
+export type RefusalCode = 'too-large' | 'storage-failed' | 'room-full' | 'rate-limited'
+
+/**
+ * Something the user deserves to know about the live session. The transport
+ * detects it, the session records the consequence, the editor renders the
+ * sentence (t() must run at display time, so no text crosses this boundary).
+ */
+export interface SyncNotice {
+ code: RefusalCode
+ /** true = the change will never reach collaborators; false = retrying */
+ permanent: boolean
+ /** how many ops were abandoned (0 when the refused frame wasn't ours to name) */
+ ops: number
+ /** the abandoned ops carried embedded media — lets the UI say "that image" */
+ media?: boolean
+}
+
/** Same-machine transport: every open tab/window of this document. */
class BroadcastTransport implements Transport {
readonly kind = 'local'
@@ -118,6 +140,7 @@ export class SyncSession {
private diffTimer: number | null = null
private heartbeat: number | null = null
private peerListeners = new Set<() => void>()
+ private noticeListeners = new Set<(n: SyncNotice) => void>()
private editingEl: string | undefined
/** extra transports (the online relay) get plugged in here */
private makeExtraTransports: Array<(docId: string, onFrame: (f: Frame) => void) => Transport> = []
@@ -415,6 +438,46 @@ export class SyncSession {
this.peerListeners.forEach((fn) => fn())
}
+ // --- relay refusals -------------------------------------------------------
+
+ /** the editor subscribes here to toast what the relay refused */
+ onNotice(fn: (n: SyncNotice) => void): () => void {
+ this.noticeListeners.add(fn)
+ return () => this.noticeListeners.delete(fn)
+ }
+
+ private emitNotice(n: SyncNotice) {
+ this.noticeListeners.forEach((fn) => fn(n))
+ }
+
+ /**
+ * A transport reports that the relay refused a frame. For the PERMANENT
+ * codes the named ops can never be delivered, so they leave the resend log.
+ *
+ * Why dropping is the right call, and why it is narrow: `missingFor` answers
+ * every peer `need` (and `onRelayReady`) out of `log`, so an op the relay
+ * will always refuse would be re-offered, re-sent, re-refused — forever.
+ * That loop is the bug this exists to break. The price is real and cannot be
+ * undone: the local document KEEPS the change, remote replicas never see it,
+ * and nothing reconciles it later (short of the file being re-opened, which
+ * re-adopts the doc wholesale). Because it is a permanent divergence we drop
+ * ONLY the exact ops the refused frame carried — never a range, never the
+ * rest of the log, and never anything when the frame couldn't be identified.
+ */
+ refused(code: RefusalCode, ops: Op[] | null) {
+ const doomed = ops ?? []
+ if (doomed.length) {
+ const keys = new Set(doomed.map((o) => `${o.a}:${o.s}`))
+ this.log = this.log.filter((o) => !keys.has(`${o.a}:${o.s}`))
+ }
+ this.emitNotice({
+ code,
+ permanent: code !== 'rate-limited',
+ ops: doomed.length,
+ ...(carriesMedia(doomed) ? { media: true } : {}),
+ })
+ }
+
// --- snapshots (online catch-up + file-fork merge) ------------------------
/** current (doc, sync-state) pair for an encrypted relay snapshot */
@@ -486,3 +549,26 @@ export class SyncSession {
this.send(frame)
}
}
+
+/**
+ * Does a refused op batch carry embedded media? A frame big enough to be
+ * refused is nearly always a pasted photo or clip, and naming it is the
+ * difference between a message the user can act on and one they can't.
+ * Structural probe only — a refused batch can be megabytes, so nothing here
+ * re-serializes or walks deep into it.
+ */
+function carriesMedia(ops: Op[]): boolean {
+ const isData = (v: unknown): boolean => typeof v === 'string' && v.startsWith('data:')
+ const inEl = (n: unknown): boolean => {
+ const el = n as { type?: string; src?: unknown } | null
+ return !!el && (el.type === 'image' || el.type === 'media') && isData(el.src)
+ }
+ return ops.some((o) => {
+ if (o.op === 'set') return isData(o.v) // element src, or a doc-level assets.<k>
+ if (o.op === 'ins') {
+ const node = o.node as { elements?: unknown[] }
+ return inEl(o.node) || !!node.elements?.some(inEl)
+ }
+ return false
+ })
+}