Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions client/src/hooks/Input/useAutoSave.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,90 @@ describe('useAutoSave — typing as a run finishes', () => {
mockSetDraft.mockReset();
});

/** A send empties the composer before its run starts. Words still in it when a run starts were
* not sent: the reader reran a reply from its row, or a run started somewhere else reached this
* conversation. Restoring the (empty) pending record over them took them out of the field, and
* the end of the run cleared the conversation's record, their only copy. */
it('keeps a draft the composer holds when a run it did not send starts', () => {
const textAreaRef = makeTextAreaRef();
const { rerender } = renderHook(
({ isSubmitting }: { isSubmitting: boolean }) =>
useAutoSave({
isSubmitting,
conversationId: 'convo-1',
textAreaRef,
files: new Map(),
setFiles: jest.fn(),
}),
{ initialProps: { isSubmitting: false } },
);
act(() => {
type(textAreaRef, 'not sent yet');
jest.advanceTimersByTime(50);
});
mockSetValue.mockClear();

act(() => {
rerender({ isSubmitting: true });
});

/** Nothing is put in the field in their place, and they are kept for the run's duration. */
expect(mockSetValue).not.toHaveBeenCalled();
expect(textAreaRef.current!.value).toBe('not sent yet');
expect(actualUtils.getDraft(actualUtils.getPendingDraftId(0))).toBe('not sent yet');

act(() => {
rerender({ isSubmitting: false });
});

/** And they are the conversation's draft again once it ends. */
expect(actualUtils.getDraft('convo-1')).toBe('not sent yet');
expect(mockSetValue).not.toHaveBeenCalledWith('text', '');
});

it('still restores the pending draft when a run starts under an empty composer', () => {
const textAreaRef = makeTextAreaRef();
const { rerender } = renderHook(
({ isSubmitting }: { isSubmitting: boolean }) =>
useAutoSave({
isSubmitting,
conversationId: 'convo-1',
textAreaRef,
files: new Map(),
setFiles: jest.fn(),
}),
{ initialProps: { isSubmitting: false } },
);
mockSetValue.mockClear();

act(() => {
rerender({ isSubmitting: true });
});

expect(mockSetValue).toHaveBeenLastCalledWith('text', '');
});

/** A composer drawn with words already in it, as one beside the chat is when the layout draws
* it again, has no earlier conversation those words could belong to. An empty record is not a
* draft to put in their place. */
it('keeps the words a composer is drawn with when there is no draft to restore', () => {
const textAreaRef = makeTextAreaRef();
textAreaRef.current!.value = 'handed to it';

renderHook(() =>
useAutoSave({
isSubmitting: true,
conversationId: 'convo-1',
textAreaRef,
files: new Map(),
setFiles: jest.fn(),
}),
);

expect(mockSetValue).not.toHaveBeenCalledWith('text', '');
expect(actualUtils.getDraft(actualUtils.getPendingDraftId(0))).toBe('handed to it');
});

/** The reported bug. The composer is keyed under PENDING while a run streams and under the
* conversation once it ends, and the key change tore off whatever the 25ms debounce had not
* written yet: the pending record still held the previous flush, run end migrated that record,
Expand Down
32 changes: 28 additions & 4 deletions client/src/hooks/Input/useAutoSave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,11 +450,21 @@ export const useAutoSave = ({
return;
}

const startsRun =
currentConversationId === conversationDraftId && conversationId === pendingDraftId;
const endsRun =
currentConversationId === pendingDraftId && conversationId === conversationDraftId;
/**
* A send empties the composer before its run starts, so words still in it when a run starts
* were not sent: a draft written before a rerun, or before a run started elsewhere reached
* this conversation. They stay in the field, as staged files do. Restoring the pending
* record over them took them out of it, and the end of the run then cleared the
* conversation's record, which by then was their only copy.
*/
const keepsWords = startsRun && (textAreaRef?.current?.value ?? '') !== '';
const sameComposerPhase =
filesRef.current.size > 0 &&
currentDraft?.conversationId === (_conversationId ?? Constants.NEW_CONVO) &&
((currentConversationId === conversationDraftId && conversationId === pendingDraftId) ||
(currentConversationId === pendingDraftId && conversationId === conversationDraftId));
(keepsWords || (filesRef.current.size > 0 && (startsRun || endsRun)));
// A rerun changes the storage phase, not the owner of an unrelated live draft.
if (!sameComposerPhase) {
setFiles((current) => (current.size === 0 ? current : new Map()));
Expand Down Expand Up @@ -586,7 +596,21 @@ export const useAutoSave = ({
saveText(textDraftId);
} else if (isFilesDraftOwnedByThisTab(getFilesDraft(filesDraftId))) {
const pendingPastes = restoreFiles(filesDraftId);
restoreText(textDraftId, pendingPastes);
/**
* A composer drawn with words already in it (handed to it by whatever drew it) and no
* record to restore keeps them: an empty record is no draft to put in their place. Only
* on its first pass, where there is no earlier conversation whose words these could be.
*/
const startsWithWords =
currentConversationId == null &&
pendingPastes.length === 0 &&
(textAreaRef?.current?.value ?? '') !== '' &&
(getDraft(textDraftId) ?? '') === '';
if (startsWithWords) {
saveText(textDraftId);
} else {
restoreText(textDraftId, pendingPastes);
}
}
} catch (e) {
console.error(e);
Expand Down
64 changes: 64 additions & 0 deletions e2e/specs/mock/scenarios/composer-draft-survives-run.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { expect, test } from '@playwright/test';
import {
replyText,
replyPrompt,
messagesView,
NEW_CHAT_PATH,
MOCK_ENDPOINTS,
selectMockEndpoint,
sendMessageAndWaitForCompletion,
} from '../helpers';

/**
* Words written in the composer and not sent stay there when a run starts that the composer did
* not send: a reply rerun from its row, for one.
*/
test.use({ viewport: { width: 1440, height: 900 }, isMobile: false, hasTouch: false });

const uniqueLabel = (prefix: string) =>
`${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;

test('a draft stays in the composer while a reply is regenerated, and after @scenario:composer-draft-survives-a-regenerate', async ({
page,
}) => {
test.setTimeout(120_000);
const label = uniqueLabel('rerun');
await page.goto(NEW_CHAT_PATH, { timeout: 10_000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
const first = await sendMessageAndWaitForCompletion(page, replyPrompt(label));
expect(first.ok()).toBeTruthy();
await expect(messagesView(page).getByText(replyText(label))).toBeVisible();

const composer = page
.locator('main form')
.first()
.getByRole('textbox', { name: 'Message input' });
await composer.click();
await page.keyboard.type('still writing this one');

const reply = messagesView(page).locator('.message-render').last();
await reply.hover();
const [rerun] = await Promise.all([
page.waitForRequest(
(request) =>
request.method() === 'POST' &&
/\/api\/agents\/chat\/[^/]+$/.test(new URL(request.url()).pathname),
),
reply.getByRole('button', { name: 'Regenerate' }).click(),
]);
expect((rerun.postDataJSON() as { isRegenerate?: boolean }).isRegenerate).toBe(true);

/** While the rerun is under way, and once it is over, the words are where they were. */
await expect(composer).toHaveValue('still writing this one');
await expect(page.getByRole('button', { name: 'Stop generating' })).toHaveCount(0, {
timeout: 60_000,
});
await expect(messagesView(page).getByText(/2\s*\/\s*2/)).toBeVisible();
await expect(composer).toHaveValue('still writing this one');

/** And they are still the conversation's draft after a reload. */
await page.reload();
await expect(
page.locator('main form').first().getByRole('textbox', { name: 'Message input' }),
).toHaveValue('still writing this one', { timeout: 30_000 });
});
Loading