From d6de8f89ed7c7d356107fe2b652f02d6f3724913 Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:09:22 +0000 Subject: [PATCH 1/3] fix(placement): keep a draft whose send failed on the machine it was sent to The composer records a sent draft's machine before the launch goes out (promotedTo), but a failed send restored the draft with the same thread id and dropped that record. A retry could then be auto-balanced, or manually switched, to another machine under the same id, while the first machine may have started it after a lost answer. restoreFailedDraftThread now keeps that machine as sentTo, persisted with the draft, whenever the id is kept. The draft store refuses to move a draft's thread id away from it (setDraftThreadContext, setLogicalProjectDraftThreadId), the composer stops auto-balancing it and says why a switch is refused. A send refused under a new id is a new intent and may go anywhere. ARC also runs the draft store suite. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/closura-arc-ci.yml | 3 +- apps/web/src/components/ChatView.tsx | 2 + .../chat/useDraftEnvironmentRouting.ts | 20 ++++ apps/web/src/composerDraftStore.test.ts | 46 ++++++++ apps/web/src/composerDraftStore.ts | 108 +++++++++++++----- 5 files changed, 150 insertions(+), 29 deletions(-) diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index 262594353d21c..dcabe32082956 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -151,7 +151,8 @@ jobs: packages/shared/src/threadPlacement.test.ts \ apps/server/src/peer/RemoteDelegation.test.ts \ apps/server/src/mcp/OrchestratorMcpService.test.ts \ - apps/server/src/cli/thread.test.ts + apps/server/src/cli/thread.test.ts \ + apps/web/src/composerDraftStore.test.ts - name: Build native T3 server shell: bash diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index fbec56205975c..6dc456b412dec 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1325,6 +1325,8 @@ export default function ChatView(props: ChatViewProps) { canAutoBalanceEnvironments && loadBalancingSettings.loadBalancingEnabled && draftThread?.environmentSelection !== "manual" && + // A send that may have started there keeps its thread id on that machine. + !draftThread?.sentTo && (!composerHasAttachments || Boolean(draftThread?.loadBalancedEnvironmentId)) && (!draftThread?.branch || draftThread.environmentSelection === "auto") && !draftThread?.worktreePath, diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts index 86664b567a658..daeb20a4f6fb5 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts @@ -226,8 +226,22 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) getDraftSession, setDraftThreadContext, ]); + // A send that may have started there keeps the draft's thread id on that machine. + const refuseMoveAfterUnconfirmedSend = () => { + const sentTo = draftId ? getDraftSession(draftId)?.sentTo : null; + if (!sentTo) return false; + toastManager.add({ + type: "warning", + id: "draft-sent-machine", + title: "This draft stays on the machine it was sent to", + description: + "Its earlier send may have started the thread there. Send it again to reach that thread, or start a new draft to run it elsewhere.", + }); + return true; + }; const onAutoEnvironment = () => { if (envLocked || !draftId || sendInFlightRef.current) return; + if (refuseMoveAfterUnconfirmedSend()) return; if (composerHasAttachments) { toastManager.add({ type: "warning", @@ -300,6 +314,12 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) (env) => env.environmentId === nextEnvironmentId, ); if (!target) return; + if ( + originalDraft.sentTo && + target.environmentId !== originalDraft.sentTo.environmentId && + refuseMoveAfterUnconfirmedSend() + ) + return; const request = { environmentId: target.environmentId, scope: environmentChangeScope }; environmentChangeRef.current = request; setBusyEnvironmentChange(null); diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index a04d00cbbc2de..f1b45bfa322e3 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1133,6 +1133,52 @@ describe("composerDraftStore project draft thread mapping", () => { expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); }); + it("keeps a draft whose send failed on the machine it was sent to, across a reload", () => { + const store = useComposerDraftStore.getState(); + const remoteProjectRef = scopeProjectRef(OTHER_TEST_ENVIRONMENT_ID, projectRef.projectId); + store.setProjectDraftThreadId(projectRef, draftId, { + threadId, + environmentSelection: "auto", + loadBalancedEnvironmentId: TEST_ENVIRONMENT_ID, + }); + const sentDraft = useComposerDraftStore.getState().getDraftSession(draftId)!; + markPromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); + // The answer never came: the machine may have started this thread, so its id stays there. + restoreFailedDraftThread(draftId, sentDraft, threadId); + // A reload keeps that, as the send's promotion itself was kept. + const merge = useComposerDraftStore.persist.getOptions().merge!; + useComposerDraftStore.setState( + merge( + JSON.parse( + JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), + ), + useComposerDraftStore.getInitialState(), + ), + ); + const sentTo = () => useComposerDraftStore.getState().getDraftSession(draftId); + + // Neither automatic balancing nor a manual switch moves it to another machine. + useComposerDraftStore.getState().setDraftThreadContext(draftId, { + projectRef: remoteProjectRef, + environmentSelection: "auto", + loadBalancedEnvironmentId: OTHER_TEST_ENVIRONMENT_ID, + }); + useComposerDraftStore + .getState() + .setProjectDraftThreadId(remoteProjectRef, draftId, { environmentSelection: "manual" }); + expect(sentTo()).toMatchObject({ environmentId: TEST_ENVIRONMENT_ID, threadId }); + // Its own machine's settings still change. + useComposerDraftStore.getState().setDraftThreadContext(draftId, { branch: "retry-base" }); + expect(sentTo()?.branch).toBe("retry-base"); + + // A send the machine refused for good restores under a new id, which may go anywhere. + restoreFailedDraftThread(draftId, sentDraft, ThreadId.make("new-intent")); + useComposerDraftStore + .getState() + .setDraftThreadContext(draftId, { projectRef: remoteProjectRef }); + expect(sentTo()?.environmentId).toBe(OTHER_TEST_ENVIRONMENT_ID); + }); + it("restores a failed draft without changing the fresh draft", () => { const store = useComposerDraftStore.getState(); store.setProjectDraftThreadId(projectRef, draftId, { threadId }); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 4066715c53b2c..84975ef508396 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -428,6 +428,14 @@ const PersistedDraftThreadState = Schema.Struct({ }), ), ), + sentTo: Schema.optionalKey( + Schema.NullOr( + Schema.Struct({ + environmentId: Schema.String, + threadId: Schema.String, + }), + ), + ), }); type PersistedDraftThreadState = typeof PersistedDraftThreadState.Type; @@ -519,6 +527,8 @@ export interface DraftSessionState { /** Linked to the thread when the draft is sent on this branch. */ checkoutPullRequest?: DraftCheckoutPullRequest; promotedTo?: ScopedThreadRef | null; + /** A send whose outcome was not confirmed: that machine may have started this thread id. */ + sentTo?: ScopedThreadRef | null; } export type DraftThreadState = DraftSessionState; @@ -1752,6 +1762,9 @@ function createDraftThreadState( startFromOrigin: nextStartFromOrigin, ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo: null, + ...(existingThread?.sentTo && existingThread.threadId === threadId + ? { sentTo: existingThread.sentTo } + : {}), }; } @@ -1772,6 +1785,32 @@ function checkoutPullRequestsEqual( return left === right || (left?.url === right?.url && left?.branch === right?.branch); } +function storedThreadRef(candidate: unknown): ScopedThreadRef | null { + const record = + candidate && typeof candidate === "object" ? (candidate as Record) : null; + return record && + typeof record.environmentId === "string" && + record.environmentId.length > 0 && + typeof record.threadId === "string" && + record.threadId.length > 0 + ? scopeThreadRef(record.environmentId as EnvironmentId, record.threadId as ThreadId) + : null; +} + +/** + * A thread id a machine may have started stays on that machine: a draft holding one + * never moves elsewhere under it, though a new id (a new intent) may go anywhere. + */ +function staysOnSentMachine( + existing: DraftThreadState | undefined, + next: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, +): boolean { + const sentTo = existing?.sentTo; + return ( + !!sentTo && sentTo.threadId === next.threadId && sentTo.environmentId !== next.environmentId + ); +} + function scopedThreadRefsEqual( left: ScopedThreadRef | null | undefined, right: ScopedThreadRef | null | undefined, @@ -1803,7 +1842,8 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea left.envMode === right.envMode && left.startFromOrigin === right.startFromOrigin && checkoutPullRequestsEqual(left.checkoutPullRequest, right.checkoutPullRequest) && - scopedThreadRefsEqual(left.promotedTo, right.promotedTo) + scopedThreadRefsEqual(left.promotedTo, right.promotedTo) && + scopedThreadRefsEqual(left.sentTo, right.sentTo) ); } @@ -1918,22 +1958,8 @@ function normalizePersistedDraftThreads( const checkoutPullRequest = normalizePersistedCheckoutPullRequest( candidateDraftThread.checkoutPullRequest, ); - const promotedToCandidate = candidateDraftThread.promotedTo; - const promotedToRecord = - promotedToCandidate && typeof promotedToCandidate === "object" - ? (promotedToCandidate as Record) - : null; - const promotedTo = - promotedToRecord && - typeof promotedToRecord.environmentId === "string" && - promotedToRecord.environmentId.length > 0 && - typeof promotedToRecord.threadId === "string" && - promotedToRecord.threadId.length > 0 - ? scopeThreadRef( - promotedToRecord.environmentId as EnvironmentId, - promotedToRecord.threadId as ThreadId, - ) - : null; + const promotedTo = storedThreadRef(candidateDraftThread.promotedTo); + const sentTo = storedThreadRef(candidateDraftThread.sentTo); if (typeof projectId !== "string" || projectId.length === 0 || environmentId === undefined) { continue; } @@ -1977,6 +2003,7 @@ function normalizePersistedDraftThreads( : {}), ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo, + ...(sentTo ? { sentTo } : {}), }; } } @@ -2762,6 +2789,14 @@ function toHydratedDraftThreadState( persistedDraftThread.promotedTo.threadId as ThreadId, ) : null, + ...(persistedDraftThread.sentTo + ? { + sentTo: scopeThreadRef( + persistedDraftThread.sentTo.environmentId as EnvironmentId, + persistedDraftThread.sentTo.threadId as ThreadId, + ), + } + : {}), }; } @@ -2886,6 +2921,7 @@ const composerDraftStore = create()( existingThread, options, ); + if (staysOnSentMachine(existingThread, nextDraftThread)) return state; const hasSameLogicalMapping = previousThreadKeyForLogicalProject === draftId; const hasNoStaleMappingsForDraft = Object.entries( state.logicalProjectDraftThreadKeyByLogicalProjectKey, @@ -2987,7 +3023,11 @@ const composerDraftStore = create()( }; if ( nextProjectRef.projectId.length === 0 || - nextProjectRef.environmentId.length === 0 + nextProjectRef.environmentId.length === 0 || + staysOnSentMachine(existing, { + environmentId: nextProjectRef.environmentId, + threadId: existing.threadId, + }) ) { return state; } @@ -3045,6 +3085,7 @@ const composerDraftStore = create()( startFromOrigin: nextStartFromOrigin, ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo: existing.promotedTo ?? null, + ...(existing.sentTo ? { sentTo: existing.sentTo } : {}), }; const isUnchanged = nextDraftThread.environmentId === existing.environmentId && @@ -4703,17 +4744,28 @@ export function restoreFailedDraftThread( draftThread: DraftThreadState, threadId: ThreadId, ): void { - useComposerDraftStore.setState((state) => ({ - draftThreadsByThreadKey: { - ...state.draftThreadsByThreadKey, - [draftId]: { - ...(state.draftThreadsByThreadKey[draftId] ?? draftThread), - threadId, - ...(threadId !== draftThread.threadId ? { createdAt: new Date().toISOString() } : {}), - promotedTo: null, + useComposerDraftStore.setState((state) => { + const current = state.draftThreadsByThreadKey[draftId] ?? draftThread; + // The send recorded its machine before it went out; the same id stays bound there. + const sentTo = + threadId === draftThread.threadId + ? (current.promotedTo ?? + current.sentTo ?? + scopeThreadRef(draftThread.environmentId, draftThread.threadId)) + : null; + return { + draftThreadsByThreadKey: { + ...state.draftThreadsByThreadKey, + [draftId]: { + ...current, + threadId, + ...(threadId !== draftThread.threadId ? { createdAt: new Date().toISOString() } : {}), + promotedTo: null, + sentTo, + }, }, - }, - })); + }; + }); } export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): void { From 6991286b83206f4466c9e9c8618ea6dba50518a2 Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:46:54 +0000 Subject: [PATCH 2/3] fix(placement): commit a draft's send machine to storage before it launches PR70-R1-F1. Draft state reaches storage through a 300 ms deferred write, flushed only on beforeunload, so a renderer that died after an accepted launch could reload the draft unbound and send its thread id elsewhere. markPromotedDraftThreadByRef now flushes the existing deferred storage and checks the stored bytes hold the promotion before the composer launches. If storage throws or drops the write, the promotion is undone, it returns false, and the send fails before any launch. A committed promotion, like sentTo, keeps the id on its machine in both retarget entry points, and a restore after an unconfirmed outcome commits sentTo best effort. Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/useComposerSend.ts | 11 +- apps/web/src/composerDraftStore.test.ts | 102 ++++++++++++++++++ apps/web/src/composerDraftStore.ts | 52 +++++++-- 3 files changed, 157 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 93ff79432708c..83503fc461f3e 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -1223,7 +1223,8 @@ export function useComposerSend(input: ComposerSendInput) { ? scopeThreadRef(environmentId, threadIdForSend) : null; // Keep new-thread flows from reusing this draft while attachments and worktree setup settle. - if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef); + // Its machine is committed to storage before anything launches; if that fails, nothing does. + const sendBound = sentDraftThreadRef ? markPromotedDraftThreadByRef(sentDraftThreadRef) : true; clearComposerDraftContent(composerDraftTarget); // The prompt ref and cursor belong to the thread on screen, which may no longer be this one. if (currentRouteThreadKeyRef.current === routeThreadKey) { @@ -1243,6 +1244,14 @@ export function useComposerSend(input: ComposerSendInput) { ); let failure: AtomCommandResult | null = null; + if (!sendBound) { + const unbound = await settlePromise(async () => { + throw new Error( + "This draft could not be saved before sending, so nothing was started. Free up browser storage, then send again.", + ); + }); + if (unbound._tag === "Failure") failure = unbound; + } if (failure === null && isServerThread) { const settingsResult = await persistThreadSettingsForNextTurn({ diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index f1b45bfa322e3..b300c832d301b 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1179,6 +1179,108 @@ describe("composerDraftStore project draft thread mapping", () => { expect(sentTo()?.environmentId).toBe(OTHER_TEST_ENVIRONMENT_ID); }); + it("commits a send's machine to storage before its launch, and launches nothing when it cannot", async () => { + let storageFails = false; + let storageDrops = false; + const memory = createMemoryStorage(); + const sharedStorage = { + getItem: (name: string) => memory.getItem(name), + removeItem: (name: string) => memory.removeItem(name), + setItem: (name: string, value: string) => { + if (storageFails) throw new Error("QuotaExceededError"); + if (storageDrops) return; + memory.setItem(name, value); + }, + }; + vi.stubGlobal("localStorage", sharedStorage); + vi.stubGlobal("window", new EventTarget()); + vi.useFakeTimers(); + vi.resetModules(); + try { + const remoteProjectRef = scopeProjectRef(OTHER_TEST_ENVIRONMENT_ID, projectRef.projectId); + const sentRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); + const committedDraft = () => + JSON.parse(sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string).state + .draftThreadsByThreadKey[draftId]; + let launches = 0; + // The composer launches only once the send's machine is committed. + const send = (tab: typeof import("./composerDraftStore")) => { + if (tab.markPromotedDraftThreadByRef(sentRef) === false) return; + launches += 1; + }; + const before = await import("./composerDraftStore"); + before.useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId, { + threadId, + environmentSelection: "auto", + loadBalancedEnvironmentId: TEST_ENVIRONMENT_ID, + }); + await vi.advanceTimersByTimeAsync(300); + expect(committedDraft()?.promotedTo ?? null).toBeNull(); + + // At the launch, with the deferred write still pending, storage already holds the machine. + send(before); + expect(launches).toBe(1); + expect(committedDraft()?.promotedTo).toEqual(sentRef); + + // The renderer dies with its pending writes; the reload reads only what was committed. + vi.clearAllTimers(); + vi.resetModules(); + const after = await import("./composerDraftStore"); + const store = after.useComposerDraftStore.getState(); + store.setDraftThreadContext(draftId, { + projectRef: remoteProjectRef, + environmentSelection: "auto", + loadBalancedEnvironmentId: OTHER_TEST_ENVIRONMENT_ID, + }); + store.setProjectDraftThreadId(remoteProjectRef, draftId, { environmentSelection: "manual" }); + expect(after.useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({ + environmentId: TEST_ENVIRONMENT_ID, + threadId, + }); + + // An unconfirmed outcome keeps that binding through the next reload too. + const sentDraft = after.useComposerDraftStore.getState().getDraftSession(draftId)!; + after.restoreFailedDraftThread(draftId, sentDraft, threadId); + vi.clearAllTimers(); + vi.resetModules(); + const reloaded = await import("./composerDraftStore"); + reloaded.useComposerDraftStore + .getState() + .setDraftThreadContext(draftId, { projectRef: remoteProjectRef }); + expect( + reloaded.useComposerDraftStore.getState().getDraftSession(draftId)?.environmentId, + ).toBe(TEST_ENVIRONMENT_ID); + + // When storage cannot commit the machine, nothing launches. + reloaded.useComposerDraftStore + .getState() + .setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId }); + await vi.advanceTimersByTimeAsync(300); + storageFails = true; + const failedLaunches = launches; + if ( + reloaded.markPromotedDraftThreadByRef( + scopeThreadRef(TEST_ENVIRONMENT_ID, otherThreadId), + ) !== false + ) + launches += 1; + expect(launches).toBe(failedLaunches); + // Nor when storage drops the write without saying so: only the stored bytes count. + storageFails = false; + storageDrops = true; + expect( + reloaded.markPromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, otherThreadId)), + ).toBe(false); + expect( + reloaded.useComposerDraftStore.getState().getDraftSession(otherDraftId)?.promotedTo, + ).toBeNull(); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + it("restores a failed draft without changing the fresh draft", () => { const store = useComposerDraftStore.getState(); store.setProjectDraftThreadId(projectRef, draftId, { threadId }); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 84975ef508396..bfd2481105237 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -1805,7 +1805,8 @@ function staysOnSentMachine( existing: DraftThreadState | undefined, next: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, ): boolean { - const sentTo = existing?.sentTo; + // A promotion is committed before its launch, so it binds the id too. + const sentTo = existing?.sentTo ?? existing?.promotedTo; return ( !!sentTo && sentTo.threadId === next.threadId && sentTo.environmentId !== next.environmentId ); @@ -4727,16 +4728,54 @@ export function usePromotingDraftThreadKeys(): ReadonlyArray { ); } -export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): void { +/** + * Marks the drafts sending as `threadRef` and commits that to storage at once, so a crash + * after the launch cannot reload them unbound: the launch may then have started there. + * False when storage did not take it; the caller must not launch, and nothing stays marked. + */ +export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): boolean { const draftStore = useComposerDraftStore.getState(); + const promoted: Array = []; for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { if ( draftThread.environmentId === threadRef.environmentId && draftThread.threadId === threadRef.threadId ) { draftStore.markDraftThreadPromoting(DraftId.make(draftId), threadRef); + promoted.push(draftId); } } + if (promoted.length === 0 || commitsDraftThreadBinding(promoted, "promotedTo", threadRef)) + return true; + useComposerDraftStore.setState((state) => ({ + draftThreadsByThreadKey: Object.fromEntries( + Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => [ + draftId, + promoted.includes(draftId) ? { ...draftThread, promotedTo: null } : draftThread, + ]), + ), + })); + return false; +} + +/** Writes pending draft state now and checks the stored bytes hold `field` for each draft. */ +function commitsDraftThreadBinding( + draftIds: ReadonlyArray, + field: "promotedTo" | "sentTo", + threadRef: ScopedThreadRef, +): boolean { + try { + composerDebouncedStorage.flush(); + const stored = readStoredComposerDraftState(); + return draftIds.every((draftId) => { + const bound = stored?.draftThreadsByThreadKey[draftId]?.[field]; + return ( + bound?.environmentId === threadRef.environmentId && bound.threadId === threadRef.threadId + ); + }); + } catch { + return false; + } } export function restoreFailedDraftThread( @@ -4748,11 +4787,7 @@ export function restoreFailedDraftThread( const current = state.draftThreadsByThreadKey[draftId] ?? draftThread; // The send recorded its machine before it went out; the same id stays bound there. const sentTo = - threadId === draftThread.threadId - ? (current.promotedTo ?? - current.sentTo ?? - scopeThreadRef(draftThread.environmentId, draftThread.threadId)) - : null; + threadId === draftThread.threadId ? (current.promotedTo ?? current.sentTo ?? null) : null; return { draftThreadsByThreadKey: { ...state.draftThreadsByThreadKey, @@ -4766,6 +4801,9 @@ export function restoreFailedDraftThread( }, }; }); + // Best effort: until this lands, the committed promotion still binds the id there. + const sentTo = useComposerDraftStore.getState().draftThreadsByThreadKey[draftId]?.sentTo; + if (sentTo) commitsDraftThreadBinding([draftId], "sentTo", sentTo); } export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): void { From e2475faea7243a56da65306fe3a3adb343956515 Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:57:29 +0000 Subject: [PATCH 3/3] fix(placement): keep a draft's earlier committed send binding when a later commit fails PR70-R1-F1, attempt 2. A failed commit cleared promotedTo on every matching draft, including a promotion an earlier, possibly accepted send had already committed (still there after a crash and reload). The common restore then left the thread id unbound, and it could be retargeted to another machine. markPromotedDraftThreadByRef now restores each draft's prior promotion on a failed commit, so the earlier binding survives, restoration turns it into sentTo, and both retarget paths keep the id on its machine. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/composerDraftStore.test.ts | 41 +++++++++++++++++++++++-- apps/web/src/composerDraftStore.ts | 16 +++++++--- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index b300c832d301b..69e0c5d53da31 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1238,9 +1238,46 @@ describe("composerDraftStore project draft thread mapping", () => { threadId, }); + // A later send of that reloaded draft fails to commit (an edit is pending, storage throws). + // It launches nothing and must keep the earlier, possibly accepted, binding. + const retriedDraft = after.useComposerDraftStore.getState().getDraftSession(draftId)!; + after.useComposerDraftStore.getState().setPrompt(draftId, "retry after reload"); + storageFails = true; + const launchesBeforeRetry = launches; + send(after); + expect(launches).toBe(launchesBeforeRetry); + after.restoreFailedDraftThread(draftId, retriedDraft, threadId); + after.useComposerDraftStore.getState().setDraftThreadContext(draftId, { + projectRef: remoteProjectRef, + environmentSelection: "auto", + loadBalancedEnvironmentId: OTHER_TEST_ENVIRONMENT_ID, + }); + after.useComposerDraftStore + .getState() + .setProjectDraftThreadId(remoteProjectRef, draftId, { environmentSelection: "manual" }); + expect(after.useComposerDraftStore.getState().getDraftSession(draftId)?.environmentId).toBe( + TEST_ENVIRONMENT_ID, + ); + // Storage recovers and the pending write lands; a reload from it still keeps the binding. + storageFails = false; + await vi.advanceTimersByTimeAsync(300); + vi.clearAllTimers(); + vi.resetModules(); + const recovered = await import("./composerDraftStore"); + recovered.useComposerDraftStore + .getState() + .setDraftThreadContext(draftId, { projectRef: remoteProjectRef }); + recovered.useComposerDraftStore + .getState() + .setProjectDraftThreadId(remoteProjectRef, draftId, { environmentSelection: "manual" }); + expect(recovered.useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({ + environmentId: TEST_ENVIRONMENT_ID, + threadId, + }); + // An unconfirmed outcome keeps that binding through the next reload too. - const sentDraft = after.useComposerDraftStore.getState().getDraftSession(draftId)!; - after.restoreFailedDraftThread(draftId, sentDraft, threadId); + const sentDraft = recovered.useComposerDraftStore.getState().getDraftSession(draftId)!; + recovered.restoreFailedDraftThread(draftId, sentDraft, threadId); vi.clearAllTimers(); vi.resetModules(); const reloaded = await import("./composerDraftStore"); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index bfd2481105237..e9b3ccab1b723 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4731,27 +4731,33 @@ export function usePromotingDraftThreadKeys(): ReadonlyArray { /** * Marks the drafts sending as `threadRef` and commits that to storage at once, so a crash * after the launch cannot reload them unbound: the launch may then have started there. - * False when storage did not take it; the caller must not launch, and nothing stays marked. + * False when storage did not take it; the caller must not launch, and each draft keeps the + * promotion it had before, which an earlier send may have committed. */ export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): boolean { const draftStore = useComposerDraftStore.getState(); - const promoted: Array = []; + const promoted = new Map(); for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { if ( draftThread.environmentId === threadRef.environmentId && draftThread.threadId === threadRef.threadId ) { + promoted.set(draftId, draftThread.promotedTo ?? null); draftStore.markDraftThreadPromoting(DraftId.make(draftId), threadRef); - promoted.push(draftId); } } - if (promoted.length === 0 || commitsDraftThreadBinding(promoted, "promotedTo", threadRef)) + if ( + promoted.size === 0 || + commitsDraftThreadBinding([...promoted.keys()], "promotedTo", threadRef) + ) return true; useComposerDraftStore.setState((state) => ({ draftThreadsByThreadKey: Object.fromEntries( Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => [ draftId, - promoted.includes(draftId) ? { ...draftThread, promotedTo: null } : draftThread, + promoted.has(draftId) + ? { ...draftThread, promotedTo: promoted.get(draftId) ?? null } + : draftThread, ]), ), }));