Skip to content

Commit 6572805

Browse files
committed
refactor(ui): unify chat outbox delivery
1 parent e7950d9 commit 6572805

8 files changed

Lines changed: 1388 additions & 1192 deletions

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

Lines changed: 86 additions & 138 deletions
Large diffs are not rendered by default.

‎ui/src/pages/chat/chat-send-actions.ts‎

Lines changed: 41 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import type { QueueMode } from "../../../../src/auto-reply/reply/queue/types.js";
21
import { t } from "../../i18n/index.ts";
3-
import type { ChatAttachment } from "../../lib/chat/chat-types.ts";
2+
import type { ChatAttachment, ChatQueueItem } from "../../lib/chat/chat-types.ts";
43
import { generateUUID } from "../../lib/uuid.ts";
54
import { loadChatBranches, loadChatHistory, type ChatState } from "./chat-history.ts";
65
import {
@@ -14,8 +13,8 @@ import {
1413
updateQueuedMessage,
1514
updateVolatileQueuedMessage,
1615
} from "./chat-queue.ts";
17-
import type { ChatSendAck } from "./chat-send-ack.ts";
1816
import type { ChatHost } from "./chat-send-contract.ts";
17+
import { chatOutboxDrainDependencies, deliverChatQueueItem } from "./chat-send-delivery.ts";
1918
import {
2019
canSendVolatileQueueItem,
2120
reconnectSafeQueuedSendState,
@@ -26,7 +25,6 @@ import {
2625
requestChatSend,
2726
resolveDisplayedLeafEntryId,
2827
} from "./chat-send-request.ts";
29-
import { chatOutboxDrainDependencies, sendQueuedChatMessage } from "./chat-send.ts";
3028
import { listStoredChatOutboxes, storedChatOutboxScopeKey } from "./composer-persistence.ts";
3129
import { formatConnectError } from "./connect-error.ts";
3230
import {
@@ -40,28 +38,18 @@ export async function sendChatMessageWithGeneratedRunId(
4038
state: ChatState,
4139
message: string,
4240
attachments?: ChatAttachment[],
43-
options: {
44-
canApplyError?: () => boolean;
45-
queueMode?: QueueMode;
46-
runId?: string;
47-
} = {},
48-
): Promise<ChatSendAck | null> {
49-
if (!state.client || !state.connected) {
50-
return null;
51-
}
41+
options: Partial<Parameters<SteerSendDependencies["sendChatMessage"]>[3]> = {},
42+
) {
5243
const msg = message.trim();
53-
const hasAttachments = attachments && attachments.length > 0;
54-
if (!msg && !hasAttachments) {
44+
if (!state.client || !state.connected || (!msg && !attachments?.length)) {
5545
return null;
5646
}
5747
const canApplyError = options.canApplyError ?? (() => true);
5848
if (canApplyError()) {
5949
setChatError(state, null);
6050
}
6151
const runId = options.runId ?? generateUUID();
62-
// Only an authoritative history/cache commit can advance this token. Optimistic
63-
// sends do not know their persisted leaf id; direct sends must fail closed while
64-
// restored outbox drains intentionally omit the precondition.
52+
// Direct sends fail closed on the authoritative leaf; restored drains omit it.
6553
const expectedLeafEntryId = resolveDisplayedLeafEntryId(state);
6654
try {
6755
return await requestChatSend(state, {
@@ -87,12 +75,25 @@ export async function sendChatMessageWithGeneratedRunId(
8775
}
8876
}
8977

78+
function findStoredOutbox(host: ChatHost, id: string) {
79+
return listStoredChatOutboxes(host).find(({ queue }) => queue.some((item) => item.id === id));
80+
}
81+
82+
const resetRetryState = (
83+
entry: ChatQueueItem,
84+
sendState: ChatQueueItem["sendState"],
85+
): ChatQueueItem => ({
86+
...entry,
87+
sendAttempts: 0,
88+
sendError: undefined,
89+
sendRunId: entry.sendState === "failed" ? generateUUID() : entry.sendRunId,
90+
sendState,
91+
});
92+
9093
export const steerSendDependencies: SteerSendDependencies = {
9194
loadChatHistory: (host) => void loadChatHistory(host as unknown as ChatState),
9295
resumeRestoredOutbox: (host, itemId) => {
93-
const restoredOutbox = listStoredChatOutboxes(host).find((outbox) =>
94-
outbox.queue.some((item) => item.id === itemId),
95-
);
96+
const restoredOutbox = findStoredOutbox(host as ChatHost, itemId);
9697
if (!host.chatRunId && restoredOutbox) {
9798
void scheduleStoredChatOutboxDrain(
9899
host as ChatHost,
@@ -105,21 +106,16 @@ export const steerSendDependencies: SteerSendDependencies = {
105106
sendChatMessageWithGeneratedRunId(host as unknown as ChatState, message, attachments, options),
106107
};
107108

108-
export function steerQueuedChatMessage(host: ChatHost, id: string) {
109-
return steerQueuedChatMessageLifecycle(host, id, steerSendDependencies);
110-
}
109+
export const steerQueuedChatMessage = (host: ChatHost, id: string) =>
110+
steerQueuedChatMessageLifecycle(host, id, steerSendDependencies);
111111

112-
export async function resumeStoredChatOutboxes(host: ChatHost) {
113-
await resumeStoredChatOutboxesDrain(host, chatOutboxDrainDependencies);
114-
}
112+
export const resumeStoredChatOutboxes = (host: ChatHost) =>
113+
resumeStoredChatOutboxesDrain(host, chatOutboxDrainDependencies);
115114

116-
export async function flushChatQueueForEvent(host: ChatHost) {
117-
await flushStoredChatOutbox(host, chatOutboxDrainDependencies);
118-
}
115+
export const flushChatQueueForEvent = (host: ChatHost) =>
116+
flushStoredChatOutbox(host, chatOutboxDrainDependencies);
119117

120-
export async function retryReconnectableQueuedChatSends(host: ChatHost) {
121-
await resumeStoredChatOutboxes(host);
122-
}
118+
export const retryReconnectableQueuedChatSends = resumeStoredChatOutboxes;
123119

124120
export async function retryQueuedChatMessage(host: ChatHost, id: string) {
125121
const item = host.chatQueue.find((entry) => entry.id === id);
@@ -133,9 +129,7 @@ export async function retryQueuedChatMessage(host: ChatHost, id: string) {
133129
) {
134130
return;
135131
}
136-
let outbox = listStoredChatOutboxes(host).find((candidate) =>
137-
candidate.queue.some((entry) => entry.id === item.id),
138-
);
132+
let outbox = findStoredOutbox(host, item.id);
139133
if (!outbox) {
140134
const wasVolatile = isVolatileQueuedMessage(host, item.id);
141135
if (!admitQueuedMessageForSession(host, item.sessionKey ?? host.sessionKey, item)) {
@@ -146,53 +140,31 @@ export async function retryQueuedChatMessage(host: ChatHost, id: string) {
146140
(item.sendState === "failed" || item.sendState === "unconfirmed") &&
147141
canSendVolatileQueueItem(host, item)
148142
) {
149-
const retry = updateVolatileQueuedMessage(host, id, (entry) => ({
150-
...entry,
151-
sendAttempts: 0,
152-
sendError: undefined,
153-
sendRunId: entry.sendState === "failed" ? generateUUID() : entry.sendRunId,
154-
sendState: undefined,
155-
}));
143+
const retry = updateVolatileQueuedMessage(host, id, (entry) =>
144+
resetRetryState(entry, undefined),
145+
);
156146
if (!retry) {
157147
setChatError(host, OFFLINE_QUEUE_STORAGE_ERROR);
158148
return;
159149
}
160-
await sendQueuedChatMessage(
161-
host,
162-
retry.id,
163-
{
164-
routingSessionKey: retry.sessionKey ?? host.sessionKey,
165-
storageMode: "memory",
166-
},
167-
retry.sessionKey ?? host.sessionKey,
168-
);
150+
await deliverChatQueueItem(host, retry, {
151+
routingSessionKey: retry.sessionKey ?? host.sessionKey,
152+
storageMode: "memory",
153+
});
169154
return;
170155
}
171156
setChatError(host, OFFLINE_QUEUE_STORAGE_ERROR);
172157
return;
173158
}
174-
outbox = listStoredChatOutboxes(host).find((candidate) =>
175-
candidate.queue.some((entry) => entry.id === item.id),
176-
);
177159
}
178-
if (!outbox) {
179-
setChatError(host, OFFLINE_QUEUE_STORAGE_ERROR);
180-
return;
181-
}
182-
const retry = updateQueuedMessage(host, id, (entry) => ({
183-
...entry,
184-
sendAttempts: 0,
185-
sendError: undefined,
186-
sendRunId: entry.sendState === "failed" ? generateUUID() : entry.sendRunId,
187-
sendState: reconnectSafeQueuedSendState(host),
188-
}));
160+
const retry = updateQueuedMessage(host, id, (entry) =>
161+
resetRetryState(entry, reconnectSafeQueuedSendState(host)),
162+
);
189163
if (!retry) {
190164
setChatError(host, OFFLINE_QUEUE_STORAGE_ERROR);
191165
return;
192166
}
193-
outbox = listStoredChatOutboxes(host).find((candidate) =>
194-
candidate.queue.some((entry) => entry.id === retry.id),
195-
);
167+
outbox = findStoredOutbox(host, retry.id);
196168
if (!outbox) {
197169
setChatError(host, OFFLINE_QUEUE_STORAGE_ERROR);
198170
return;

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

Lines changed: 50 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -150,27 +150,62 @@ export function restoreFailedCommandComposer(
150150
return retained;
151151
}
152152

153-
export function restoreComposerAfterFailedSend(
153+
type PendingComposerSnapshot = {
154+
previousAttachments?: ChatAttachment[];
155+
previousDraft?: string;
156+
};
157+
158+
function strictComposerRestore(host: ChatHost, snapshot: PendingComposerSnapshot) {
159+
// An attachment-only edit is still a newer draft. Restoring old text beside it
160+
// would combine two independently authored sends.
161+
const composerBlank = !host.chatMessage.trim() && host.chatAttachments.length === 0;
162+
const attachments = Boolean(
163+
snapshot.previousAttachments?.length && host.chatAttachments.length === 0 && composerBlank,
164+
);
165+
return { attachments, draft: snapshot.previousDraft != null && composerBlank };
166+
}
167+
168+
export function restoreComposer(host: ChatHost, snapshot: PendingComposerSnapshot): void {
169+
if (snapshot.previousDraft != null && !host.chatMessage.trim()) {
170+
host.chatMessage = snapshot.previousDraft;
171+
}
172+
if (snapshot.previousAttachments?.length && host.chatAttachments.length === 0) {
173+
host.chatAttachments = snapshot.previousAttachments;
174+
}
175+
}
176+
177+
export function cancelChatDelivery(
154178
host: ChatHost,
155-
opts: {
156-
previousAttachments?: ChatAttachment[];
157-
previousDraft?: string;
158-
},
159-
) {
160-
if (opts.previousDraft != null && !host.chatMessage.trim()) {
161-
host.chatMessage = opts.previousDraft;
179+
item: ChatQueueItem,
180+
snapshot: PendingComposerSnapshot,
181+
): void {
182+
const removed = removeVisibleOrScopedQueuedMessageWithoutReleasing(
183+
host,
184+
item.id,
185+
item.sessionKey,
186+
);
187+
const plan = removed ? strictComposerRestore(host, snapshot) : null;
188+
if (plan?.draft) {
189+
host.chatMessage = snapshot.previousDraft ?? "";
190+
}
191+
if (plan?.attachments) {
192+
host.chatAttachments = snapshot.previousAttachments ?? [];
162193
}
163-
if (opts.previousAttachments?.length && host.chatAttachments.length === 0) {
164-
host.chatAttachments = opts.previousAttachments;
194+
if (removed && !plan?.attachments) {
195+
releaseChatAttachmentPayloads(excludeComposerAttachments(host, removed.attachments));
165196
}
166197
}
167198

168-
type PendingComposerSnapshot = {
169-
previousAttachments?: ChatAttachment[];
170-
previousDraft?: string;
171-
};
199+
export function canRestoreComposer(host: ChatHost, snapshot?: PendingComposerSnapshot): boolean {
200+
const plan = strictComposerRestore(host, snapshot ?? {});
201+
return (
202+
(snapshot?.previousDraft !== undefined || snapshot?.previousAttachments !== undefined) &&
203+
(!snapshot.previousDraft?.trim() || plan.draft) &&
204+
(!snapshot.previousAttachments?.length || plan.attachments)
205+
);
206+
}
172207

173-
export function pendingComposerRestorePlan(host: ChatHost, snapshot: PendingComposerSnapshot) {
208+
function pendingComposerRestorePlan(host: ChatHost, snapshot: PendingComposerSnapshot) {
174209
const willRestoreDraft = snapshot.previousDraft != null && !host.chatMessage.trim();
175210
const willRestoreAttachments = Boolean(
176211
snapshot.previousAttachments?.length &&
@@ -185,32 +220,3 @@ export function pendingComposerRestorePlan(host: ChatHost, snapshot: PendingComp
185220
willRestoreDraft,
186221
};
187222
}
188-
189-
export function cancelPendingSendBeforeRequest(
190-
host: ChatHost,
191-
queued: ChatQueueItem,
192-
opts: PendingComposerSnapshot & {
193-
restoreComposer?: boolean;
194-
},
195-
) {
196-
const removed = removeVisibleOrScopedQueuedMessageWithoutReleasing(
197-
host,
198-
queued.id,
199-
queued.sessionKey,
200-
);
201-
const restoreComposer = opts.restoreComposer !== false && removed != null;
202-
const restorePlan = pendingComposerRestorePlan(host, opts);
203-
const willRestoreDraft = restoreComposer && restorePlan.willRestoreDraft;
204-
const willRestoreAttachments = restoreComposer && restorePlan.willRestoreAttachments;
205-
if (restoreComposer) {
206-
if (willRestoreDraft) {
207-
host.chatMessage = opts.previousDraft ?? "";
208-
}
209-
if (willRestoreAttachments) {
210-
host.chatAttachments = opts.previousAttachments ?? [];
211-
}
212-
}
213-
if (removed && !willRestoreAttachments) {
214-
releaseChatAttachmentPayloads(excludeComposerAttachments(host, removed.attachments));
215-
}
216-
}

0 commit comments

Comments
 (0)