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.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..868f6cdb9 100644 --- a/apps/web/src/components/ChatView.sending.browser.tsx +++ b/apps/web/src/components/ChatView.sending.browser.tsx @@ -1375,6 +1375,227 @@ 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("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. + 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 965897805..7be7461ef 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) @@ -3491,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, ); @@ -3502,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: @@ -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, @@ -6324,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 && @@ -6333,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, }); } @@ -6719,6 +6766,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 @@ -6774,13 +6823,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 +6875,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 +6899,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 +6926,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 +6973,9 @@ export default function ChatView(props: ChatViewProps) { isSendBusy, isServerThread, persistThreadSettingsForNextTurn, + queryClient, runtimeMode, sendEnvMode, - setThreadError, ], ); @@ -9289,7 +9345,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 ba50fb57b..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) => { @@ -42,15 +49,18 @@ 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. + answeredInviteIds.add(invite.requestId); } 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..9f2ce1cae 100644 --- a/apps/web/src/hooks/useNewWorktreeBaseBranch.ts +++ b/apps/web/src/hooks/useNewWorktreeBaseBranch.ts @@ -1,9 +1,51 @@ 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. + */ +/** 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, SEND_SETTINGS_WAIT_MS))?.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