Skip to content

Commit e7140ca

Browse files
jlcjakclaude
andcommitted
Keep unsent attachments when the page reloads
Text drafts survived reload while their attachments disappeared. Keep the picked bytes in this browser and restore them through the normal upload admission path; remove saved bytes after detach or send. Found by e2e c5-2. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 62433c2 commit e7140ca

3 files changed

Lines changed: 165 additions & 2 deletions

File tree

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
const { test } = require('node:test');
2+
const assert = require('node:assert/strict');
3+
const fs = require('node:fs');
4+
const path = require('node:path');
5+
const { File } = require('node:buffer');
6+
const source = fs.readFileSync(path.join(__dirname, '../../src/web/draft-attachments.js'), 'utf8');
7+
const modulePromise = import('data:text/javascript;base64,' + Buffer.from(source).toString('base64'));
8+
9+
// Exercise the lifecycle independently of IndexedDB's transaction plumbing.
10+
// The desktop check separately verifies that picked bytes survive a reload.
11+
async function cache(records = []) {
12+
const { DraftAttachments } = await modulePromise;
13+
const store = Object.create(DraftAttachments.prototype);
14+
store.started = new Set();
15+
store.restoring = new Set();
16+
const rows = new Map([['t', records]]);
17+
store.change = async (thread, update) => { rows.set(thread, update(rows.get(thread) || [])); };
18+
store.rows = () => rows.get('t') || [];
19+
return store;
20+
}
21+
const note = () => new File(['unsent notes'], 'notes.txt', { type: 'text/plain' });
22+
23+
test('a stale empty frame cannot delete a newly saved attachment', async () => {
24+
const store = await cache();
25+
await store.sync('t', [], () => assert.fail('nothing to restore'), () => true);
26+
await store.remember('t', '/new-notes.txt', note());
27+
await store.sync('t', [], () => assert.fail('already restored'), () => true);
28+
assert.equal(store.rows().length, 1);
29+
assert.equal(await store.rows()[0].file.text(), 'unsent notes');
30+
});
31+
32+
test('reload uploads the saved bytes and replaces the old reference once', async () => {
33+
const file = note(), store = await cache([{ path: '/old-notes.txt', file }]);
34+
let uploads = 0;
35+
await store.sync('t', [], async (picked, previous) => {
36+
uploads++;
37+
assert.equal(picked, file);
38+
assert.equal(await picked.text(), 'unsent notes');
39+
await store.remember('t', '/new-notes.txt', picked, previous);
40+
return '/new-notes.txt';
41+
}, () => true);
42+
await store.sync('t', ['/new-notes.txt'], () => assert.fail('duplicate upload'), () => true);
43+
assert.equal(uploads, 1);
44+
assert.deepEqual(store.rows().map(r => r.path), ['/new-notes.txt']);
45+
});
46+
47+
test('an attachment the live actor still has is not uploaded twice', async () => {
48+
const store = await cache([{ path: '/kept.txt', file: note() }]);
49+
await store.sync('t', ['/kept.txt'], () => assert.fail('duplicate upload'), () => true);
50+
assert.equal(store.rows().length, 1);
51+
});
52+
53+
test('acknowledged removal preserves a file added after that action', async () => {
54+
const store = await cache([{ path: '/sent.txt', file: note() }]);
55+
await store.remember('t', '/later.txt', note());
56+
await store.forget('t', ['/sent.txt']);
57+
assert.deepEqual(store.rows().map(r => r.path), ['/later.txt']);
58+
});
59+
60+
test('switching threads retains the file and permits a later retry', async () => {
61+
const store = await cache([{ path: '/unsent.txt', file: note() }]);
62+
await store.sync('t', [], () => assert.fail('wrong thread'), () => false);
63+
assert.equal(store.rows().length, 1);
64+
assert.equal(store.started.has('t'), false);
65+
});
66+
67+
test('a refused restore retains its bytes for the next connection', async () => {
68+
const store = await cache([{ path: '/unsent.txt', file: note() }]);
69+
await store.sync('t', [], async () => undefined, () => true);
70+
assert.equal(store.rows().length, 1);
71+
assert.equal(store.started.has('t'), false);
72+
});

‎src/web/draft-attachments.js‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Keep the picked bytes locally. Restoring uploads them through the usual
2+
// admission path; saved browser data never supplies attachment authority.
3+
export class DraftAttachments {
4+
constructor() {
5+
this.started = new Set();
6+
this.restoring = new Set();
7+
this.queue = Promise.resolve();
8+
this.db = new Promise((resolve, reject) => {
9+
const request = indexedDB.open('backplane-draft-attachments', 1);
10+
request.onupgradeneeded = () => request.result.createObjectStore('threads');
11+
request.onsuccess = () => resolve(request.result);
12+
request.onerror = () => reject(request.error);
13+
});
14+
this.db.catch(() => {});
15+
}
16+
change(thread, update) {
17+
const next = this.queue.then(async () => {
18+
const db = await this.db;
19+
return new Promise((resolve, reject) => {
20+
const tx = db.transaction('threads', 'readwrite'), store = tx.objectStore('threads');
21+
const request = store.get(thread);
22+
request.onsuccess = () => {
23+
const original = request.result || [], records = update(original);
24+
if (records === original) return;
25+
if (records.length) store.put(records, thread); else store.delete(thread);
26+
};
27+
tx.oncomplete = resolve;
28+
tx.onerror = () => reject(tx.error);
29+
tx.onabort = () => reject(tx.error);
30+
});
31+
});
32+
this.queue = next.catch(() => {});
33+
return next;
34+
}
35+
remember(thread, path, file, previous = '') {
36+
return this.change(thread, records => [...records.filter(r => r.path !== path && r.path !== previous), { path, file }]);
37+
}
38+
forget(thread, paths) {
39+
return this.change(thread, records => records.filter(r => !paths.includes(r.path)));
40+
}
41+
async sync(thread, paths, upload, current) {
42+
if (!thread || thread.startsWith('@') || this.restoring.has(thread)) return;
43+
if (this.started.has(thread)) return;
44+
this.started.add(thread);
45+
this.restoring.add(thread);
46+
try {
47+
let records;
48+
await this.change(thread, saved => { records = saved; return saved; });
49+
for (const record of records) {
50+
if (!current()) { this.started.delete(thread); return; }
51+
if (!paths.includes(record.path) && !await upload(record.file, record.path)) {
52+
this.started.delete(thread);
53+
return;
54+
}
55+
}
56+
} catch {
57+
this.started.delete(thread);
58+
} finally {
59+
this.restoring.delete(thread);
60+
}
61+
}
62+
}

‎src/web/host.js‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import { ModelFeedback } from "./model-feedback.js";
6464
const modelFeedback = new ModelFeedback(() => later());
6565
import { BodyWindows } from "./body-windows.js";
6666
import { ThinContinuations } from "./thin-continuations.js";
67+
import { DraftAttachments } from "./draft-attachments.js";
6768
import { ThinMailDraft, mailReplyField } from "./mail-drafts.js";
6869
import { ThinViews, viewCapability } from "./thin.js";
6970
import * as Wire from "./wire.js";
@@ -1109,7 +1110,15 @@ function dispatch(action, value, timer) {
11091110
if (action === "hold-bottom") { holdBottom();return true; }
11101111
const layer = document.querySelector('[data-local-models="1"]');
11111112
const settled = layer ? modelFeedback.choice(action, value, layer.style.display !== "none") : undefined;
1112-
return thin.request(action, value, settled);
1113+
const thread = currentSession().sel;
1114+
const attachments = ["detach", "send", "send-alt"].includes(action) ? draftAttachmentPaths(currentSession(), thread) : [];
1115+
return thin.request(action, value, accepted => {
1116+
settled?.(accepted);
1117+
if (accepted && attachments.length) {
1118+
const kept = draftAttachmentPaths(currentSession(), thread);
1119+
void draftAttachments.forget(thread, attachments.filter(path => !kept.includes(path))).catch(() => {});
1120+
}
1121+
});
11131122
}
11141123
if (!timer) showViewStatus("Saved conversation is read-only until connected.");
11151124
return true;
@@ -1219,6 +1228,17 @@ function inputValue(el) {
12191228
// Files: each goes whole as the body of one POST /attach to the hub (the
12201229
// pairing cookie carries the token); "attach-up" and "attach-end" tell
12211230
// app.bend it started and what the hub answered, and it decides the rest
1231+
const draftAttachments = new DraftAttachments();
1232+
function draftAttachmentPaths(session, thread) {
1233+
return (session.drafts?.["@att:" + thread] || "").split("\n").filter(Boolean);
1234+
}
1235+
function restoreDraftAttachments(session) {
1236+
const scope = uploadScope(), thread = session.sel;
1237+
if (!scope.controller?.ready || scope.thread !== thread || session.drafts?.["@att.up:" + thread]) return;
1238+
void draftAttachments.sync(thread, draftAttachmentPaths(session, thread),
1239+
(file, previous) => upload("attach", file, scope, previous),
1240+
() => thin === scope.controller && thin.ready && currentSession().sel === thread).catch(() => {});
1241+
}
12221242
function uploadScope() {
12231243
const controller = viewMode === "compatibility" ? null : thin;
12241244
return { mode: viewMode, controller,
@@ -1229,7 +1249,7 @@ function uploadScope() {
12291249
async function uploadFiles(action, files, scope = uploadScope()) {
12301250
for (const file of files) await upload(action, file, scope);
12311251
}
1232-
async function upload(action, file, scope = uploadScope()) {
1252+
async function upload(action, file, scope = uploadScope(), previous = "") {
12331253
const key = Array.from(crypto.getRandomValues(new Uint8Array(4)), (b) => b.toString(16).padStart(2, "0")).join("");
12341254
const name = file.name || "pasted." + ((file.type || "").split("/")[1] || "bin");
12351255
if (file.size === 0) return;
@@ -1256,6 +1276,13 @@ async function upload(action, file, scope = uploadScope()) {
12561276
answer = JSON.stringify({ text: "the upload did not reach the hub", thread, upload: true });
12571277
}
12581278
if (!current()) return;
1279+
let result;try { result = JSON.parse(answer); } catch { return; }
1280+
if (result.attached && result.thread === thread) {
1281+
try { await draftAttachments.remember(thread, result.attached, file, previous); } catch {
1282+
showViewStatus("This attachment could not be kept for reload. Send it before leaving this page.");
1283+
}
1284+
}
1285+
if (!current()) return;
12591286
if (viewMode === "compatibility") dispatch("attach-end", answer);
12601287
else if (thin === uploadController) {
12611288
// The HTTP body and completion stay bound to the original chosen thread,
@@ -1268,6 +1295,7 @@ async function upload(action, file, scope = uploadScope()) {
12681295
// of this completion. A retired view never retargets it into a new actor.
12691296
await uploadController.perform("attach-end", answer);
12701297
}
1298+
return result.attached && result.thread === thread ? result.attached : undefined;
12711299
}
12721300

12731301
document.addEventListener("change", (e) => {
@@ -2420,6 +2448,7 @@ async function startThin(again = false, reason = "initial") {
24202448
ui = App.unsync(App.presentation_handoff(ui, presentationJson(session)));
24212449
document.documentElement.lang = App.lang(ui);
24222450
keepViewer();
2451+
setTimeout(() => restoreDraftAttachments(currentSession()), 0);
24232452
// A hub action can open a thread too (Ctrl+N, Fork, the palette).
24242453
// Keep the accepted selection as well as explicit sidebar clicks.
24252454
try { localStorage.setItem("backplane-selected", session.sel || ""); } catch {}

0 commit comments

Comments
 (0)