diff --git a/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx b/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx index c7764696c7f..f7660d18d18 100644 --- a/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx +++ b/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx @@ -2207,7 +2207,7 @@ describe("PluginNewThreadComposer seeding", () => { expect(promptBoxText()).toBe("review every PR for slop"); }); - it("does not replace a new draft when submission fails", async () => { + it("merges a failed submission ahead of a new draft", async () => { let failSubmit: (() => void) | null = null; const onSubmit = vi.fn( () => @@ -2235,7 +2235,7 @@ describe("PluginNewThreadComposer seeding", () => { await waitFor(() => { expect(latestPromptBoxProps().isSubmitting).toBe(false); }); - expect(promptBoxText()).toBe("next thread"); + expect(promptBoxText()).toBe("review every PR for slop\n\nnext thread"); }); it("accepts overlapping uploads and stays busy until every batch settles", async () => { diff --git a/apps/app/src/components/promptbox/NewThreadComposer.tsx b/apps/app/src/components/promptbox/NewThreadComposer.tsx index 7609a06f340..e395cc1a2c4 100644 --- a/apps/app/src/components/promptbox/NewThreadComposer.tsx +++ b/apps/app/src/components/promptbox/NewThreadComposer.tsx @@ -107,6 +107,7 @@ import { useSidebarNavigation } from "@/hooks/queries/sidebar-navigation-query"; import { useSystemConfig } from "@/hooks/queries/system-queries"; import type { CommandSuggestionSource } from "@/hooks/useCommandSuggestions"; import { + sendPromptDraft, usePromptDraftController, usePromptDraftInputEmpty, type PromptDraftController, @@ -750,14 +751,14 @@ async function submitNewThreadRequest({ isSubmittingRef.current = true; setIsSubmitting(true); setAttachmentError(null); - const clearedSubmittedDraft = - promptDraft.clearIfCurrentMatches(submittedDraft); recordTelemetryEvent({ name: "new_thread_submit", properties: { outcome: "started" }, }); try { - await onSubmit(request); + await sendPromptDraft(promptDraft, submittedDraft, async () => { + await onSubmit(request); + }); recordTelemetryEvent({ name: "new_thread_submit", properties: { outcome: "accepted" }, @@ -771,9 +772,6 @@ async function submitNewThreadRequest({ failure_reason: operationFailureReason(submitError), }, }); - if (clearedSubmittedDraft) { - promptDraft.restoreIfEmpty(submittedDraft); - } throw submitError; } finally { isSubmittingRef.current = false; @@ -1672,7 +1670,7 @@ export function NewThreadComposer({ ); const initialPromptDraft = useInitialPromptDraft(seed?.initialPrompt ?? null); - const seedInitialPrompt = promptDraft.restoreIfEmpty; + const seedInitialPrompt = promptDraft.seedIfEmpty; const focusPromptBox = useCallback(() => { setLocalPromptBoxFocusRequest((current) => (current ?? 0) + 1); }, []); diff --git a/apps/app/src/components/thread/composer/useInlineQueuedMessageEditing.ts b/apps/app/src/components/thread/composer/useInlineQueuedMessageEditing.ts index 24b0ff66647..6e196c0ac40 100644 --- a/apps/app/src/components/thread/composer/useInlineQueuedMessageEditing.ts +++ b/apps/app/src/components/thread/composer/useInlineQueuedMessageEditing.ts @@ -9,12 +9,18 @@ import { import type { ThreadQueuedMessage } from "@bb/domain"; import type { QueuedMessageEditRequest } from "@/components/promptbox/banner/LazyQueuedMessagesList"; import type { PromptDraftState } from "@bb/client-core"; -import { queuedInputToDraft } from "@bb/client-core"; +import { + arePromptDraftStatesEqual, + isPromptDraftEmpty, + queuedInputToDraft, +} from "@bb/client-core"; +import { useLatestRef } from "@/hooks/useLatestRef"; import type { InlineComposerDraftSession } from "./useActiveComposerDraft"; import { useQueuedMessageEditHold } from "./useQueuedMessageEditHold"; export interface InlineQueuedMessageEditState { draft: PromptDraftState; + initialDraft: PromptDraftState; editSessionId: number; expectedUpdatedAt: number; model: ThreadQueuedMessage["model"]; @@ -30,6 +36,7 @@ interface UseInlineQueuedMessageEditingArgs { ownerThreadId: string; queuedMessages: readonly ThreadQueuedMessage[]; onBeginEdit?: () => void; + onUnsavedEditLost: (draft: PromptDraftState) => void; } interface UseInlineQueuedMessageEditingResult { @@ -44,10 +51,18 @@ interface UseInlineQueuedMessageEditingResult { ) => InlineQueuedMessageEditState | null, ) => void; dismissInlineQueuedMessageEditor: () => void; + abandonInlineQueuedMessageEdit: () => void; beginEditQueuedMessage: (request: QueuedMessageEditRequest) => void; queuedMessageDraftSession: InlineComposerDraftSession | null; } +function hasUnsavedChanges(edit: InlineQueuedMessageEditState): boolean { + return ( + !isPromptDraftEmpty(edit.draft) && + !arePromptDraftStatesEqual(edit.draft, edit.initialDraft) + ); +} + function isLiveInlineQueuedMessageEdit( edit: InlineQueuedMessageEditState, ownerThreadId: string, @@ -63,7 +78,9 @@ export function useInlineQueuedMessageEditing({ ownerThreadId, queuedMessages, onBeginEdit, + onUnsavedEditLost, }: UseInlineQueuedMessageEditingArgs): UseInlineQueuedMessageEditingResult { + const onUnsavedEditLostRef = useLatestRef(onUnsavedEditLost); const [inlineEditingQueuedMessageState, setInlineEditingQueuedMessage] = useState(null); const inlineEditingQueuedMessageRef = @@ -107,6 +124,21 @@ export function useInlineQueuedMessageEditing({ const dismissInlineQueuedMessageEditor = useCallback(() => { commitInlineQueuedMessage(null); }, [commitInlineQueuedMessage]); + const recoverUnsavedEdit = useCallback( + (edit: InlineQueuedMessageEditState) => { + if (hasUnsavedChanges(edit)) { + onUnsavedEditLostRef.current(edit.draft); + } + }, + [onUnsavedEditLostRef], + ); + const abandonInlineQueuedMessageEdit = useCallback(() => { + const current = inlineEditingQueuedMessageRef.current; + if (current !== null) { + recoverUnsavedEdit(current); + } + commitInlineQueuedMessage(null); + }, [commitInlineQueuedMessage, recoverUnsavedEdit]); const inlineEditingQueuedMessage = useMemo( () => @@ -133,12 +165,15 @@ export function useInlineQueuedMessageEditing({ !isLiveInlineQueuedMessageEdit(current, ownerThreadId, queuedMessages) ) { inlineEditingQueuedMessageRef.current = null; + if (current.ownerThreadId === ownerThreadId) { + recoverUnsavedEdit(current); + } } - }, [ownerThreadId, queuedMessages]); + }, [ownerThreadId, queuedMessages, recoverUnsavedEdit]); useQueuedMessageEditHold({ queuedMessageId: inlineEditingQueuedMessage?.queuedMessageId ?? null, threadId: inlineEditingQueuedMessage?.ownerThreadId ?? null, - onRejected: dismissInlineQueuedMessageEditor, + onRejected: abandonInlineQueuedMessageEdit, }); const beginEditQueuedMessage = useCallback( @@ -147,8 +182,10 @@ export function useInlineQueuedMessageEditing({ if (!queuedMessage) { return; } + const initialDraft = queuedInputToDraft(queuedMessage.content); commitInlineQueuedMessage({ - draft: queuedInputToDraft(queuedMessage.content), + draft: initialDraft, + initialDraft, editSessionId: (inlineEditSessionIdRef.current += 1), expectedUpdatedAt: queuedMessage.updatedAt, model: queuedMessage.model, @@ -189,6 +226,7 @@ export function useInlineQueuedMessageEditing({ commitInlineQueuedMessage, updateInlineQueuedMessage, dismissInlineQueuedMessageEditor, + abandonInlineQueuedMessageEdit, beginEditQueuedMessage, queuedMessageDraftSession, }; diff --git a/apps/app/src/components/thread/composer/useQueuedMessageActions.ts b/apps/app/src/components/thread/composer/useQueuedMessageActions.ts index bc198b2b5fb..812229c16ea 100644 --- a/apps/app/src/components/thread/composer/useQueuedMessageActions.ts +++ b/apps/app/src/components/thread/composer/useQueuedMessageActions.ts @@ -48,6 +48,7 @@ interface UseQueuedMessageActionsArgs { onSaveSuccess?: () => void; inlineEditingQueuedMessage: InlineQueuedMessageEditState | null; dismissInlineQueuedMessageEditor: () => void; + abandonInlineQueuedMessageEdit: () => void; activeComposerDraftInput: PromptInput[]; } @@ -149,6 +150,7 @@ async function saveInlineQueuedMessage({ updateQueuedMessage, onSaveSuccess, dismissInlineQueuedMessageEditor, + abandonInlineQueuedMessageEdit, setProcessingQueuedMessage, }: { edit: InlineQueuedMessageEditState; @@ -160,6 +162,7 @@ async function saveInlineQueuedMessage({ >; onSaveSuccess: (() => void) | undefined; dismissInlineQueuedMessageEditor: () => void; + abandonInlineQueuedMessageEdit: () => void; setProcessingQueuedMessage: SetProcessingQueuedMessage; }): Promise { const { expectedUpdatedAt, ownerThreadId, queuedMessageId } = edit; @@ -176,7 +179,7 @@ async function saveInlineQueuedMessage({ dismissInlineQueuedMessageEditor(); } catch (error) { if (error instanceof BbHttpError && error.status === 404) { - dismissInlineQueuedMessageEditor(); + abandonInlineQueuedMessageEdit(); } showMutationErrorToast({ error, @@ -198,6 +201,7 @@ export function useQueuedMessageActions({ onSaveSuccess, inlineEditingQueuedMessage, dismissInlineQueuedMessageEditor, + abandonInlineQueuedMessageEdit, activeComposerDraftInput, }: UseQueuedMessageActionsArgs): UseQueuedMessageActionsResult { const updateQueuedMessage = useUpdateThreadQueuedMessage(); @@ -269,7 +273,7 @@ export function useQueuedMessageActions({ (message) => message.id === inlineEditingQueuedMessage.queuedMessageId, ) ) { - dismissInlineQueuedMessageEditor(); + abandonInlineQueuedMessageEdit(); return; } const queuedMessage = queuedMessagesRef.current.find( @@ -282,9 +286,11 @@ export function useQueuedMessageActions({ updateQueuedMessage, onSaveSuccess, dismissInlineQueuedMessageEditor, + abandonInlineQueuedMessageEdit, setProcessingQueuedMessage, }); }, [ + abandonInlineQueuedMessageEdit, activeComposerDraftInput, dismissInlineQueuedMessageEditor, inlineEditingQueuedMessage, diff --git a/apps/app/src/hooks/usePromptDraftStorage.test.tsx b/apps/app/src/hooks/usePromptDraftStorage.test.tsx index 98bf872fdbd..b97662ba479 100644 --- a/apps/app/src/hooks/usePromptDraftStorage.test.tsx +++ b/apps/app/src/hooks/usePromptDraftStorage.test.tsx @@ -6,6 +6,7 @@ import { act, cleanup, render, renderHook } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { getPromptDraftAccessor, + sendPromptDraft, usePromptDraftController, usePromptDraftInputEmpty, usePromptDraftInputThreadIds, @@ -406,3 +407,58 @@ describe("usePromptDraftController", () => { expect(result.current.text).toBe("typed"); }); }); + +describe("sendPromptDraft", () => { + const submitted = { + text: "message being sent", + mentions: [], + attachments: [ + { type: "localFile" as const, path: "uploads/a.txt", name: "a.txt" }, + ], + }; + + it("clears the draft and leaves it cleared when the send succeeds", async () => { + const draft = getPromptDraftAccessor(uniqueScope()); + draft.setDraft(submitted); + + await sendPromptDraft(draft, submitted, async () => { + expect(draft.getCurrent().text).toBe(""); + }); + + expect(draft.getCurrent().text).toBe(""); + }); + + it("merges a failed send back ahead of text typed while it was pending", async () => { + const draft = getPromptDraftAccessor(uniqueScope()); + draft.setDraft(submitted); + + await expect( + sendPromptDraft(draft, submitted, async () => { + draft.setTextAndMentions("next thought", []); + throw new Error("Simulated transport failure"); + }), + ).rejects.toThrow("Simulated transport failure"); + + expect(draft.getCurrent()).toEqual({ + ...submitted, + text: "message being sent\n\nnext thought", + }); + }); + + it("does not restore a draft it never cleared", async () => { + const draft = getPromptDraftAccessor(uniqueScope()); + draft.setDraft({ + text: "changed before send", + mentions: [], + attachments: [], + }); + + await expect( + sendPromptDraft(draft, submitted, async () => { + throw new Error("Simulated transport failure"); + }), + ).rejects.toThrow("Simulated transport failure"); + + expect(draft.getCurrent().text).toBe("changed before send"); + }); +}); diff --git a/apps/app/src/hooks/usePromptDraftStorage.ts b/apps/app/src/hooks/usePromptDraftStorage.ts index 1bafb40c96b..b5bfd3457bb 100644 --- a/apps/app/src/hooks/usePromptDraftStorage.ts +++ b/apps/app/src/hooks/usePromptDraftStorage.ts @@ -5,6 +5,7 @@ import { arePromptDraftStatesEqual, emptyPromptDraftState, isPromptDraftEmpty, + mergeUnsentPromptDraft, parsePromptDraftStorage, promptDraftToInput, serializePromptDraftStorage, @@ -205,7 +206,7 @@ function writePromptDraft( emitPromptDraftChange(storageKey); } -function restorePromptDraftIfEmpty( +function seedPromptDraftIfEmpty( storageKey: string | null, value: PromptDraftState, ): boolean { @@ -258,7 +259,29 @@ export interface PromptDraftController { ) => void; clear: () => void; clearIfCurrentMatches: (expectedDraft: PromptDraftState) => boolean; - restoreIfEmpty: (nextDraft: PromptDraftState) => void; + seedIfEmpty: (nextDraft: PromptDraftState) => void; + restoreUnsent: (unsentDraft: PromptDraftState) => void; +} + +type PromptDraftSendTarget = Pick< + PromptDraftController, + "clearIfCurrentMatches" | "restoreUnsent" +>; + +export async function sendPromptDraft( + target: PromptDraftSendTarget, + submittedDraft: PromptDraftState, + send: () => Promise, +): Promise { + const cleared = target.clearIfCurrentMatches(submittedDraft); + try { + return await send(); + } catch (error) { + if (cleared) { + target.restoreUnsent(submittedDraft); + } + throw error; + } } function createPromptDraftController( @@ -316,8 +339,14 @@ function createPromptDraftController( writePromptDraft(storageKey, EMPTY_PROMPT_DRAFT); return true; }, - restoreIfEmpty: (nextDraft) => { - restorePromptDraftIfEmpty(storageKey, nextDraft); + seedIfEmpty: (nextDraft) => { + seedPromptDraftIfEmpty(storageKey, nextDraft); + }, + restoreUnsent: (unsentDraft) => { + writePromptDraft( + storageKey, + mergeUnsentPromptDraft(unsentDraft, readPromptDraft(storageKey)), + ); }, }; } diff --git a/apps/app/src/test/thread-detail-prompt-area-harness.tsx b/apps/app/src/test/thread-detail-prompt-area-harness.tsx index b10705ceeee..91a42a849c3 100644 --- a/apps/app/src/test/thread-detail-prompt-area-harness.tsx +++ b/apps/app/src/test/thread-detail-prompt-area-harness.tsx @@ -42,7 +42,8 @@ export const promptAreaMocks = { getCurrent: vi.fn(), mentions: [] as PromptTextMention[], updateAttachments: vi.fn(), - restoreIfEmpty: vi.fn(), + restoreUnsent: vi.fn(), + seedIfEmpty: vi.fn(), setDraft: vi.fn(), setTextAndMentions: vi.fn(), storageKey: "bb.promptbox.contents-proj_1-thr_1-3", @@ -61,6 +62,7 @@ export const promptAreaMocks = { setServiceTier: vi.fn(), supportsServiceTier: false, toastError: vi.fn(), + toastWarning: vi.fn(), restoreThreadEnvironmentMutate: vi.fn(), unarchiveThreadMutate: vi.fn(), updateThreadMutate: vi.fn(), @@ -594,7 +596,10 @@ vi.mock( ); vi.mock("@/components/ui/app-toast", () => ({ - appToast: { error: promptAreaMocks.toastError }, + appToast: { + error: promptAreaMocks.toastError, + warning: promptAreaMocks.toastWarning, + }, })); vi.mock("@/hooks/usePromptMentions", async () => diff --git a/apps/app/src/views/RootComposeView.tsx b/apps/app/src/views/RootComposeView.tsx index 850e6e9f8f3..2e5e52a90b4 100644 --- a/apps/app/src/views/RootComposeView.tsx +++ b/apps/app/src/views/RootComposeView.tsx @@ -536,7 +536,7 @@ function RootComposeSurface({ const searchInitialDraft = useInitialPromptDraft(searchInitialPrompt); const stateInitialDraft = useInitialPromptDraft(stateInitialPrompt); const setPromptDraft = composerActions.restoreDraft; - const restorePromptDraftIfEmpty = promptDraft.restoreIfEmpty; + const seedPromptDraftIfEmpty = promptDraft.seedIfEmpty; useEffect(() => { const initialPrompt = readInitialPromptFromSearch(location.search); @@ -611,7 +611,7 @@ function RootComposeSurface({ if (shouldReplaceInitialPromptFromLocationState(location.state)) { setPromptDraft(nextDraft); } else { - restorePromptDraftIfEmpty(nextDraft); + seedPromptDraftIfEmpty(nextDraft); } void navigate(getRootComposeRoutePath() + location.search, { replace: true, @@ -621,7 +621,7 @@ function RootComposeSurface({ location.search, location.state, navigate, - restorePromptDraftIfEmpty, + seedPromptDraftIfEmpty, setPromptDraft, stateInitialDraft, ]); diff --git a/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx b/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx index b6ae08f1f08..1718d43441b 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailPromptArea.test.tsx @@ -248,7 +248,7 @@ describe("shared draft submission ownership", () => { ["modifier", "ordinary"], ["modifier", "modifier"], ] as const)( - "serializes %s then %s without losing edits", + "serializes %s then %s and merges the failed send into newer edits", async (firstAction, secondAction) => { const threadId = `thr_lock_${++nextId}`; const draft = draftFor(threadId); @@ -307,7 +307,10 @@ describe("shared draft submission ownership", () => { } expect({ requests: calls, draft: draft.getCurrent() }).toEqual({ requests: 1, - draft: newer, + draft: { + ...original, + text: "first message\n\nedited while pending", + }, }); expect(await secondAttempt).toBeInstanceOf(Error); if (lifetime !== "same callback") expect(pendingVisible).toBe(true); @@ -352,6 +355,49 @@ describe("shared draft submission ownership", () => { }); } }); + + it("merges a failed handoff back into a draft typed while it was pending", async () => { + const threadId = `thr_handoff_${++nextId}`; + const draft = draftFor(threadId); + draft.setDraft({ text: "hand this off", mentions: [], attachments: [] }); + const created = createDeferredPromise<{ id: string; projectId: string }>(); + mocks.createThreadMutateAsync.mockReturnValueOnce(created.promise); + const view = renderPromptArea({ thread: makeThread({ id: threadId }) }); + fireEvent.click( + within(view.container).getByRole("button", { name: "Start handoff" }), + ); + fireEvent.click( + within(view.container).getByRole("button", { + name: "Capture plugin host", + }), + ); + const submit = mocks.composerSubmit; + if (!submit) throw new Error("Missing composer submit"); + const submitted = draft.getCurrent(); + + let attempt: Promise = Promise.resolve(); + act(() => { + attempt = Promise.resolve(submit()).catch((error: unknown) => error); + }); + await waitFor(() => + expect(mocks.createThreadMutateAsync).toHaveBeenCalledOnce(), + ); + expect(draft.getCurrent().text).toBe(""); + act(() => { + draft.setDraft({ text: "newer idea", mentions: [], attachments: [] }); + }); + await act(async () => { + created.reject(new Error("Simulated transport failure")); + await attempt; + }); + + expect(await attempt).toBeInstanceOf(Error); + expect(draft.getCurrent()).toEqual({ + text: `${submitted.text}\n\nnewer idea`, + mentions: submitted.mentions, + attachments: [], + }); + }); }); beforeEach(() => { @@ -373,7 +419,8 @@ beforeEach(() => { updateAttachments: mocks.promptDraft.updateAttachments, clear: vi.fn(), clearIfCurrentMatches: mocks.promptDraft.clearIfCurrentMatches, - restoreIfEmpty: mocks.promptDraft.restoreIfEmpty, + restoreUnsent: mocks.promptDraft.restoreUnsent, + seedIfEmpty: mocks.promptDraft.seedIfEmpty, }; vi.mocked(usePromptDraftController).mockImplementation( () => promptDraftController, @@ -1562,6 +1609,100 @@ describe("ThreadDetailPromptArea", () => { ); }); + describe("unsaved queued message edits", () => { + const mainDraft = () => + getPromptDraftAccessor({ + kind: "thread", + projectId: "proj_1", + threadId: "thr_1", + }); + + beforeEach(() => { + mainDraft().setDraft({ + text: "newer composer text", + mentions: [], + attachments: [], + }); + mocks.queuedMessages = [makeQueuedMessage()]; + }); + + afterEach(() => { + mainDraft().clear(); + }); + + function editQueuedMessage(text: string | null) { + const view = renderPromptArea(); + fireEvent.click( + screen.getByRole("button", { name: "Edit queued message 1" }), + ); + if (text !== null) { + fireEvent.change( + within(screen.getByTestId("inline-queued-message-editor")).getByRole( + "textbox", + { name: "Composer message" }, + ), + { target: { value: text } }, + ); + } + return view; + } + + it("moves the edit into the composer when the message leaves the queue", () => { + const view = editQueuedMessage("Already queued, but edited"); + + mocks.queuedMessages = []; + view.rerender(buildPromptAreaElement()); + + expect(screen.queryByTestId("inline-queued-message-editor")).toBeNull(); + expect(mainDraft().getCurrent().text).toBe( + "Already queued, but edited\n\nnewer composer text", + ); + expect(mocks.toastWarning).toHaveBeenCalledWith( + "Your queued message edit is in the composer", + { + description: "The message left the queue before the edit was saved.", + }, + ); + }); + + it("leaves the composer alone when the edit had no changes", () => { + const view = editQueuedMessage(null); + + mocks.queuedMessages = []; + view.rerender(buildPromptAreaElement()); + + expect(screen.queryByTestId("inline-queued-message-editor")).toBeNull(); + expect(mainDraft().getCurrent().text).toBe("newer composer text"); + expect(mocks.toastWarning).not.toHaveBeenCalled(); + }); + + it("moves the edit into the composer when saving finds the message gone", async () => { + mocks.updateQueuedMessageMutateAsync.mockRejectedValueOnce( + new BbHttpError({ + body: null, + code: "invalid_request", + status: 404, + message: "Queued message not found", + }), + ); + editQueuedMessage("Already queued, but edited"); + + fireEvent.click( + within(screen.getByTestId("inline-queued-message-editor")).getByRole( + "button", + { name: "Submit composer" }, + ), + ); + + await waitFor(() => + expect(mainDraft().getCurrent().text).toBe( + "Already queued, but edited\n\nnewer composer text", + ), + ); + expect(screen.queryByTestId("inline-queued-message-editor")).toBeNull(); + }); + }); + it("auto-collapses concurrently running workflows into a stack that expands to independently expandable cards", () => { renderPromptArea({ activeWorkflows: [ diff --git a/apps/app/src/views/thread-detail/ThreadDetailPromptArea.tsx b/apps/app/src/views/thread-detail/ThreadDetailPromptArea.tsx index 8e1ecd46890..00e933b5baf 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailPromptArea.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailPromptArea.tsx @@ -96,6 +96,11 @@ import type { MachineProviderPresentation } from "@/components/plugin/MachinePro import type { WorkspaceCheckoutDisplay } from "@bb/shared-ui/lib/workspace-checkout-display"; import { useComposerTextEffects } from "@/lib/composer-text-effects"; import { useLatestRef } from "@/hooks/useLatestRef"; +import { + getPromptDraftAccessor, + sendPromptDraft, +} from "@/hooks/usePromptDraftStorage"; +import { appToast } from "@/components/ui/app-toast"; import { useThreadCreationOptions } from "@/hooks/useThreadCreationOptions"; import { useProjectDisplayName } from "@/hooks/queries/sidebar-navigation-query"; import { @@ -567,6 +572,7 @@ export function ThreadDetailPromptArea({ commitInlineQueuedMessage, updateInlineQueuedMessage, dismissInlineQueuedMessageEditor, + abandonInlineQueuedMessageEdit, beginEditQueuedMessage, queuedMessageDraftSession, } = useInlineQueuedMessageEditing({ @@ -576,6 +582,16 @@ export function ThreadDetailPromptArea({ clearInlineAttachmentErrorRef.current(); setEditFocusNonce((nonce) => nonce + 1); }, + onUnsavedEditLost: (draft) => { + getPromptDraftAccessor({ + kind: "thread", + projectId, + threadId: thread.id, + }).restoreUnsent(draft); + appToast.warning("Your queued message edit is in the composer", { + description: "The message left the queue before the edit was saved.", + }); + }, }); const inlineDraftSession = queuedMessageDraftSession; const inlineDraftSessionRef = useLatestRef(inlineDraftSession); @@ -1106,6 +1122,7 @@ export function ThreadDetailPromptArea({ onSaveSuccess: () => setInlineAttachmentError(null), inlineEditingQueuedMessage, dismissInlineQueuedMessageEditor, + abandonInlineQueuedMessageEdit, activeComposerDraftInput: inlineComposerDraftInput, }); const isQueueMutationPending = @@ -1314,23 +1331,18 @@ export function ThreadDetailPromptArea({ await runWhileCreatingHandoffThread( isCreatingHandoffThreadRef, async () => { - const clearedSubmittedDraft = - promptDraft.clearIfCurrentMatches(submittedDraft); setBottomAttachmentError(null); - try { - const created = await createThread.mutateAsync(request); - navigate( - getThreadRoutePath({ - projectId: created.projectId, - threadId: created.id, - }), - ); - } catch (error) { - if (clearedSubmittedDraft) { - promptDraft.restoreIfEmpty(submittedDraft); - } - throw error; - } + const created = await sendPromptDraft( + promptDraft, + submittedDraft, + () => createThread.mutateAsync(request), + ); + navigate( + getThreadRoutePath({ + projectId: created.projectId, + threadId: created.id, + }), + ); }, ); return true; @@ -1393,7 +1405,6 @@ export function ThreadDetailPromptArea({ throw new Error("This thread's model options are still loading."); } - promptDraft.clearIfCurrentMatches(submittedDraft); setBottomAttachmentError(null); const compactRequestFirst = compactFirst && sendAt === undefined; @@ -1407,24 +1418,25 @@ export function ThreadDetailPromptArea({ ? "queue_message" : "send_message"; try { - const request = buildAutoFollowUpRequest({ - compactFirst: compactRequestFirst, - threadId: thread.id, - input: submittedInput, - execution: followUpExecutionSelection, - }); - if (request) { - await sendMessage.mutateAsync({ - ...request, - ...sendAtFields, - ...pluginSubmissionFields, + await sendPromptDraft(promptDraft, submittedDraft, async () => { + const request = buildAutoFollowUpRequest({ + compactFirst: compactRequestFirst, + threadId: thread.id, + input: submittedInput, + execution: followUpExecutionSelection, }); - if (!isQueuingMessage) { - setFullHistoryThreadId(null); + if (request) { + await sendMessage.mutateAsync({ + ...request, + ...sendAtFields, + ...pluginSubmissionFields, + }); + if (!isQueuingMessage) { + setFullHistoryThreadId(null); + } } - } + }); } catch (nextError) { - promptDraft.restoreIfEmpty(submittedDraft); throw reportMutationError({ error: nextError, fallbackMessage: failureMessage, @@ -1478,19 +1490,19 @@ export function ThreadDetailPromptArea({ const pluginSubmissionFields = pluginSubmission === undefined ? {} : { pluginSubmission }; await submitDraft(async () => { - promptDraft.clearIfCurrentMatches(submittedDraft); setBottomAttachmentError(null); await runWhileFollowUpShortcutSending( setIsFollowUpShortcutSending, async () => { try { - await sendMessage.mutateAsync({ - ...shortcutRequest.request, - ...sendAtFields, - ...pluginSubmissionFields, - }); + await sendPromptDraft(promptDraft, submittedDraft, () => + sendMessage.mutateAsync({ + ...shortcutRequest.request, + ...sendAtFields, + ...pluginSubmissionFields, + }), + ); } catch (nextError) { - promptDraft.restoreIfEmpty(submittedDraft); throw reportMutationError({ error: nextError, fallbackMessage: "Failed to send message", diff --git a/apps/app/src/views/thread-detail/ThreadScreen.test.tsx b/apps/app/src/views/thread-detail/ThreadScreen.test.tsx index 946d6f72cb2..b80af11e853 100644 --- a/apps/app/src/views/thread-detail/ThreadScreen.test.tsx +++ b/apps/app/src/views/thread-detail/ThreadScreen.test.tsx @@ -299,6 +299,39 @@ describe("ThreadScreen", () => { expect(latestSentMessageEdit()).toBeUndefined(); }); + it("moves a changed edit into the composer when its message leaves the timeline", () => { + const draft = getPromptDraftAccessor({ + kind: "thread", + projectId: THREAD.projectId, + threadId: THREAD.id, + }); + draft.setDraft({ + text: "newer composer text", + mentions: [], + attachments: [], + }); + const view = renderScreen({ kind: "page" }, timelineWithRowIds(["msg_1"])); + startEditingMessage("msg_1"); + act(() => { + latestSentMessageEdit()!.updateDraft((current) => ({ + ...current, + text: "/compact keep it short", + })); + }); + + mocks.timeline = timelineWithRowIds(["msg_2"]); + view.rerender(screenElement({ kind: "page" })); + + expect(latestSentMessageEdit()).toBeUndefined(); + expect(draft.getCurrent().text).toBe( + "/compact keep it short\n\nnewer composer text", + ); + expect(mocks.toastWarning).toHaveBeenCalledWith( + "Your message edit is in the composer", + { description: "The message being edited is no longer available." }, + ); + }); + it("discards a failed edit whose message left the timeline while it was submitting", async () => { let rejectEdit!: (error: Error) => void; mocks.editMessageMutateAsync.mockReturnValue( diff --git a/apps/app/src/views/thread-detail/ThreadScreen.tsx b/apps/app/src/views/thread-detail/ThreadScreen.tsx index 40213d67866..0b7c9d20efb 100644 --- a/apps/app/src/views/thread-detail/ThreadScreen.tsx +++ b/apps/app/src/views/thread-detail/ThreadScreen.tsx @@ -3,6 +3,7 @@ import { useEffect, useId, useMemo, + useRef, useState, type ReactNode, } from "react"; @@ -11,6 +12,8 @@ import { defaultAppSettings, type Environment } from "@bb/domain"; import type { ThreadResponse, TimelineRow } from "@bb/server-contract"; import { appendQuoteAndAttachmentsToDraft, + arePromptDraftStatesEqual, + isPromptDraftEmpty, promptInputToDraft, type PromptDraftAttachment, type PromptDraftState, @@ -258,13 +261,35 @@ function useChildThreadsSection( interface UseSentMessageEditingArgs { canStartEdit: boolean; + projectId: string; threadId: string; timelineLoading: boolean; timelineRows: readonly TimelineRow[]; } +interface DiscardedSentMessageEdit { + operationId: string; + unsavedDraft: PromptDraftState | null; +} + +function unsavedSentMessageEditDraft( + session: SentMessageEditSession, +): PromptDraftState | null { + if ( + isPromptDraftEmpty(session.draft) || + arePromptDraftStatesEqual( + session.draft, + promptInputToDraft(session.target.input), + ) + ) { + return null; + } + return session.draft; +} + function useSentMessageEditing({ canStartEdit, + projectId, threadId, timelineLoading, timelineRows, @@ -310,20 +335,39 @@ function useSentMessageEditing({ sentMessageEditSession?.submitting === false && !timelineLoading && !sentMessageEditTargetStillPresent; - const [discardedSentMessageEditId, setDiscardedSentMessageEditId] = useState< - string | null - >(null); + const [discardedSentMessageEdit, setDiscardedSentMessageEdit] = + useState(null); + const handledDiscardOperationIdRef = useRef(null); if (shouldDiscardMissingSentMessageEdit && sentMessageEditSession !== null) { setSentMessageEditHostElement(null); setSentMessageEditSession(null); - setDiscardedSentMessageEditId(sentMessageEditSession.operationId); + setDiscardedSentMessageEdit({ + operationId: sentMessageEditSession.operationId, + unsavedDraft: unsavedSentMessageEditDraft(sentMessageEditSession), + }); } useEffect(() => { - if (discardedSentMessageEditId === null) { + if ( + discardedSentMessageEdit === null || + handledDiscardOperationIdRef.current === + discardedSentMessageEdit.operationId + ) { return; } - appToast.warning("The message being edited is no longer available."); - }, [discardedSentMessageEditId]); + handledDiscardOperationIdRef.current = discardedSentMessageEdit.operationId; + if (discardedSentMessageEdit.unsavedDraft === null) { + appToast.warning("The message being edited is no longer available."); + return; + } + getPromptDraftAccessor({ + kind: "thread", + projectId, + threadId, + }).restoreUnsent(discardedSentMessageEdit.unsavedDraft); + appToast.warning("Your message edit is in the composer", { + description: "The message being edited is no longer available.", + }); + }, [discardedSentMessageEdit, projectId, threadId]); const activeSentMessageEditOperationId = activeSentMessageEditSession?.operationId ?? null; const updateSentMessageEditDraft = useCallback( @@ -524,6 +568,7 @@ export function ThreadScreen({ !hasPendingInteraction && !sendMessage.isPending && !isThreadTimelinePending, + projectId: thread.projectId, threadId: thread.id, timelineLoading, timelineRows, diff --git a/packages/client-core/src/prompt/prompt-draft.ts b/packages/client-core/src/prompt/prompt-draft.ts index e01554282f7..2c0ed38218c 100644 --- a/packages/client-core/src/prompt/prompt-draft.ts +++ b/packages/client-core/src/prompt/prompt-draft.ts @@ -113,30 +113,36 @@ export function appendQuoteToDraftText( return { ...state, text }; } -export function appendQuoteAndAttachmentsToDraft< - Draft extends { text: string; attachments: readonly PromptDraftAttachment[] }, ->( - state: Draft, - quotedText: string, - attachments: readonly PromptDraftAttachment[], -): Draft { - const quotedState = appendQuoteToDraftText(state, quotedText); - if (attachments.length === 0) { - return quotedState; - } - +function appendMissingAttachments( + existing: readonly PromptDraftAttachment[], + additions: readonly PromptDraftAttachment[], +): PromptDraftAttachment[] { const existingAttachmentPaths = new Set( - quotedState.attachments.map((attachment) => attachment.path), + existing.map((attachment) => attachment.path), ); - const mergedAttachments = [...quotedState.attachments]; - for (const attachment of attachments) { + const mergedAttachments = [...existing]; + for (const attachment of additions) { if (existingAttachmentPaths.has(attachment.path)) { continue; } existingAttachmentPaths.add(attachment.path); mergedAttachments.push(attachment); } + return mergedAttachments; +} +export function appendQuoteAndAttachmentsToDraft< + Draft extends { text: string; attachments: readonly PromptDraftAttachment[] }, +>( + state: Draft, + quotedText: string, + attachments: readonly PromptDraftAttachment[], +): Draft { + const quotedState = appendQuoteToDraftText(state, quotedText); + const mergedAttachments = appendMissingAttachments( + quotedState.attachments, + attachments, + ); if (mergedAttachments.length === quotedState.attachments.length) { return quotedState; } @@ -144,6 +150,43 @@ export function appendQuoteAndAttachmentsToDraft< return { ...quotedState, attachments: mergedAttachments }; } +const UNSENT_DRAFT_SEPARATOR = "\n\n"; + +export function mergeUnsentPromptDraft( + unsent: PromptDraftState, + current: PromptDraftState, +): PromptDraftState { + if ( + isPromptDraftEmpty(unsent) || + arePromptDraftStatesEqual(unsent, current) + ) { + return current; + } + if (isPromptDraftEmpty(current)) { + return unsent; + } + const separator = + unsent.text.length > 0 && current.text.length > 0 + ? UNSENT_DRAFT_SEPARATOR + : ""; + const offset = unsent.text.length + separator.length; + return { + text: `${unsent.text}${separator}${current.text}`, + mentions: [ + ...unsent.mentions, + ...current.mentions.map((mention) => ({ + ...mention, + start: mention.start + offset, + end: mention.end + offset, + })), + ], + attachments: appendMissingAttachments( + unsent.attachments, + current.attachments, + ), + }; +} + export function isPromptDraftEmpty(draft: PromptDraftState): boolean { return ( draft.text.length === 0 && diff --git a/packages/client-core/test/prompt-draft.test.ts b/packages/client-core/test/prompt-draft.test.ts index ac9ac5e22db..2b8667d6aae 100644 --- a/packages/client-core/test/prompt-draft.test.ts +++ b/packages/client-core/test/prompt-draft.test.ts @@ -6,6 +6,7 @@ import { emptyPromptDraftState, isPromptDraftEmpty, getProjectStoredPromptAttachmentPaths, + mergeUnsentPromptDraft, parsePromptDraftStorage, promptDraftToInput, promptInputToDraft, @@ -189,7 +190,11 @@ describe("prompt draft helpers", () => { { start: 30, end: 48, resource: removed }, ], attachments: [ - { type: "localFile", path: "Pasted-text-1.txt", name: "Pasted text.txt" }, + { + type: "localFile", + path: "Pasted-text-1.txt", + name: "Pasted text.txt", + }, ], }); @@ -419,3 +424,65 @@ describe("appendQuoteAndAttachmentsToDraft", () => { expect(appendQuoteAndAttachmentsToDraft(base, "", [attachment])).toBe(base); }); }); + +describe("mergeUnsentPromptDraft", () => { + const threadMention = { + start: 0, + end: 5, + resource: { kind: "thread" as const, threadId: "thr_a", label: "a.ts" }, + }; + const spec = { + type: "localFile" as const, + path: "uploads/spec.md", + name: "spec.md", + }; + const log = { + type: "localFile" as const, + path: "uploads/log.txt", + name: "log.txt", + }; + + it("restores the unsent draft into an empty composer", () => { + const unsent = { text: "sent", mentions: [], attachments: [spec] }; + expect(mergeUnsentPromptDraft(unsent, emptyPromptDraftState())).toBe( + unsent, + ); + }); + + it("puts the unsent draft ahead of newer text and keeps both mention sets aligned", () => { + const merged = mergeUnsentPromptDraft( + { text: "@a.ts fix it", mentions: [threadMention], attachments: [spec] }, + { + text: "@a.ts then this", + mentions: [threadMention], + attachments: [log, spec], + }, + ); + + expect(merged).toEqual({ + text: "@a.ts fix it\n\n@a.ts then this", + mentions: [threadMention, { ...threadMention, start: 14, end: 19 }], + attachments: [spec, log], + }); + expect(merged.text.slice(14, 19)).toBe("@a.ts"); + }); + + it("keeps attachment-only drafts without inserting a separator", () => { + expect( + mergeUnsentPromptDraft( + { text: "", mentions: [], attachments: [spec] }, + { text: "newer", mentions: [], attachments: [] }, + ), + ).toEqual({ text: "newer", mentions: [], attachments: [spec] }); + }); + + it("does not duplicate a draft the composer already holds", () => { + const current = { text: "same", mentions: [], attachments: [] }; + expect( + mergeUnsentPromptDraft( + { text: "same", mentions: [], attachments: [] }, + current, + ), + ).toBe(current); + }); +});