Skip to content

Commit 7e08e54

Browse files
committed
fix(web): release the composer before background worktree setup
1 parent 50ff4c3 commit 7e08e54

4 files changed

Lines changed: 144 additions & 52 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 86 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ import {
288288
type DraftThreadEnvMode,
289289
finalizePromotedDraftThreadByRef,
290290
markPromotedDraftThreadByRef,
291+
restoreFailedBackgroundDraftThread,
291292
useComposerDraftStore,
292293
DraftId,
293294
} from "../composerDraftStore";
@@ -7893,6 +7894,7 @@ export default function ChatView(props: ChatViewProps) {
78937894
}
78947895

78957896
let turnStartSucceeded = false;
7897+
let backgroundDraftOpened = false;
78967898
if (failure === null && turnAttachmentsResult._tag === "Success") {
78977899
const bootstrap =
78987900
isLocalDraftThread || baseBranchForWorktree
@@ -7931,7 +7933,7 @@ export default function ChatView(props: ChatViewProps) {
79317933
if (backgroundThreadRef) {
79327934
beginBackgroundDraftSubmissionByRef(backgroundThreadRef);
79337935
}
7934-
const startResult = await startThreadTurn({
7936+
const startPromise = startThreadTurn({
79357937
environmentId,
79367938
input: {
79377939
threadId: threadIdForSend,
@@ -7975,10 +7977,32 @@ export default function ChatView(props: ChatViewProps) {
79757977
createdAt: messageCreatedAt,
79767978
},
79777979
});
7978-
if (startResult._tag === "Failure") {
7979-
if (backgroundThreadRef) {
7980+
if (backgroundThreadRef) {
7981+
markPromotedDraftThreadByRef(backgroundThreadRef);
7982+
try {
7983+
backgroundDraftOpened = Boolean(
7984+
await handleNewThread(
7985+
scopeProjectRef(activeProject.environmentId, activeProject.id),
7986+
resolveBackgroundDraftWorkspaceOptions({
7987+
envMode: sendEnvMode,
7988+
branch: activeThreadBranch,
7989+
startFromOrigin,
7990+
}),
7991+
),
7992+
);
7993+
} catch (error) {
79807994
clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
7995+
toastManager.add(
7996+
stackedThreadToast({
7997+
type: "warning",
7998+
title: "Could not open a fresh composer",
7999+
description: error instanceof Error ? error.message : undefined,
8000+
}),
8001+
);
79818002
}
8003+
}
8004+
const startResult = await startPromise;
8005+
if (startResult._tag === "Failure") {
79828006
failure = startResult;
79838007
} else {
79848008
turnStartSucceeded = true;
@@ -7991,56 +8015,42 @@ export default function ChatView(props: ChatViewProps) {
79918015
}
79928016
acknowledgeActiveThreadWoke();
79938017
if (backgroundThreadRef) {
7994-
markPromotedDraftThreadByRef(backgroundThreadRef);
7995-
try {
7996-
const nextDraft = await handleNewThread(
7997-
scopeProjectRef(activeProject.environmentId, activeProject.id),
7998-
resolveBackgroundDraftWorkspaceOptions({
7999-
envMode: sendEnvMode,
8000-
branch: activeThreadBranch,
8001-
startFromOrigin,
8002-
}),
8003-
);
8004-
if (nextDraft) {
8005-
finalizePromotedDraftThreadByRef(backgroundThreadRef);
8006-
toastManager.add(
8007-
stackedThreadToast({
8008-
type: "success",
8009-
title: "Started in background",
8010-
timeout: 5_000,
8011-
actionProps: {
8012-
children: "Open",
8013-
onClick: () => {
8014-
void navigate({
8015-
to: "/$environmentId/$threadId",
8016-
params: buildThreadRouteParams(backgroundThreadRef),
8017-
});
8018-
},
8019-
},
8020-
}),
8021-
);
8022-
} else {
8023-
clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
8024-
}
8025-
} catch (error) {
8026-
clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
8027-
resetLocalDispatch();
8018+
if (backgroundDraftOpened) {
8019+
finalizePromotedDraftThreadByRef(backgroundThreadRef);
80288020
toastManager.add(
80298021
stackedThreadToast({
8030-
type: "warning",
8031-
title: "Task started in the background",
8032-
description:
8033-
error instanceof Error
8034-
? `Could not open a fresh composer: ${error.message}`
8035-
: "Could not open a fresh composer.",
8022+
type: "success",
8023+
title: "Started in background",
8024+
timeout: 5_000,
8025+
actionProps: {
8026+
children: "Open",
8027+
onClick: () => {
8028+
void navigate({
8029+
to: "/$environmentId/$threadId",
8030+
params: buildThreadRouteParams(backgroundThreadRef),
8031+
});
8032+
},
8033+
},
80368034
}),
80378035
);
8036+
} else {
8037+
clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
80388038
}
80398039
}
80408040
}
80418041
}
80428042

80438043
if (failure !== null) {
8044+
if (resolvedSubmissionIntent === "background" && draftId && draftThread) {
8045+
restoreFailedBackgroundDraftThread(
8046+
draftId,
8047+
draftThread,
8048+
wasBootstrapThreadDeleted(squashAtomCommandFailure(failure))
8049+
? newThreadId()
8050+
: threadIdForSend,
8051+
);
8052+
clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
8053+
}
80448054
if (queuedMessage) {
80458055
setOptimisticUserMessages((existing) => {
80468056
const removed = existing.filter((message) => message.id === messageIdForSend);
@@ -8059,14 +8069,18 @@ export default function ChatView(props: ChatViewProps) {
80598069
});
80608070
}
80618071
} else if (
8062-
promptRef.current.length === 0 &&
8063-
composerImagesRef.current.length === 0 &&
8064-
composerFilesRef.current.length === 0 &&
8065-
composerTerminalContextsRef.current.length === 0 &&
8066-
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.previewAnnotations
8067-
.length ?? 0) === 0 &&
8068-
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.reviewComments
8069-
.length ?? 0) === 0
8072+
backgroundDraftOpened
8073+
? !composerDraftHasUserContent(
8074+
useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
8075+
)
8076+
: promptRef.current.length === 0 &&
8077+
composerImagesRef.current.length === 0 &&
8078+
composerFilesRef.current.length === 0 &&
8079+
composerTerminalContextsRef.current.length === 0 &&
8080+
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)
8081+
?.previewAnnotations.length ?? 0) === 0 &&
8082+
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.reviewComments
8083+
.length ?? 0) === 0
80708084
) {
80718085
setOptimisticUserMessages((existing) => {
80728086
const removed = existing.filter((message) => message.id === messageIdForSend);
@@ -8095,7 +8109,12 @@ export default function ChatView(props: ChatViewProps) {
80958109
}
80968110
if (!isAtomCommandInterrupted(failure)) {
80978111
const error = squashAtomCommandFailure(failure);
8098-
if (isLocalDraftThread && draftId && wasBootstrapThreadDeleted(error)) {
8112+
if (
8113+
resolvedSubmissionIntent !== "background" &&
8114+
isLocalDraftThread &&
8115+
draftId &&
8116+
wasBootstrapThreadDeleted(error)
8117+
) {
80998118
const failedDraftSession = getDraftSession(draftId);
81008119
if (failedDraftSession?.threadId === threadIdForSend) {
81018120
setLogicalProjectDraftThreadId(
@@ -8113,6 +8132,21 @@ export default function ChatView(props: ChatViewProps) {
81138132
threadIdForSend,
81148133
error instanceof Error ? error.message : "Failed to send message.",
81158134
);
8135+
if (backgroundDraftOpened && draftId) {
8136+
toastManager.add(
8137+
stackedThreadToast({
8138+
type: "error",
8139+
title: "Background task failed",
8140+
description: error instanceof Error ? error.message : "Failed to send message.",
8141+
actionProps: {
8142+
children: "Open draft",
8143+
onClick: () => {
8144+
void navigate({ to: "/draft/$draftId", params: { draftId } });
8145+
},
8146+
},
8147+
}),
8148+
);
8149+
}
81168150
}
81178151
}
81188152
sendInFlightRef.current = false;

‎apps/web/src/composerDraftStore.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import {
7070
composerDraftHasUserContent,
7171
finalizePromotedDraftThreadByRef,
7272
markPromotedDraftThreadByRef,
73+
restoreFailedBackgroundDraftThread,
7374
type ComposerFileAttachment,
7475
type ComposerImageAttachment,
7576
composerFileNeedsReattach,
@@ -1337,6 +1338,45 @@ describe("composerDraftStore project draft thread mapping", () => {
13371338
);
13381339
});
13391340

1341+
it.each([false, true])(
1342+
"restores a failed background draft without replacing the next draft (finalized: %s)",
1343+
(finalized) => {
1344+
const store = useComposerDraftStore.getState();
1345+
const nextDraftId = DraftId.make("next-draft");
1346+
const retryThreadId = ThreadId.make("retry-thread");
1347+
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
1348+
store.setProjectDraftThreadId(projectRef, draftId, {
1349+
threadId,
1350+
branch: "main",
1351+
envMode: "worktree",
1352+
startFromOrigin: true,
1353+
});
1354+
const sentDraft = store.getDraftSession(draftId)!;
1355+
markPromotedDraftThreadByRef(threadRef);
1356+
store.setProjectDraftThreadId(projectRef, nextDraftId, {
1357+
threadId: ThreadId.make("next-thread"),
1358+
});
1359+
store.setPrompt(nextDraftId, "My next task");
1360+
const nextDraft = store.getDraftSession(nextDraftId);
1361+
if (finalized) finalizePromotedDraftThreadByRef(threadRef);
1362+
1363+
restoreFailedBackgroundDraftThread(draftId, sentDraft, retryThreadId);
1364+
store.setPrompt(draftId, "Retry the first task");
1365+
1366+
expect(store.getDraftThreadByProjectRef(projectRef)?.draftId).toBe(nextDraftId);
1367+
expect(store.getDraftSession(nextDraftId)).toBe(nextDraft);
1368+
expect(store.getComposerDraft(nextDraftId)?.prompt).toBe("My next task");
1369+
expect(store.getDraftSession(draftId)).toMatchObject({
1370+
threadId: retryThreadId,
1371+
promotedTo: null,
1372+
branch: "main",
1373+
envMode: "worktree",
1374+
startFromOrigin: true,
1375+
});
1376+
expect(store.getComposerDraft(draftId)?.prompt).toBe("Retry the first task");
1377+
},
1378+
);
1379+
13401380
it("clears only matching project draft mapping entries", () => {
13411381
const store = useComposerDraftStore.getState();
13421382
store.setProjectDraftThreadId(projectRef, draftId, { threadId });

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4254,6 +4254,23 @@ export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): void {
42544254
}
42554255
}
42564256

4257+
export function restoreFailedBackgroundDraftThread(
4258+
draftId: DraftId,
4259+
draftThread: DraftThreadState,
4260+
threadId: ThreadId,
4261+
): void {
4262+
useComposerDraftStore.setState((state) => ({
4263+
draftThreadsByThreadKey: {
4264+
...state.draftThreadsByThreadKey,
4265+
[draftId]: {
4266+
...draftThread,
4267+
threadId,
4268+
promotedTo: null,
4269+
},
4270+
},
4271+
}));
4272+
}
4273+
42574274
export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): void {
42584275
const draftStore = useComposerDraftStore.getState();
42594276
for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) {

‎apps/web/src/routes/_chat.draft.$draftId.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ function DraftChatThreadRouteView() {
7878
return (
7979
<SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">
8080
<ChatView
81+
key={draftId}
8182
draftId={draftId}
8283
environmentId={draftSession.environmentId}
8384
threadId={draftSession.threadId}

0 commit comments

Comments
 (0)