Skip to content

Commit 352f035

Browse files
authored
Recover the same Workbench Chat Turn after a lost submission receipt (#10056)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent c7ba1a9 commit 352f035

2 files changed

Lines changed: 74 additions & 1 deletion

File tree

‎apps/workbench/packages/web/src/components/StewardConversation.tsx‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ export function StewardConversation({
142142
const turnRef = useRef<ManagerTurn | null>(null);
143143
const attemptRef = useRef(0);
144144
const cursorRef = useRef<string>('');
145+
const unconfirmedPost = useRef<{ sessionId: string; message: string; clientTurnId: string } | null>(null);
145146
const sendAbort = useRef<AbortController | null>(null);
146147
const streamAbort = useRef<AbortController | null>(null);
147148
const scrollAnchor = useRef<HTMLDivElement | null>(null);
@@ -172,6 +173,7 @@ export function StewardConversation({
172173
// a later status refresh does not open another session over the one already open.
173174
if (sessionOwner.current !== token) {
174175
sessionOwner.current = token;
176+
unconfirmedPost.current = null;
175177
attemptRef.current++;
176178
sendAbort.current?.abort();
177179
streamAbort.current?.abort();
@@ -365,7 +367,11 @@ export function StewardConversation({
365367
}
366368
setError(null);
367369
const localId = `local-${Date.now()}-${attempt}`;
368-
const clientTurnId = (crypto.randomUUID?.() ?? `${Date.now()}-${attempt}`);
370+
const previous = unconfirmedPost.current;
371+
const retry = previous?.sessionId === id && previous.message === body ? previous : null;
372+
// Rejecting a retry does not resolve the original POST whose receipt was lost.
373+
unconfirmedPost.current = retry;
374+
const clientTurnId = retry?.clientTurnId ?? (crypto.randomUUID?.() ?? `${Date.now()}-${attempt}`);
369375
showTurn({ turnId: clientTurnId, eventsPath: '', state: 'sending', steps: [], answer: '', error: null });
370376
setDraft('');
371377
setMessages(current => [...(current ?? []), { id: localId, role: 'user', text: body, createdAt: null, turnId: null }]);
@@ -374,6 +380,7 @@ export function StewardConversation({
374380
try {
375381
const { turnId, eventsPath } = await sendManagerTurn(token, id, body, clientTurnId, postController.signal);
376382
if (!ownsAttempt()) return;
383+
unconfirmedPost.current = null;
377384
showTurn({ turnId, eventsPath, state: 'streaming', steps: [], answer: '', error: null });
378385
await runStream(id, turnId, eventsPath, attempt);
379386
} catch (cause) {
@@ -389,6 +396,11 @@ export function StewardConversation({
389396
await runStream(id, turnId, eventsPath, attempt);
390397
return;
391398
}
399+
// A transport or gateway failure can hide a committed Core Turn. Resubmitting
400+
// the restored draft must recover that receipt with its original request ID.
401+
if (!(cause instanceof ManagerError) || cause.status >= 500 || cause.status === 408) {
402+
unconfirmedPost.current = { sessionId: id, message: body, clientTurnId };
403+
}
392404
showTurn(null);
393405
const message = managerErrorText(cause);
394406
setError(message);
@@ -652,6 +664,7 @@ export function StewardConversation({
652664
aria-label={t('composer.message')}
653665
onChange={event => {
654666
const nextValue = event.target.value;
667+
unconfirmedPost.current = null;
655668
setDraft(nextValue);
656669
if (canLookupSessions) {
657670
const start = typeof event.target.selectionStart === 'number' ? event.target.selectionStart : nextValue.length;

‎apps/workbench/packages/web/test/steward-conversation.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -613,6 +613,66 @@ test('pending waiting Goals float in a quiet orb chip above the steward composer
613613
}
614614
});
615615

616+
test('retry a lost POST receipt with the same identity only for the restored draft and session', async t => {
617+
const location = Object.getOwnPropertyDescriptor(globalThis, 'location');
618+
Object.defineProperty(globalThis, 'location', { configurable: true, value: { origin: 'http://localhost' } });
619+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
620+
const submissions: { client_turn_id: string; message: string }[] = [];
621+
let renderer: ReactTestRenderer | undefined;
622+
let loseReceipt = true;
623+
t.mock.method(globalThis, 'fetch', async (input: RequestInfo | URL, init: RequestInit) => {
624+
const url = String(input);
625+
if (url.endsWith('/sessions')) return json({ session_id: 'original' });
626+
if (url.endsWith('/sessions/original')) return json({ messages: [] });
627+
if (url.endsWith('/turns')) {
628+
submissions.push(JSON.parse(String(init.body)));
629+
if (submissions.length === 2) return new Response(null, { status: 429 });
630+
if (loseReceipt) throw new TypeError('response lost after acceptance');
631+
return json({ turn_id: 'accepted', events_url: '/api/chat/sessions/original/turns/accepted/events' });
632+
}
633+
if (url.endsWith('/events')) return new Response('event: turn.completed\ndata: {}\n\n');
634+
throw new Error('Unexpected endpoint ' + url);
635+
});
636+
const submit = async (text?: string) => {
637+
if (text !== undefined) await act(async () => {
638+
renderer!.root.findByType('textarea').props.onChange({ target: { value: text } });
639+
});
640+
await act(async () => { renderer!.root.findByType('form').props.onSubmit({ preventDefault() {} }); await tick(); });
641+
};
642+
const open = async (token: string) => {
643+
const element = createElement(StewardConversation, { token, failure: null });
644+
await act(async () => {
645+
if (renderer) renderer.update(element);
646+
else renderer = create(element, { createNodeMock: () => ({ scrollIntoView() {} }) });
647+
await tick();
648+
});
649+
};
650+
try {
651+
await open('scope-one');
652+
await submit('Check the draft');
653+
assert.equal(renderer!.root.findByType('textarea').props.value, 'Check the draft');
654+
loseReceipt = false;
655+
await submit();
656+
assert.deepEqual(submissions[1], submissions[0]);
657+
// A rejection of the retry leaves the outcome of the first submission unknown.
658+
assert.equal(renderer!.root.findByType('textarea').props.value, 'Check the draft');
659+
await submit();
660+
assert.deepEqual(submissions[2], submissions[0]);
661+
loseReceipt = true;
662+
await submit('Check the draft');
663+
assert.notEqual(submissions[3]!.client_turn_id, submissions[2]!.client_turn_id);
664+
await submit('Check the revision');
665+
assert.notEqual(submissions[4]!.client_turn_id, submissions[3]!.client_turn_id);
666+
await open('scope-two');
667+
await submit('Check the revision');
668+
assert.notEqual(submissions[5]!.client_turn_id, submissions[4]!.client_turn_id);
669+
} finally {
670+
await act(async () => renderer?.unmount());
671+
if (location) Object.defineProperty(globalThis, 'location', location);
672+
else Reflect.deleteProperty(globalThis, 'location');
673+
}
674+
});
675+
616676
test('deferring session open while a session open is pending clears the loading hint and shows the greeting', async () => {
617677
const saved = globalThis.fetch;
618678
const oldLocation = Object.getOwnPropertyDescriptor(globalThis, 'location');

0 commit comments

Comments
 (0)