Skip to content

Commit a57d9b5

Browse files
authored
fix(ui): never restore a stored draft over typed new-session composer text (#125884)
* fix(ui): never restore a stored draft over typed new-session composer text After a reload the new-session composer renders before the gateway recovery scope arrives; selectRoute then zeroes the draft revision, so text typed in that window lost to the stored draft's higher revision and the async restore overwrote (or, interleaved with input, appended to) what the user had typed. Seen on PR #125690 CI (checks-ui-e2e 5/12, run 32122284238) as a doubled composer value. NewSessionDraftPersistence now records a pristine baseline at each programmatic content replacement (page reset, navigation handoff, restore apply) and restores only when no user mutation happened past it; otherwise the typed text wins and persists above the stored revision, including minting a revision for text typed before route activation so that draft still lands. The chat composer sibling is unaffected: its revision lineage persists synchronously to localStorage. * test(ui): run draft-persistence regression in the isolated ui lane The regression test mocks the statically imported durable-composer-persistence helper (the store runtime is only dynamically imported, so under the shared isolate:false module graph its mock alone is packing-dependent). Isolating the file makes the mocks deterministic and keeps the shared-lane file set unchanged so sibling packing does not shift.
1 parent d1a194b commit a57d9b5

4 files changed

Lines changed: 173 additions & 3 deletions

File tree

‎test/vitest/vitest.ui-isolated-paths.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export const uiIsolatedTestFiles = [
2929
"ui/src/pages/config/config-page.custom-theme.test.ts",
3030
"ui/src/pages/config/memory-mutation-owner.test.ts",
3131
"ui/src/pages/config/memory-page.test.ts",
32+
"ui/src/pages/new-session/draft-persistence.test.ts",
3233
"ui/src/pages/sessions/sessions-page.archived.test.ts",
3334
"ui/src/pages/workboard/view.test.ts",
3435
];
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
/* @vitest-environment jsdom */
2+
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import type { DraftGatewayState } from "./draft-gateway-state.ts";
5+
import type { DraftPlaceState } from "./draft-place-state.ts";
6+
import { DraftSubmissionFlow } from "./draft-submission-flow.ts";
7+
8+
type StoreReadResult =
9+
| {
10+
status: "found";
11+
draft: { revision: number; text: string; attachments: unknown[]; writeId: string };
12+
}
13+
| { status: "not-found"; revision?: number; writeId?: string };
14+
15+
const store = vi.hoisted(() => {
16+
const pendingReads: Array<(result: unknown) => void> = [];
17+
return {
18+
pendingReads,
19+
readDurableComposerDraft: vi.fn(
20+
() =>
21+
new Promise((resolve) => {
22+
pendingReads.push(resolve as (result: unknown) => void);
23+
}),
24+
),
25+
writeDurableComposerDraft: vi.fn(async () => ({ status: "persisted" as const })),
26+
retireDurableComposerDraft: vi.fn(async () => ({ status: "persisted" as const })),
27+
writeDurableComposerSnapshot: vi.fn(async (_snapshot: unknown) => ({
28+
result: { status: "persisted" as const },
29+
payloadUnavailable: false,
30+
})),
31+
};
32+
});
33+
34+
vi.mock("../../lib/chat/composer-draft-store.runtime.ts", () => ({
35+
readDurableComposerDraft: store.readDurableComposerDraft,
36+
writeDurableComposerDraft: store.writeDurableComposerDraft,
37+
retireDurableComposerDraft: store.retireDurableComposerDraft,
38+
}));
39+
40+
// The store runtime above is only dynamically imported, so a shared module
41+
// graph could reuse a draft-persistence.ts evaluated without the mock.
42+
// Mocking this statically imported helper forces a fresh evaluation and gives
43+
// a deterministic write seam; the file also runs in the isolated ui lane
44+
// (vitest.ui-isolated-paths.mjs) so the re-evaluation cannot perturb sibling
45+
// files' module singletons.
46+
vi.mock("../chat/durable-composer-persistence.ts", async (importOriginal) => {
47+
const actual = await importOriginal<typeof import("../chat/durable-composer-persistence.ts")>();
48+
return { ...actual, writeDurableComposerSnapshot: store.writeDurableComposerSnapshot };
49+
});
50+
51+
async function resolvePendingRead(result: StoreReadResult) {
52+
// The read is issued behind the store's lazy import; wait for it to land.
53+
await vi.waitFor(() => {
54+
if (store.pendingReads.length === 0) {
55+
throw new Error("no pending durable draft read");
56+
}
57+
});
58+
store.pendingReads.shift()?.(result);
59+
}
60+
61+
// Drain the restore's promise chain (store load, read, write) in one macrotask.
62+
function settle() {
63+
return new Promise((resolve) => {
64+
setTimeout(resolve, 0);
65+
});
66+
}
67+
68+
// The gateway/place states are untouched by draft persistence and typing paths.
69+
function createFlow() {
70+
return new DraftSubmissionFlow(
71+
{} as DraftGatewayState,
72+
{} as DraftPlaceState,
73+
() => ({ context: undefined, data: undefined, isConnected: false }),
74+
{ requestUpdate: vi.fn(), closeTransientUi: vi.fn() },
75+
);
76+
}
77+
78+
afterEach(() => {
79+
store.pendingReads.length = 0;
80+
vi.clearAllMocks();
81+
});
82+
83+
describe("NewSessionDraftPersistence restore race", () => {
84+
it("never applies a stored draft over text typed before the restore resolves", async () => {
85+
const flow = createFlow();
86+
// Reload flow: the composer renders and the user types before the gateway
87+
// recovery scope arrives, so the route activates after the mutation.
88+
flow.setMessage("typed before restore");
89+
flow.draftPersistence.setOwner("ws://gateway.test", "recovery-a");
90+
flow.draftPersistence.activateRoute("agent:main");
91+
await resolvePendingRead({
92+
status: "found",
93+
draft: { revision: 7, text: "stored draft", attachments: [], writeId: "w-1" },
94+
});
95+
await settle();
96+
expect(flow.message).toBe("typed before restore");
97+
// The typed text also wins persistence: local-wins writes it above the
98+
// stored revision instead of leaving the stale draft in place.
99+
const write = store.writeDurableComposerSnapshot.mock.calls.at(-1)?.[0] as
100+
| { revision: number; text: string }
101+
| undefined;
102+
expect(write?.text).toBe("typed before restore");
103+
expect(write?.revision).toBeGreaterThan(7);
104+
});
105+
106+
it("persists text typed before activation even when no stored draft exists", async () => {
107+
const flow = createFlow();
108+
flow.setMessage("typed before restore");
109+
flow.draftPersistence.setOwner("ws://gateway.test", "recovery-a");
110+
flow.draftPersistence.activateRoute("agent:main");
111+
await resolvePendingRead({ status: "not-found" });
112+
await settle();
113+
expect(flow.message).toBe("typed before restore");
114+
const write = store.writeDurableComposerSnapshot.mock.calls.at(-1)?.[0] as
115+
| { text: string }
116+
| undefined;
117+
expect(write?.text).toBe("typed before restore");
118+
});
119+
120+
it("restores a stored draft into a pristine composer", async () => {
121+
const flow = createFlow();
122+
flow.draftPersistence.setOwner("ws://gateway.test", "recovery-a");
123+
flow.draftPersistence.activateRoute("agent:main");
124+
await resolvePendingRead({
125+
status: "found",
126+
draft: { revision: 7, text: "stored draft", attachments: [], writeId: "w-1" },
127+
});
128+
await settle();
129+
expect(flow.message).toBe("stored draft");
130+
});
131+
132+
it("re-arms restore for the next route once the page resets the draft", async () => {
133+
const flow = createFlow();
134+
flow.draftPersistence.setOwner("ws://gateway.test", "recovery-a");
135+
flow.draftPersistence.activateRoute("agent:route-a");
136+
await resolvePendingRead({ status: "not-found" });
137+
await settle();
138+
flow.setMessage("typed on route a");
139+
// Route switch: the page persists, resets the composer, then activates.
140+
flow.draftPersistence.persistNow();
141+
flow.resetDraft();
142+
flow.draftPersistence.activateRoute("agent:route-b");
143+
await resolvePendingRead({
144+
status: "found",
145+
draft: { revision: 9, text: "route b draft", attachments: [], writeId: "w-2" },
146+
});
147+
await settle();
148+
expect(flow.message).toBe("route b draft");
149+
});
150+
});

‎ui/src/pages/new-session/draft-persistence.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ export class NewSessionDraftPersistence {
4343
private routeKey = "";
4444
private revision = 0;
4545
private mutationGeneration = 0;
46+
// Mutation counter at the last programmatic content replacement (reset,
47+
// handoff, restore). A generation beyond it means the composer holds text
48+
// the user typed; a restore must never apply over that, and `revision`
49+
// cannot arbitrate because `selectRoute` zeroes it after late owner setup.
50+
private pristineMutationBaseline = 0;
4651
private restoreGeneration = 0;
4752
private restoredIdentity = "";
4853
private pending: DraftSnapshot | null = null;
@@ -137,6 +142,10 @@ export class NewSessionDraftPersistence {
137142
void this.restoreScope(scope, generation, mutationGeneration, signature);
138143
}
139144

145+
noteDraftReplaced() {
146+
this.pristineMutationBaseline = this.mutationGeneration;
147+
}
148+
140149
noteUserMutation() {
141150
this.mutationGeneration += 1;
142151
this.revision = nextDraftRevision(this.revision);
@@ -375,13 +384,21 @@ export class NewSessionDraftPersistence {
375384
) {
376385
return;
377386
}
387+
// Restore only into a pristine composer: anything the user typed on this
388+
// route wins over the stored draft, even when the stored revision is
389+
// higher (after a reload `revision` restarts at 0, so revision order
390+
// cannot arbitrate against live input).
378391
if (
379392
storedRevision === undefined ||
380393
storedRevision < this.revision ||
381-
(mutationGeneration > 0 && storedRevision <= this.revision)
394+
mutationGeneration > this.pristineMutationBaseline
382395
) {
383396
if (storedRevision !== undefined && storedRevision >= this.revision) {
384397
this.revision = nextDraftRevision(storedRevision);
398+
} else if (this.revision <= 0 && mutationGeneration > this.pristineMutationBaseline) {
399+
// Text typed before route activation: selectRoute zeroed its revision,
400+
// so mint one or the snapshot below is empty and the draft never lands.
401+
this.revision = nextDraftRevision(0);
385402
}
386403
this.pending = this.snapshot();
387404
this.persistNow();

‎ui/src/pages/new-session/draft-submission-flow.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ export class DraftSubmissionFlow {
106106
}
107107

108108
restoreMessage(message: string) {
109+
this.draftPersistence.noteDraftReplaced();
109110
this.messageValue = message;
110111
this.callbacks.requestUpdate();
111112
}
@@ -115,6 +116,7 @@ export class DraftSubmissionFlow {
115116
attachments: ChatAttachment[];
116117
visibility: NewSessionVisibility;
117118
}) {
119+
this.draftPersistence.noteDraftReplaced();
118120
this.messageValue = state.message;
119121
this.visibilityValue = state.visibility;
120122
this.attachmentDraft.restore(state.attachments);
@@ -143,8 +145,7 @@ export class DraftSubmissionFlow {
143145

144146
clearErrorIf(error: string) {
145147
if (this.error === error) {
146-
this.error = null;
147-
this.callbacks.requestUpdate();
148+
this.clearError();
148149
}
149150
}
150151

@@ -357,6 +358,7 @@ export class DraftSubmissionFlow {
357358
this.pendingCloud.restored = false;
358359
} else {
359360
this.clearPendingCloudRecovery();
361+
this.draftPersistence.noteDraftReplaced();
360362
this.messageValue = "";
361363
}
362364
this.error = null;

0 commit comments

Comments
 (0)