Skip to content

Commit e54cb3c

Browse files
authored
refactor(ui): simplify outbox custody and draft persistence (#133409)
1 parent a2a9edf commit e54cb3c

25 files changed

Lines changed: 155 additions & 298 deletions

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -675,7 +675,6 @@ suite.define(() => {
675675
expectedRevision: 0,
676676
revision: 59,
677677
text: "stale attachment draft",
678-
attachments: [],
679678
storedAttachments: null,
680679
writeId: "stale-missing-payload",
681680
});

‎ui/src/lib/chat/composer-draft-store.runtime.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -231,14 +231,13 @@ export async function prepareDurableComposerRecovery(
231231
const values: unknown[] = await requestResult(
232232
store.index(OWNER_INDEX).getAll(ownerKey({ ...owner, scopeKey: "" })),
233233
);
234+
const records = values.map(parseStoredDraft).filter((record) => record !== null);
234235
const entries: DurableComposerRecoveryEntry[] = [];
235-
let activeCount = values.filter((value) => {
236-
const record = parseStoredDraft(value);
237-
return record && isActiveDraft(record) && !isLegacyChatDraft(record);
238-
}).length;
239-
for (const value of values) {
240-
const record = parseStoredDraft(value);
241-
if (!record || !isLegacyChatDraft(record)) {
236+
let activeCount = records.filter(
237+
(record) => isActiveDraft(record) && !isLegacyChatDraft(record),
238+
).length;
239+
for (const record of records) {
240+
if (!isLegacyChatDraft(record)) {
242241
continue;
243242
}
244243
if (
@@ -253,7 +252,9 @@ export async function prepareDurableComposerRecovery(
253252
...owner,
254253
scopeKey: `${CHAT_SCOPE_PREFIX}${originalScope ? storedChatOutboxScopeKey(originalScope) : record.scopeKey}`,
255254
};
256-
const destination = await requestResult(store.get(recordKey(scope)));
255+
const destination = identifiable
256+
? await requestResult(store.get(recordKey(scope)))
257+
: undefined;
257258
const retired = parseStoredDraft(destination);
258259
// Only an exact known target can retire its older draft. Today's config
259260
// cannot identify an old global bucket or retarget a qualified main key.

‎ui/src/lib/chat/outbox-recovery.ts‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,7 @@ import {
55
outboxPayloadMatchesOwner,
66
} from "./outbox-payload-store.runtime.ts";
77
import { normalizeStoredSession } from "./outbox-store-codec.ts";
8-
import {
9-
nextDraftRevision,
10-
rememberedDraftAttempt,
11-
rememberedDraftRevision,
12-
} from "./outbox-store-draft-state.ts";
8+
import { nextDraftRevision, readDraftRevisionState } from "./outbox-store-draft-state.ts";
139
import {
1410
notifyStoredChatOutboxChanges,
1511
readStoredOutboxStore,
@@ -70,11 +66,8 @@ export function captureChatOutboxRecoveryDestination(
7066
gatewayOwner: target.gatewayOwner,
7167
recoveryScope: observeOutboxRecoveryOwner(state),
7268
session: JSON.stringify(session),
73-
revision: Math.max(
74-
session?.draftRevision ?? 0,
75-
rememberedDraftRevision(storage, target.key, storeSessionKey),
76-
rememberedDraftAttempt(storage, target.key, storeSessionKey),
77-
),
69+
revision: readDraftRevisionState(storage, target.key, storeSessionKey, session?.draftRevision)
70+
.latestAttempt,
7871
};
7972
}
8073

‎ui/src/lib/chat/outbox-store-codec.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,19 @@ export type StoredComposerSession = {
2424
updatedAt: number;
2525
};
2626

27+
export function sameQueuedDeliveryVersion(left: ChatQueueItem, right: ChatQueueItem): boolean {
28+
return (
29+
left.id === right.id &&
30+
left.sendRunId === right.sendRunId &&
31+
left.sendAttempts === right.sendAttempts &&
32+
left.sendState === right.sendState &&
33+
left.agentId === right.agentId &&
34+
left.sessionKey === right.sessionKey &&
35+
left.orderKey === right.orderKey &&
36+
left.attachmentPayload?.key === right.attachmentPayload?.key
37+
);
38+
}
39+
2740
function normalizeOptionalBoolean(value: unknown): boolean | undefined {
2841
return typeof value === "boolean" ? value : undefined;
2942
}

‎ui/src/lib/chat/outbox-store-draft-state.ts‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,21 @@ export function rememberDraftAttempt(
5353
bySession.set(storeSessionKey, Math.max(bySession.get(storeSessionKey) ?? 0, draftRevision));
5454
}
5555

56-
export function rememberedDraftRevision(
56+
export function readDraftRevisionState(
5757
storage: Storage,
5858
storageKey: string,
5959
storeSessionKey: string,
60-
): number {
61-
return draftRevisionHighWaterByStorage.get(storage)?.get(storageKey)?.get(storeSessionKey) ?? 0;
62-
}
63-
64-
export function rememberedDraftAttempt(
65-
storage: Storage,
66-
storageKey: string,
67-
storeSessionKey: string,
68-
): number {
69-
return draftAttemptHighWaterByStorage.get(storage)?.get(storageKey)?.get(storeSessionKey) ?? 0;
60+
storedRevision: number | undefined,
61+
): { committed: number; latestAttempt: number } {
62+
const committed = Math.max(
63+
storedRevision ?? 0,
64+
draftRevisionHighWaterByStorage.get(storage)?.get(storageKey)?.get(storeSessionKey) ?? 0,
65+
);
66+
return {
67+
committed,
68+
latestAttempt: Math.max(
69+
committed,
70+
draftAttemptHighWaterByStorage.get(storage)?.get(storageKey)?.get(storeSessionKey) ?? 0,
71+
),
72+
};
7073
}

‎ui/src/lib/chat/outbox-store-retirement.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
import { getSafeSessionStorage } from "../../local-storage.ts";
2-
import { normalizeStoredSession } from "./outbox-store-codec.ts";
32
import {
43
nextDraftRevision,
5-
rememberedDraftAttempt,
6-
rememberedDraftRevision,
4+
readDraftRevisionState,
75
rememberDraftAttempt,
86
rememberDraftRevision,
97
} from "./outbox-store-draft-state.ts";
@@ -71,11 +69,12 @@ export function retireStoredComposerDrafts(
7169
const storeSessionKey = storedChatOutboxScopeKey(scope);
7270
const session = store.sessions[storeSessionKey];
7371
const storedRevision = session?.draftRevision ?? 0;
74-
const currentRevision = Math.max(
72+
const currentRevision = readDraftRevisionState(
73+
storage,
74+
storageTarget.key,
75+
storeSessionKey,
7576
storedRevision,
76-
rememberedDraftRevision(storage, storageTarget.key, storeSessionKey),
77-
rememberedDraftAttempt(storage, storageTarget.key, storeSessionKey),
78-
);
77+
).latestAttempt;
7978
let minimumRevision = target.retireBeforeRevision;
8079
if (storedRevision < target.retireBeforeRevision) {
8180
minimumRevision = nextDraftRevision(Math.max(currentRevision, target.retireBeforeRevision));
@@ -103,7 +102,7 @@ export function retireStoredComposerDrafts(
103102
writeStoredOutboxStore(storage, storageTarget, store);
104103
const persisted = readStoredOutboxStore(storage, storageTarget);
105104
for (const { storeSessionKey, revision } of written) {
106-
const session = normalizeStoredSession(persisted.sessions[storeSessionKey]);
105+
const session = persisted.sessions[storeSessionKey];
107106
if (
108107
session?.draftRevision !== revision ||
109108
Boolean(session.draft) ||

‎ui/src/lib/chat/outbox-store.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,9 @@ function holdComposerRecovery(
260260
}
261261
for (const item of queue ?? []) {
262262
const owner = item.attachmentPayload?.recoveryScope;
263-
groups.set(owner, [...(groups.get(owner) ?? []), item]);
263+
const rows = groups.get(owner) ?? [];
264+
rows.push(item);
265+
groups.set(owner, rows);
264266
}
265267
for (const [owner, rows] of groups) {
266268
store.recovery[`${id}:${JSON.stringify(owner ?? null)}`] = {
@@ -414,7 +416,9 @@ export function readStoredOutboxStore(
414416
) {
415417
return true;
416418
}
417-
identified.set(identifiedKey, [...(identified.get(identifiedKey) ?? []), item]);
419+
const rows = identified.get(identifiedKey) ?? [];
420+
rows.push(item);
421+
identified.set(identifiedKey, rows);
418422
return false;
419423
});
420424
for (const [identifiedKey, queue] of identified) {
@@ -547,13 +551,14 @@ export function writeStoredOutboxStore(
547551
if (pendingLegacyTransfers.has(store) && retained.length < entries.length) {
548552
throw new Error("Chat outbox migration exceeds retention; source retained");
549553
}
550-
const payload = JSON.stringify({
554+
const retainedStore: StoredComposerState = {
551555
version: 4,
552556
gatewayOwner: target.gatewayOwner,
553557
sessions: Object.fromEntries(retained),
554558
recovery: store.recovery,
555559
...(store.legacyReceipts ? { legacyReceipts: store.legacyReceipts } : {}),
556-
});
560+
};
561+
const payload = JSON.stringify(retainedStore);
557562
// Verification precedes deleting any legacy source, including quota/no-op writes.
558563
storage.setItem(target.key, payload);
559564
if (storage.getItem(target.key) !== payload) {
@@ -569,15 +574,15 @@ export function writeStoredOutboxStore(
569574
}
570575
}
571576
pendingLegacyTransfers.delete(store);
572-
retireRemovedOutboxPayloads(storage, target, previous, payload);
577+
retireRemovedOutboxPayloads(storage, target, previous, retainedStore);
573578
}
574579

575580
// Cleanup follows a verified metadata commit, never a credential-filtered view.
576581
function retireRemovedOutboxPayloads(
577582
storage: Storage,
578583
target: ComposerStorageTarget,
579584
previous: string | null,
580-
current: string | null,
585+
current: StoredComposerState | null,
581586
): void {
582587
if (!previous) {
583588
return;
@@ -592,11 +597,10 @@ function retireRemovedOutboxPayloads(
592597
) {
593598
return;
594599
}
595-
const references = (raw: string | null) => {
596-
if (raw === null) {
600+
const references = (value: unknown) => {
601+
if (value === null) {
597602
return [];
598603
}
599-
const value: unknown = JSON.parse(raw);
600604
if (
601605
!isRecord(value) ||
602606
value.version !== 4 ||
@@ -640,7 +644,7 @@ function retireRemovedOutboxPayloads(
640644
});
641645
};
642646
const remaining = new Set(references(current).map((ref) => ref.key));
643-
const removed = references(previous).filter((ref) => !remaining.has(ref.key));
647+
const removed = references(JSON.parse(previous)).filter((ref) => !remaining.has(ref.key));
644648
if (removed.length) {
645649
void removeOutboxPayloads(removed);
646650
}

‎ui/src/pages/chat/chat-outbox-drain.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { GatewayRequestError, type GatewayBrowserClient } from "../../api/gateway.ts";
22
import type { ChatAttachment, ChatQueueItem } from "../../lib/chat/chat-types.ts";
3+
import { sameQueuedDeliveryVersion } from "../../lib/chat/outbox-store-codec.ts";
34
import { formatUiError } from "../../lib/format-error.ts";
45
import { isSessionRunActive } from "../../lib/session-run-state.ts";
56
import { visibleSessionMatches } from "../../lib/sessions/index.ts";
@@ -26,7 +27,6 @@ import {
2627
anyChatOutboxPaneMatches,
2728
readQueuedMessageById,
2829
removeQueuedMessageWithoutReleasing,
29-
sameQueuedDeliveryVersion,
3030
syncVisibleChatQueueProjection,
3131
updateQueuedMessageForSession,
3232
} from "./chat-queue.ts";

‎ui/src/pages/chat/chat-outbox-owner.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,12 @@ class ChatOutboxGatewayOwner {
8686
}
8787
return projected;
8888
}
89-
snapshot(host: Host, scope: Scope): ChatQueueItem[] {
89+
snapshot(
90+
host: Host,
91+
scope: Scope,
92+
durable = this.outbox(host, scope)?.queue ?? [],
93+
): ChatQueueItem[] {
9094
const key = storedChatOutboxScopeKey(scope);
91-
const durable = this.outbox(host, scope)?.queue ?? [];
9295
const state = this.state(host);
9396
const local = state.byScope.get(key) ?? [];
9497
const localById = new Map(local.map((item) => [item.id, item]));
@@ -139,14 +142,14 @@ class ChatOutboxGatewayOwner {
139142
return;
140143
}
141144
if (result.status === "ready") {
142-
if (result.item.attachmentPayload?.key !== key) {
145+
if (result.update.attachmentPayload?.key !== key) {
143146
// Copy adoption must not overwrite a retry that replaced the captured row.
144147
if (
145148
!updateStoredChatComposerQueueItem(
146149
host,
147150
outbox.sessionKey,
148151
item,
149-
result.item,
152+
{ ...item, ...result.update },
150153
outbox.agentId,
151154
)
152155
) {
@@ -155,12 +158,12 @@ class ChatOutboxGatewayOwner {
155158
}
156159
this.keep(host, outbox, {
157160
...current,
158-
attachments: result.item.attachments,
159-
...(result.item.attachmentPayload?.key !== key
161+
attachments: result.update.attachments,
162+
...(result.update.attachmentPayload?.key !== key
160163
? {
161-
attachmentPayload: result.item.attachmentPayload,
162-
sendState: result.item.sendState,
163-
sendError: result.item.sendError,
164+
attachmentPayload: result.update.attachmentPayload,
165+
sendState: result.update.sendState,
166+
sendError: result.update.sendError,
164167
}
165168
: {}),
166169
});
@@ -378,7 +381,9 @@ class ChatOutboxGatewayOwner {
378381
this.prune(host);
379382
}
380383
allItems(host: Host): ChatQueueItem[] {
381-
const durable = listStoredChatOutboxes(host).flatMap((outbox) => this.snapshot(host, outbox));
384+
const durable = listStoredChatOutboxes(host).flatMap((outbox) =>
385+
this.snapshot(host, outbox, outbox.queue),
386+
);
382387
const local = [...this.state(host).byScope.values()].flat();
383388
// The snapshot already merges durable and live state. A stale pane-local
384389
// copy must not hide its sending overlay during connection retirement.

‎ui/src/pages/chat/chat-pending-inputs.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ describe("server-owned pending input display", () => {
244244
if (prepared.status !== "ready") {
245245
throw new Error(`Could not prepare custody attachment: ${prepared.reason}`);
246246
}
247-
queued = prepared.item;
247+
queued = { ...queued, ...prepared.update };
248248
expect(queued.attachmentPayload).toBeDefined();
249249
}
250250
const reference = queued.attachmentPayload;

0 commit comments

Comments
 (0)