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/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/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..69e0c5d53da31 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1133,6 +1133,191 @@ 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("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, + }); + + // 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 = recovered.useComposerDraftStore.getState().getDraftSession(draftId)!; + recovered.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 4066715c53b2c..e9b3ccab1b723 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,33 @@ 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 { + // 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 + ); +} + function scopedThreadRefsEqual( left: ScopedThreadRef | null | undefined, right: ScopedThreadRef | null | undefined, @@ -1803,7 +1843,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 +1959,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 +2004,7 @@ function normalizePersistedDraftThreads( : {}), ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo, + ...(sentTo ? { sentTo } : {}), }; } } @@ -2762,6 +2790,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 +2922,7 @@ const composerDraftStore = create()( existingThread, options, ); + if (staysOnSentMachine(existingThread, nextDraftThread)) return state; const hasSameLogicalMapping = previousThreadKeyForLogicalProject === draftId; const hasNoStaleMappingsForDraft = Object.entries( state.logicalProjectDraftThreadKeyByLogicalProjectKey, @@ -2987,7 +3024,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 +3086,7 @@ const composerDraftStore = create()( startFromOrigin: nextStartFromOrigin, ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo: existing.promotedTo ?? null, + ...(existing.sentTo ? { sentTo: existing.sentTo } : {}), }; const isUnchanged = nextDraftThread.environmentId === existing.environmentId && @@ -4686,16 +4728,60 @@ 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 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 = 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); } } + 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.has(draftId) + ? { ...draftThread, promotedTo: promoted.get(draftId) ?? 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( @@ -4703,17 +4789,27 @@ 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 ?? null) : null; + return { + draftThreadsByThreadKey: { + ...state.draftThreadsByThreadKey, + [draftId]: { + ...current, + threadId, + ...(threadId !== draftThread.threadId ? { createdAt: new Date().toISOString() } : {}), + promotedTo: null, + sentTo, + }, }, - }, - })); + }; + }); + // 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 {