Skip to content

Commit e040e1a

Browse files
committed
fix(ui): harden offline queue replay
1 parent 470343f commit e040e1a

13 files changed

Lines changed: 2814 additions & 134 deletions

‎ui/src/lib/chat/chat-types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export type ChatQueueItem = {
3030
| "waiting-model"
3131
| "waiting-idle"
3232
| "executing-command"
33+
| "steering"
3334
| "sending"
3435
| "waiting-reconnect"
3536
| "unconfirmed"

‎ui/src/pages/chat/chat-pane.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,21 @@ import type { SidebarContent } from "./components/chat-sidebar.ts";
1717

1818
type TestChatPane = HTMLElement & {
1919
active: boolean;
20+
chatState: { attach: (state: ChatPageHost) => void };
2021
context: ApplicationContext;
2122
state: ChatPageHost;
2223
connectedClient: GatewayBrowserClient | null;
24+
connectedCallback: () => void;
2325
connectionGeneration: number;
2426
createSession: () => Promise<boolean>;
27+
disconnectedCallback: () => void;
2528
acceptTaskSuggestion: (suggestion: TaskSuggestion) => Promise<void>;
2629
handleDocumentKeydown: (event: KeyboardEvent) => void;
2730
handleTaskSuggestionEvent: (event: TaskSuggestionEvent) => void;
2831
refreshTaskSuggestions: () => Promise<void>;
2932
taskSuggestions: TaskSuggestion[];
3033
onPaneSessionChange?: (paneId: string, sessionKey: string) => void;
34+
sessionKey: string;
3135
};
3236

3337
const suggestion: TaskSuggestion = {
@@ -113,6 +117,52 @@ function createTestChatPane(params: { client: GatewayBrowserClient; sessions: Se
113117
return { pane, requestUpdate, state };
114118
}
115119

120+
describe("chat pane initialization", () => {
121+
it("sets the pane route before attaching outbox projection", () => {
122+
const pane = document.createElement("openclaw-chat-pane") as unknown as TestChatPane;
123+
const targetSessionKey = "agent:main:pane-b";
124+
pane.sessionKey = targetSessionKey;
125+
pane.context = {
126+
basePath: "",
127+
gateway: { snapshot: { hello: null } },
128+
config: {
129+
current: {
130+
assistantIdentity: {
131+
agentId: null,
132+
name: "Assistant",
133+
avatar: null,
134+
avatarSource: null,
135+
avatarStatus: null,
136+
avatarReason: null,
137+
},
138+
serverVersion: null,
139+
localMediaPreviewRoots: [],
140+
embedSandboxMode: "strict",
141+
allowExternalEmbedUrls: false,
142+
chatMessageMaxWidth: null,
143+
terminalEnabled: false,
144+
},
145+
},
146+
agentSelection: { state: { selectedId: "main" } },
147+
agents: { state: { agentsList: null } },
148+
sessions: {},
149+
} as unknown as ApplicationContext;
150+
const stopAfterAttach = new Error("stop after attach");
151+
let attachedSessionKey: string | undefined;
152+
vi.spyOn(pane.chatState, "attach").mockImplementation((state) => {
153+
attachedSessionKey = state.sessionKey;
154+
throw stopAfterAttach;
155+
});
156+
157+
try {
158+
expect(() => pane.connectedCallback()).toThrow(stopAfterAttach);
159+
expect(attachedSessionKey).toBe(targetSessionKey);
160+
} finally {
161+
pane.disconnectedCallback();
162+
}
163+
});
164+
});
165+
116166
describe("chat pane keyboard shortcuts", () => {
117167
it("toggles only the active pane's session workspace", () => {
118168
const client = {} as GatewayBrowserClient;

‎ui/src/pages/chat/chat-pane.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -828,6 +828,9 @@ class ChatPane extends OpenClawLightDomElement {
828828
pageState.requestUpdate?.();
829829
};
830830
this.state = pageState;
831+
if (this.sessionKey) {
832+
this.setPaneSessionKey(this.sessionKey);
833+
}
831834
chatState.attach(pageState);
832835
const mediaDevices = globalThis.navigator?.mediaDevices;
833836
if (mediaDevices?.addEventListener) {
@@ -837,9 +840,6 @@ class ChatPane extends OpenClawLightDomElement {
837840
mediaDevices.removeEventListener("devicechange", handleDeviceChange),
838841
);
839842
}
840-
if (this.sessionKey) {
841-
this.setPaneSessionKey(this.sessionKey);
842-
}
843843
chatState.restoreComposer({ preserveCurrent: true });
844844
chatState.startComposerPersistence();
845845
if (this.draft !== undefined) {

‎ui/src/pages/chat/chat-queue.ts‎

Lines changed: 185 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,63 @@ type ChatQueueSessionHost = ChatQueueStoreHost &
3838
type ChatQueueScopedSessionHost = ChatQueueSessionHost & SessionScopeHost;
3939

4040
const chatOutboxProjectionHosts = new Set<ChatQueueScopedSessionHost>();
41+
// Durable rows use crash-safe states. Overlay live work process-wide so panes
42+
// attached mid-operation cannot retry or remove it before the owner settles.
43+
const transientQueueProjections = new Map<string, ChatQueueItem>();
44+
// A failed row may exist only in one pane when storage admission fails. Track
45+
// that provenance so projection keeps it without resurrecting removed durable rows.
46+
const localRecoveryItemIds = new WeakMap<ChatQueueScopedSessionHost, Set<string>>();
47+
48+
function markLocalRecoveryItem(host: ChatQueueScopedSessionHost, id: string): void {
49+
const ids = localRecoveryItemIds.get(host) ?? new Set<string>();
50+
ids.add(id);
51+
localRecoveryItemIds.set(host, ids);
52+
}
53+
54+
function clearLocalRecoveryItem(host: ChatQueueScopedSessionHost, id: string): void {
55+
const ids = localRecoveryItemIds.get(host);
56+
ids?.delete(id);
57+
if (ids?.size === 0) {
58+
localRecoveryItemIds.delete(host);
59+
}
60+
}
61+
62+
function queueProjectionGatewayKey(host: ChatComposerScope): string {
63+
return host.settings?.gatewayUrl?.trim() || "default";
64+
}
65+
66+
function transientQueueProjectionKey(
67+
host: ChatComposerScope,
68+
scope: StoredChatOutboxScope,
69+
id: string,
70+
): string {
71+
return `${queueProjectionGatewayKey(host)}\u0000${storedChatOutboxScopeKey(scope)}\u0000${id}`;
72+
}
73+
74+
function transientQueueProjection(
75+
host: ChatComposerScope,
76+
outbox: StoredChatOutbox,
77+
id: string,
78+
): ChatQueueItem | undefined {
79+
return transientQueueProjections.get(transientQueueProjectionKey(host, outbox, id));
80+
}
81+
82+
function isProcessLiveQueueProjection(item: ChatQueueItem): boolean {
83+
return item.sendState === "sending" || item.sendState === "executing-command";
84+
}
85+
86+
function updateProcessLiveQueueProjection(
87+
host: ChatComposerScope,
88+
scope: StoredChatOutboxScope,
89+
item: ChatQueueItem,
90+
): void {
91+
const key = transientQueueProjectionKey(host, scope, item.id);
92+
if (isProcessLiveQueueProjection(item)) {
93+
transientQueueProjections.set(key, item);
94+
} else {
95+
transientQueueProjections.delete(key);
96+
}
97+
}
4198

4299
function storedOutboxContainingItem(
43100
host: ChatComposerScope,
@@ -46,7 +103,7 @@ function storedOutboxContainingItem(
46103
return listStoredChatOutboxes(host).find((outbox) => outbox.queue.some((item) => item.id === id));
47104
}
48105

49-
function sameStoredOutboxScope(left: StoredChatOutbox, right: StoredChatOutbox): boolean {
106+
function sameStoredOutboxScope(left: StoredChatOutboxScope, right: StoredChatOutboxScope): boolean {
50107
return left.sessionKey === right.sessionKey && left.agentId === right.agentId;
51108
}
52109

@@ -63,18 +120,32 @@ function outboxAfterMutation(host: ChatComposerScope, before: StoredChatOutbox):
63120
export function syncChatQueueFromStoredOutbox(
64121
host: ChatQueueScopedSessionHost,
65122
outbox: StoredChatOutbox,
123+
options: { requestUpdate?: boolean } = {},
66124
) {
67125
const visible = visibleSessionMatches(host, outbox.sessionKey, outbox.agentId);
68126
const scopeKey = storedChatOutboxScopeKey(outbox);
69127
const current = visible ? host.chatQueue : (host.chatQueueByScope?.[scopeKey] ?? []);
70128
const ephemeral = current.filter((item) => item.pendingRunId);
129+
const ephemeralById = new Map(ephemeral.map((item) => [item.id, item]));
71130
const storedIds = new Set(outbox.queue.map((item) => item.id));
72131
// Storage failures can leave a manual-retry row in memory only. Projection
73132
// must not erase that last recoverable copy while another send is active.
74133
const localRecovery = current.filter(
75-
(item) => item.sendState === "failed" && !item.pendingRunId && !storedIds.has(item.id),
134+
(item) =>
135+
item.sendState === "failed" &&
136+
!item.pendingRunId &&
137+
!storedIds.has(item.id) &&
138+
localRecoveryItemIds.get(host)?.has(item.id),
76139
);
77140
const projected = outbox.queue.map((item) => {
141+
const ephemeralItem = ephemeralById.get(item.id);
142+
if (ephemeralItem) {
143+
return ephemeralItem;
144+
}
145+
const transientItem = transientQueueProjection(host, outbox, item.id);
146+
if (transientItem) {
147+
return transientItem;
148+
}
78149
const local = current.find(
79150
(candidate) => candidate.id === item.id && candidate.sendRunId === item.sendRunId,
80151
);
@@ -104,7 +175,8 @@ export function syncChatQueueFromStoredOutbox(
104175
: {}),
105176
};
106177
});
107-
const queue = [...projected, ...localRecovery, ...ephemeral].toSorted(
178+
const detachedEphemeral = ephemeral.filter((item) => !storedIds.has(item.id));
179+
const queue = [...projected, ...localRecovery, ...detachedEphemeral].toSorted(
108180
(left, right) => left.createdAt - right.createdAt,
109181
);
110182
if (visible) {
@@ -118,7 +190,21 @@ export function syncChatQueueFromStoredOutbox(
118190
}
119191
host.chatQueueByScope = queueByScope;
120192
}
121-
host.requestUpdate?.();
193+
if (options.requestUpdate !== false) {
194+
host.requestUpdate?.();
195+
}
196+
}
197+
198+
export function syncVisibleChatQueueProjection(
199+
host: ChatQueueScopedSessionHost,
200+
options: { requestUpdate?: boolean } = {},
201+
): void {
202+
const outbox = listStoredChatOutboxes(host).find((candidate) =>
203+
visibleSessionMatches(host, candidate.sessionKey, candidate.agentId),
204+
);
205+
if (outbox) {
206+
syncChatQueueFromStoredOutbox(host, outbox, options);
207+
}
122208
}
123209

124210
function publishStoredOutbox(source: ChatQueueScopedSessionHost, outbox: StoredChatOutbox) {
@@ -138,8 +224,60 @@ function publishStoredOutbox(source: ChatQueueScopedSessionHost, outbox: StoredC
138224
}
139225
}
140226

227+
function storedOutboxForProjection(
228+
host: ChatQueueScopedSessionHost,
229+
scope: StoredChatOutboxScope,
230+
): StoredChatOutbox {
231+
return (
232+
listStoredChatOutboxes(host).find((outbox) => sameStoredOutboxScope(outbox, scope)) ?? {
233+
...scope,
234+
queue: [],
235+
}
236+
);
237+
}
238+
239+
export function setTransientQueuedMessageProjection(
240+
host: ChatQueueScopedSessionHost,
241+
sessionKey: string,
242+
item: ChatQueueItem,
243+
agentId?: string,
244+
): boolean {
245+
const scope = resolveStoredChatOutboxScope(host, sessionKey, agentId);
246+
const outbox = storedOutboxForProjection(host, scope);
247+
if (!outbox.queue.some((entry) => entry.id === item.id)) {
248+
return false;
249+
}
250+
transientQueueProjections.set(transientQueueProjectionKey(host, scope, item.id), item);
251+
syncChatQueueFromStoredOutbox(host, outbox);
252+
publishStoredOutbox(host, outbox);
253+
return true;
254+
}
255+
256+
export function clearTransientQueuedMessageProjection(
257+
host: ChatQueueScopedSessionHost,
258+
sessionKey: string,
259+
id: string,
260+
agentId?: string,
261+
) {
262+
const scope = resolveStoredChatOutboxScope(host, sessionKey, agentId);
263+
transientQueueProjections.delete(transientQueueProjectionKey(host, scope, id));
264+
const outbox = storedOutboxForProjection(host, scope);
265+
syncChatQueueFromStoredOutbox(host, outbox);
266+
publishStoredOutbox(host, outbox);
267+
}
268+
141269
export function subscribeChatOutboxProjection(host: ChatQueueScopedSessionHost): () => void {
142270
chatOutboxProjectionHosts.add(host);
271+
for (const outbox of listStoredChatOutboxes(host)) {
272+
const visible = visibleSessionMatches(host, outbox.sessionKey, outbox.agentId);
273+
const hasCachedScope = Object.hasOwn(
274+
host.chatQueueByScope ?? {},
275+
storedChatOutboxScopeKey(outbox),
276+
);
277+
if (visible || hasCachedScope) {
278+
syncChatQueueFromStoredOutbox(host, outbox);
279+
}
280+
}
143281
return () => chatOutboxProjectionHosts.delete(host);
144282
}
145283

@@ -205,6 +343,29 @@ export function readChatQueueForScope(
205343
: (host.chatQueueByScope?.[storedChatOutboxScopeKey(scope)] ?? []);
206344
}
207345

346+
export function replacePendingQueuedMessageProjection(
347+
host: ChatQueueScopedSessionHost,
348+
sessionKey: string,
349+
id: string,
350+
pendingRunId: string,
351+
replacement: ChatQueueItem,
352+
agentId?: string,
353+
): boolean {
354+
const queue = readChatQueueForScope(host, sessionKey, agentId);
355+
if (!queue.some((item) => item.id === id && item.pendingRunId === pendingRunId)) {
356+
return false;
357+
}
358+
writeChatQueueForScope(
359+
host,
360+
sessionKey,
361+
queue.map((item) =>
362+
item.id === id && item.pendingRunId === pendingRunId ? replacement : item,
363+
),
364+
agentId,
365+
);
366+
return true;
367+
}
368+
208369
function writeChatQueueForScope(
209370
host: ChatQueueScopedSessionHost,
210371
sessionKey: string,
@@ -314,9 +475,15 @@ export function updateQueuedMessageForSession(
314475
stored.agentId ?? current.agentId ?? nextItem.agentId,
315476
)
316477
) {
317-
syncChatQueueFromStoredOutbox(host, outboxAfterMutation(host, stored));
478+
if (!isProcessLiveQueueProjection(nextItem)) {
479+
updateProcessLiveQueueProjection(host, scope, nextItem);
480+
}
481+
const persisted = outboxAfterMutation(host, stored);
482+
syncChatQueueFromStoredOutbox(host, persisted);
483+
publishStoredOutbox(host, persisted);
318484
return null;
319485
}
486+
updateProcessLiveQueueProjection(host, scope, nextItem);
320487
const nextQueue = queue.map((item) => (item.id === id ? nextItem : item));
321488
if (location) {
322489
writeLocatedChatQueue(host, location, nextQueue);
@@ -339,8 +506,12 @@ export function admitQueuedMessageForSession(
339506
item: ChatQueueItem,
340507
): boolean {
341508
if (!admitStoredChatComposerQueueItem(host, sessionKey, item, item.agentId)) {
509+
if (item.sendState === "failed") {
510+
markLocalRecoveryItem(host, item.id);
511+
}
342512
return false;
343513
}
514+
clearLocalRecoveryItem(host, item.id);
344515
const stored = storedOutboxContainingItem(host, item.id);
345516
if (!stored) {
346517
return false;
@@ -375,9 +546,14 @@ export function removeQueuedMessageWithoutReleasing(
375546
stored.agentId ?? item.agentId,
376547
)
377548
) {
378-
syncChatQueueFromStoredOutbox(host, outboxAfterMutation(host, stored));
549+
const persisted = outboxAfterMutation(host, stored);
550+
syncChatQueueFromStoredOutbox(host, persisted);
551+
publishStoredOutbox(host, persisted);
379552
return null;
380553
}
554+
if (item) {
555+
transientQueueProjections.delete(transientQueueProjectionKey(host, scope, item.id));
556+
}
381557
const nextQueue = queue.filter((entry) => entry.id !== id);
382558
if (location) {
383559
writeLocatedChatQueue(host, location, nextQueue);
@@ -387,6 +563,9 @@ export function removeQueuedMessageWithoutReleasing(
387563
if (stored) {
388564
publishStoredOutbox(host, outboxAfterMutation(host, stored));
389565
}
566+
if (item) {
567+
clearLocalRecoveryItem(host, id);
568+
}
390569
return item;
391570
}
392571

0 commit comments

Comments
 (0)