Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
fix(media): pause every pending upload when the account is refused (#6755)
Alex Newman7e66d1c783bb
diff --git a/src/services/media/cloud.ts b/src/services/media/cloud.tsindex b5cca235c..4f04ba36a 100644--- a/src/services/media/cloud.ts+++ b/src/services/media/cloud.ts@@ -76,17 +76,21 @@ export interface CloudMediaDescriptor {}/**- * `retry`: transient (network, timeout, 401/402/403, 429, 5xx, not-ready,- * quota, busy). These never consume an attempt budget: they back off (capped- * at one hour) for as long as it takes, so an outage or a lapsed subscription- * never strands an upload or deletion. `final`: a deterministic 4xx (manifest,- * format, checksum, tombstone) that can never succeed by retrying.+ * `retry`: transient (network, timeout, 408/429, 5xx, not-ready, quota, busy).+ * These back off per image, capped at one hour. `pause`: the account cannot+ * accept uploads (401/402/403, or the server's 409 stop). Every pending image+ * waits together, so a lapsed account does not POST each file again. `final`:+ * a deterministic 4xx (manifest, format, checksum, tombstone).*/export type CloudCallOutcome<T> =| { kind: 'ok'; value: T }| { kind: 'retry'; code: MediaErrorCode }+ | { kind: 'pause'; code: MediaErrorCode; delayMs: number }| { kind: 'final'; code: MediaErrorCode };+const UPLOAD_PAUSE_MIN_MS = 60 * 60 * 1000;+const UPLOAD_PAUSE_MAX_MS = 24 * 60 * 60 * 1000;+async function readBoundedBody(response: Response, maximumBytes: number): Promise<Buffer> {const declared = Number(response.headers.get('content-length'));if (Number.isFinite(declared) && declared > maximumBytes) {@@ -120,6 +124,49 @@ async function errorCodeOf(response: Response): Promise<MediaErrorCode | null> {}}+function retryAfterMs(header: string | null): number | null {+ if (!header) return null;+ const seconds = Number(header.trim());+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > 24 * 60 * 60) return null;+ return Math.round(seconds * 1000);+}++function clampUploadPause(delayMs: number): number {+ return Math.min(UPLOAD_PAUSE_MAX_MS, Math.max(UPLOAD_PAUSE_MIN_MS, delayMs));+}++/**+ * Account-wide upload pause. 402 is the old subscription refusal. 409 with+ * `retry_limit` or `reason: subscription_inactive` is the same refusal from a+ * server that had to pick a code installed workers already treat as final.+ * 403 and a frozen 409 stop a dead account from posting every image.+ */+function uploadPause(+ status: number,+ failure: { code: MediaErrorCode | null; reason: string | null },+ retryAfterHeader: string | null,+): { code: MediaErrorCode; delayMs: number } | null {+ const headerDelay = retryAfterMs(retryAfterHeader);+ if (status === 402 || failure.reason === 'subscription_inactive' || (status === 409 && failure.code === 'retry_limit')) {+ return { code: 'retry_limit', delayMs: clampUploadPause(headerDelay ?? 6 * 60 * 60 * 1000) };+ }+ if (status === 403 || (status === 409 && failure.code === 'account_frozen')) {+ return { code: 'account_frozen', delayMs: clampUploadPause(headerDelay ?? 24 * 60 * 60 * 1000) };+ }+ if (status === 401) return { code: 'unauthorized_owner', delayMs: UPLOAD_PAUSE_MIN_MS };+ return null;+}++async function uploadFailureBody(response: Response): Promise<{ code: MediaErrorCode | null; reason: string | null }> {+ try {+ const parsed = JSON.parse((await readBoundedBody(response, ERROR_BODY_MAX_BYTES)).toString('utf8')) as { error?: unknown; reason?: unknown };+ const reason = typeof parsed?.reason === 'string' && /^[a-z_]{2,40}$/.test(parsed.reason) ? parsed.reason : null;+ return { code: isMediaErrorCode(parsed?.error) ? parsed.error : null, reason };+ } catch {+ return { code: null, reason: null };+ }+}+function classifyFailure<T>(status: number, code: MediaErrorCode | null): CloudCallOutcome<T> {if (status === 401 || status === 402 || status === 403) return { kind: 'retry', code: code ?? 'unauthorized_owner' };if (status === 408 || status === 429 || status >= 500) return { kind: 'retry', code: code ?? 'storage_unavailable' };@@ -196,7 +243,12 @@ export class MediaCloudClient {form.append('canonical', new Blob([new Uint8Array(canonicalBytes)], { type: 'image/webp' }), 'canonical.webp');const response = await this.request('', { method: 'POST', body: form });if (!response) return { kind: 'retry', code: 'storage_unavailable' };- if (!response.ok) return classifyFailure(response.status, await errorCodeOf(response));+ if (!response.ok) {+ const failure = await uploadFailureBody(response);+ const pause = uploadPause(response.status, failure, response.headers.get('retry-after'));+ if (pause) return { kind: 'pause', code: pause.code, delayMs: pause.delayMs };+ return classifyFailure(response.status, failure.code);+ }try {const body = JSON.parse((await readBoundedBody(response, DESCRIPTOR_MAX_BYTES)).toString('utf8'));return { kind: 'ok', value: parseCloudDescriptor(body, manifest.id) };@@ -364,12 +416,17 @@ export class MediaCloudSync {}private async drainUploads(result: MediaCloudDrainResult): Promise<void> {+ // Images an older worker parked after the server's stop response. One+ // probe after this is enough: a still-lapsed account pauses the rest.+ this.db.prepare(`UPDATE media_attachments SET upload_state='pending', upload_retry_at=?, upload_error=NULL+ WHERE origin='native' AND state='ready' AND upload_state='failed'+ AND upload_error IN ('retry_limit', 'account_frozen')`).run(this.now());const candidates = this.db.prepare(`SELECT id, provenance, encoder_version, variants, upload_attempts FROM media_attachmentsWHERE origin='native' AND state='ready' AND upload_state='pending' AND upload_retry_at<=?ORDER BY created_at LIMIT ${UPLOAD_BATCH}`).all(this.now()) as UploadCandidate[];for (const candidate of candidates) {if (this.stopped || !this.options.uploadsEnabled()) return;- await this.uploadOne(candidate, result);+ if (await this.uploadOne(candidate, result) === 'paused') return;}}@@ -388,12 +445,12 @@ export class MediaCloudSync {};}- private async uploadOne(candidate: UploadCandidate, result: MediaCloudDrainResult): Promise<void> {+ private async uploadOne(candidate: UploadCandidate, result: MediaCloudDrainResult): Promise<'paused' | 'done'> {// Count the attempt durably BEFORE the request: a response lost after the// cloud committed it still makes a later local deletion queue a cloud one.const claimed = this.db.prepare(`UPDATE media_attachments SET upload_attempts=upload_attempts+1WHERE id=? AND origin='native' AND state='ready' AND upload_state='pending'`).run(candidate.id);- if (claimed.changes === 0) return;+ if (claimed.changes === 0) return 'done';const attempted = { ...candidate, upload_attempts: candidate.upload_attempts + 1 };let manifest: CloudUploadManifest;let canonicalBytes: Buffer;@@ -401,21 +458,31 @@ export class MediaCloudSync {manifest = this.buildManifest(candidate);canonicalBytes = await this.store.readVariant(candidate.id, 'viewer');} catch (error) {- if (this.stopped) return;+ if (this.stopped) return 'done';const code = error instanceof MediaError ? error.code : 'invalid_manifest';// A deletion that won during the read is not an upload failure.- if (code === 'media_not_found') return;+ if (code === 'media_not_found') return 'done';this.recordUploadFailure(attempted, { kind: code === 'storage_unavailable' ? 'retry' : 'final', code }, result);- return;+ return 'done';}// Consent may change while the file read is pending. Do not begin a new// cloud send after opt-out; the retained row stays pending for an opt-in.- if (this.stopped || !this.options.uploadsEnabled()) return;+ if (this.stopped || !this.options.uploadsEnabled()) return 'done';const outcome = await this.client.upload(manifest, canonicalBytes);- if (this.stopped) return;+ if (this.stopped) return 'done';+ if (outcome.kind === 'pause') {+ // One refusal covers the whole backlog. The image that was just sent+ // stays pending, and so does every other one, until the pause ends.+ this.db.prepare(`UPDATE media_attachments SET upload_retry_at=?, upload_error=?+ WHERE origin='native' AND state='ready' AND upload_state='pending'`)+ .run(this.now() + outcome.delayMs, outcome.code);+ result.uploadRetries++;+ logger.warn('CLOUD_SYNC', 'Media uploads paused', { code: outcome.code, delayMs: outcome.delayMs });+ return 'paused';+ }if (outcome.kind !== 'ok') {this.recordUploadFailure(attempted, outcome, result);- return;+ return 'done';}this.db.transaction(() => {const marked = this.db.prepare(`UPDATE media_attachments SET upload_state='uploaded', upload_error=NULL@@ -427,6 +494,7 @@ export class MediaCloudSync {}})();result.uploaded++;+ return 'done';}private recordUploadFailure(candidate: UploadCandidate, outcome: { kind: 'retry' | 'final'; code: MediaErrorCode }, result: MediaCloudDrainResult): void {@@ -453,8 +521,8 @@ export class MediaCloudSync {* the next read retries. Removal arrives as the text tombstone, which deletes* the replica row and its media. Integrity failures keep their bounded code.*/-function replicaReadError(outcome: { kind: 'retry' | 'final'; code: MediaErrorCode }): MediaError {- if (outcome.kind === 'retry' || outcome.code === 'media_not_found' || outcome.code === 'media_not_ready') return new MediaError('media_not_ready');+function replicaReadError(outcome: { kind: 'retry' | 'pause' | 'final'; code: MediaErrorCode }): MediaError {+ if (outcome.kind === 'retry' || outcome.kind === 'pause' || outcome.code === 'media_not_found' || outcome.code === 'media_not_ready') return new MediaError('media_not_ready');return new MediaError(outcome.code === 'checksum_mismatch' ? 'checksum_mismatch' : 'storage_unavailable');}diff --git a/tests/media/cloud-transient-failures.test.ts b/tests/media/cloud-transient-failures.test.tsindex 09cf321f4..a875ae342 100644--- a/tests/media/cloud-transient-failures.test.ts+++ b/tests/media/cloud-transient-failures.test.ts@@ -27,6 +27,21 @@ test('an interrupted image body remains eligible for a later replica read', asynassert.deepEqual(await interrupted.readVariant(id, 'viewer', variant), { kind: 'retry', code: 'storage_unavailable' });});+test('a subscription or frozen refusal pauses the upload instead of retrying that one image', async () => {+ const lapsed = await client(() => new Response(JSON.stringify({ error: 'subscription_inactive' }), { status: 402 })).upload(manifest, bytes);+ assert.deepEqual(lapsed, { kind: 'pause', code: 'retry_limit', delayMs: 6 * 60 * 60 * 1000 });+ const stopped = await client(() => new Response(JSON.stringify({ error: 'retry_limit', reason: 'subscription_inactive' }), {+ status: 409,+ headers: { 'retry-after': '21600' },+ })).upload(manifest, bytes);+ assert.deepEqual(stopped, { kind: 'pause', code: 'retry_limit', delayMs: 6 * 60 * 60 * 1000 });+ const frozen = await client(() => new Response(JSON.stringify({ error: 'account_frozen' }), { status: 409 })).upload(manifest, bytes);+ assert.equal(frozen.kind, 'pause');+ // A 409 that is not a stop signal stays final. Replica reads are unchanged.+ assert.equal((await client(() => new Response(JSON.stringify({ error: 'checksum_mismatch' }), { status: 409 })).upload(manifest, bytes)).kind, 'final');+ assert.equal((await client(() => new Response(JSON.stringify({ error: 'subscription_inactive' }), { status: 402 })).describe(id)).kind, 'retry');+});+test('deterministic descriptor, size and checksum failures stay final', async () => {assert.deepEqual(await client(() => new Response('{}')).describe(id), { kind: 'final', code: 'invalid_manifest' });assert.deepEqual(await client(() => new Response('not JSON')).describe(id), { kind: 'final', code: 'invalid_manifest' });diff --git a/tests/media/media-sync.test.ts b/tests/media/media-sync.test.tsindex 405c3fb06..61bf8c319 100644--- a/tests/media/media-sync.test.ts+++ b/tests/media/media-sync.test.ts@@ -600,19 +600,38 @@ describe('media upload state is independent of text sync', () => {expect(pro.tombstones.has(doomed.ref.id)).toBe(true);});- it('auth refusal (402) backs off without consuming a budget', async () => {+ it('a subscription refusal pauses every pending image instead of resending each one', async () => {const pro = makeFakePro();const device = makeDevice('a');- const capture = await captureImage(device, 'lapsed');+ const first = await captureImage(device, 'lapsed');+ const second = await captureImage(device, 'lapsed-2', otherPng);const sync = mediaCloud(device, pro);- for (let attempt = 0; attempt < 12; attempt++) {- pro.state.failNextUploadStatus = { status: 402, error: 'subscription_inactive' };- await sync.drain();- clock += 60 * 60 * 1000;- }- expect(device.db.prepare('SELECT upload_state, upload_attempts FROM media_attachments WHERE id=?').get(capture.ref.id)).toEqual({ upload_state: 'pending', upload_attempts: 12 });+ pro.state.failNextUploadStatus = { status: 402, error: 'subscription_inactive' };+ await sync.drain();+ expect(pro.uploads()).toHaveLength(1);+ const row = (id: string) => device.db.prepare('SELECT upload_state, upload_error FROM media_attachments WHERE id=?').get(id) as { upload_state: string; upload_error: string | null };+ expect(row(first.ref.id)).toMatchObject({ upload_state: 'pending', upload_error: 'retry_limit' });+ expect(row(second.ref.id)).toMatchObject({ upload_state: 'pending', upload_error: 'retry_limit' });++ clock += 60 * 60 * 1000;await sync.drain();+ expect(pro.uploads()).toHaveLength(1);++ clock += 6 * 60 * 60 * 1000;+ await sync.drain();+ expect(pro.uploads()).toHaveLength(3);+ expect(row(first.ref.id).upload_state).toBe('uploaded');+ expect(row(second.ref.id).upload_state).toBe('uploaded');+ });++ it('puts back images an older worker parked after the server told it to stop', async () => {+ const pro = makeFakePro();+ const device = makeDevice('a');+ const capture = await captureImage(device, 'parked');+ device.db.prepare("UPDATE media_attachments SET upload_state='failed', upload_error='retry_limit' WHERE id=?").run(capture.ref.id);+ await mediaCloud(device, pro).drain();expect(device.db.prepare('SELECT upload_state FROM media_attachments WHERE id=?').get(capture.ref.id)).toEqual({ upload_state: 'uploaded' });+ expect(pro.uploads()).toHaveLength(1);});it('transient server failures retry; checksum mismatch and a cloud tombstone are final', async () => {