Skip to content

Commit 5e5b3d5

Browse files
fix(ui): preserve attachments across offline reloads (#131753)
1 parent 84fb68e commit 5e5b3d5

3 files changed

Lines changed: 155 additions & 6 deletions

File tree

‎ui/src/e2e/chat-attachment-read-lifecycle.e2e.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,59 @@ async function waitForCommittedAttachmentDraft(
125125
}
126126

127127
suite.define(() => {
128+
it("restores an attachment staged offline after reload and reconnect", async () => {
129+
await suite.withPage(
130+
{
131+
locale: "en-US",
132+
serviceWorkers: "block",
133+
viewport: { height: 900, width: 1280 },
134+
},
135+
async ({ page }) => {
136+
const gateway = await installMockGateway(page);
137+
const sessionKey = "global";
138+
const text = "offline attachment draft";
139+
const contents = "offline attachment contents";
140+
await page.goto(controlUiSessionUrl(suite.server.baseUrl, sessionKey));
141+
const composer = page.locator(".agent-chat__composer-combobox textarea");
142+
await composer.waitFor();
143+
144+
await gateway.setOnline(false);
145+
await page.locator('.agent-chat__composer-underlaps[data-tone="warn"]').waitFor();
146+
await composer.fill(text);
147+
await page.locator(".agent-chat__file-input").setInputFiles({
148+
name: "offline.txt",
149+
mimeType: "text/plain",
150+
buffer: Buffer.from(contents),
151+
});
152+
await expect.poll(() => page.locator(".chat-attachment-thumb").count()).toBe(1);
153+
await waitForCommittedAttachmentDraft(page, sessionKey, text);
154+
155+
await page.reload();
156+
await gateway.setOnline(true);
157+
await expect.poll(() => composer.inputValue()).toBe(text);
158+
await expect.poll(() => page.locator(".chat-attachment-thumb").count()).toBe(1);
159+
const artifactDir = process.env.OPENCLAW_UI_E2E_ARTIFACT_DIR?.trim();
160+
if (artifactDir) {
161+
await mkdir(artifactDir, { recursive: true });
162+
await page.screenshot({ path: path.join(artifactDir, "offline-draft-restored.png") });
163+
}
164+
await composer.press("Enter");
165+
166+
const request = await gateway.waitForRequest("chat.send");
167+
expect(request.params).toMatchObject({
168+
attachments: [
169+
{
170+
content: Buffer.from(contents).toString("base64"),
171+
fileName: "offline.txt",
172+
mimeType: "text/plain",
173+
},
174+
],
175+
message: text,
176+
});
177+
},
178+
);
179+
});
180+
128181
it("restores isolated session drafts across fresh pages and retires sent or removed attachments", async () => {
129182
const firstSession = "agent:main:restart-session-a";
130183
const secondSession = "agent:main:restart-session-b";

‎ui/src/e2e/composer-draft-store.e2e.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,80 @@ async function rawDraftRecords(page: Page, scopes: readonly TestDraftScope[], ex
6464
}
6565

6666
suite.define(() => {
67+
it("does not reuse a cached composer owner while reconnect authentication is unresolved", async () => {
68+
await suite.withPage({ locale: "en-US", serviceWorkers: "block" }, async ({ page }) => {
69+
await installMockGateway(page);
70+
await page.goto(`${suite.server.baseUrl}chat`);
71+
const storeHandle = await page.evaluateHandle<
72+
typeof import("../lib/chat/composer-draft-store.runtime.ts")
73+
>('import("/src/lib/chat/composer-draft-store.runtime.ts")');
74+
const composerHandle = await page.evaluateHandle<
75+
typeof import("../pages/chat/composer-persistence.ts")
76+
>('import("/src/pages/chat/composer-persistence.ts")');
77+
const result = await page.evaluate(
78+
async ({ draftStore, composer }) => {
79+
const client = { recoveryScope: "credential-a", recoveryScopeReady: true };
80+
const state = {
81+
settings: { gatewayUrl: "owner-fence-gateway" },
82+
sessionKey: "agent:main:owner-fence",
83+
chatMessage: "",
84+
chatAttachments: [],
85+
chatQueue: [],
86+
client,
87+
connected: true,
88+
selectedChatSessionIncognito: false,
89+
};
90+
const scope = {
91+
gatewayOwner: state.settings.gatewayUrl,
92+
recoveryScope: client.recoveryScope,
93+
scopeKey: composer.storedChatOutboxScopeKey(
94+
composer.resolveStoredChatOutboxScope(state, state.sessionKey),
95+
),
96+
};
97+
const persistence = new composer.ChatComposerPersistence(() => state);
98+
persistence.start();
99+
state.connected = false;
100+
client.recoveryScopeReady = false;
101+
state.chatMessage = "authenticated offline draft";
102+
persistence.persistChangedState();
103+
let offlineStored = false;
104+
for (let attempt = 0; attempt < 100; attempt += 1) {
105+
const stored = await draftStore.readDurableComposerDraft(scope);
106+
if (stored.status === "found" && stored.draft.text === state.chatMessage) {
107+
offlineStored = true;
108+
break;
109+
}
110+
await new Promise((resolve) => {
111+
setTimeout(resolve, 10);
112+
});
113+
}
114+
if (!offlineStored) {
115+
throw new Error("offline composer draft did not settle");
116+
}
117+
118+
state.connected = true;
119+
state.chatMessage = "unresolved reconnect draft";
120+
persistence.persistChangedState();
121+
// Let a wrongly admitted fire-and-forget write open its transaction,
122+
// then commit a later transaction in the same object store as a barrier.
123+
await Promise.resolve();
124+
await draftStore.writeDurableComposerDraft(
125+
{ ...scope, recoveryScope: "credential-b", scopeKey: "reconnect-barrier" },
126+
{ revision: 1, text: "barrier", attachments: [] },
127+
{ expectedRevision: 0, writeId: "reconnect-barrier" },
128+
);
129+
return draftStore.readDurableComposerDraft(scope);
130+
},
131+
{ draftStore: storeHandle, composer: composerHandle },
132+
);
133+
134+
expect(result).toMatchObject({
135+
status: "found",
136+
draft: { text: "authenticated offline draft" },
137+
});
138+
});
139+
});
140+
67141
it("reads the requested draft before global expiry maintenance settles", async () => {
68142
await suite.withPage(
69143
{ locale: "en-US", serviceWorkers: "block" },

‎ui/src/pages/chat/composer-persistence.ts‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -727,7 +727,13 @@ export class ChatComposerPersistence {
727727
private committedDraftRevision = 0;
728728
private latestDraftRevision = 0;
729729
private durableRestoreProtected = false;
730-
private durableOwnerKey = "";
730+
// A transient disconnect invalidates scope readiness, not the owner authenticated
731+
// by this client. Client or Gateway replacement still fences the cached owner.
732+
private durableOwner: {
733+
client: ChatComposerPersistenceState["client"];
734+
gatewayOwner: string;
735+
recoveryScope: string;
736+
} | null = null;
731737
private durableRetiredScopeKey = "";
732738
private forceDurableOwnerRestore = false;
733739
private readonly durablePersistence = new DurableChatComposerPersistence(
@@ -1044,7 +1050,16 @@ export class ChatComposerPersistence {
10441050
if (state.selectedChatSessionIncognito) {
10451051
return null;
10461052
}
1047-
return this.resolveConnectedDurableScope(state, scope);
1053+
return (
1054+
this.resolveConnectedDurableScope(state, scope) ??
1055+
(this.durableOwner &&
1056+
!state.connected &&
1057+
this.durableOwner.client === state.client &&
1058+
this.durableOwner.gatewayOwner ===
1059+
storageTargetForGateway(state.settings?.gatewayUrl).gatewayOwner
1060+
? { ...this.durableOwner, scopeKey: storedChatOutboxScopeKey(scope) }
1061+
: null)
1062+
);
10481063
}
10491064

10501065
private resolveConnectedDurableScope(
@@ -1073,7 +1088,7 @@ export class ChatComposerPersistence {
10731088
const scopeKey = durableComposerScopeIdentity(connectedScope);
10741089
if (this.durableRetiredScopeKey !== scopeKey) {
10751090
this.durableRetiredScopeKey = scopeKey;
1076-
this.durableOwnerKey = "";
1091+
this.durableOwner = null;
10771092
this.forceDurableOwnerRestore = false;
10781093
this.durableRestoreProtected = false;
10791094
this.durablePersistence.retire(connectedScope, this.latestDraftRevision);
@@ -1086,8 +1101,11 @@ export class ChatComposerPersistence {
10861101
if (!scope) {
10871102
return;
10881103
}
1089-
const ownerKey = JSON.stringify([scope.gatewayOwner, scope.recoveryScope]);
1090-
if (this.durableOwnerKey && this.durableOwnerKey !== ownerKey) {
1104+
if (
1105+
this.durableOwner &&
1106+
(this.durableOwner.gatewayOwner !== scope.gatewayOwner ||
1107+
this.durableOwner.recoveryScope !== scope.recoveryScope)
1108+
) {
10911109
releaseChatAttachmentPayloads(state.chatAttachments);
10921110
state.chatMessage = "";
10931111
state.chatGoalDraftMode = null;
@@ -1108,7 +1126,11 @@ export class ChatComposerPersistence {
11081126
this.durablePersistence.resetRestoreScope();
11091127
state.requestUpdate?.();
11101128
}
1111-
this.durableOwnerKey = ownerKey;
1129+
this.durableOwner = {
1130+
client: state.client,
1131+
gatewayOwner: scope.gatewayOwner,
1132+
recoveryScope: scope.recoveryScope,
1133+
};
11121134
if (this.durableRestoreProtected) {
11131135
this.durableRestoreProtected = false;
11141136
const snapshot = this.snapshot(

0 commit comments

Comments
 (0)