From 78f11507d79ff5518b9b585c54f72787bb199e3a Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:03:14 -0500 Subject: [PATCH 1/3] fix(web): new worktree sends wait for their branch, and invite answers can't go twice A first send in New worktree mode failed with "Select a base branch" while the branch list for the "New worktrees from" setting was still loading (1.5s typical, up to 16s on a busy repository), even though the footer already named a branch. The send and goal paths now wait for the same lookup the branch picker uses (fetchNewWorktreeBaseBranch, sharing its queries) and only fail when no branch fits. The agent invite card turned its buttons back on as soon as the answer returned, while the card stayed up until the thread update arrived. A second click in that gap was refused as an invite already answered. The buttons now stay off after a successful answer. --- .../components/ChatView.agents.browser.tsx | 12 ++++ .../components/ChatView.sending.browser.tsx | 67 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 69 +++++++++++++------ .../chat/ComposerAgentInvitePanel.tsx | 6 +- .../web/src/hooks/useNewWorktreeBaseBranch.ts | 42 ++++++++++- 5 files changed, 171 insertions(+), 25 deletions(-) diff --git a/apps/web/src/components/ChatView.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx index c4ce72d4d..4f338e56e 100644 --- a/apps/web/src/components/ChatView.agents.browser.tsx +++ b/apps/web/src/components/ChatView.agents.browser.tsx @@ -837,6 +837,18 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { ).toMatchObject({ requestId, choice: "review" }), { timeout: 8_000, interval: 16 }, ); + // The server took the answer, but the thread has not caught up yet, so + // the card is still there. Its buttons stay off: a second answer in + // that gap would be refused as an invite already answered. + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(document.querySelector('[data-testid="agent-invite-panel"]')).toBe(panel); + expect( + [...panel.querySelectorAll("button")] + .filter((button) => + ["Not now", "Add to thread", "Review only"].includes(button.textContent ?? ""), + ) + .map((button) => button.disabled), + ).toEqual([true, true, true]); } finally { await mounted.cleanup(); } diff --git a/apps/web/src/components/ChatView.sending.browser.tsx b/apps/web/src/components/ChatView.sending.browser.tsx index 307daf03d..96241fff5 100644 --- a/apps/web/src/components/ChatView.sending.browser.tsx +++ b/apps/web/src/components/ChatView.sending.browser.tsx @@ -1375,6 +1375,73 @@ describe("ChatView (full app): first sends and worktree setup", () => { } }); + it("waits for a slow branch list instead of failing a New worktree send", async () => { + const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); + // The branch list on a busy repository can take seconds. It answers only + // once the message has been sent. + let releaseRefs: () => void = () => {}; + const refsReleased = new Promise((resolve) => { + releaseRefs = resolve; + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, + ), + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.vcsListRefs) { + return refsReleased.then(() => ({ + isRepo: true, + hasPrimaryRemote: true, + nextCursor: null, + totalCount: 2, + refs: [ + { name: "feature/current", current: true, isDefault: false, worktreePath: null }, + { name: "main", current: false, isDefault: true, worktreePath: null }, + ], + })); + } + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { sequence: fixture.snapshot.snapshotSequence + 1 }; + } + return undefined; + }, + }); + + const turnStart = () => + wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.turn.start", + ) as { bootstrap?: { prepareWorktree?: { baseBranch?: string } } } | undefined; + + try { + (await waitForButtonByText("Current checkout")).click(); + await clickSelectItemContainingText("New worktree"); + useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); + await waitForLayout(); + (await waitForSendButton()).click(); + await waitForLayout(); + + expect(document.body.textContent).not.toContain("Select a base branch"); + expect(turnStart()).toBeUndefined(); + + releaseRefs(); + // The "New worktrees from" setting's default: the default branch, not + // the branch the project's checkout is on. + await vi.waitFor( + () => expect(turnStart()?.bootstrap?.prepareWorktree?.baseBranch).toBe("main"), + { timeout: 8_000, interval: 16 }, + ); + } finally { + releaseRefs(); + await mounted.cleanup(); + } + }); + it("clears pending worktree overrides when switching empty server threads", async () => { const secondThreadId = "thread-browser-test-second" as ThreadId; const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 965897805..a32bdfd88 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -59,6 +59,7 @@ import { resolveThreadWorkingCwd } from "@threadlines/shared/threadCwd"; import { formatForkSourceExcerpt, truncate } from "@threadlines/shared/String"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { Debouncer } from "@tanstack/react-pacer"; +import { useQueryClient } from "@tanstack/react-query"; import * as Option from "effect/Option"; import { lazy, @@ -76,6 +77,7 @@ import { useShallow } from "zustand/react/shallow"; import { useGitStatus } from "~/lib/gitStatusState"; import { shouldShowCheckoutPicker } from "~/lib/checkoutRecovery"; import { useCheckoutRecovery } from "../hooks/useCheckoutRecovery"; +import { fetchNewWorktreeBaseBranch } from "../hooks/useNewWorktreeBaseBranch"; import { buildCheckoutMissingNotice } from "./chat/checkoutMissingNotice"; import { usePrimaryEnvironmentId } from "../environments/primary"; import { readEnvironmentApi, useEnvironmentApiAvailable } from "../environmentApi"; @@ -1211,6 +1213,7 @@ export default function ChatView(props: ChatViewProps) { useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]), ); const setStoreThreadError = useStore((store) => store.setError); + const queryClient = useQueryClient(); const activeThreadSeenAt = useUiStateStore((store) => routeKind === "server" ? selectThreadSeenAt(store, routeThreadKey, serverThread?.lastSeenAt) @@ -5916,14 +5919,23 @@ export default function ChatView(props: ChatViewProps) { envMode: sendEnvMode, worktreePath: activeThread.worktreePath, }); - const baseBranchForWorktree = shouldCreateWorktree ? activeThreadBranch : null; - - // In worktree mode, require an explicit base branch so we don't silently - // fall back to local execution when branch selection is missing. - if (shouldCreateWorktree && !activeThreadBranch) { - setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode."); - return; - } + // A new worktree's base is the branch picked below the composer, or the + // "New worktrees from" setting's branch, which the picker fills in once + // the branch list loads. A send before then waits for that list (seconds + // on a busy repository) instead of failing while the picker already + // names the branch. + let baseBranchForWorktree = shouldCreateWorktree ? activeThreadBranch : null; + const worktreeBaseLookup = + shouldCreateWorktree && !activeThreadBranch + ? fetchNewWorktreeBaseBranch({ + queryClient, + environmentId, + cwd: activeProject.cwd, + }) + : null; + // Awaited where the send needs it; until then a send that stops early + // leaves no unhandled failure behind. + worktreeBaseLookup?.catch(() => undefined); sendInFlightRef.current = true; // Sending again by hand retires an older failure's Retry. @@ -5955,7 +5967,7 @@ export default function ChatView(props: ChatViewProps) { useLocalDispatchStore.getState().begin({ threadRef: threadRefForSend, sendId: messageIdForSend, - snapshot: dispatchSnapshotForSend, + snapshot: { ...dispatchSnapshotForSend, worktreeBase: baseBranchForWorktree }, firstSend: isLocalDraftThread ? { modelSelection: threadCreateModelSelection, participantId: roomRecipientId } : null, @@ -6242,6 +6254,14 @@ export default function ChatView(props: ChatViewProps) { } const turnAttachments = await turnAttachmentsPromise; + if (worktreeBaseLookup !== null) { + baseBranchForWorktree = await worktreeBaseLookup; + if (baseBranchForWorktree === null) { + throw new Error( + "Couldn't find a branch to start the new worktree from. Pick one below the message box.", + ); + } + } if (baseBranchForWorktree) { requestSetupTerminalReveal(scopedThreadKey(threadRefForSend), new Date().toISOString()); } @@ -6253,7 +6273,7 @@ export default function ChatView(props: ChatViewProps) { modelSelection: threadCreateModelSelection, runtimeMode, interactionMode, - branch: activeThreadBranch, + branch: baseBranchForWorktree ?? activeThreadBranch, worktreePath: activeThread.worktreePath, ...existingWorktreeCreateFields({ thread: activeThread, @@ -6774,13 +6794,6 @@ export default function ChatView(props: ChatViewProps) { envMode: sendEnvMode, worktreePath: activeThread.worktreePath, }); - if (goalNeedsWorktree && !activeThreadBranch) { - setThreadError( - threadId, - "Select a base branch before setting a goal in New worktree mode.", - ); - return; - } // A first send (or another goal) already setting this thread up makes // it, or its worktree; the goal can go once that is done. const goalThreadKey = scopedThreadKey(scopeThreadRef(environmentId, threadId)); @@ -6833,6 +6846,20 @@ export default function ChatView(props: ChatViewProps) { setGoalDispatchingThreadId(threadId); const endGoalSetup = goalSetsThreadUp ? beginGoalThreadSetup(goalThreadKey) : () => {}; try { + // Its worktree starts where a first send's would (see onSend). + const goalWorktreeBase = goalNeedsWorktree + ? (activeThreadBranch ?? + (await fetchNewWorktreeBaseBranch({ + queryClient, + environmentId, + cwd: activeProject.cwd, + }))) + : null; + if (goalNeedsWorktree && goalWorktreeBase === null) { + throw new Error( + "Couldn't find a branch to start the new worktree from. Pick one below the message box.", + ); + } // A goal on a draft makes its thread with it, so the session spins up // and the goal's work begins without waiting for a user message. const createThread = @@ -6843,7 +6870,7 @@ export default function ChatView(props: ChatViewProps) { modelSelection: goalModelSelection, runtimeMode, interactionMode: "default" as const, - branch: activeThreadBranch, + branch: goalWorktreeBase ?? activeThreadBranch, worktreePath: activeThread.worktreePath, ...existingWorktreeCreateFields({ thread: activeThread, @@ -6870,8 +6897,8 @@ export default function ChatView(props: ChatViewProps) { ? buildThreadStartBootstrap({ createThread, worktree: - goalNeedsWorktree && activeThreadBranch - ? { projectCwd: activeProject.cwd, baseBranch: activeThreadBranch } + goalWorktreeBase !== null + ? { projectCwd: activeProject.cwd, baseBranch: goalWorktreeBase } : null, }) : undefined; @@ -6917,9 +6944,9 @@ export default function ChatView(props: ChatViewProps) { isSendBusy, isServerThread, persistThreadSettingsForNextTurn, + queryClient, runtimeMode, sendEnvMode, - setThreadError, ], ); diff --git a/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx b/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx index ba50fb57b..81e630c11 100644 --- a/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx +++ b/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx @@ -42,15 +42,17 @@ export const ComposerAgentInvitePanel = memo(function ComposerAgentInvitePanel(p choice, createdAt: new Date().toISOString(), }); + // Answered: the buttons stay off until the thread's update takes the + // panel away, which can land a moment after the reply. A second click + // in that gap would be refused as an invite already answered. } catch (error) { + setResponding(false); toastManager.add( failureNotice({ title: `Couldn't bring in ${invite.toName}`, error, }), ); - } finally { - setResponding(false); } }; diff --git a/apps/web/src/hooks/useNewWorktreeBaseBranch.ts b/apps/web/src/hooks/useNewWorktreeBaseBranch.ts index 79a1a6067..a46b0724d 100644 --- a/apps/web/src/hooks/useNewWorktreeBaseBranch.ts +++ b/apps/web/src/hooks/useNewWorktreeBaseBranch.ts @@ -1,9 +1,47 @@ import type { EnvironmentId } from "@threadlines/contracts"; import { findRefForBranchName, resolveNewWorktreeBaseBranch } from "@threadlines/shared/git"; -import { useInfiniteQuery } from "@tanstack/react-query"; +import { type QueryClient, useInfiniteQuery } from "@tanstack/react-query"; import { gitBranchSearchInfiniteQueryOptions } from "../lib/gitReactQuery"; -import { useComputerConfig } from "../newThreadDefaults"; +import { useComputerConfig, waitForComputerConfig } from "../newThreadDefaults"; + +/** + * The same base as `useNewWorktreeBaseBranch`, for a send that goes before + * the hook has it: the branch list can take seconds on a busy repository, + * and the first message of a new worktree thread waits for it rather than + * failing. Shares the hook's queries, so a lookup already running is joined, + * not repeated. Null when the computer's settings never come or no branch + * fits; a failed lookup rejects. + */ +export async function fetchNewWorktreeBaseBranch(input: { + readonly queryClient: QueryClient; + readonly environmentId: EnvironmentId; + readonly cwd: string; +}): Promise { + const base = (await waitForComputerConfig(input.environmentId))?.settings.newWorktreeBase; + if (base === undefined) { + return null; + } + const namedBranch = base.from === "named" ? base.branch : ""; + const lookup = (query: string) => + input.queryClient.fetchInfiniteQuery( + gitBranchSearchInfiniteQueryOptions({ + environmentId: input.environmentId, + cwd: input.cwd, + query, + }), + ); + const [listed, named] = await Promise.all([ + lookup(""), + namedBranch.length > 0 ? lookup(namedBranch) : null, + ]); + const listedRefs = listed.pages.flatMap((page) => page.refs); + return resolveNewWorktreeBaseBranch({ + base, + refs: [...listedRefs, ...(named?.pages.flatMap((page) => page.refs) ?? [])], + currentBranch: listedRefs.find((candidate) => candidate.current)?.name ?? null, + }); +} /** * The branch a new worktree starts from until the user picks one: the From e89f068dbc8bf09ad3126081bcd1b925fa56c526 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:12:47 -0500 Subject: [PATCH 2/3] fix(web): pickers stay put while a first send waits for its branch From review of the first commit: - The branch, workspace and computer pickers below the composer are off while a message or goal is on its way. A first send can now wait seconds for its worktree's branch, and a branch picked in that window was ignored (or, once the message showed, acted as a checkout switch on the thread). - The send waits up to 15s for a computer's settings instead of 3s, so a slow-to-connect computer doesn't fail with "Couldn't find a branch". - An answered invite's buttons stay off when its thread is left and opened again before the thread update arrives. --- apps/web/src/components/BranchToolbar.tsx | 5 ++ .../BranchToolbarBranchSelector.tsx | 6 +- .../components/ChatView.sending.browser.tsx | 80 +++++++++++++++++++ apps/web/src/components/ChatView.tsx | 12 ++- .../chat/ComposerAgentInvitePanel.tsx | 10 ++- .../web/src/hooks/useNewWorktreeBaseBranch.ts | 6 +- 6 files changed, 113 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 923411674..6c59a7bcd 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -64,6 +64,8 @@ interface BranchToolbarProps { options?: { readonly fromSetting?: boolean }, ) => void; envLocked: boolean; + /** The branch can't be changed now (a message or goal is on its way). */ + branchLocked?: boolean; onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; availableEnvironments?: readonly EnvironmentOption[]; @@ -268,6 +270,7 @@ export const BranchToolbar = memo(function BranchToolbar({ activeThreadBranchOverrideFromSetting, onActiveThreadBranchOverrideChange, envLocked, + branchLocked = false, onCheckoutPullRequestRequest, onComposerFocusRequest, availableEnvironments, @@ -448,6 +451,7 @@ export const BranchToolbar = memo(function BranchToolbar({ threadId={threadId} {...(draftId ? { draftId } : {})} envLocked={envLocked} + locked={branchLocked} {...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})} {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})} {...(activeThreadBranchOverrideFromSetting @@ -526,6 +530,7 @@ export const BranchToolbar = memo(function BranchToolbar({ threadId={threadId} {...(draftId ? { draftId } : {})} envLocked={envLocked} + locked={branchLocked} {...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})} {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})} {...(activeThreadBranchOverrideFromSetting diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index d492052b3..14d0f03c6 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -82,6 +82,8 @@ interface BranchToolbarBranchSelectorProps { threadId: ThreadId; draftId?: DraftId; envLocked: boolean; + /** The picker is off: a message or goal on its way has its branch. */ + locked?: boolean; effectiveEnvModeOverride?: "local" | "worktree"; activeThreadBranchOverride?: string | null; /** The override is the base the "New worktrees from" setting gave, not a pick. */ @@ -126,6 +128,7 @@ export function BranchToolbarBranchSelector({ threadId, draftId, envLocked, + locked = false, effectiveEnvModeOverride, activeThreadBranchOverride, activeThreadBranchOverrideFromSetting, @@ -670,7 +673,8 @@ export function BranchToolbarBranchSelector({ }), selectedCheckoutMissing, ); - const triggerDisabled = (isBranchesSearchPending && refs.length === 0) || isBranchActionPending; + const triggerDisabled = + locked || (isBranchesSearchPending && refs.length === 0) || isBranchActionPending; function renderPickerItem(itemValue: string, index: number) { if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) { diff --git a/apps/web/src/components/ChatView.sending.browser.tsx b/apps/web/src/components/ChatView.sending.browser.tsx index 96241fff5..75161d217 100644 --- a/apps/web/src/components/ChatView.sending.browser.tsx +++ b/apps/web/src/components/ChatView.sending.browser.tsx @@ -1442,6 +1442,86 @@ describe("ChatView (full app): first sends and worktree setup", () => { } }); + it("keeps a waiting New worktree send's branch picker off until it goes", async () => { + const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); + // The setting names `develop`, whose search is slow; the plain list is not. + let releaseSearch: () => void = () => {}; + const searchReleased = new Promise((resolve) => { + releaseSearch = resolve; + }); + const refsPage = (refs: ReadonlyArray>) => ({ + isRepo: true, + hasPrimaryRemote: true, + nextCursor: null, + totalCount: refs.length, + refs, + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, + ), + }, + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + settings: { + ...nextFixture.serverConfig.settings, + newWorktreeBase: { from: "named", branch: "develop" }, + }, + }; + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.vcsListRefs) { + return body.query === "develop" + ? searchReleased.then(() => + refsPage([ + { name: "develop", current: false, isDefault: false, worktreePath: null }, + ]), + ) + : refsPage([ + { name: "main", current: true, isDefault: true, worktreePath: null }, + { name: "release/next", current: false, isDefault: false, worktreePath: null }, + ]); + } + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { sequence: fixture.snapshot.snapshotSequence + 1 }; + } + return undefined; + }, + }); + + try { + (await waitForButtonByText("Current checkout")).click(); + await clickSelectItemContainingText("New worktree"); + useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); + await waitForLayout(); + (await waitForSendButton()).click(); + await waitForLayout(); + + // The send has its place while it waits for the setting's branch. + expect((await waitForButtonByText("From main")).disabled).toBe(true); + releaseSearch(); + + await vi.waitFor( + () => { + const turnStartRequest = wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.turn.start", + ) as { bootstrap?: { prepareWorktree?: { baseBranch?: string } } } | undefined; + expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("develop"); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + releaseSearch(); + await mounted.cleanup(); + } + }); + it("clears pending worktree overrides when switching empty server threads", async () => { const secondThreadId = "thread-browser-test-second" as ThreadId; const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index a32bdfd88..44982c74d 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3494,7 +3494,7 @@ export default function ChatView(props: ChatViewProps) { // project in that environment while keeping the same logical project. const onEnvironmentChange = useCallback( (nextEnvironmentId: EnvironmentId) => { - if (envLocked || !draftId) return; + if (envLocked || isSendBusy || !draftId) return; const target = logicalProjectEnvironments.find( (env) => env.environmentId === nextEnvironmentId, ); @@ -3505,7 +3505,7 @@ export default function ChatView(props: ChatViewProps) { // The move drops the draft's agents: they were the old computer's. void applyMovedDraftDefaults(draftId, target.environmentId); }, - [draftId, envLocked, logicalProjectEnvironments, setDraftThreadContext], + [draftId, envLocked, isSendBusy, logicalProjectEnvironments, setDraftThreadContext], ); // A new thread can also go to a computer that hasn't got the project yet: @@ -6739,6 +6739,8 @@ export default function ChatView(props: ChatViewProps) { }; const [goalDispatchingThreadId, setGoalDispatchingThreadId] = useState(null); + const placementBusy = + isSendBusy || (activeThread !== undefined && goalDispatchingThreadId === activeThread.id); // Bridges the gap between dispatching a goal and its authoritative state // arriving through the projection stream — without it the bar flickers out // while a brand-new thread materializes (and edits briefly show the stale @@ -9316,7 +9318,11 @@ export default function ChatView(props: ChatViewProps) { onActiveThreadBranchOverrideChange: onPendingServerThreadBaseChange, } : {})} - envLocked={envLocked} + // A message or goal on its way has its place: the computer, + // workspace and branch stay put until it lands or fails + // (a first send can wait seconds for its worktree's branch). + envLocked={envLocked || placementBusy} + branchLocked={placementBusy} onComposerFocusRequest={scheduleComposerFocus} {...(canCheckoutPullRequestIntoThread ? { onCheckoutPullRequestRequest: openPullRequestDialog } diff --git a/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx b/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx index 81e630c11..ac095ce6a 100644 --- a/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx +++ b/apps/web/src/components/chat/ComposerAgentInvitePanel.tsx @@ -9,6 +9,13 @@ import { Button } from "../ui/button"; import { failureNotice, toastManager } from "../ui/toast"; import { addComputerNotConnectedNotice } from "../computerConnectionNotices"; +/** + * Invites answered from this window. The panel stays up until the thread's + * update takes it away, and it can be left and opened again meanwhile; its + * buttons stay off for an answered invite either way. + */ +const answeredInviteIds = new Set(); + /** * An agent asks to bring in another agent for a review * (docs/design/rooms-agent-invites.md). Docked above the message box like a @@ -20,7 +27,7 @@ export const ComposerAgentInvitePanel = memo(function ComposerAgentInvitePanel(p invite: PendingRoomInvite; }) { const { invite } = props; - const [responding, setResponding] = useState(false); + const [responding, setResponding] = useState(() => answeredInviteIds.has(invite.requestId)); const [showRequest, setShowRequest] = useState(false); const respond = async (choice: RoomAgentInviteChoice) => { @@ -45,6 +52,7 @@ export const ComposerAgentInvitePanel = memo(function ComposerAgentInvitePanel(p // Answered: the buttons stay off until the thread's update takes the // panel away, which can land a moment after the reply. A second click // in that gap would be refused as an invite already answered. + answeredInviteIds.add(invite.requestId); } catch (error) { setResponding(false); toastManager.add( diff --git a/apps/web/src/hooks/useNewWorktreeBaseBranch.ts b/apps/web/src/hooks/useNewWorktreeBaseBranch.ts index a46b0724d..9f2ce1cae 100644 --- a/apps/web/src/hooks/useNewWorktreeBaseBranch.ts +++ b/apps/web/src/hooks/useNewWorktreeBaseBranch.ts @@ -13,12 +13,16 @@ import { useComputerConfig, waitForComputerConfig } from "../newThreadDefaults"; * not repeated. Null when the computer's settings never come or no branch * fits; a failed lookup rejects. */ +/** How long a send waits for a computer's settings (a remote one can be slow to connect). */ +const SEND_SETTINGS_WAIT_MS = 15_000; + export async function fetchNewWorktreeBaseBranch(input: { readonly queryClient: QueryClient; readonly environmentId: EnvironmentId; readonly cwd: string; }): Promise { - const base = (await waitForComputerConfig(input.environmentId))?.settings.newWorktreeBase; + const base = (await waitForComputerConfig(input.environmentId, SEND_SETTINGS_WAIT_MS))?.settings + .newWorktreeBase; if (base === undefined) { return null; } From d3056bb97a8061c5cd1a024474e232aae7c6370d Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:22:18 -0500 Subject: [PATCH 3/3] fix(web): a send that never went out leaves the chat and goes back in the box A send that fails before any command is dispatched (a new worktree's branch not found, an attachment that can't be read) used to stay in the chat as if sent when the user had started typing again, because the message only came back to an empty box. Now it always leaves the chat, and its text, attachments and contexts go back in the box ahead of whatever was written since. A send that failed in transit may have reached the server, so it still comes back only to an empty box. --- .../components/ChatView.sending.browser.tsx | 74 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 75 +++++++++++++------ 2 files changed, 125 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/ChatView.sending.browser.tsx b/apps/web/src/components/ChatView.sending.browser.tsx index 75161d217..868f6cdb9 100644 --- a/apps/web/src/components/ChatView.sending.browser.tsx +++ b/apps/web/src/components/ChatView.sending.browser.tsx @@ -1442,6 +1442,80 @@ describe("ChatView (full app): first sends and worktree setup", () => { } }); + it("takes back a New worktree send whose branch isn't found, keeping what was typed since", async () => { + const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); + let releaseRefs: () => void = () => {}; + const refsReleased = new Promise((resolve) => { + releaseRefs = resolve; + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread, + ), + }, + resolveRpc: (body) => { + if (body._tag === WS_METHODS.vcsListRefs) { + // No branches at all: nothing for a new worktree to start from. + return refsReleased.then(() => ({ + isRepo: true, + hasPrimaryRemote: true, + nextCursor: null, + totalCount: 0, + refs: [], + })); + } + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { sequence: fixture.snapshot.snapshotSequence + 1 }; + } + return undefined; + }, + }); + const userMessages = () => + [...document.querySelectorAll('[data-message-role="user"]')].map( + (row) => row.textContent ?? "", + ); + + try { + (await waitForButtonByText("Current checkout")).click(); + await clickSelectItemContainingText("New worktree"); + useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it"); + await waitForLayout(); + (await waitForSendButton()).click(); + await vi.waitFor( + () => expect(userMessages().some((text) => text.includes("Ship it"))).toBe(true), + { + timeout: 8_000, + interval: 16, + }, + ); + // The user starts the next message while the first one waits. + useComposerDraftStore.getState().setPrompt(THREAD_REF, "Next idea"); + releaseRefs(); + + await vi.waitFor( + () => + expect(useComposerDraftStore.getState().getComposerDraft(THREAD_REF)?.prompt).toBe( + "Ship it\n\nNext idea", + ), + { timeout: 8_000, interval: 16 }, + ); + expect(userMessages().some((text) => text.includes("Ship it"))).toBe(false); + expect( + wsRequests.some( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.turn.start", + ), + ).toBe(false); + } finally { + releaseRefs(); + await mounted.cleanup(); + } + }); + it("keeps a waiting New worktree send's branch picker off until it goes", async () => { const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID); // The setting names `develop`, whose search is slow; the plain list is not. diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 44982c74d..7be7461ef 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -6344,8 +6344,7 @@ export default function ChatView(props: ChatViewProps) { } // Retry can only resend a message the composer got back, as it came back. let retryContents: string | null = null; - if ( - !dispatchSucceeded && + const composerEmpty = promptRef.current.length === 0 && composerAttachmentsRef.current.length === 0 && composerTerminalContextsRef.current.length === 0 && @@ -6353,41 +6352,69 @@ export default function ChatView(props: ChatViewProps) { composerFileSelectionContextsRef.current.length === 0 && composerPickedElementContextsRef.current.length === 0 && (useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.drawingContexts - .length ?? 0) === 0 - ) { + .length ?? 0) === 0; + // A send that failed before anything went out (a new worktree's branch + // not found, an attachment that can't be read) never reached the + // server: it leaves the chat whatever the user wrote meanwhile, and + // goes back in the box ahead of that. One that failed in transit may + // have arrived, so it comes back only to an empty box. + if (!dispatchSucceeded && (composerEmpty || dispatchedSend === null)) { takeBackOutgoingMessage(optimisticMessage); - promptRef.current = promptForSend; + const writtenSince = promptRef.current; + const restoredPrompt = + writtenSince.length > 0 ? `${promptForSend}\n\n${writtenSince}` : promptForSend; + promptRef.current = restoredPrompt; const retryComposerAttachments = composerAttachmentsSnapshot.map( cloneComposerAttachmentForRetry, ); - composerAttachmentsRef.current = retryComposerAttachments; - composerTerminalContextsRef.current = composerTerminalContextsSnapshot; - composerTranscriptHighlightContextsRef.current = - composerTranscriptHighlightContextsSnapshot; - composerFileSelectionContextsRef.current = composerFileSelectionContextsSnapshot; - setComposerDraftPrompt(composerDraftTarget, promptForSend); + composerAttachmentsRef.current = [ + ...composerAttachmentsRef.current, + ...retryComposerAttachments, + ]; + const terminalContexts = [ + ...composerTerminalContextsSnapshot, + ...composerTerminalContextsRef.current, + ]; + const transcriptHighlightContexts = [ + ...composerTranscriptHighlightContextsSnapshot, + ...composerTranscriptHighlightContextsRef.current, + ]; + const pickedElementContexts = [ + ...composerPickedElementContextsSnapshot, + ...composerPickedElementContextsRef.current, + ]; + composerTerminalContextsRef.current = terminalContexts; + composerTranscriptHighlightContextsRef.current = transcriptHighlightContexts; + // Added after what is there, as the store adds them below. + composerFileSelectionContextsRef.current = [ + ...composerFileSelectionContextsRef.current, + ...composerFileSelectionContextsSnapshot, + ]; + composerPickedElementContextsRef.current = pickedElementContexts; + setComposerDraftPrompt(composerDraftTarget, restoredPrompt); addComposerDraftAttachments(composerDraftTarget, retryComposerAttachments); - setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot); + setComposerDraftTerminalContexts(composerDraftTarget, terminalContexts); setComposerDraftTranscriptHighlightContexts( composerDraftTarget, - composerTranscriptHighlightContextsSnapshot, + transcriptHighlightContexts, ); for (const context of composerFileSelectionContextsSnapshot) { addComposerDraftFileSelectionContext(composerDraftTarget, context); } - composerPickedElementContextsRef.current = composerPickedElementContextsSnapshot; const draftStore = useComposerDraftStore.getState(); - draftStore.setPickedElementContexts( - composerDraftTarget, - composerPickedElementContextsSnapshot, - ); - draftStore.setDrawingContexts(composerDraftTarget, composerDrawingContextsSnapshot); - retryContents = composerContentsKey( - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), - ); + draftStore.setPickedElementContexts(composerDraftTarget, pickedElementContexts); + draftStore.setDrawingContexts(composerDraftTarget, [ + ...composerDrawingContextsSnapshot, + ...(draftStore.getComposerDraft(composerDraftTarget)?.drawingContexts ?? []), + ]); + if (composerEmpty) { + retryContents = composerContentsKey( + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), + ); + } composerRef.current?.resetCursorState({ - cursor: collapseExpandedComposerCursor(promptForSend, promptForSend.length), - prompt: promptForSend, + cursor: collapseExpandedComposerCursor(restoredPrompt, promptForSend.length), + prompt: restoredPrompt, detectTrigger: true, }); }