@devries-cameron20 / t3code-1 / commits / 0e1431f61c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): the chat view and composer no longer keep old renders alive (#19869)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 15, 2026 at 04:52 UTC 0e1431f61c8c549310b9f04c9d7068e6e1ec773b
3 files changed +3505 -4022
apps/web/src/components/ChatView.tsx
+2293 -2576
@@ -24,6 +24,7 @@ import {
24 } from "./ChatView.logic";
25 import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";
26 import { useScratchProject } from "../hooks/useScratchProject";
27 +import { useStableCallback } from "../hooks/useStableCallback";
28 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
29 import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
30 import {
@@ -203,6 +204,7 @@ import {
204 findLatestProposedPlan,
205 hasActionableProposedPlan,
206 isLatestRunSettled,
207 + type PendingUserInput,
208 } from "../session-logic";
209 import { type LegendListRef } from "@legendapp/list/react";
210 import {
@@ -1578,6 +1580,110 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | n
1580 /** Runs with a workspace preparation retry in flight, across ChatView instances. */
1581 const retryingWorkspacePreparationRunIds = new Set<RunId>();
1582
1583 +// The factories below build functions ChatView calls during render, or hands
1584 +// to ChatComposer, which can call them after an await. They live outside the
1585 +// component so each closure keeps only its inputs, not a whole render scope
1586 +// (see useStableCallback), while still acting on the render that made them.
1587 +
1588 +/** Records a thread error in local state, keyed by the route the making render saw. */
1589 +function makeThreadErrorSetter(input: {
1590 + readonly routeThreadRef: ScopedThreadRef;
1591 + readonly routeThreadKey: string;
1592 + readonly draftId: DraftId | null;
1593 + readonly serverThreadRef: ScopedThreadRef | null;
1594 + readonly setLocalServerErrorsByThreadKey: (
1595 + update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1596 + ) => void;
1597 + readonly setLocalDraftErrorsByDraftId: (
1598 + update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1599 + ) => void;
1600 +}) {
1601 + return (targetThreadId: ThreadId | null, error: string | null) => {
1602 + if (!targetThreadId) return;
1603 + const nextError = sanitizeThreadErrorMessage(error);
1604 + const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
1605 + const { routeThreadRef, serverThreadRef } = input;
1606 + if (
1607 + serverThreadRef &&
1608 + targetThreadId === routeThreadRef.threadId &&
1609 + serverThreadRef.environmentId === routeThreadRef.environmentId &&
1610 + serverThreadRef.threadId === targetThreadId
1611 + ) {
1612 + input.setLocalServerErrorsByThreadKey((existing) => {
1613 + if ((existing[input.routeThreadKey]?.message ?? null) === nextError) {
1614 + return existing;
1615 + }
1616 + return { ...existing, [input.routeThreadKey]: nextEntry };
1617 + });
1618 + return;
1619 + }
1620 + const localDraftErrorKey = input.draftId ?? targetThreadId;
1621 + input.setLocalDraftErrorsByDraftId((existing) => {
1622 + if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
1623 + return existing;
1624 + }
1625 + return { ...existing, [localDraftErrorKey]: nextEntry };
1626 + });
1627 + };
1628 +}
1629 +
1630 +/** Writes the custom answer for a question of the pending user input the making render saw. */
1631 +function makePendingCustomAnswerSetter(input: {
1632 + readonly activePendingUserInput: PendingUserInput | null;
1633 + readonly activePendingRequestKey: string;
1634 + readonly promptRef: { current: string };
1635 + readonly setPendingUserInputAnswersByRequestId: (
1636 + update: SetStateAction<Record<string, Record<string, PendingUserInputDraftAnswer>>>,
1637 + ) => void;
1638 +}) {
1639 + return (questionId: string, value: string) => {
1640 + const { activePendingUserInput, activePendingRequestKey } = input;
1641 + if (!activePendingUserInput) {
1642 + return;
1643 + }
1644 + const question = activePendingUserInput.questions.find((entry) => entry.id === questionId);
1645 + if (!question || question.allowCustomAnswer === false) {
1646 + return;
1647 + }
1648 + input.promptRef.current = value;
1649 + input.setPendingUserInputAnswersByRequestId((existing) => ({
1650 + ...existing,
1651 + [activePendingRequestKey]: {
1652 + ...existing[activePendingRequestKey],
1653 + [questionId]: setPendingUserInputCustomAnswer(
1654 + existing[activePendingRequestKey]?.[questionId],
1655 + value,
1656 + question,
1657 + ),
1658 + },
1659 + }));
1660 + // The editor owns this selection. Resetting it before the answer renders
1661 + // can re-enter Lexical with offsets from the previous skill token.
1662 + };
1663 +}
1664 +
1665 +/** Draft id for editing a queued run of `threadRef`. */
1666 +function makeQueuedEditDraftTarget(threadRef: ScopedThreadRef) {
1667 + return (runId: RunId) => DraftId.make(`queued-edit:${scopedThreadKey(threadRef)}:${runId}`);
1668 +}
1669 +
1670 +/** Why the model picker should disable a model, or null when it can be chosen. */
1671 +function makeModelDisabledReason(
1672 + context: Omit<
1673 + Parameters<typeof getStartedThreadModelChangeBlockReason>[0],
1674 + "nextModelSelection"
1675 + > | null,
1676 +) {
1677 + return (instanceId: ProviderInstanceId, model: string): string | null => {
1678 + if (!context) return null;
1679 + const reason = getStartedThreadModelChangeBlockReason({
1680 + ...context,
1681 + nextModelSelection: { instanceId, model },
1682 + });
1683 + return reason ? `${reason.description} Start a new thread to use this model.` : null;
1684 + };
1685 +}
1686 +
1687 export default function ChatView(props: ChatViewProps) {
1688 const {
1689 environmentId,
@@ -1589,10 +1695,8 @@ export default function ChatView(props: ChatViewProps) {
1695 } = props;
1696 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
1697 const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
1592 - const hasTerminalWriteAccess = useCallback(
1593 - () => readEnvironmentScope(environmentId, AuthTerminalOperateScope),
1594 - [environmentId],
1595 - );
1698 + const hasTerminalWriteAccess = () =>
1699 + readEnvironmentScope(environmentId, AuthTerminalOperateScope);
1700 const canReadTerminal = useEnvironmentScope(environmentId, AuthTerminalReadScope);
1701 const draftId = routeKind === "draft" ? props.draftId : null;
1702 const handleNewThread = useNewThreadHandler();
@@ -1693,8 +1797,8 @@ export default function ChatView(props: ChatViewProps) {
1797 readonly existingAttachments: ReadonlyArray<ContractChatAttachment>;
1798 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
1799 } | null>(null);
1696 - const queuedEditDraftTargetFor = useCallback(
1697 - (runId: RunId) => DraftId.make(`queued-edit:${scopedThreadKey(routeThreadRef)}:${runId}`),
1800 + const queuedEditDraftTargetFor = useMemo(
1801 + () => makeQueuedEditDraftTarget(routeThreadRef),
1802 [routeThreadRef],
1803 );
1804 const baseComposerDraftTarget: ScopedThreadRef | DraftId =
@@ -1858,21 +1962,21 @@ export default function ChatView(props: ChatViewProps) {
1962 const [restingComposerControlsHost, setRestingComposerControlsHost] =
1963 useState<HTMLDivElement | null>(null);
1964 const [restingComposerControlsVisible, setRestingComposerControlsVisible] = useState(false);
1861 - const citeAssistantText = useCallback(
1862 - (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => {
1863 - const inserted = composerRef.current?.citeAssistantText(citation, sourceAnchor) ?? false;
1864 - if (!inserted) {
1865 - toastManager.add({
1866 - type: "warning",
1867 - title: "The composer is not ready",
1868 - description:
1869 - "Try citing the selection after the connection or pending input is resolved.",
1870 - });
1871 - }
1872 - return inserted;
1873 - },
1874 - [composerRef],
1875 - );
1965 + const citeAssistantText = (
1966 + citation: AssistantCitation,
1967 + sourceAnchor: AssistantCitationSourceAnchor,
1968 + ) => {
1969 + const inserted = composerRef.current?.citeAssistantText(citation, sourceAnchor) ?? false;
1970 + if (!inserted) {
1971 + toastManager.add({
1972 + type: "warning",
1973 + title: "The composer is not ready",
1974 + description: "Try citing the selection after the connection or pending input is resolved.",
1975 + });
1976 + }
1977 + return inserted;
1978 + };
1979 + const citeAssistantTextStable = useStableCallback(citeAssistantText);
1980 const [showScrollToBottom, setShowScrollToBottom] = useState(false);
1981 const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false);
1982 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
@@ -1973,10 +2077,8 @@ export default function ChatView(props: ChatViewProps) {
2077 LastInvokedScriptByProjectSchema,
2078 );
2079 const legendListRef = useRef<LegendListRef | null>(null);
1976 - const getTimelineScrollableNode = useCallback(
1977 - () => legendListRef.current?.getScrollableNode() ?? null,
1978 - [],
1979 - );
2080 + const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null;
2081 + const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode);
2082 const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);
2083 // Space the timeline keeps clear above its end. Tracks the overlay while the
2084 // composer is expanded and holds that height while it rests, so the resting
@@ -1988,10 +2090,9 @@ export default function ChatView(props: ChatViewProps) {
2090 const composerMountedRef = useRef(true);
2091 const [scrollToEndClearance, setScrollToEndClearance] = useState(0);
2092 const isAtEndRef = useRef(true);
1991 - const isTimelineAtLogicalEnd = useCallback(
1992 - () => resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current,
1993 - [],
1994 - );
2093 + const isTimelineAtLogicalEnd = () =>
2094 + resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;
2095 + const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);
2096 // Whether the timeline's rows extend past the viewport above the composer.
2097 // The composer only rests when there is reading space to give back.
2098 const [timelineOverflows, setTimelineOverflows] = useState(false);
@@ -2006,15 +2107,15 @@ export default function ChatView(props: ChatViewProps) {
2107 const isResuming = resumingThreadKeys.has(routeThreadKey);
2108 const composerSendGenerationRef = useRef(0);
2109 const multipleModelSelections = fanoutState.selections;
2009 - const setMultipleModelSelections = useCallback(
2010 - (selections: SetStateAction<ReadonlyArray<ModelSelection> | null>) => {
2011 - appAtomRegistry.update(fanoutStateAtom, (current) => ({
2012 - ...current,
2013 - selections: typeof selections === "function" ? selections(current.selections) : selections,
2014 - }));
2015 - },
2016 - [fanoutStateAtom],
2017 - );
2110 + const setMultipleModelSelections = (
2111 + selections: SetStateAction<ReadonlyArray<ModelSelection> | null>,
2112 + ) => {
2113 + appAtomRegistry.update(fanoutStateAtom, (current) => ({
2114 + ...current,
2115 + selections: typeof selections === "function" ? selections(current.selections) : selections,
2116 + }));
2117 + };
2118 + const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);
2119 const multipleModelSelectionsRef = useRef(multipleModelSelections);
2120 multipleModelSelectionsRef.current = multipleModelSelections;
2121 const uncertainMultipleSubmissionsRef = fanoutState.uncertainSubmissions;
@@ -2353,16 +2454,13 @@ export default function ChatView(props: ChatViewProps) {
2454 [activeKnownTerminalIds, panelTerminalIds],
2455 );
2456 const canReuseTerminal = activeThreadKnownSessionsRaw !== null;
2356 - const allocateTerminalId = useCallback(
2357 - () =>
2358 - nextTerminalId(
2359 - allocatableActiveTerminalIds,
2360 - canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope)
2361 - ? undefined
2362 - : randomUUID(),
2363 - ),
2364 - [allocatableActiveTerminalIds, canReuseTerminal, environmentId],
2365 - );
2457 + const allocateTerminalId = () =>
2458 + nextTerminalId(
2459 + allocatableActiveTerminalIds,
2460 + canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope)
2461 + ? undefined
2462 + : randomUUID(),
2463 + );
2464 const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable;
2465 const rightPanelOpen = rightPanelState.isOpen;
2466 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
@@ -2513,25 +2611,23 @@ export default function ChatView(props: ChatViewProps) {
2611 const removeClonedProject = useRemoveClonedProject();
2612 // The banner mirrors the server's clone state, so a request that never got
2613 // there needs its own feedback.
2516 - const runProjectCloneAction = useCallback(
2517 - async (
2518 - title: string,
2519 - action: () => Promise<AtomCommandResult<unknown, unknown>>,
2520 - ): Promise<void> => {
2521 - const result = await action();
2522 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2523 - const error = squashAtomCommandFailure(result);
2524 - toastManager.add(
2525 - stackedThreadToast({
2526 - type: "error",
2527 - title,
2528 - description: error instanceof Error ? error.message : "An error occurred.",
2529 - }),
2530 - );
2531 - }
2532 - },
2533 - [],
2534 - );
2614 + const runProjectCloneAction = async (
2615 + title: string,
2616 + action: () => Promise<AtomCommandResult<unknown, unknown>>,
2617 + ): Promise<void> => {
2618 + const result = await action();
2619 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2620 + const error = squashAtomCommandFailure(result);
2621 + toastManager.add(
2622 + stackedThreadToast({
2623 + type: "error",
2624 + title,
2625 + description: error instanceof Error ? error.message : "An error occurred.",
2626 + }),
2627 + );
2628 + }
2629 + };
2630 + const runProjectCloneActionStable = useStableCallback(runProjectCloneAction);
2631 const projectCloneSendBlockReason =
2632 activeProjectClone === null
2633 ? null
@@ -2559,7 +2655,7 @@ export default function ChatView(props: ChatViewProps) {
2655 size="xs"
2656 variant="ghost"
2657 onClick={() =>
2562 - void runProjectCloneAction("Failed to cancel clone", () =>
2658 + void runProjectCloneActionStable("Failed to cancel clone", () =>
2659 cancelProjectClone({ environmentId, input: { projectId } }),
2660 )
2661 }
@@ -2589,7 +2685,7 @@ export default function ChatView(props: ChatViewProps) {
2685 size="xs"
2686 variant="ghost"
2687 onClick={() =>
2592 - void runProjectCloneAction("Failed to retry clone", () =>
2688 + void runProjectCloneActionStable("Failed to retry clone", () =>
2689 retryProjectClone({ environmentId, input: { projectId } }),
2690 )
2691 }
@@ -2605,24 +2701,26 @@ export default function ChatView(props: ChatViewProps) {
2701 cancelProjectClone,
2702 removeClonedProject,
2703 retryProjectClone,
2608 - runProjectCloneAction,
2704 + runProjectCloneActionStable,
2705 ]);
2706 const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection;
2611 - const handleNewThreadInActiveProject = useCallback(() => {
2707 + const handleNewThreadInActiveProject = () => {
2708 startNewThreadForProject(activeProjectRef, handleNewThread);
2613 - }, [activeProjectRef, handleNewThread]);
2709 + };
2710 + const handleNewThreadInActiveProjectStable = useStableCallback(handleNewThreadInActiveProject);
2711 const projectGroupingSettings = selectProjectGroupingSettings(settings);
2712 const activeDraftLogicalProjectKey =
2713 !isServerThread && activeProject
2714 ? deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings)
2715 : undefined;
2619 - const handleOpenDraftProjectSettings = useCallback(() => {
2716 + const handleOpenDraftProjectSettings = () => {
2717 if (!activeDraftLogicalProjectKey) return;
2718 void navigate({
2719 to: "/projects/$projectKey",
2720 params: { projectKey: activeDraftLogicalProjectKey },
2721 });
2625 - }, [activeDraftLogicalProjectKey, navigate]);
2722 + };
2723 + const handleOpenDraftProjectSettingsStable = useStableCallback(handleOpenDraftProjectSettings);
2724 const activeEnvironmentShell = useEnvironmentQuery(
2725 activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null,
2726 );
@@ -2636,24 +2734,22 @@ export default function ChatView(props: ChatViewProps) {
2734 const pendingFileSurfaceIds = activeProjectKey
2735 ? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS)
2736 : EMPTY_PENDING_FILE_SURFACE_IDS;
2639 - const handleFilePendingChange = useCallback(
2640 - (relativePath: string, pending: boolean) => {
2641 - if (!activeProjectKey) return;
2642 - setPendingFileSurfaceIdsByProject((currentByProject) => {
2643 - const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS;
2644 - const surfaceId = `file:${relativePath}`;
2645 - if (current.has(surfaceId) === pending) return currentByProject;
2646 - const next = new Set(current);
2647 - if (pending) next.add(surfaceId);
2648 - else next.delete(surfaceId);
2649 - const nextByProject = new Map(currentByProject);
2650 - if (next.size === 0) nextByProject.delete(activeProjectKey);
2651 - else nextByProject.set(activeProjectKey, next);
2652 - return nextByProject;
2653 - });
2654 - },
2655 - [activeProjectKey],
2656 - );
2737 + const handleFilePendingChange = (relativePath: string, pending: boolean) => {
2738 + if (!activeProjectKey) return;
2739 + setPendingFileSurfaceIdsByProject((currentByProject) => {
2740 + const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS;
2741 + const surfaceId = `file:${relativePath}`;
2742 + if (current.has(surfaceId) === pending) return currentByProject;
2743 + const next = new Set(current);
2744 + if (pending) next.add(surfaceId);
2745 + else next.delete(surfaceId);
2746 + const nextByProject = new Map(currentByProject);
2747 + if (next.size === 0) nextByProject.delete(activeProjectKey);
2748 + else nextByProject.set(activeProjectKey, next);
2749 + return nextByProject;
2750 + });
2751 + };
2752 + const handleFilePendingChangeStable = useStableCallback(handleFilePendingChange);
2753 const configuredPreviewUrls = useMemo(
2754 () => getConfiguredPreviewUrls(activeProjectScripts),
2755 [activeProjectScripts],
@@ -2707,21 +2803,21 @@ export default function ChatView(props: ChatViewProps) {
2803 connection: activeEnvironment.connection,
2804 };
2805 }, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]);
2710 - const handleReconnectActiveEnvironment = useCallback(
2711 - async (environmentId: EnvironmentId) => {
2712 - const result = await retryEnvironment(environmentId);
2713 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2714 - const error = squashAtomCommandFailure(result);
2715 - toastManager.add(
2716 - stackedThreadToast({
2717 - type: "error",
2718 - title: "Could not reconnect environment",
2719 - description: error instanceof Error ? error.message : "Failed to reconnect.",
2720 - }),
2721 - );
2722 - }
2723 - },
2724 - [retryEnvironment],
2806 + const handleReconnectActiveEnvironment = async (environmentId: EnvironmentId) => {
2807 + const result = await retryEnvironment(environmentId);
2808 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2809 + const error = squashAtomCommandFailure(result);
2810 + toastManager.add(
2811 + stackedThreadToast({
2812 + type: "error",
2813 + title: "Could not reconnect environment",
2814 + description: error instanceof Error ? error.message : "Failed to reconnect.",
2815 + }),
2816 + );
2817 + }
2818 + };
2819 + const handleReconnectActiveEnvironmentStable = useStableCallback(
2820 + handleReconnectActiveEnvironment,
2821 );
2822 const disconnectDelayElapsed = useEnvironmentDisconnectDelay(
2823 activeEnvironmentUnavailable ? activeEnvironment.environmentId : null,
@@ -2732,27 +2828,27 @@ export default function ChatView(props: ChatViewProps) {
2828 activeEnvironment.entry.target._tag !== "PrimaryConnectionTarget" &&
2829 !isDesktopLocalConnectionTarget(activeEnvironment.entry.target);
2830 const [disconnectingEnvironment, setDisconnectingEnvironment] = useState(false);
2735 - const handleDisconnectActiveEnvironment = useCallback(
2736 - async (environmentId: EnvironmentId) => {
2737 - setDisconnectingEnvironment(true);
2738 - const result = await setEnvironmentEnabled({ environmentId, enabled: false });
2739 - setDisconnectingEnvironment(false);
2740 - if (result._tag === "Failure") {
2741 - if (!isAtomCommandInterrupted(result)) {
2742 - const error = squashAtomCommandFailure(result);
2743 - toastManager.add(
2744 - stackedThreadToast({
2745 - type: "error",
2746 - title: "Could not disconnect server",
2747 - description: error instanceof Error ? error.message : "Failed to disconnect.",
2748 - }),
2749 - );
2750 - }
2751 - return;
2831 + const handleDisconnectActiveEnvironment = async (environmentId: EnvironmentId) => {
2832 + setDisconnectingEnvironment(true);
2833 + const result = await setEnvironmentEnabled({ environmentId, enabled: false });
2834 + setDisconnectingEnvironment(false);
2835 + if (result._tag === "Failure") {
2836 + if (!isAtomCommandInterrupted(result)) {
2837 + const error = squashAtomCommandFailure(result);
2838 + toastManager.add(
2839 + stackedThreadToast({
2840 + type: "error",
2841 + title: "Could not disconnect server",
2842 + description: error instanceof Error ? error.message : "Failed to disconnect.",
2843 + }),
2844 + );
2845 }
2753 - void navigate({ to: "/", replace: true });
2754 - },
2755 - [navigate, setEnvironmentEnabled],
2846 + return;
2847 + }
2848 + void navigate({ to: "/", replace: true });
2849 + };
2850 + const handleDisconnectActiveEnvironmentStable = useStableCallback(
2851 + handleDisconnectActiveEnvironment,
2852 );
2853 const { scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
2854 const activeProjectIsScratch =
@@ -2834,112 +2930,96 @@ export default function ChatView(props: ChatViewProps) {
2930 activeEnvironment: activeEnvironmentOption,
2931 canPickEnvironment: hasMultipleEnvironments,
2932 });
2837 - const openPullRequestDialog = useCallback(
2838 - (reference?: string) => {
2839 - if (!canCheckoutPullRequestIntoThread) {
2840 - return;
2841 - }
2842 - setPullRequestDialogState({
2843 - initialReference: reference ?? null,
2844 - key: Date.now(),
2845 - });
2846 - },
2847 - [canCheckoutPullRequestIntoThread],
2848 - );
2933 + const openPullRequestDialog = (reference?: string) => {
2934 + if (!canCheckoutPullRequestIntoThread) {
2935 + return;
2936 + }
2937 + setPullRequestDialogState({
2938 + initialReference: reference ?? null,
2939 + key: Date.now(),
2940 + });
2941 + };
2942 + const openPullRequestDialogStable = useStableCallback(openPullRequestDialog);
2943
2850 - const closePullRequestDialog = useCallback(() => {
2944 + const closePullRequestDialog = () => {
2945 setPullRequestDialogState(null);
2852 - }, []);
2853 -
2854 - const openOrReuseProjectDraftThread = useCallback(
2855 - async (input: { branch: string; worktreePath: string | null; envMode: DraftThreadEnvMode }) => {
2856 - if (!activeProject) {
2857 - throw new Error("No active project is available for this pull request.");
2858 - }
2859 - const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id);
2860 - const logicalProjectKey = deriveLogicalProjectKeyFromSettings(
2861 - activeProject,
2862 - projectGroupingSettings,
2863 - );
2864 - const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);
2865 - if (storedDraftSession) {
2866 - setDraftThreadContext(storedDraftSession.draftId, input);
2867 - setLogicalProjectDraftThreadId(
2868 - logicalProjectKey,
2869 - activeProjectRef,
2870 - storedDraftSession.draftId,
2871 - {
2872 - threadId: storedDraftSession.threadId,
2873 - ...input,
2874 - },
2875 - );
2876 - if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) {
2877 - await navigate({
2878 - to: "/draft/$draftId",
2879 - params: buildDraftThreadRouteParams(storedDraftSession.draftId),
2880 - });
2881 - }
2882 - return storedDraftSession.threadId;
2883 - }
2946 + };
2947
2885 - const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null;
2886 - if (
2887 - !isServerThread &&
2888 - activeDraftSession?.logicalProjectKey === logicalProjectKey &&
2889 - draftId
2890 - ) {
2891 - setDraftThreadContext(draftId, input);
2892 - setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, {
2893 - threadId: activeDraftSession.threadId,
2894 - createdAt: activeDraftSession.createdAt,
2895 - runtimeMode: activeDraftSession.runtimeMode,
2896 - interactionMode: activeDraftSession.interactionMode,
2948 + const openOrReuseProjectDraftThread = async (input: {
2949 + branch: string;
2950 + worktreePath: string | null;
2951 + envMode: DraftThreadEnvMode;
2952 + }) => {
2953 + if (!activeProject) {
2954 + throw new Error("No active project is available for this pull request.");
2955 + }
2956 + const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id);
2957 + const logicalProjectKey = deriveLogicalProjectKeyFromSettings(
2958 + activeProject,
2959 + projectGroupingSettings,
2960 + );
2961 + const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);
2962 + if (storedDraftSession) {
2963 + setDraftThreadContext(storedDraftSession.draftId, input);
2964 + setLogicalProjectDraftThreadId(
2965 + logicalProjectKey,
2966 + activeProjectRef,
2967 + storedDraftSession.draftId,
2968 + {
2969 + threadId: storedDraftSession.threadId,
2970 ...input,
2971 + },
2972 + );
2973 + if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) {
2974 + await navigate({
2975 + to: "/draft/$draftId",
2976 + params: buildDraftThreadRouteParams(storedDraftSession.draftId),
2977 });
2899 - return activeDraftSession.threadId;
2978 }
2979 + return storedDraftSession.threadId;
2980 + }
2981
2902 - const nextDraftId = newDraftId();
2903 - const nextThreadId = newThreadId();
2904 - setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, {
2905 - threadId: nextThreadId,
2906 - createdAt: new Date().toISOString(),
2907 - runtimeMode: resolveProjectSettings(settings, activeProject.id, activeProject).settings
2908 - .defaultRuntimeMode,
2909 - interactionMode: DEFAULT_INTERACTION_MODE,
2982 + const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null;
2983 + if (!isServerThread && activeDraftSession?.logicalProjectKey === logicalProjectKey && draftId) {
2984 + setDraftThreadContext(draftId, input);
2985 + setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, {
2986 + threadId: activeDraftSession.threadId,
2987 + createdAt: activeDraftSession.createdAt,
2988 + runtimeMode: activeDraftSession.runtimeMode,
2989 + interactionMode: activeDraftSession.interactionMode,
2990 ...input,
2991 });
2912 - await navigate({
2913 - to: "/draft/$draftId",
2914 - params: buildDraftThreadRouteParams(nextDraftId),
2915 - });
2916 - return nextThreadId;
2917 - },
2918 - [
2919 - activeProject,
2920 - draftId,
2921 - getDraftSession,
2922 - getDraftSessionByLogicalProjectKey,
2923 - isServerThread,
2924 - navigate,
2925 - projectGroupingSettings,
2926 - routeKind,
2927 - settings,
2928 - setDraftThreadContext,
2929 - setLogicalProjectDraftThreadId,
2930 - ],
2931 - );
2992 + return activeDraftSession.threadId;
2993 + }
2994
2933 - const handlePreparedPullRequestThread = useCallback(
2934 - async (input: { branch: string; worktreePath: string | null }) => {
2935 - await openOrReuseProjectDraftThread({
2936 - branch: input.branch,
2937 - worktreePath: input.worktreePath,
2938 - envMode: input.worktreePath ? "worktree" : "local",
2939 - });
2940 - },
2941 - [openOrReuseProjectDraftThread],
2942 - );
2995 + const nextDraftId = newDraftId();
2996 + const nextThreadId = newThreadId();
2997 + setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, {
2998 + threadId: nextThreadId,
2999 + createdAt: new Date().toISOString(),
3000 + runtimeMode: resolveProjectSettings(settings, activeProject.id, activeProject).settings
3001 + .defaultRuntimeMode,
3002 + interactionMode: DEFAULT_INTERACTION_MODE,
3003 + ...input,
3004 + });
3005 + await navigate({
3006 + to: "/draft/$draftId",
3007 + params: buildDraftThreadRouteParams(nextDraftId),
3008 + });
3009 + return nextThreadId;
3010 + };
3011 +
3012 + const handlePreparedPullRequestThread = async (input: {
3013 + branch: string;
3014 + worktreePath: string | null;
3015 + }) => {
3016 + await openOrReuseProjectDraftThread({
3017 + branch: input.branch,
3018 + worktreePath: input.worktreePath,
3019 + envMode: input.worktreePath ? "worktree" : "local",
3020 + });
3021 + };
3022 + const handlePreparedPullRequestThreadStable = useStableCallback(handlePreparedPullRequestThread);
3023
3024 useEffect(() => {
3025 if (!serverThread?.id) return;
@@ -3106,7 +3186,9 @@ export default function ChatView(props: ChatViewProps) {
3186 disabled={disconnectingEnvironment}
3187 title="Hide this server's threads. Switch it on again in Connections."
3188 onClick={() =>
3109 - void handleDisconnectActiveEnvironment(activeEnvironmentUnavailableState.environmentId)
3189 + void handleDisconnectActiveEnvironmentStable(
3190 + activeEnvironmentUnavailableState.environmentId,
3191 + )
3192 }
3193 >
3194 Disconnect server
@@ -3134,7 +3216,7 @@ export default function ChatView(props: ChatViewProps) {
3216 size="xs"
3217 variant="ghost"
3218 onClick={() =>
3137 - void handleReconnectActiveEnvironment(
3219 + void handleReconnectActiveEnvironmentStable(
3220 activeEnvironmentUnavailableState.environmentId,
3221 )
3222 }
@@ -3233,10 +3315,10 @@ export default function ChatView(props: ChatViewProps) {
3315 automaticEnvironment,
3316 autoBalanceUpdateBanner,
3317 activeEnvironmentUnavailableState,
3236 - handleReconnectActiveEnvironment,
3318 + handleReconnectActiveEnvironmentStable,
3319 canDisconnectActiveEnvironment,
3320 disconnectingEnvironment,
3239 - handleDisconnectActiveEnvironment,
3321 + handleDisconnectActiveEnvironmentStable,
3322 setDismissedVersionMismatchKey,
3323 showVersionMismatchBanner,
3324 reconnectWarningGraceElapsed,
@@ -3554,7 +3636,7 @@ export default function ChatView(props: ChatViewProps) {
3636 activeProviderStatus !== null &&
3637 hasProviderUsageLimits(activeProviderStatus.driver, providerStatuses, usageLimitSources);
3638 // Answered locally from the last Limits snapshot; the agent never sees it.
3557 - const openUsageLimits = useCallback(() => {
3639 + const openUsageLimits = () => {
3640 const now = Date.now();
3641 const report =
3642 activeProviderInstanceId !== null && usageLimitsKey !== null
@@ -3572,21 +3654,13 @@ export default function ChatView(props: ChatViewProps) {
3654 setUsageLimitsPanel(null);
3655 toastManager.add({ type: "info", title: "Usage limits are unavailable for this provider" });
3656 return false;
3575 - }, [
3576 - activeProviderInstanceId,
3577 - providerStatuses,
3578 - routeThreadKey,
3579 - usageLimitSources,
3580 - usageLimitsKey,
3581 - ]);
3657 + };
3658 + const openUsageLimitsStable = useStableCallback(openUsageLimits);
3659 // Responses can resolve after navigating away; only the originating thread's panel clears.
3583 - const clearUsageLimitsFor = useCallback(
3584 - (threadKey: string) =>
3585 - setUsageLimitsPanel((current) =>
3586 - current !== null && current.threadKey === threadKey ? null : current,
3587 - ),
3588 - [],
3589 - );
3660 + const clearUsageLimitsFor = (threadKey: string) =>
3661 + setUsageLimitsPanel((current) =>
3662 + current !== null && current.threadKey === threadKey ? null : current,
3663 + );
3664 const {
3665 beginLocalDispatch,
3666 resetLocalDispatch,
@@ -3688,27 +3762,28 @@ export default function ChatView(props: ChatViewProps) {
3762 useEffect(() => {
3763 attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
3764 }, [attachmentPreviewHandoffByMessageId]);
3691 - const clearAttachmentPreviewHandoff = useCallback(
3692 - (messageId: MessageId, previewUrls?: ReadonlyArray<string>) => {
3693 - delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
3694 - const currentPreviewUrls =
3695 - previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
3696 - setAttachmentPreviewHandoffByMessageId((existing) => {
3697 - if (!(messageId in existing)) {
3698 - return existing;
3699 - }
3700 - const next = { ...existing };
3701 - delete next[messageId];
3702 - attachmentPreviewHandoffByMessageIdRef.current = next;
3703 - return next;
3704 - });
3705 - for (const previewUrl of currentPreviewUrls) {
3706 - revokeBlobPreviewUrl(previewUrl);
3765 + const clearAttachmentPreviewHandoff = (
3766 + messageId: MessageId,
3767 + previewUrls?: ReadonlyArray<string>,
3768 + ) => {
3769 + delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
3770 + const currentPreviewUrls =
3771 + previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
3772 + setAttachmentPreviewHandoffByMessageId((existing) => {
3773 + if (!(messageId in existing)) {
3774 + return existing;
3775 }
3708 - },
3709 - [],
3710 - );
3711 - const clearAttachmentPreviewHandoffs = useCallback(() => {
3776 + const next = { ...existing };
3777 + delete next[messageId];
3778 + attachmentPreviewHandoffByMessageIdRef.current = next;
3779 + return next;
3780 + });
3781 + for (const previewUrl of currentPreviewUrls) {
3782 + revokeBlobPreviewUrl(previewUrl);
3783 + }
3784 + };
3785 + const clearAttachmentPreviewHandoffStable = useStableCallback(clearAttachmentPreviewHandoff);
3786 + const clearAttachmentPreviewHandoffs = () => {
3787 attachmentPreviewPromotionInFlightByMessageIdRef.current = {};
3788 for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {
3789 for (const previewUrl of previewUrls) {
@@ -3717,16 +3792,17 @@ export default function ChatView(props: ChatViewProps) {
3792 }
3793 attachmentPreviewHandoffByMessageIdRef.current = {};
3794 setAttachmentPreviewHandoffByMessageId({});
3720 - }, []);
3795 + };
3796 + const clearAttachmentPreviewHandoffsStable = useStableCallback(clearAttachmentPreviewHandoffs);
3797 useEffect(() => {
3798 return () => {
3723 - clearAttachmentPreviewHandoffs();
3799 + clearAttachmentPreviewHandoffsStable();
3800 for (const message of optimisticUserMessagesRef.current) {
3801 revokeUserMessagePreviewUrls(message);
3802 }
3803 };
3728 - }, [clearAttachmentPreviewHandoffs]);
3729 - const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {
3804 + }, [clearAttachmentPreviewHandoffsStable]);
3805 + const handoffAttachmentPreviews = (messageId: MessageId, previewUrls: string[]) => {
3806 if (previewUrls.length === 0) return;
3807
3808 const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
@@ -3744,45 +3820,42 @@ export default function ChatView(props: ChatViewProps) {
3820 attachmentPreviewHandoffByMessageIdRef.current = next;
3821 return next;
3822 });
3747 - }, []);
3748 - const downloadFileAttachment = useCallback(
3749 - async (attachment: ChatFileAttachment) => {
3750 - const connection = readPreparedConnection(environmentId);
3751 - if (!connection) {
3752 - toastManager.add({ type: "error", title: "The environment is not connected." });
3753 - return;
3754 - }
3823 + };
3824 + const handoffAttachmentPreviewsStable = useStableCallback(handoffAttachmentPreviews);
3825 + const downloadFileAttachment = async (attachment: ChatFileAttachment) => {
3826 + const connection = readPreparedConnection(environmentId);
3827 + if (!connection) {
3828 + toastManager.add({ type: "error", title: "The environment is not connected." });
3829 + return;
3830 + }
3831
3756 - try {
3757 - const url = await resolveFileAttachmentUrl({
3758 - attachment,
3759 - environmentId,
3760 - httpBaseUrl: connection.httpBaseUrl,
3761 - createAssetUrl: createAttachmentAssetUrl,
3762 - });
3763 - const anchor = document.createElement("a");
3764 - anchor.href = url;
3765 - anchor.download = attachment.name;
3766 - anchor.click();
3767 - } catch (error) {
3768 - toastManager.add({
3769 - type: "error",
3770 - title: "Could not download " + attachment.name,
3771 - description: error instanceof Error ? error.message : "The attachment is unavailable.",
3772 - });
3773 - }
3774 - },
3775 - [createAttachmentAssetUrl, environmentId],
3776 - );
3777 - const openFileAttachment = useCallback(
3778 - (attachment: ChatFileAttachment) => {
3779 - if (activeThreadRef) {
3780 - useRightPanelStore.getState().openAttachment(activeThreadRef, attachment);
3781 - return;
3782 - }
3783 - },
3784 - [activeThreadRef],
3785 - );
3832 + try {
3833 + const url = await resolveFileAttachmentUrl({
3834 + attachment,
3835 + environmentId,
3836 + httpBaseUrl: connection.httpBaseUrl,
3837 + createAssetUrl: createAttachmentAssetUrl,
3838 + });
3839 + const anchor = document.createElement("a");
3840 + anchor.href = url;
3841 + anchor.download = attachment.name;
3842 + anchor.click();
3843 + } catch (error) {
3844 + toastManager.add({
3845 + type: "error",
3846 + title: "Could not download " + attachment.name,
3847 + description: error instanceof Error ? error.message : "The attachment is unavailable.",
3848 + });
3849 + }
3850 + };
3851 + const downloadFileAttachmentStable = useStableCallback(downloadFileAttachment);
3852 + const openFileAttachment = (attachment: ChatFileAttachment) => {
3853 + if (activeThreadRef) {
3854 + useRightPanelStore.getState().openAttachment(activeThreadRef, attachment);
3855 + return;
3856 + }
3857 + };
3858 + const openFileAttachmentStable = useStableCallback(openFileAttachment);
3859 const serverAttachmentResources = useMemo(
3860 () =>
3861 selectHandoffImageResources(
@@ -3873,7 +3946,7 @@ export default function ChatView(props: ChatViewProps) {
3946 if (cancelled) {
3947 return;
3948 }
3876 - clearAttachmentPreviewHandoff(messageId as MessageId, handoffPreviewUrls);
3949 + clearAttachmentPreviewHandoffStable(messageId as MessageId, handoffPreviewUrls);
3950 })
3951 .catch(() => {
3952 if (!cancelled) {
@@ -3897,7 +3970,7 @@ export default function ChatView(props: ChatViewProps) {
3970 };
3971 }, [
3972 attachmentPreviewHandoffByMessageId,
3900 - clearAttachmentPreviewHandoff,
3973 + clearAttachmentPreviewHandoffStable,
3974 serverAttachmentUrlById,
3975 serverVisibleTurnItems,
3976 ]);
@@ -4064,25 +4137,24 @@ export default function ChatView(props: ChatViewProps) {
4137 () => new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
4138 [retryableRunIdsKey],
4139 );
4067 - const onRetryWorkspacePreparation = useCallback(
4068 - (runId: RunId) => {
4069 - // One retry per failed run: a second click lands after the run is preparing again.
4070 - if (!activeThreadRef || retryingWorkspacePreparationRunIds.has(runId)) return;
4071 - retryingWorkspacePreparationRunIds.add(runId);
4072 - void retryWorkspacePreparation({
4073 - environmentId: activeThreadRef.environmentId,
4074 - input: { threadId: activeThreadRef.threadId, runId },
4075 - }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));
4076 - },
4077 - [activeThreadRef, retryWorkspacePreparation],
4078 - );
4079 - const onCancelWorktreeSetup = useCallback(() => {
4140 + const onRetryWorkspacePreparation = (runId: RunId) => {
4141 + // One retry per failed run: a second click lands after the run is preparing again.
4142 + if (!activeThreadRef || retryingWorkspacePreparationRunIds.has(runId)) return;
4143 + retryingWorkspacePreparationRunIds.add(runId);
4144 + void retryWorkspacePreparation({
4145 + environmentId: activeThreadRef.environmentId,
4146 + input: { threadId: activeThreadRef.threadId, runId },
4147 + }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));
4148 + };
4149 + const onRetryWorkspacePreparationStable = useStableCallback(onRetryWorkspacePreparation);
4150 + const onCancelWorktreeSetup = () => {
4151 if (!worktreeSetup || worktreeSetup.phase !== "running") return;
4152 void cancelWorktreeSetup({
4153 environmentId: setupTarget.environmentId,
4154 input: { threadId: worktreeSetup.threadId },
4155 });
4085 - }, [cancelWorktreeSetup, setupTarget.environmentId, worktreeSetup]);
4156 + };
4157 + const onCancelWorktreeSetupStable = useStableCallback(onCancelWorktreeSetup);
4158 // The setup terminal belongs to the thread that was set up. A failed
4159 // bootstrap deletes that thread and closes its terminals, so only offer the
4160 // terminal while the setup thread is still the active one.
@@ -4349,7 +4421,7 @@ export default function ChatView(props: ChatViewProps) {
4421 () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions),
4422 [keybindings, terminalShortcutLabelOptions],
4423 );
4352 - const onToggleDiff = useCallback(() => {
4424 + const onToggleDiff = () => {
4425 if (!isServerThread) {
4426 return;
4427 }
@@ -4359,7 +4431,8 @@ export default function ChatView(props: ChatViewProps) {
4431 if (activeThreadRef) {
4432 useRightPanelStore.getState().toggle(activeThreadRef, "diff");
4433 }
4362 - }, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]);
4434 + };
4435 + const onToggleDiffStable = useStableCallback(onToggleDiff);
4436
4437 const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
4438 const loadBalancingCandidates = useMemo(
@@ -4425,7 +4498,7 @@ export default function ChatView(props: ChatViewProps) {
4498 logicalProjectEnvironments,
4499 setDraftThreadContext,
4500 ]);
4428 - const onAutoEnvironment = useCallback(() => {
4501 + const onAutoEnvironment = () => {
4502 if (envLocked || !draftId) return;
4503 if (composerHasAttachments) {
4504 toastManager.add({
@@ -4446,14 +4519,8 @@ export default function ChatView(props: ChatViewProps) {
4519 branch: null,
4520 worktreePath: null,
4521 });
4449 - }, [
4450 - envLocked,
4451 - draftId,
4452 - setDraftThreadContext,
4453 - loadBalancing.refresh,
4454 - logicalProjectEnvironments,
4455 - composerHasAttachments,
4456 - ]);
4522 + };
4523 + const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
4524 const autoEnvironmentLabel = automaticEnvironment
4525 ? draftThread?.loadBalancedEnvironmentId
4526 ? "Auto balance"
@@ -4474,83 +4541,69 @@ export default function ChatView(props: ChatViewProps) {
4541 };
4542 }, [draftId, activeProjectKey]);
4543
4477 - const onEnvironmentChange = useCallback(
4478 - (nextEnvironmentId: EnvironmentId) => {
4479 - if (envLocked || !draftId || sendInFlightRef.current) return;
4480 - const originalDraft = getDraftSession(draftId);
4481 - if (!originalDraft || originalDraft.promotedTo) return;
4482 - const target = logicalProjectEnvironments.find(
4483 - (env) => env.environmentId === nextEnvironmentId,
4484 - );
4485 - if (!target) return;
4486 - const request = { environmentId: target.environmentId };
4487 - environmentChangeRef.current = request;
4488 - setIsEnvironmentChanging(false);
4489 - const retarget = (project: (typeof allProjects)[number]) => {
4490 - const currentDraft = getDraftSession(draftId);
4491 - if (
4492 - environmentChangeRef.current !== request ||
4493 - sendInFlightRef.current ||
4494 - !currentDraft ||
4495 - currentDraft.promotedTo ||
4496 - currentDraft.environmentId !== originalDraft.environmentId ||
4497 - currentDraft.projectId !== originalDraft.projectId
4498 - )
4499 - return;
4500 - const projectRef = scopeProjectRef(target.environmentId, project.id);
4501 - if (activeProjectIsScratch) {
4502 - // Scratch projects are machine-local, so move their logical mapping too.
4503 - setLogicalProjectDraftThreadId(
4504 - deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
4505 - projectRef,
4506 - draftId,
4507 - { environmentSelection: "manual", loadBalancedEnvironmentId: null },
4508 - );
4509 - } else {
4510 - setDraftThreadContext(draftId, {
4511 - projectRef,
4512 - environmentSelection: "manual",
4513 - loadBalancedEnvironmentId: null,
4514 - });
4515 - }
4516 - };
4517 - const finish = () => {
4518 - if (environmentChangeRef.current === request) {
4519 - environmentChangeRef.current = null;
4520 - setIsEnvironmentChanging(false);
4521 - }
4522 - };
4523 - if (target.projectId !== null) {
4524 - const project = allProjects.find(
4525 - (project) =>
4526 - project.environmentId === target.environmentId && project.id === target.projectId,
4527 - );
4528 - if (project) retarget(project);
4529 - finish();
4544 + const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
4545 + if (envLocked || !draftId || sendInFlightRef.current) return;
4546 + const originalDraft = getDraftSession(draftId);
4547 + if (!originalDraft || originalDraft.promotedTo) return;
4548 + const target = logicalProjectEnvironments.find(
4549 + (env) => env.environmentId === nextEnvironmentId,
4550 + );
4551 + if (!target) return;
4552 + const request = { environmentId: target.environmentId };
4553 + environmentChangeRef.current = request;
4554 + setIsEnvironmentChanging(false);
4555 + const retarget = (project: (typeof allProjects)[number]) => {
4556 + const currentDraft = getDraftSession(draftId);
4557 + if (
4558 + environmentChangeRef.current !== request ||
4559 + sendInFlightRef.current ||
4560 + !currentDraft ||
4561 + currentDraft.promotedTo ||
4562 + currentDraft.environmentId !== originalDraft.environmentId ||
4563 + currentDraft.projectId !== originalDraft.projectId
4564 + )
4565 return;
4566 + const projectRef = scopeProjectRef(target.environmentId, project.id);
4567 + if (activeProjectIsScratch) {
4568 + // Scratch projects are machine-local, so move their logical mapping too.
4569 + setLogicalProjectDraftThreadId(
4570 + deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings),
4571 + projectRef,
4572 + draftId,
4573 + { environmentSelection: "manual", loadBalancedEnvironmentId: null },
4574 + );
4575 + } else {
4576 + setDraftThreadContext(draftId, {
4577 + projectRef,
4578 + environmentSelection: "manual",
4579 + loadBalancedEnvironmentId: null,
4580 + });
4581 }
4532 - // Keep send disabled until the destination Scratch project is ready.
4533 - setIsEnvironmentChanging(true);
4534 - void openScratchProject(target.environmentId, "Could not switch machine")
4535 - .then((project) => {
4536 - if (project) retarget(project);
4537 - })
4538 - .finally(finish);
4539 - },
4540 - [
4541 - activeProjectIsScratch,
4542 - allProjects,
4543 - draftId,
4544 - envLocked,
4545 - getDraftSession,
4546 - logicalProjectEnvironments,
4547 - openScratchProject,
4548 - projectGroupingSettings,
4549 - sendInFlightRef,
4550 - setDraftThreadContext,
4551 - setLogicalProjectDraftThreadId,
4552 - ],
4553 - );
4582 + };
4583 + const finish = () => {
4584 + if (environmentChangeRef.current === request) {
4585 + environmentChangeRef.current = null;
4586 + setIsEnvironmentChanging(false);
4587 + }
4588 + };
4589 + if (target.projectId !== null) {
4590 + const project = allProjects.find(
4591 + (project) =>
4592 + project.environmentId === target.environmentId && project.id === target.projectId,
4593 + );
4594 + if (project) retarget(project);
4595 + finish();
4596 + return;
4597 + }
4598 + // Keep send disabled until the destination Scratch project is ready.
4599 + setIsEnvironmentChanging(true);
4600 + void openScratchProject(target.environmentId, "Could not switch machine")
4601 + .then((project) => {
4602 + if (project) retarget(project);
4603 + })
4604 + .finally(finish);
4605 + };
4606 + const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange);
4607
4608 const activeTerminalGroup =
4609 terminalUiState.terminalGroups.find(
@@ -4562,48 +4615,28 @@ export default function ChatView(props: ChatViewProps) {
4615 null;
4616 const hasReachedSplitLimit =
4617 (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP;
4565 - const setThreadError = useCallback(
4566 - (targetThreadId: ThreadId | null, error: string | null) => {
4567 - if (!targetThreadId) return;
4568 - const nextError = sanitizeThreadErrorMessage(error);
4569 - const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
4570 - if (
4571 - serverThread &&
4572 - targetThreadId === routeThreadRef.threadId &&
4573 - serverThread.environmentId === routeThreadRef.environmentId &&
4574 - serverThread.id === targetThreadId
4575 - ) {
4576 - setLocalServerErrorsByThreadKey((existing) => {
4577 - if ((existing[routeThreadKey]?.message ?? null) === nextError) {
4578 - return existing;
4579 - }
4580 - return {
4581 - ...existing,
4582 - [routeThreadKey]: nextEntry,
4583 - };
4584 - });
4585 - return;
4586 - }
4587 - const localDraftErrorKey = draftId ?? targetThreadId;
4588 - setLocalDraftErrorsByDraftId((existing) => {
4589 - if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
4590 - return existing;
4591 - }
4592 - return {
4593 - ...existing,
4594 - [localDraftErrorKey]: nextEntry,
4595 - };
4596 - });
4597 - },
4598 - [draftId, routeThreadKey, routeThreadRef, serverThread],
4618 + const setThreadError = useMemo(
4619 + () =>
4620 + makeThreadErrorSetter({
4621 + routeThreadRef,
4622 + routeThreadKey,
4623 + draftId,
4624 + serverThreadRef: serverThread
4625 + ? { threadId: serverThread.id, environmentId: serverThread.environmentId }
4626 + : null,
4627 + setLocalServerErrorsByThreadKey,
4628 + setLocalDraftErrorsByDraftId,
4629 + }),
4630 + [draftId, routeThreadKey, routeThreadRef, serverThread?.id, serverThread?.environmentId],
4631 );
4632
4601 - const focusComposer = useCallback(() => {
4633 + const focusComposer = () => {
4634 composerRef.current?.focusAtEnd();
4603 - }, [composerRef]);
4635 + };
4636 + const focusComposerStable = useStableCallback(focusComposer);
4637 const canInterruptRunningThread =
4638 canOperateThread && deriveCanInterruptRunningThread(activeThread !== undefined, activeRuntime);
4606 - const onInterrupt = useCallback(async () => {
4639 + const onInterrupt = async () => {
4640 if (
4641 !activeThread ||
4642 !readEnvironmentScope(activeThread.environmentId, AuthOrchestrationOperateScope)
@@ -4620,56 +4653,54 @@ export default function ChatView(props: ChatViewProps) {
4653 error instanceof Error ? error.message : "Failed to interrupt the current turn.",
4654 );
4655 }
4623 - }, [activeThread, environmentId, interruptThreadTurn, setThreadError]);
4624 - useEffect(() => subscribeSnapShotComposerFocus(focusComposer), [focusComposer]);
4625 - const scheduleComposerFocus = useCallback(() => {
4656 + };
4657 + const onInterruptStable = useStableCallback(onInterrupt);
4658 + useEffect(() => subscribeSnapShotComposerFocus(focusComposerStable), [focusComposerStable]);
4659 + const scheduleComposerFocus = () => {
4660 window.requestAnimationFrame(() => {
4661 focusComposer();
4662 });
4629 - }, [focusComposer]);
4630 - const useArtifactTemplate = useCallback(
4631 - (template: CodexArtifactTemplate) => {
4632 - const composer = composerRef.current;
4633 - if (!composer) return;
4634 -
4635 - const currentDraft = composer.getSendContext().prompt;
4636 - const prompt = codexArtifactTemplatePromptToAppend(currentDraft, template);
4637 - if (prompt !== null && !composer.insertTextAtEnd(prompt, { ensureLeadingBoundary: true })) {
4638 - toastManager.add({
4639 - type: "error",
4640 - title: "Unable to add to chat",
4641 - description: "The composer is busy; try again once it is ready.",
4642 - });
4643 - return;
4644 - }
4645 - scheduleComposerFocus();
4646 - },
4647 - [composerRef, scheduleComposerFocus],
4648 - );
4663 + };
4664 + const scheduleComposerFocusStable = useStableCallback(scheduleComposerFocus);
4665 + const useArtifactTemplate = (template: CodexArtifactTemplate) => {
4666 + const composer = composerRef.current;
4667 + if (!composer) return;
4668 +
4669 + const currentDraft = composer.getSendContext().prompt;
4670 + const prompt = codexArtifactTemplatePromptToAppend(currentDraft, template);
4671 + if (prompt !== null && !composer.insertTextAtEnd(prompt, { ensureLeadingBoundary: true })) {
4672 + toastManager.add({
4673 + type: "error",
4674 + title: "Unable to add to chat",
4675 + description: "The composer is busy; try again once it is ready.",
4676 + });
4677 + return;
4678 + }
4679 + scheduleComposerFocus();
4680 + };
4681 + const useArtifactTemplateStable = useStableCallback(useArtifactTemplate);
4682 // An MCP App's approved `ui/message`: queued like a typed message, so it
4683 // never steers or interrupts a running turn.
4651 - const sendAppMessage = useCallback(
4652 - async (text: string) => {
4653 - if (!isServerThread || activeThreadId === null) {
4654 - throw new Error("Messages from apps need a started thread.");
4655 - }
4656 - const result = await startThreadTurn({
4657 - environmentId,
4658 - input: {
4659 - threadId: activeThreadId,
4660 - message: { messageId: newMessageId(), role: "user", text, attachments: [] },
4661 - runtimeMode,
4662 - interactionMode,
4663 - dispatchMode: "queue",
4664 - },
4665 - });
4666 - if (result._tag === "Failure") {
4667 - const error = squashAtomCommandFailure(result);
4668 - throw error instanceof Error ? error : new Error("Could not send the app's message.");
4669 - }
4670 - },
4671 - [activeThreadId, environmentId, interactionMode, isServerThread, runtimeMode, startThreadTurn],
4672 - );
4684 + const sendAppMessage = async (text: string) => {
4685 + if (!isServerThread || activeThreadId === null) {
4686 + throw new Error("Messages from apps need a started thread.");
4687 + }
4688 + const result = await startThreadTurn({
4689 + environmentId,
4690 + input: {
4691 + threadId: activeThreadId,
4692 + message: { messageId: newMessageId(), role: "user", text, attachments: [] },
4693 + runtimeMode,
4694 + interactionMode,
4695 + dispatchMode: "queue",
4696 + },
4697 + });
4698 + if (result._tag === "Failure") {
4699 + const error = squashAtomCommandFailure(result);
4700 + throw error instanceof Error ? error : new Error("Could not send the app's message.");
4701 + }
4702 + };
4703 + const sendAppMessageStable = useStableCallback(sendAppMessage);
4704 const editQueuedRunCommand = useAtomCommand(threadEnvironment.editQueuedRun, {
4705 reportFailure: false,
4706 });
@@ -4697,48 +4728,34 @@ export default function ChatView(props: ChatViewProps) {
4728 url: urlByAttachmentId.get(attachment.id) ?? null,
4729 }));
4730 }, [editingQueuedRun, queuedEditImageResources, queuedEditImageUrls]);
4700 - const beginEditingQueuedRun = useCallback(
4701 - (request: EditQueuedRunRequest) => {
4702 - if (!activeThread) return;
4703 - if (editingQueuedRun !== null && editingQueuedRun.runId !== request.runId) {
4704 - clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId));
4705 - }
4706 - const target = queuedEditDraftTargetFor(request.runId);
4707 - clearComposerDraftContent(target);
4708 - setComposerDraftPrompt(target, request.text);
4709 - setEditingQueuedRun({
4710 - threadId: activeThread.id,
4711 - runId: request.runId,
4712 - messageId: request.messageId,
4713 - originalText: request.text,
4714 - existingAttachments: request.attachments,
4715 - context: serverProjection?.messages.find((message) => message.id === request.messageId)
4716 - ?.context,
4717 - });
4718 - scheduleComposerFocus();
4719 - },
4720 - [
4721 - activeThread,
4722 - clearComposerDraftContent,
4723 - editingQueuedRun,
4724 - queuedEditDraftTargetFor,
4725 - serverProjection,
4726 - scheduleComposerFocus,
4727 - setComposerDraftPrompt,
4728 - ],
4729 - );
4730 - const cancelEditingQueuedRun = useCallback(() => {
4731 + const beginEditingQueuedRun = (request: EditQueuedRunRequest) => {
4732 + if (!activeThread) return;
4733 + if (editingQueuedRun !== null && editingQueuedRun.runId !== request.runId) {
4734 + clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId));
4735 + }
4736 + const target = queuedEditDraftTargetFor(request.runId);
4737 + clearComposerDraftContent(target);
4738 + setComposerDraftPrompt(target, request.text);
4739 + setEditingQueuedRun({
4740 + threadId: activeThread.id,
4741 + runId: request.runId,
4742 + messageId: request.messageId,
4743 + originalText: request.text,
4744 + existingAttachments: request.attachments,
4745 + context: serverProjection?.messages.find((message) => message.id === request.messageId)
4746 + ?.context,
4747 + });
4748 + scheduleComposerFocus();
4749 + };
4750 + const beginEditingQueuedRunStable = useStableCallback(beginEditingQueuedRun);
4751 + const cancelEditingQueuedRun = () => {
4752 if (editingQueuedRun === null) return;
4753 clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId));
4754 setEditingQueuedRun(null);
4755 scheduleComposerFocus();
4735 - }, [
4736 - clearComposerDraftContent,
4737 - editingQueuedRun,
4738 - queuedEditDraftTargetFor,
4739 - scheduleComposerFocus,
4740 - ]);
4741 - const removeEditingQueuedAttachment = useCallback((attachmentId: string) => {
4756 + };
4757 + const cancelEditingQueuedRunStable = useStableCallback(cancelEditingQueuedRun);
4758 + const removeEditingQueuedAttachment = (attachmentId: string) => {
4759 setEditingQueuedRun((current) =>
4760 current === null
4761 ? current
@@ -4749,7 +4766,8 @@ export default function ChatView(props: ChatViewProps) {
4766 ),
4767 },
4768 );
4752 - }, []);
4769 + };
4770 + const removeEditingQueuedAttachmentStable = useStableCallback(removeEditingQueuedAttachment);
4771 // Exit edit mode when the edited run leaves the queue (it started, or was
4772 // cancelled from another client). A dirty edit moves into the thread's own
4773 // draft when that draft is empty; otherwise it is dropped with a toast.
@@ -4792,20 +4810,16 @@ export default function ChatView(props: ChatViewProps) {
4810 queuedEditDraftTargetFor,
4811 serverProjection,
4812 ]);
4795 - const addTerminalContextToDraft = useCallback(
4796 - (selection: TerminalContextSelection) => {
4797 - composerRef.current?.addTerminalContext(selection);
4798 - },
4799 - [composerRef],
4800 - );
4801 - const setTerminalOpen = useCallback(
4802 - (open: boolean) => {
4803 - if (!activeThreadRef) return;
4804 - storeSetTerminalOpen(activeThreadRef, open);
4805 - },
4806 - [activeThreadRef, storeSetTerminalOpen],
4807 - );
4808 - const toggleTerminalVisibility = useCallback(() => {
4813 + const addTerminalContextToDraft = (selection: TerminalContextSelection) => {
4814 + composerRef.current?.addTerminalContext(selection);
4815 + };
4816 + const addTerminalContextToDraftStable = useStableCallback(addTerminalContextToDraft);
4817 + const setTerminalOpen = (open: boolean) => {
4818 + if (!activeThreadRef) return;
4819 + storeSetTerminalOpen(activeThreadRef, open);
4820 + };
4821 + const setTerminalOpenStable = useStableCallback(setTerminalOpen);
4822 + const toggleTerminalVisibility = () => {
4823 if (!activeThreadRef) return;
4824 const nextOpen = !terminalUiState.terminalOpen;
4825 if (
@@ -4849,76 +4863,45 @@ export default function ChatView(props: ChatViewProps) {
4863 return;
4864 }
4865 setTerminalOpen(nextOpen);
4852 - }, [
4853 - activeServerOrderedTerminalIds,
4854 - activeProject,
4855 - activeThreadId,
4856 - activeThreadRef,
4857 - activeThreadWorktreePath,
4858 - allocateTerminalId,
4859 - environmentId,
4860 - gitCwd,
4861 - openTerminal,
4862 - panelTerminalIds,
4863 - runningTerminalIds,
4864 - hasTerminalWriteAccess,
4865 - setTerminalOpen,
4866 - storeEnsureTerminal,
4867 - terminalUiState.terminalIds.length,
4868 - terminalUiState.terminalOpen,
4869 - ]);
4870 - const splitTerminal = useCallback(
4871 - (direction: "horizontal" | "vertical" = "horizontal") => {
4872 - if (
4873 - !hasTerminalWriteAccess() ||
4874 - !activeThreadRef ||
4875 - hasReachedSplitLimit ||
4876 - !activeThreadId ||
4877 - !activeProject
4878 - ) {
4879 - return;
4880 - }
4881 - const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
4882 - if (!cwdForOpen) {
4883 - return;
4884 - }
4885 - const terminalId = allocateTerminalId();
4886 - if (direction === "vertical") {
4887 - storeSplitTerminalVertical(activeThreadRef, terminalId);
4888 - } else {
4889 - storeSplitTerminal(activeThreadRef, terminalId);
4890 - }
4891 - setTerminalFocusRequestId((value) => value + 1);
4892 - void openTerminal({
4893 - environmentId,
4894 - input: {
4895 - threadId: activeThreadId,
4896 - terminalId,
4897 - cwd: cwdForOpen,
4898 - ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
4899 - env: projectScriptRuntimeEnv({
4900 - project: { cwd: activeProject.workspaceRoot },
4901 - worktreePath: activeThreadWorktreePath,
4902 - }),
4903 - },
4904 - });
4905 - },
4906 - [
4907 - activeProject,
4908 - activeThreadId,
4909 - allocateTerminalId,
4910 - activeThreadRef,
4911 - openTerminal,
4912 - hasTerminalWriteAccess,
4913 - activeThreadWorktreePath,
4866 + };
4867 + const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility);
4868 + const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
4869 + if (
4870 + !hasTerminalWriteAccess() ||
4871 + !activeThreadRef ||
4872 + hasReachedSplitLimit ||
4873 + !activeThreadId ||
4874 + !activeProject
4875 + ) {
4876 + return;
4877 + }
4878 + const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
4879 + if (!cwdForOpen) {
4880 + return;
4881 + }
4882 + const terminalId = allocateTerminalId();
4883 + if (direction === "vertical") {
4884 + storeSplitTerminalVertical(activeThreadRef, terminalId);
4885 + } else {
4886 + storeSplitTerminal(activeThreadRef, terminalId);
4887 + }
4888 + setTerminalFocusRequestId((value) => value + 1);
4889 + void openTerminal({
4890 environmentId,
4915 - gitCwd,
4916 - hasReachedSplitLimit,
4917 - storeSplitTerminal,
4918 - storeSplitTerminalVertical,
4919 - ],
4920 - );
4921 - const createNewTerminal = useCallback(() => {
4891 + input: {
4892 + threadId: activeThreadId,
4893 + terminalId,
4894 + cwd: cwdForOpen,
4895 + ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
4896 + env: projectScriptRuntimeEnv({
4897 + project: { cwd: activeProject.workspaceRoot },
4898 + worktreePath: activeThreadWorktreePath,
4899 + }),
4900 + },
4901 + });
4902 + };
4903 + const splitTerminalStable = useStableCallback(splitTerminal);
4904 + const createNewTerminal = () => {
4905 if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) {
4906 return;
4907 }
@@ -4942,206 +4925,162 @@ export default function ChatView(props: ChatViewProps) {
4925 }),
4926 },
4927 });
4945 - }, [
4946 - activeProject,
4947 - activeThreadId,
4948 - allocateTerminalId,
4949 - activeThreadRef,
4950 - openTerminal,
4951 - hasTerminalWriteAccess,
4952 - activeThreadWorktreePath,
4953 - environmentId,
4954 - gitCwd,
4955 - storeNewTerminal,
4956 - ]);
4957 - const closeTerminal = useCallback(
4958 - (terminalId: string) => {
4959 - if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return;
4960 - const fallbackExitWrite = () =>
4961 - writeTerminal({
4962 - environmentId,
4963 - input: { threadId: activeThreadId, terminalId, data: "exit\n" },
4964 - });
4965 - void (async () => {
4966 - const closeResult = await closeTerminalMutation({
4967 - environmentId,
4968 - input: {
4969 - threadId: activeThreadId,
4970 - terminalId,
4971 - deleteHistory: true,
4972 - },
4973 - });
4974 - if (
4975 - closeResult._tag === "Failure" &&
4976 - !isAtomCommandInterrupted(closeResult) &&
4977 - hasTerminalWriteAccess()
4978 - ) {
4979 - await fallbackExitWrite();
4980 - }
4981 - })();
4982 - storeCloseTerminal(activeThreadRef, terminalId);
4983 - setTerminalFocusRequestId((value) => value + 1);
4984 - },
4985 - [
4986 - activeThreadId,
4987 - activeThreadRef,
4988 - closeTerminalMutation,
4989 - hasTerminalWriteAccess,
4990 - environmentId,
4991 - storeCloseTerminal,
4992 - writeTerminal,
4993 - ],
4994 - );
4995 - const runProjectScript = useCallback(
4996 - async (
4997 - script: ProjectScript,
4998 - options?: {
4999 - cwd?: string;
5000 - env?: Record<string, string>;
5001 - worktreePath?: string | null;
5002 - preferNewTerminal?: boolean;
5003 - rememberAsLastInvoked?: boolean;
5004 - },
5005 - ) => {
5006 - if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return;
5007 - if (options?.rememberAsLastInvoked !== false) {
5008 - setLastInvokedScriptByProjectId((current) => {
5009 - if (current[activeProject.id] === script.id) return current;
5010 - return { ...current, [activeProject.id]: script.id };
5011 - });
5012 - }
5013 - const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot;
5014 - const baseTerminalId =
5015 - terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
5016 - const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId);
5017 - const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
5018 - const shouldCreateNewTerminal =
5019 - wantsNewTerminal ||
5020 - !canReuseTerminal ||
5021 - !readEnvironmentScope(environmentId, AuthTerminalReadScope);
5022 - const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
5023 -
5024 - setTerminalUiLaunchContext({
5025 - threadId: activeThreadId,
5026 - cwd: targetCwd,
5027 - worktreePath: targetWorktreePath,
5028 - });
5029 - setTerminalOpen(true);
5030 - if (!activeThreadRef) {
5031 - return;
5032 - }
5033 - setTerminalFocusRequestId((value) => value + 1);
5034 -
5035 - const runtimeEnv = projectScriptRuntimeEnv({
5036 - project: {
5037 - cwd: activeProject.workspaceRoot,
5038 - },
5039 - worktreePath: targetWorktreePath,
5040 - ...(options?.env ? { extraEnv: options.env } : {}),
4928 + };
4929 + const createNewTerminalStable = useStableCallback(createNewTerminal);
4930 + const closeTerminal = (terminalId: string) => {
4931 + if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return;
4932 + const fallbackExitWrite = () =>
4933 + writeTerminal({
4934 + environmentId,
4935 + input: { threadId: activeThreadId, terminalId, data: "exit\n" },
4936 });
5042 - const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId;
5043 - const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
5044 - ? {
5045 - threadId: activeThreadId,
5046 - terminalId: targetTerminalId,
5047 - cwd: targetCwd,
5048 - ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
5049 - env: runtimeEnv,
5050 - cols: SCRIPT_TERMINAL_COLS,
5051 - rows: SCRIPT_TERMINAL_ROWS,
5052 - }
5053 - : {
5054 - threadId: activeThreadId,
5055 - terminalId: targetTerminalId,
5056 - cwd: targetCwd,
5057 - ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
5058 - env: runtimeEnv,
5059 - };
5060 -
5061 - if (shouldCreateNewTerminal) {
5062 - storeNewTerminal(activeThreadRef, targetTerminalId);
5063 - } else {
5064 - storeSetActiveTerminal(activeThreadRef, targetTerminalId);
5065 - }
5066 -
5067 - const openResult = await openTerminal({ environmentId, input: openTerminalInput });
5068 - if (openResult._tag === "Failure") {
5069 - if (!isAtomCommandInterrupted(openResult)) {
5070 - const error = squashAtomCommandFailure(openResult);
5071 - setThreadError(
5072 - activeThreadId,
5073 - error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
5074 - );
5075 - }
5076 - return;
5077 - }
5078 -
5079 - if (!hasTerminalWriteAccess()) return;
5080 - const writeResult = await writeTerminal({
4937 + void (async () => {
4938 + const closeResult = await closeTerminalMutation({
4939 environmentId,
4940 input: {
4941 threadId: activeThreadId,
5084 - terminalId: targetTerminalId,
5085 - data: `${script.command}\r`,
4942 + terminalId,
4943 + deleteHistory: true,
4944 },
4945 });
5088 - if (writeResult._tag === "Failure") {
5089 - if (!isAtomCommandInterrupted(writeResult)) {
5090 - const error = squashAtomCommandFailure(writeResult);
5091 - setThreadError(
5092 - activeThreadId,
5093 - error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
5094 - );
5095 - }
5096 - return;
4946 + if (
4947 + closeResult._tag === "Failure" &&
4948 + !isAtomCommandInterrupted(closeResult) &&
4949 + hasTerminalWriteAccess()
4950 + ) {
4951 + await fallbackExitWrite();
4952 }
5098 - if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) {
5099 - const previewResult = await openUrlInPreview({
5100 - threadRef: activeThreadRef,
5101 - url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl),
5102 - openPreview,
5103 - });
5104 - if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) {
5105 - const error = squashAtomCommandFailure(previewResult);
5106 - toastManager.add(
5107 - stackedThreadToast({
5108 - type: "error",
5109 - title: "Could not open preview",
5110 - description: error instanceof Error ? error.message : "An unexpected error occurred.",
5111 - }),
5112 - );
4953 + })();
4954 + storeCloseTerminal(activeThreadRef, terminalId);
4955 + setTerminalFocusRequestId((value) => value + 1);
4956 + };
4957 + const runProjectScript = async (
4958 + script: ProjectScript,
4959 + options?: {
4960 + cwd?: string;
4961 + env?: Record<string, string>;
4962 + worktreePath?: string | null;
4963 + preferNewTerminal?: boolean;
4964 + rememberAsLastInvoked?: boolean;
4965 + },
4966 + ) => {
4967 + if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return;
4968 + if (options?.rememberAsLastInvoked !== false) {
4969 + setLastInvokedScriptByProjectId((current) => {
4970 + if (current[activeProject.id] === script.id) return current;
4971 + return { ...current, [activeProject.id]: script.id };
4972 + });
4973 + }
4974 + const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot;
4975 + const baseTerminalId =
4976 + terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
4977 + const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId);
4978 + const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
4979 + const shouldCreateNewTerminal =
4980 + wantsNewTerminal ||
4981 + !canReuseTerminal ||
4982 + !readEnvironmentScope(environmentId, AuthTerminalReadScope);
4983 + const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
4984 +
4985 + setTerminalUiLaunchContext({
4986 + threadId: activeThreadId,
4987 + cwd: targetCwd,
4988 + worktreePath: targetWorktreePath,
4989 + });
4990 + setTerminalOpen(true);
4991 + if (!activeThreadRef) {
4992 + return;
4993 + }
4994 + setTerminalFocusRequestId((value) => value + 1);
4995 +
4996 + const runtimeEnv = projectScriptRuntimeEnv({
4997 + project: {
4998 + cwd: activeProject.workspaceRoot,
4999 + },
5000 + worktreePath: targetWorktreePath,
5001 + ...(options?.env ? { extraEnv: options.env } : {}),
5002 + });
5003 + const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId;
5004 + const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
5005 + ? {
5006 + threadId: activeThreadId,
5007 + terminalId: targetTerminalId,
5008 + cwd: targetCwd,
5009 + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
5010 + env: runtimeEnv,
5011 + cols: SCRIPT_TERMINAL_COLS,
5012 + rows: SCRIPT_TERMINAL_ROWS,
5013 }
5014 + : {
5015 + threadId: activeThreadId,
5016 + terminalId: targetTerminalId,
5017 + cwd: targetCwd,
5018 + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),
5019 + env: runtimeEnv,
5020 + };
5021 +
5022 + if (shouldCreateNewTerminal) {
5023 + storeNewTerminal(activeThreadRef, targetTerminalId);
5024 + } else {
5025 + storeSetActiveTerminal(activeThreadRef, targetTerminalId);
5026 + }
5027 +
5028 + const openResult = await openTerminal({ environmentId, input: openTerminalInput });
5029 + if (openResult._tag === "Failure") {
5030 + if (!isAtomCommandInterrupted(openResult)) {
5031 + const error = squashAtomCommandFailure(openResult);
5032 + setThreadError(
5033 + activeThreadId,
5034 + error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
5035 + );
5036 }
5115 - },
5116 - [
5117 - activeProject,
5118 - activeThread,
5119 - activeThreadId,
5120 - activeThreadRef,
5121 - gitCwd,
5122 - setTerminalOpen,
5123 - setThreadError,
5124 - storeNewTerminal,
5125 - storeSetActiveTerminal,
5126 - setLastInvokedScriptByProjectId,
5037 + return;
5038 + }
5039 +
5040 + if (!hasTerminalWriteAccess()) return;
5041 + const writeResult = await writeTerminal({
5042 environmentId,
5128 - openTerminal,
5129 - openPreview,
5130 - hasTerminalWriteAccess,
5131 - activeKnownTerminalIds,
5132 - canReuseTerminal,
5133 - allocateTerminalId,
5134 - runningTerminalIds,
5135 - terminalUiState.activeTerminalId,
5136 - writeTerminal,
5137 - ],
5138 - );
5043 + input: {
5044 + threadId: activeThreadId,
5045 + terminalId: targetTerminalId,
5046 + data: `${script.command}\r`,
5047 + },
5048 + });
5049 + if (writeResult._tag === "Failure") {
5050 + if (!isAtomCommandInterrupted(writeResult)) {
5051 + const error = squashAtomCommandFailure(writeResult);
5052 + setThreadError(
5053 + activeThreadId,
5054 + error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
5055 + );
5056 + }
5057 + return;
5058 + }
5059 + if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) {
5060 + const previewResult = await openUrlInPreview({
5061 + threadRef: activeThreadRef,
5062 + url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl),
5063 + openPreview,
5064 + });
5065 + if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) {
5066 + const error = squashAtomCommandFailure(previewResult);
5067 + toastManager.add(
5068 + stackedThreadToast({
5069 + type: "error",
5070 + title: "Could not open preview",
5071 + description: error instanceof Error ? error.message : "An unexpected error occurred.",
5072 + }),
5073 + );
5074 + }
5075 + }
5076 + };
5077 + const runProjectScriptStable = useStableCallback(runProjectScript);
5078
5140 - const runProjectScriptRef = useRef(runProjectScript);
5079 + const runProjectScriptRef = useRef(runProjectScriptStable);
5080 useLayoutEffect(() => {
5142 - runProjectScriptRef.current = runProjectScript;
5143 - }, [runProjectScript]);
5144 - const runShellCommand = useCallback((command: string) => {
5081 + runProjectScriptRef.current = runProjectScriptStable;
5082 + }, [runProjectScriptStable]);
5083 + const runShellCommand = (command: string) => {
5084 void runProjectScriptRef.current(
5085 {
5086 id: "chat-code-block",
@@ -5152,334 +5091,302 @@ export default function ChatView(props: ChatViewProps) {
5091 },
5092 { rememberAsLastInvoked: false },
5093 );
5155 - }, []);
5094 + };
5095 + const runShellCommandStable = useStableCallback(runShellCommand);
5096
5097 const supportsProjectSettingsOverrides =
5098 environmentById.get(environmentId)?.serverConfig?.environment.capabilities
5099 .projectSettingsOverrides === true;
5160 - const persistProjectScripts = useCallback(
5161 - async (input: {
5162 - projectId: ProjectId;
5163 - projectCwd: string;
5164 - previousScripts: ReadonlyArray<ProjectScript>;
5165 - nextScripts: ReadonlyArray<ProjectScript>;
5166 - keybinding: NewProjectScriptInput["keybinding"];
5167 - keybindingCommand: KeybindingCommand | null;
5168 - }): Promise<AtomCommandResult<void, unknown>> => {
5169 - const previousKeybinding = keybindingValueForCommand(
5170 - appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [],
5171 - input.keybindingCommand,
5172 - );
5173 - const isDeletingScript = !input.nextScripts.some(
5174 - (script) => commandForProjectScript(script.id) === input.keybindingCommand,
5175 - );
5176 - const changesKeybinding =
5177 - input.keybinding !== undefined &&
5178 - (input.keybinding?.trim() || null) !== previousKeybinding &&
5179 - (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));
5180 - if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
5181 - return AsyncResult.failure(
5182 - Cause.fail(
5183 - new EnvironmentAuthorizationError({
5184 - requiredScope: AuthSettingsWriteScope,
5185 - message: "This connection cannot change keyboard shortcuts.",
5186 - }),
5187 - ),
5188 - );
5189 - }
5190 - const keybindingRule = changesKeybinding
5191 - ? decodeProjectScriptKeybindingRule({
5192 - keybinding: input.keybinding,
5193 - command: input.keybindingCommand,
5194 - })
5195 - : null;
5196 - const updateResult = mapAtomCommandResult(
5197 - await updateProjectScriptSettings({
5198 - environmentId,
5199 - input: {
5200 - // The canonical key on servers that understand it; the legacy
5201 - // per-project map is still translated on older ones.
5202 - patch: supportsProjectSettingsOverrides
5203 - ? {
5204 - projectSettingsOverrides: {
5205 - [input.projectId]: {
5206 - ...settings.projectSettingsOverrides[input.projectId],
5207 - defaultProjectScripts: input.nextScripts,
5208 - },
5209 - },
5210 - }
5211 - : {
5212 - projectScriptOverrides: {
5213 - [input.projectId]: input.nextScripts,
5214 - },
5215 - },
5216 - },
5217 - }),
5218 - () => undefined,
5100 + const persistProjectScripts = async (input: {
5101 + projectId: ProjectId;
5102 + projectCwd: string;
5103 + previousScripts: ReadonlyArray<ProjectScript>;
5104 + nextScripts: ReadonlyArray<ProjectScript>;
5105 + keybinding: NewProjectScriptInput["keybinding"];
5106 + keybindingCommand: KeybindingCommand | null;
5107 + }): Promise<AtomCommandResult<void, unknown>> => {
5108 + const previousKeybinding = keybindingValueForCommand(
5109 + appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [],
5110 + input.keybindingCommand,
5111 + );
5112 + const isDeletingScript = !input.nextScripts.some(
5113 + (script) => commandForProjectScript(script.id) === input.keybindingCommand,
5114 + );
5115 + const changesKeybinding =
5116 + input.keybinding !== undefined &&
5117 + (input.keybinding?.trim() || null) !== previousKeybinding &&
5118 + (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));
5119 + if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
5120 + return AsyncResult.failure(
5121 + Cause.fail(
5122 + new EnvironmentAuthorizationError({
5123 + requiredScope: AuthSettingsWriteScope,
5124 + message: "This connection cannot change keyboard shortcuts.",
5125 + }),
5126 + ),
5127 );
5220 - if (updateResult._tag === "Failure") {
5221 - return updateResult;
5222 - }
5223 -
5224 - if (!changesKeybinding) return updateResult;
5225 - if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
5226 - return AsyncResult.failure(
5227 - Cause.fail(
5228 - new EnvironmentAuthorizationError({
5229 - requiredScope: AuthSettingsWriteScope,
5230 - message: isDeletingScript
5231 - ? "The script was deleted, but its keyboard shortcut could not be removed because permission changed."
5232 - : "The script was saved, but this connection can no longer change keyboard shortcuts.",
5233 - }),
5234 - ),
5235 - );
5236 - }
5237 -
5238 - const scriptId = input.keybindingCommand
5239 - ? projectScriptIdFromCommand(input.keybindingCommand)
5240 - : null;
5241 - if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) {
5242 - return updateResult;
5243 - }
5244 - const retainedElsewhere =
5245 - !input.nextScripts.some((script) => script.id === scriptId) &&
5246 - (settings.defaultProjectScripts.some((script) => script.id === scriptId) ||
5247 - Object.entries(settings.projectSettingsOverrides).some(
5248 - ([projectId, entry]) =>
5249 - projectId !== input.projectId &&
5250 - entry.defaultProjectScripts?.some((script) => script.id === scriptId),
5251 - ) ||
5252 - allProjects.some(
5253 - (other) =>
5254 - other.environmentId === environmentId &&
5255 - other.id !== input.projectId &&
5256 - resolveProjectScripts(settings, other).some((script) => script.id === scriptId),
5257 - ));
5258 - if (!keybindingRule && retainedElsewhere) return updateResult;
5259 -
5260 - const previousRules = (
5261 - environmentById.get(environmentId)?.serverConfig?.keybindings ?? []
5262 - ).flatMap((binding) => {
5263 - if (binding.command !== input.keybindingCommand || binding.whenAst) return [];
5264 - const previous = decodeProjectScriptKeybindingRule({
5265 - keybinding: keybindingValueForCommand([binding], input.keybindingCommand),
5128 + }
5129 + const keybindingRule = changesKeybinding
5130 + ? decodeProjectScriptKeybindingRule({
5131 + keybinding: input.keybinding,
5132 command: input.keybindingCommand,
5267 - });
5268 - return previous ? [previous] : [];
5269 - });
5270 - const previous = previousRules.at(-1);
5271 - for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) {
5272 - const result = await removeKeybinding({ environmentId, input: rule });
5273 - if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined);
5274 - }
5275 - return keybindingRule
5276 - ? mapAtomCommandResult(
5277 - await upsertKeybinding({
5278 - environmentId,
5279 - input:
5280 - previous && previous.key !== keybindingRule.key
5281 - ? { ...keybindingRule, replace: previous }
5282 - : keybindingRule,
5283 - }),
5284 - () => undefined,
5285 - )
5286 - : updateResult;
5287 - },
5288 - [
5289 - allProjects,
5290 - environmentById,
5291 - environmentId,
5292 - removeKeybinding,
5293 - settings,
5294 - supportsProjectSettingsOverrides,
5295 - updateProjectScriptSettings,
5296 - upsertKeybinding,
5297 - ],
5298 - );
5299 - const saveProjectScript = useCallback(
5300 - async (input: NewProjectScriptInput): Promise<AtomCommandResult<void, unknown>> => {
5301 - if (!activeProject) {
5302 - return AsyncResult.success(undefined);
5303 - }
5304 - const nextId = nextProjectScriptId(
5305 - input.name,
5306 - activeProjectScripts.map((script) => script.id),
5133 + })
5134 + : null;
5135 + const updateResult = mapAtomCommandResult(
5136 + await updateProjectScriptSettings({
5137 + environmentId,
5138 + input: {
5139 + // The canonical key on servers that understand it; the legacy
5140 + // per-project map is still translated on older ones.
5141 + patch: supportsProjectSettingsOverrides
5142 + ? {
5143 + projectSettingsOverrides: {
5144 + [input.projectId]: {
5145 + ...settings.projectSettingsOverrides[input.projectId],
5146 + defaultProjectScripts: input.nextScripts,
5147 + },
5148 + },
5149 + }
5150 + : {
5151 + projectScriptOverrides: {
5152 + [input.projectId]: input.nextScripts,
5153 + },
5154 + },
5155 + },
5156 + }),
5157 + () => undefined,
5158 + );
5159 + if (updateResult._tag === "Failure") {
5160 + return updateResult;
5161 + }
5162 +
5163 + if (!changesKeybinding) return updateResult;
5164 + if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
5165 + return AsyncResult.failure(
5166 + Cause.fail(
5167 + new EnvironmentAuthorizationError({
5168 + requiredScope: AuthSettingsWriteScope,
5169 + message: isDeletingScript
5170 + ? "The script was deleted, but its keyboard shortcut could not be removed because permission changed."
5171 + : "The script was saved, but this connection can no longer change keyboard shortcuts.",
5172 + }),
5173 + ),
5174 );
5308 - const nextScript = buildProjectScript(nextId, input);
5309 - const nextScripts = [
5310 - ...activeProjectScripts.map((script) => releaseClaimedRoles(script, input)),
5311 - nextScript,
5312 - ];
5175 + }
5176
5314 - return persistProjectScripts({
5315 - projectId: activeProject.id,
5316 - projectCwd: activeProject.workspaceRoot,
5317 - previousScripts: activeProjectScripts,
5318 - nextScripts,
5319 - keybinding: input.keybinding,
5320 - keybindingCommand: commandForProjectScript(nextId),
5177 + const scriptId = input.keybindingCommand
5178 + ? projectScriptIdFromCommand(input.keybindingCommand)
5179 + : null;
5180 + if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) {
5181 + return updateResult;
5182 + }
5183 + const retainedElsewhere =
5184 + !input.nextScripts.some((script) => script.id === scriptId) &&
5185 + (settings.defaultProjectScripts.some((script) => script.id === scriptId) ||
5186 + Object.entries(settings.projectSettingsOverrides).some(
5187 + ([projectId, entry]) =>
5188 + projectId !== input.projectId &&
5189 + entry.defaultProjectScripts?.some((script) => script.id === scriptId),
5190 + ) ||
5191 + allProjects.some(
5192 + (other) =>
5193 + other.environmentId === environmentId &&
5194 + other.id !== input.projectId &&
5195 + resolveProjectScripts(settings, other).some((script) => script.id === scriptId),
5196 + ));
5197 + if (!keybindingRule && retainedElsewhere) return updateResult;
5198 +
5199 + const previousRules = (
5200 + environmentById.get(environmentId)?.serverConfig?.keybindings ?? []
5201 + ).flatMap((binding) => {
5202 + if (binding.command !== input.keybindingCommand || binding.whenAst) return [];
5203 + const previous = decodeProjectScriptKeybindingRule({
5204 + keybinding: keybindingValueForCommand([binding], input.keybindingCommand),
5205 + command: input.keybindingCommand,
5206 });
5322 - },
5323 - [activeProject, activeProjectScripts, persistProjectScripts],
5324 - );
5325 - const updateProjectScript = useCallback(
5326 - async (
5327 - scriptId: string,
5328 - input: NewProjectScriptInput,
5329 - ): Promise<AtomCommandResult<void, unknown>> => {
5330 - if (!activeProject) {
5331 - return AsyncResult.success(undefined);
5332 - }
5333 - const existingScript = activeProjectScripts.find((script) => script.id === scriptId);
5334 - if (!existingScript) {
5335 - return AsyncResult.failure(Cause.fail(new Error("Script not found.")));
5336 - }
5207 + return previous ? [previous] : [];
5208 + });
5209 + const previous = previousRules.at(-1);
5210 + for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) {
5211 + const result = await removeKeybinding({ environmentId, input: rule });
5212 + if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined);
5213 + }
5214 + return keybindingRule
5215 + ? mapAtomCommandResult(
5216 + await upsertKeybinding({
5217 + environmentId,
5218 + input:
5219 + previous && previous.key !== keybindingRule.key
5220 + ? { ...keybindingRule, replace: previous }
5221 + : keybindingRule,
5222 + }),
5223 + () => undefined,
5224 + )
5225 + : updateResult;
5226 + };
5227 + const saveProjectScript = async (
5228 + input: NewProjectScriptInput,
5229 + ): Promise<AtomCommandResult<void, unknown>> => {
5230 + if (!activeProject) {
5231 + return AsyncResult.success(undefined);
5232 + }
5233 + const nextId = nextProjectScriptId(
5234 + input.name,
5235 + activeProjectScripts.map((script) => script.id),
5236 + );
5237 + const nextScript = buildProjectScript(nextId, input);
5238 + const nextScripts = [
5239 + ...activeProjectScripts.map((script) => releaseClaimedRoles(script, input)),
5240 + nextScript,
5241 + ];
5242
5338 - const updatedScript = buildProjectScript(existingScript.id, input);
5339 - const nextScripts = activeProjectScripts.map((script) =>
5340 - script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input),
5341 - );
5243 + return persistProjectScripts({
5244 + projectId: activeProject.id,
5245 + projectCwd: activeProject.workspaceRoot,
5246 + previousScripts: activeProjectScripts,
5247 + nextScripts,
5248 + keybinding: input.keybinding,
5249 + keybindingCommand: commandForProjectScript(nextId),
5250 + });
5251 + };
5252 + const saveProjectScriptStable = useStableCallback(saveProjectScript);
5253 + const updateProjectScript = async (
5254 + scriptId: string,
5255 + input: NewProjectScriptInput,
5256 + ): Promise<AtomCommandResult<void, unknown>> => {
5257 + if (!activeProject) {
5258 + return AsyncResult.success(undefined);
5259 + }
5260 + const existingScript = activeProjectScripts.find((script) => script.id === scriptId);
5261 + if (!existingScript) {
5262 + return AsyncResult.failure(Cause.fail(new Error("Script not found.")));
5263 + }
5264
5343 - return persistProjectScripts({
5344 - projectId: activeProject.id,
5345 - projectCwd: activeProject.workspaceRoot,
5346 - previousScripts: activeProjectScripts,
5347 - nextScripts,
5348 - keybinding: input.keybinding,
5349 - keybindingCommand: commandForProjectScript(scriptId),
5350 - });
5351 - },
5352 - [activeProject, activeProjectScripts, persistProjectScripts],
5353 - );
5354 - const deleteProjectScript = useCallback(
5355 - async (scriptId: string): Promise<AtomCommandResult<void, unknown>> => {
5356 - if (!activeProject) {
5357 - return AsyncResult.success(undefined);
5358 - }
5359 - const nextScripts = activeProjectScripts.filter((script) => script.id !== scriptId);
5265 + const updatedScript = buildProjectScript(existingScript.id, input);
5266 + const nextScripts = activeProjectScripts.map((script) =>
5267 + script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input),
5268 + );
5269 +
5270 + return persistProjectScripts({
5271 + projectId: activeProject.id,
5272 + projectCwd: activeProject.workspaceRoot,
5273 + previousScripts: activeProjectScripts,
5274 + nextScripts,
5275 + keybinding: input.keybinding,
5276 + keybindingCommand: commandForProjectScript(scriptId),
5277 + });
5278 + };
5279 + const updateProjectScriptStable = useStableCallback(updateProjectScript);
5280 + const deleteProjectScript = async (
5281 + scriptId: string,
5282 + ): Promise<AtomCommandResult<void, unknown>> => {
5283 + if (!activeProject) {
5284 + return AsyncResult.success(undefined);
5285 + }
5286 + const nextScripts = activeProjectScripts.filter((script) => script.id !== scriptId);
5287
5361 - const deletedName = activeProjectScripts.find((s) => s.id === scriptId)?.name;
5288 + const deletedName = activeProjectScripts.find((s) => s.id === scriptId)?.name;
5289
5363 - const result = await persistProjectScripts({
5364 - projectId: activeProject.id,
5365 - projectCwd: activeProject.workspaceRoot,
5366 - previousScripts: activeProjectScripts,
5367 - nextScripts,
5368 - keybinding: null,
5369 - keybindingCommand: commandForProjectScript(scriptId),
5290 + const result = await persistProjectScripts({
5291 + projectId: activeProject.id,
5292 + projectCwd: activeProject.workspaceRoot,
5293 + previousScripts: activeProjectScripts,
5294 + nextScripts,
5295 + keybinding: null,
5296 + keybindingCommand: commandForProjectScript(scriptId),
5297 + });
5298 + if (result._tag === "Success") {
5299 + toastManager.add({
5300 + type: "success",
5301 + title: `Deleted action "${deletedName ?? "Unknown"}"`,
5302 });
5371 - if (result._tag === "Success") {
5372 - toastManager.add({
5373 - type: "success",
5374 - title: `Deleted action "${deletedName ?? "Unknown"}"`,
5375 - });
5376 - } else if (!isAtomCommandInterrupted(result)) {
5377 - const error = squashAtomCommandFailure(result);
5378 - toastManager.add(
5379 - stackedThreadToast({
5380 - type: "error",
5381 - title: "Could not delete action",
5382 - description: error instanceof Error ? error.message : "An unexpected error occurred.",
5383 - }),
5384 - );
5385 - }
5386 - return result;
5387 - },
5388 - [activeProject, activeProjectScripts, persistProjectScripts],
5389 - );
5303 + } else if (!isAtomCommandInterrupted(result)) {
5304 + const error = squashAtomCommandFailure(result);
5305 + toastManager.add(
5306 + stackedThreadToast({
5307 + type: "error",
5308 + title: "Could not delete action",
5309 + description: error instanceof Error ? error.message : "An unexpected error occurred.",
5310 + }),
5311 + );
5312 + }
5313 + return result;
5314 + };
5315 + const deleteProjectScriptStable = useStableCallback(deleteProjectScript);
5316
5391 - const handleRuntimeModeChange = useCallback(
5392 - (mode: RuntimeMode) => {
5393 - if (mode === runtimeMode) return;
5394 - setComposerDraftRuntimeMode(composerDraftTarget, mode);
5395 - if (isLocalDraftThread) {
5396 - setDraftThreadContext(composerDraftTarget, { runtimeMode: mode });
5397 - }
5398 - scheduleComposerFocus();
5399 - },
5400 - [
5401 - isLocalDraftThread,
5402 - runtimeMode,
5403 - scheduleComposerFocus,
5404 - composerDraftTarget,
5405 - setComposerDraftRuntimeMode,
5406 - setDraftThreadContext,
5407 - ],
5408 - );
5317 + const handleRuntimeModeChange = (mode: RuntimeMode) => {
5318 + if (mode === runtimeMode) return;
5319 + setComposerDraftRuntimeMode(composerDraftTarget, mode);
5320 + if (isLocalDraftThread) {
5321 + setDraftThreadContext(composerDraftTarget, { runtimeMode: mode });
5322 + }
5323 + scheduleComposerFocus();
5324 + };
5325 + const handleRuntimeModeChangeStable = useStableCallback(handleRuntimeModeChange);
5326
5410 - const handleInteractionModeChange = useCallback(
5411 - (mode: ProviderInteractionMode) => {
5412 - if (mode === "plan" && !interactionModeEnabled) return;
5413 - if (mode === interactionMode) return;
5414 - setComposerDraftInteractionMode(composerDraftTarget, mode);
5415 - if (isLocalDraftThread) {
5416 - setDraftThreadContext(composerDraftTarget, { interactionMode: mode });
5417 - }
5418 - scheduleComposerFocus();
5419 - },
5420 - [
5421 - interactionMode,
5422 - interactionModeEnabled,
5423 - isLocalDraftThread,
5424 - scheduleComposerFocus,
5425 - composerDraftTarget,
5426 - setComposerDraftInteractionMode,
5427 - setDraftThreadContext,
5428 - ],
5429 - );
5430 - const toggleInteractionMode = useCallback(() => {
5327 + const handleInteractionModeChange = (mode: ProviderInteractionMode) => {
5328 + if (mode === "plan" && !interactionModeEnabled) return;
5329 + if (mode === interactionMode) return;
5330 + setComposerDraftInteractionMode(composerDraftTarget, mode);
5331 + if (isLocalDraftThread) {
5332 + setDraftThreadContext(composerDraftTarget, { interactionMode: mode });
5333 + }
5334 + scheduleComposerFocus();
5335 + };
5336 + const handleInteractionModeChangeStable = useStableCallback(handleInteractionModeChange);
5337 + const toggleInteractionMode = () => {
5338 if (!interactionModeEnabled) return;
5339 handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
5433 - }, [handleInteractionModeChange, interactionMode, interactionModeEnabled]);
5434 - const openProviderSetup = useCallback(
5435 - (instanceId: ProviderInstanceId) => {
5436 - void navigate({
5437 - to: "/settings/providers",
5438 - search: { environmentId, instanceId },
5439 - });
5440 - },
5441 - [environmentId, navigate],
5442 - );
5340 + };
5341 + const toggleInteractionModeStable = useStableCallback(toggleInteractionMode);
5342 + const openProviderSetup = (instanceId: ProviderInstanceId) => {
5343 + void navigate({
5344 + to: "/settings/providers",
5345 + search: { environmentId, instanceId },
5346 + });
5347 + };
5348 + const openProviderSetupStable = useStableCallback(openProviderSetup);
5349 const canOperatePreview = useEnvironmentScope(
5350 activeThreadRef?.environmentId ?? null,
5351 AuthPreviewOperateScope,
5352 );
5447 - const createBrowserSurface = useCallback(
5448 - (profileId?: string) => {
5449 - if (!activeThreadRef || !canOperatePreview) return;
5450 - void addBrowserSurface({
5451 - threadRef: activeThreadRef,
5452 - openPreview,
5453 - ...(profileId === undefined ? {} : { profileId }),
5454 - }).then((result) => {
5455 - if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
5456 - const error = squashAtomCommandFailure(result);
5457 - if (error instanceof BrowserSettingsReadError) {
5458 - toastManager.add(
5459 - stackedThreadToast({
5460 - type: "error",
5461 - title: "Unable to open browser",
5462 - description: error.message,
5463 - }),
5464 - );
5465 - }
5466 - });
5467 - },
5468 - [activeThreadRef, canOperatePreview, openPreview],
5469 - );
5470 - const addDiffSurface = useCallback(() => {
5353 + const createBrowserSurface = (profileId?: string) => {
5354 + if (!activeThreadRef || !canOperatePreview) return;
5355 + void addBrowserSurface({
5356 + threadRef: activeThreadRef,
5357 + openPreview,
5358 + ...(profileId === undefined ? {} : { profileId }),
5359 + }).then((result) => {
5360 + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
5361 + const error = squashAtomCommandFailure(result);
5362 + if (error instanceof BrowserSettingsReadError) {
5363 + toastManager.add(
5364 + stackedThreadToast({
5365 + type: "error",
5366 + title: "Unable to open browser",
5367 + description: error.message,
5368 + }),
5369 + );
5370 + }
5371 + });
5372 + };
5373 + const createBrowserSurfaceStable = useStableCallback(createBrowserSurface);
5374 + const addDiffSurface = () => {
5375 if (!activeThreadRef || !isServerThread || !isGitRepo) return;
5376 useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch");
5377 useRightPanelStore.getState().open(activeThreadRef, "diff");
5378 onDiffPanelOpen?.();
5475 - }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]);
5476 - const openChangesFromThreadPanel = useCallback(() => {
5379 + };
5380 + const addDiffSurfaceStable = useStableCallback(addDiffSurface);
5381 + const openChangesFromThreadPanel = () => {
5382 addDiffSurface();
5478 - }, [addDiffSurface]);
5479 - const addFilesSurface = useCallback(() => {
5383 + };
5384 + const openChangesFromThreadPanelStable = useStableCallback(openChangesFromThreadPanel);
5385 + const addFilesSurface = () => {
5386 if (!activeThreadRef || !activeProject) return;
5387 useRightPanelStore.getState().open(activeThreadRef, "files");
5482 - }, [activeProject, activeThreadRef]);
5388 + };
5389 + const addFilesSurfaceStable = useStableCallback(addFilesSurface);
5390 const supportsThreadPullRequests =
5391 serverConfig?.environment.capabilities.threadPullRequests === true;
5392 const visiblePullRequests = visibleThreadPullRequests(
@@ -5488,22 +5395,24 @@ export default function ChatView(props: ChatViewProps) {
5395 const visiblePullRequestCount = visiblePullRequests.length;
5396 const pullRequestsSurfaceAvailable =
5397 isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0;
5491 - const addPullRequestsSurface = useCallback(() => {
5398 + const addPullRequestsSurface = () => {
5399 if (!activeThreadRef || !pullRequestsSurfaceAvailable) return;
5400 useRightPanelStore.getState().open(activeThreadRef, "pull-requests");
5494 - }, [activeThreadRef, pullRequestsSurfaceAvailable]);
5401 + };
5402 + const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface);
5403 const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState(
5404 activeThreadRef?.environmentId ?? null,
5405 );
5406 const [deviceSetupThread, setDeviceSetupThread] = useState<ScopedThreadRef | null>(null);
5499 - const addDeviceSurface = useCallback(() => {
5407 + const addDeviceSurface = () => {
5408 if (!activeThreadRef) return;
5409 if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
5410 setDeviceSetupThread(activeThreadRef);
5411 return;
5412 }
5413 useRightPanelStore.getState().open(activeThreadRef, "device");
5506 - }, [activeThreadRef, deviceState.onboardingCompleted, deviceState.hostStatus]);
5414 + };
5415 + const addDeviceSurfaceStable = useStableCallback(addDeviceSurface);
5416 // A device the agent opens floats over chat like an agent-driven browser,
5417 // or becomes a panel tab when floating previews are off. Sessions opened by
5418 // another client arrive the same way; sheet layouts get neither. The first
@@ -5617,13 +5526,11 @@ export default function ChatView(props: ChatViewProps) {
5526 );
5527 if (!sessionStillExists) usePreviewMiniPlayerStore.getState().close(activeThreadRef);
5528 }, [activePreviewMiniPlayer, activeThreadRef, deviceState.sessions, deviceStateLoaded]);
5620 - const openFileSurface = useCallback(
5621 - (relativePath: string) => {
5622 - if (!activeThreadRef || !activeProject) return;
5623 - useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
5624 - },
5625 - [activeProject, activeThreadRef],
5626 - );
5529 + const openFileSurface = (relativePath: string) => {
5530 + if (!activeThreadRef || !activeProject) return;
5531 + useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
5532 + };
5533 + const openFileSurfaceStable = useStableCallback(openFileSurface);
5534 // The thread's own change request, placed against the project it belongs to. Without a
5535 // project there is nothing to resolve it against, so the caller falls back to the browser.
5536 const persistedLinkedThreadPullRequest = isServerThread
@@ -5890,7 +5797,7 @@ export default function ChatView(props: ChatViewProps) {
5797 shouldUsePlanSidebarSheet,
5798 threadDetailLoading,
5799 ]);
5893 - const closePreviewPanel = useCallback(() => {
5800 + const closePreviewPanel = () => {
5801 if (activeThreadRef) {
5802 // Closing the panel on a live browser or device floats it instead of dropping it.
5803 if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) {
@@ -5905,8 +5812,9 @@ export default function ChatView(props: ChatViewProps) {
5812 useRightPanelStore.getState().setMaximized(activeThreadRef, false);
5813 useRightPanelStore.getState().close(activeThreadRef);
5814 }
5908 - }, [activeRightPanelSurface, activeThreadRef]);
5909 - const togglePreviewPanel = useCallback(() => {
5815 + };
5816 + const closePreviewPanelStable = useStableCallback(closePreviewPanel);
5817 + const togglePreviewPanel = () => {
5818 if (!activeThreadRef || !browserAvailable) return;
5819 if (previewPanelOpen) {
5820 closePreviewPanel();
@@ -5919,16 +5827,9 @@ export default function ChatView(props: ChatViewProps) {
5827 } else {
5828 createBrowserSurface();
5829 }
5922 - }, [
5923 - activePreviewState.activeTabId,
5924 - activeThreadRef,
5925 - browserAvailable,
5926 - canOperatePreview,
5927 - closePreviewPanel,
5928 - createBrowserSurface,
5929 - previewPanelOpen,
5930 - ]);
5931 - const addTerminalSurface = useCallback(() => {
5830 + };
5831 + const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);
5832 + const addTerminalSurface = () => {
5833 if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) return;
5834 const cwd = gitCwd ?? activeProject.workspaceRoot;
5835 const terminalId = allocateTerminalId();
@@ -5947,151 +5848,118 @@ export default function ChatView(props: ChatViewProps) {
5848 }),
5849 },
5850 });
5950 - }, [
5951 - activeProject,
5952 - activeThreadId,
5953 - activeThreadRef,
5954 - activeThreadWorktreePath,
5955 - allocateTerminalId,
5956 - gitCwd,
5957 - openTerminal,
5958 - hasTerminalWriteAccess,
5959 - ]);
5960 - const splitPanelTerminal = useCallback(
5961 - (direction: "horizontal" | "vertical" = "horizontal") => {
5962 - if (
5963 - !hasTerminalWriteAccess() ||
5964 - !activeThreadRef ||
5965 - !activeThreadId ||
5966 - !activeProject ||
5967 - activeRightPanelSurface?.kind !== "terminal" ||
5968 - activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP
5969 - ) {
5970 - return;
5971 - }
5972 - const terminalId = allocateTerminalId();
5973 - const cwd = gitCwd ?? activeProject.workspaceRoot;
5974 - useRightPanelStore
5975 - .getState()
5976 - .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction);
5977 - setTerminalFocusRequestId((value) => value + 1);
5978 - void openTerminal({
5979 - environmentId: activeThreadRef.environmentId,
5980 - input: {
5981 - threadId: activeThreadId,
5982 - terminalId,
5983 - cwd,
5984 - ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
5985 - env: projectScriptRuntimeEnv({
5986 - project: { cwd: activeProject.workspaceRoot },
5987 - worktreePath: activeThreadWorktreePath,
5988 - }),
5989 - },
5990 - });
5991 - },
5992 - [
5993 - activeProject,
5994 - activeRightPanelSurface,
5995 - activeThreadId,
5996 - activeThreadRef,
5997 - activeThreadWorktreePath,
5998 - allocateTerminalId,
5999 - gitCwd,
6000 - openTerminal,
6001 - hasTerminalWriteAccess,
6002 - ],
6003 - );
6004 - const splitPanelTerminalVertical = useCallback(() => {
5851 + };
5852 + const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);
5853 + const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {
5854 + if (
5855 + !hasTerminalWriteAccess() ||
5856 + !activeThreadRef ||
5857 + !activeThreadId ||
5858 + !activeProject ||
5859 + activeRightPanelSurface?.kind !== "terminal" ||
5860 + activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP
5861 + ) {
5862 + return;
5863 + }
5864 + const terminalId = allocateTerminalId();
5865 + const cwd = gitCwd ?? activeProject.workspaceRoot;
5866 + useRightPanelStore
5867 + .getState()
5868 + .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction);
5869 + setTerminalFocusRequestId((value) => value + 1);
5870 + void openTerminal({
5871 + environmentId: activeThreadRef.environmentId,
5872 + input: {
5873 + threadId: activeThreadId,
5874 + terminalId,
5875 + cwd,
5876 + ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),
5877 + env: projectScriptRuntimeEnv({
5878 + project: { cwd: activeProject.workspaceRoot },
5879 + worktreePath: activeThreadWorktreePath,
5880 + }),
5881 + },
5882 + });
5883 + };
5884 + const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);
5885 + const splitPanelTerminalVertical = () => {
5886 splitPanelTerminal("vertical");
6006 - }, [splitPanelTerminal]);
6007 - const activatePanelTerminal = useCallback(
6008 - (terminalId: string) => {
6009 - if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;
6010 - useRightPanelStore
6011 - .getState()
6012 - .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
6013 - setTerminalFocusRequestId((value) => value + 1);
6014 - },
6015 - [activeRightPanelSurface, activeThreadRef],
6016 - );
6017 - const closePanelTerminal = useCallback(
6018 - (terminalId: string) => {
6019 - if (
6020 - !hasTerminalWriteAccess() ||
6021 - !activeThreadRef ||
6022 - activeRightPanelSurface?.kind !== "terminal"
6023 - )
6024 - return;
6025 - void closeTerminalMutation({
6026 - environmentId: activeThreadRef.environmentId,
6027 - input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
6028 - });
6029 - storeCloseTerminal(activeThreadRef, terminalId);
6030 - useRightPanelStore
6031 - .getState()
6032 - .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
6033 - setTerminalFocusRequestId((value) => value + 1);
6034 - },
6035 - [
6036 - hasTerminalWriteAccess,
6037 - activeRightPanelSurface,
6038 - activeThreadRef,
6039 - closeTerminalMutation,
6040 - storeCloseTerminal,
6041 - ],
6042 - );
6043 - const requestCloseTerminal = useCallback(
6044 - (terminalId: string) => {
6045 - if (!hasTerminalWriteAccess()) return;
6046 - const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
6047 - void confirmTerminalClose([label]).then((confirmed) => {
6048 - if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
6049 - closeTerminal(terminalId);
6050 - }
6051 - });
6052 - },
6053 - [hasTerminalWriteAccess, activeTerminalLabelsById, closeTerminal, environmentId],
6054 - );
6055 - const requestClosePanelTerminal = useCallback(
6056 - (terminalId: string) => {
6057 - if (!hasTerminalWriteAccess()) return;
6058 - const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
6059 - void confirmTerminalClose([label]).then((confirmed) => {
6060 - if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
6061 - closePanelTerminal(terminalId);
6062 - }
6063 - });
6064 - },
6065 - [hasTerminalWriteAccess, activeTerminalLabelsById, closePanelTerminal, environmentId],
6066 - );
6067 - const activateRightPanelSurface = useCallback(
6068 - (surface: RightPanelSurface) => {
6069 - if (!activeThreadRef) return;
6070 - useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
6071 - if (surface.kind === "preview" && surface.resourceId) {
6072 - setActivePreviewTab(activeThreadRef, surface.resourceId);
6073 - }
6074 - if (surface.kind === "terminal") {
6075 - setTerminalFocusRequestId((value) => value + 1);
5887 + };
5888 + const splitPanelTerminalVerticalStable = useStableCallback(splitPanelTerminalVertical);
5889 + const activatePanelTerminal = (terminalId: string) => {
5890 + if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;
5891 + useRightPanelStore
5892 + .getState()
5893 + .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
5894 + setTerminalFocusRequestId((value) => value + 1);
5895 + };
5896 + const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
5897 + const closePanelTerminal = (terminalId: string) => {
5898 + if (
5899 + !hasTerminalWriteAccess() ||
5900 + !activeThreadRef ||
5901 + activeRightPanelSurface?.kind !== "terminal"
5902 + )
5903 + return;
5904 + void closeTerminalMutation({
5905 + environmentId: activeThreadRef.environmentId,
5906 + input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
5907 + });
5908 + storeCloseTerminal(activeThreadRef, terminalId);
5909 + useRightPanelStore
5910 + .getState()
5911 + .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
5912 + setTerminalFocusRequestId((value) => value + 1);
5913 + };
5914 + const closePanelTerminalStable = useStableCallback(closePanelTerminal);
5915 + const requestCloseTerminal = (terminalId: string) => {
5916 + if (!hasTerminalWriteAccess()) return;
5917 + const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
5918 + void confirmTerminalClose([label]).then((confirmed) => {
5919 + if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
5920 + closeTerminal(terminalId);
5921 }
6077 - if (surface.kind === "diff" && !diffOpen) {
6078 - onDiffPanelOpen?.();
5922 + });
5923 + };
5924 + const requestCloseTerminalStable = useStableCallback(requestCloseTerminal);
5925 + const requestClosePanelTerminal = (terminalId: string) => {
5926 + if (!hasTerminalWriteAccess()) return;
5927 + const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
5928 + void confirmTerminalClose([label]).then((confirmed) => {
5929 + if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
5930 + closePanelTerminal(terminalId);
5931 }
6080 - },
6081 - [activeThreadRef, diffOpen, onDiffPanelOpen],
6082 - );
6083 - const toggleRightPanel = useCallback(() => {
5932 + });
5933 + };
5934 + const requestClosePanelTerminalStable = useStableCallback(requestClosePanelTerminal);
5935 + const activateRightPanelSurface = (surface: RightPanelSurface) => {
5936 + if (!activeThreadRef) return;
5937 + useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
5938 + if (surface.kind === "preview" && surface.resourceId) {
5939 + setActivePreviewTab(activeThreadRef, surface.resourceId);
5940 + }
5941 + if (surface.kind === "terminal") {
5942 + setTerminalFocusRequestId((value) => value + 1);
5943 + }
5944 + if (surface.kind === "diff" && !diffOpen) {
5945 + onDiffPanelOpen?.();
5946 + }
5947 + };
5948 + const activateRightPanelSurfaceStable = useStableCallback(activateRightPanelSurface);
5949 + const toggleRightPanel = () => {
5950 if (!activeThreadRef) return;
5951 if (rightPanelOpen) {
5952 closePreviewPanel();
5953 return;
5954 }
5955 useRightPanelStore.getState().toggleVisibility(activeThreadRef);
6090 - }, [activeThreadRef, closePreviewPanel, rightPanelOpen]);
6091 - const toggleThreadPanel = useCallback(() => {
5956 + };
5957 + const toggleRightPanelStable = useStableCallback(toggleRightPanel);
5958 + const toggleThreadPanel = () => {
5959 if (!activeThreadRef) return;
5960 useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation);
6094 - }, [activeThreadRef, threadPanelPresentation]);
5961 + };
5962 + const toggleThreadPanelStable = useStableCallback(toggleThreadPanel);
5963 // A thread started for a link the OS opened shows its browser maximized, like a browser window.
5964 useEffect(() => {
5965 if (!canMaximizeRightPanel) return;
@@ -6099,70 +5967,61 @@ export default function ChatView(props: ChatViewProps) {
5967 useRightPanelStore.getState().setMaximized(routeThreadRef, true);
5968 }
5969 }, [canMaximizeRightPanel, routeThreadRef]);
6102 - const toggleRightPanelMaximized = useCallback(() => {
5970 + const toggleRightPanelMaximized = () => {
5971 if (!canMaximizeRightPanel || !activeThreadRef) return;
5972 useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized);
6105 - }, [activeThreadRef, canMaximizeRightPanel, rightPanelMaximized]);
6106 - const cleanupRightPanelSurfaces = useCallback(
6107 - (surfaces: readonly RightPanelSurface[]) => {
6108 - if (!activeThreadRef) return;
6109 - for (const surface of surfaces) {
6110 - // Without preview access only the local surface goes away. The
6111 - // server record is in-memory bookkeeping, not a live view, and stays
6112 - // listed until a client with the scope closes it or the server restarts.
6113 - if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {
6114 - void closePreviewSession({
6115 - closePreview,
6116 - snapshot: activePreviewState.sessions[surface.resourceId] ?? null,
6117 - tabId: surface.resourceId,
6118 - threadRef: activeThreadRef,
5973 + };
5974 + const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized);
5975 + const cleanupRightPanelSurfaces = (surfaces: readonly RightPanelSurface[]) => {
5976 + if (!activeThreadRef) return;
5977 + for (const surface of surfaces) {
5978 + // Without preview access only the local surface goes away. The
5979 + // server record is in-memory bookkeeping, not a live view, and stays
5980 + // listed until a client with the scope closes it or the server restarts.
5981 + if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {
5982 + void closePreviewSession({
5983 + closePreview,
5984 + snapshot: activePreviewState.sessions[surface.resourceId] ?? null,
5985 + tabId: surface.resourceId,
5986 + threadRef: activeThreadRef,
5987 + });
5988 + }
5989 + if (
5990 + surface.kind === "terminal" &&
5991 + readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)
5992 + ) {
5993 + for (const terminalId of surface.terminalIds) {
5994 + storeCloseTerminal(activeThreadRef, terminalId);
5995 + void closeTerminalMutation({
5996 + environmentId: activeThreadRef.environmentId,
5997 + input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
5998 });
5999 }
6121 - if (
6122 - surface.kind === "terminal" &&
6123 - readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)
6124 - ) {
6125 - for (const terminalId of surface.terminalIds) {
6126 - storeCloseTerminal(activeThreadRef, terminalId);
6127 - void closeTerminalMutation({
6128 - environmentId: activeThreadRef.environmentId,
6129 - input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
6130 - });
6131 - }
6132 - }
6133 - }
6134 - },
6135 - [
6136 - activeThreadRef,
6137 - activePreviewState.sessions,
6138 - canOperatePreview,
6139 - closePreview,
6140 - closeTerminalMutation,
6141 - storeCloseTerminal,
6142 - ],
6143 - );
6144 - const closeAfterAgentBrowserConfirmation = useCallback(
6145 - (surfaces: readonly RightPanelSurface[], closeSurfaces: () => void) => {
6146 - const message = agentControlledBrowserCloseConfirmation(
6147 - surfaces,
6148 - activePreviewState.desktopByTabId,
6149 - );
6150 - if (!message) {
6151 - closeSurfaces();
6152 - return;
6000 }
6154 - const localApi = readLocalApi();
6155 - if (!localApi) return;
6156 - void localApi.dialogs.confirm(message, { variant: "destructive" }).then(
6157 - (confirmed) => {
6158 - if (confirmed) closeSurfaces();
6159 - },
6160 - () => undefined,
6161 - );
6162 - },
6163 - [activePreviewState.desktopByTabId],
6164 - );
6165 - const syncActivePreviewSurface = useCallback(() => {
6001 + }
6002 + };
6003 + const closeAfterAgentBrowserConfirmation = (
6004 + surfaces: readonly RightPanelSurface[],
6005 + closeSurfaces: () => void,
6006 + ) => {
6007 + const message = agentControlledBrowserCloseConfirmation(
6008 + surfaces,
6009 + activePreviewState.desktopByTabId,
6010 + );
6011 + if (!message) {
6012 + closeSurfaces();
6013 + return;
6014 + }
6015 + const localApi = readLocalApi();
6016 + if (!localApi) return;
6017 + void localApi.dialogs.confirm(message, { variant: "destructive" }).then(
6018 + (confirmed) => {
6019 + if (confirmed) closeSurfaces();
6020 + },
6021 + () => undefined,
6022 + );
6023 + };
6024 + const syncActivePreviewSurface = () => {
6025 if (!activeThreadRef) return;
6026 const nextActiveSurface = selectActiveRightPanelSurface(
6027 useRightPanelStore.getState().byThreadKey,
@@ -6171,110 +6030,80 @@ export default function ChatView(props: ChatViewProps) {
6030 if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
6031 setActivePreviewTab(activeThreadRef, nextActiveSurface.resourceId);
6032 }
6174 - }, [activeThreadRef]);
6175 - const finishRightPanelSurfaceClose = useCallback(
6176 - (surfaces: readonly RightPanelSurface[]) => {
6177 - if (!activeThreadRef) return;
6178 - const store = useRightPanelStore.getState();
6179 - const activeId = selectThreadRightPanelState(
6180 - store.byThreadKey,
6181 - activeThreadRef,
6182 - ).activeSurfaceId;
6183 - const ordered = surfaces.toSorted(
6184 - (left, right) => Number(left.id === activeId) - Number(right.id === activeId),
6033 + };
6034 + const finishRightPanelSurfaceClose = (surfaces: readonly RightPanelSurface[]) => {
6035 + if (!activeThreadRef) return;
6036 + const store = useRightPanelStore.getState();
6037 + const activeId = selectThreadRightPanelState(
6038 + store.byThreadKey,
6039 + activeThreadRef,
6040 + ).activeSurfaceId;
6041 + const ordered = surfaces.toSorted(
6042 + (left, right) => Number(left.id === activeId) - Number(right.id === activeId),
6043 + );
6044 + for (const surface of ordered) {
6045 + cleanupRightPanelSurfaces([surface]);
6046 + store.closeSurface(activeThreadRef, surface.id);
6047 + }
6048 + syncActivePreviewSurface();
6049 + };
6050 + const closeRightPanelSurface = (surface: RightPanelSurface) => {
6051 + if (!activeThreadRef) return;
6052 + const finishClose = () => finishRightPanelSurfaceClose([surface]);
6053 + if (surface.kind === "preview") {
6054 + closeAfterAgentBrowserConfirmation([surface], finishClose);
6055 + return;
6056 + }
6057 + if (
6058 + surface.kind !== "terminal" ||
6059 + !readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)
6060 + ) {
6061 + finishClose();
6062 + return;
6063 + }
6064 + const activeLabel =
6065 + activeTerminalLabelsById.get(surface.activeTerminalId) ??
6066 + getTerminalLabel(surface.activeTerminalId);
6067 + const otherLabels = surface.terminalIds
6068 + .filter((terminalId) => terminalId !== surface.activeTerminalId)
6069 + .map(
6070 + (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId),
6071 );
6186 - for (const surface of ordered) {
6187 - cleanupRightPanelSurfaces([surface]);
6188 - store.closeSurface(activeThreadRef, surface.id);
6189 - }
6190 - syncActivePreviewSurface();
6191 - },
6192 - [activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface],
6193 - );
6194 - const closeRightPanelSurface = useCallback(
6195 - (surface: RightPanelSurface) => {
6196 - if (!activeThreadRef) return;
6197 - const finishClose = () => finishRightPanelSurfaceClose([surface]);
6198 - if (surface.kind === "preview") {
6199 - closeAfterAgentBrowserConfirmation([surface], finishClose);
6200 - return;
6201 - }
6202 - if (
6203 - surface.kind !== "terminal" ||
6204 - !readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)
6205 - ) {
6072 + void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => {
6073 + if (confirmed) {
6074 finishClose();
6207 - return;
6075 }
6209 - const activeLabel =
6210 - activeTerminalLabelsById.get(surface.activeTerminalId) ??
6211 - getTerminalLabel(surface.activeTerminalId);
6212 - const otherLabels = surface.terminalIds
6213 - .filter((terminalId) => terminalId !== surface.activeTerminalId)
6214 - .map(
6215 - (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId),
6216 - );
6217 - void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => {
6218 - if (confirmed) {
6219 - finishClose();
6220 - }
6221 - });
6222 - },
6223 - [
6224 - activeThreadRef,
6225 - activeTerminalLabelsById,
6226 - closeAfterAgentBrowserConfirmation,
6227 - finishRightPanelSurfaceClose,
6228 - ],
6229 - );
6230 - const closeOtherRightPanelSurfaces = useCallback(
6231 - (surface: RightPanelSurface) => {
6232 - if (!activeThreadRef) return;
6233 - const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id);
6234 - const finishClose = () => finishRightPanelSurfaceClose(surfaces);
6235 - closeAfterAgentBrowserConfirmation(surfaces, finishClose);
6236 - },
6237 - [
6238 - activeThreadRef,
6239 - closeAfterAgentBrowserConfirmation,
6240 - finishRightPanelSurfaceClose,
6241 - rightPanelState.surfaces,
6242 - ],
6243 - );
6244 - const closeRightPanelSurfacesToRight = useCallback(
6245 - (surface: RightPanelSurface) => {
6246 - if (!activeThreadRef) return;
6247 - const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id);
6248 - if (surfaceIndex < 0) return;
6249 - const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1);
6250 - const finishClose = () => finishRightPanelSurfaceClose(surfaces);
6251 - closeAfterAgentBrowserConfirmation(surfaces, finishClose);
6252 - },
6253 - [
6254 - activeThreadRef,
6255 - closeAfterAgentBrowserConfirmation,
6256 - finishRightPanelSurfaceClose,
6257 - rightPanelState.surfaces,
6258 - ],
6259 - );
6260 - const closeAllRightPanelSurfaces = useCallback(() => {
6076 + });
6077 + };
6078 + const closeRightPanelSurfaceStable = useStableCallback(closeRightPanelSurface);
6079 + const closeOtherRightPanelSurfaces = (surface: RightPanelSurface) => {
6080 + if (!activeThreadRef) return;
6081 + const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id);
6082 + const finishClose = () => finishRightPanelSurfaceClose(surfaces);
6083 + closeAfterAgentBrowserConfirmation(surfaces, finishClose);
6084 + };
6085 + const closeOtherRightPanelSurfacesStable = useStableCallback(closeOtherRightPanelSurfaces);
6086 + const closeRightPanelSurfacesToRight = (surface: RightPanelSurface) => {
6087 + if (!activeThreadRef) return;
6088 + const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id);
6089 + if (surfaceIndex < 0) return;
6090 + const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1);
6091 + const finishClose = () => finishRightPanelSurfaceClose(surfaces);
6092 + closeAfterAgentBrowserConfirmation(surfaces, finishClose);
6093 + };
6094 + const closeRightPanelSurfacesToRightStable = useStableCallback(closeRightPanelSurfacesToRight);
6095 + const closeAllRightPanelSurfaces = () => {
6096 if (!activeThreadRef) return;
6097 const finishClose = () => finishRightPanelSurfaceClose(rightPanelState.surfaces);
6098 closeAfterAgentBrowserConfirmation(rightPanelState.surfaces, finishClose);
6264 - }, [
6265 - activeThreadRef,
6266 - closeAfterAgentBrowserConfirmation,
6267 - finishRightPanelSurfaceClose,
6268 - rightPanelState.surfaces,
6269 - ]);
6270 - const moveRightPanelSurface = useCallback(
6271 - (surfaceId: string, toIndex: number) => {
6272 - if (activeThreadRef)
6273 - useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex);
6274 - },
6275 - [activeThreadRef],
6276 - );
6277 - const copyRightPanelFilePath = useCallback((relativePath: string) => {
6099 + };
6100 + const closeAllRightPanelSurfacesStable = useStableCallback(closeAllRightPanelSurfaces);
6101 + const moveRightPanelSurface = (surfaceId: string, toIndex: number) => {
6102 + if (activeThreadRef)
6103 + useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex);
6104 + };
6105 + const moveRightPanelSurfaceStable = useStableCallback(moveRightPanelSurface);
6106 + const copyRightPanelFilePath = (relativePath: string) => {
6107 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
6108 toastManager.add(
6109 stackedThreadToast({
@@ -6304,88 +6133,80 @@ export default function ChatView(props: ChatViewProps) {
6133 );
6134 },
6135 );
6307 - }, []);
6136 + };
6137 + const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath);
6138 useEffect(
6139 () =>
6140 subscribePreviewAction((action) => {
6311 - if (action === "toggle-panel") togglePreviewPanel();
6141 + if (action === "toggle-panel") togglePreviewPanelStable();
6142 }),
6313 - [togglePreviewPanel],
6143 + [togglePreviewPanelStable],
6144 );
6315 - const persistThreadSettingsForNextTurn = useCallback(
6316 - async (input: {
6317 - threadId: ThreadId;
6318 - createdAt: string;
6319 - branch?: string;
6320 - runtimeMode: RuntimeMode;
6321 - interactionMode: ProviderInteractionMode;
6322 - }): Promise<AtomCommandResult<void, unknown>> => {
6323 - if (!serverThread) {
6324 - return AsyncResult.success(undefined);
6325 - }
6326 -
6327 - let result: AtomCommandResult<void, unknown> = AsyncResult.success(undefined);
6328 - const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({
6329 - currentModelSelection: serverThread.modelSelection,
6330 - currentBranch: serverThread.branch,
6331 - ...(input.branch ? { nextBranch: input.branch } : {}),
6332 - });
6333 - if (metadataUpdate) {
6334 - result = mapAtomCommandResult(
6335 - await updateThreadMetadata({
6336 - environmentId,
6337 - input: {
6338 - threadId: input.threadId,
6339 - ...metadataUpdate,
6340 - },
6341 - }),
6342 - () => undefined,
6343 - );
6344 - if (result._tag === "Failure") {
6345 - return result;
6346 - }
6145 + const persistThreadSettingsForNextTurn = async (input: {
6146 + threadId: ThreadId;
6147 + createdAt: string;
6148 + branch?: string;
6149 + runtimeMode: RuntimeMode;
6150 + interactionMode: ProviderInteractionMode;
6151 + }): Promise<AtomCommandResult<void, unknown>> => {
6152 + if (!serverThread) {
6153 + return AsyncResult.success(undefined);
6154 + }
6155 +
6156 + let result: AtomCommandResult<void, unknown> = AsyncResult.success(undefined);
6157 + const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({
6158 + currentModelSelection: serverThread.modelSelection,
6159 + currentBranch: serverThread.branch,
6160 + ...(input.branch ? { nextBranch: input.branch } : {}),
6161 + });
6162 + if (metadataUpdate) {
6163 + result = mapAtomCommandResult(
6164 + await updateThreadMetadata({
6165 + environmentId,
6166 + input: {
6167 + threadId: input.threadId,
6168 + ...metadataUpdate,
6169 + },
6170 + }),
6171 + () => undefined,
6172 + );
6173 + if (result._tag === "Failure") {
6174 + return result;
6175 }
6176 + }
6177
6349 - if (input.runtimeMode !== serverThread.runtimeMode) {
6350 - result = mapAtomCommandResult(
6351 - await setThreadRuntimeMode({
6352 - environmentId,
6353 - input: {
6354 - threadId: input.threadId,
6355 - runtimeMode: input.runtimeMode,
6356 - createdAt: input.createdAt,
6357 - },
6358 - }),
6359 - () => undefined,
6360 - );
6361 - if (result._tag === "Failure") {
6362 - return result;
6363 - }
6178 + if (input.runtimeMode !== serverThread.runtimeMode) {
6179 + result = mapAtomCommandResult(
6180 + await setThreadRuntimeMode({
6181 + environmentId,
6182 + input: {
6183 + threadId: input.threadId,
6184 + runtimeMode: input.runtimeMode,
6185 + createdAt: input.createdAt,
6186 + },
6187 + }),
6188 + () => undefined,
6189 + );
6190 + if (result._tag === "Failure") {
6191 + return result;
6192 }
6193 + }
6194
6366 - if (input.interactionMode !== serverThread.interactionMode) {
6367 - result = mapAtomCommandResult(
6368 - await setThreadInteractionMode({
6369 - environmentId,
6370 - input: {
6371 - threadId: input.threadId,
6372 - interactionMode: input.interactionMode,
6373 - createdAt: input.createdAt,
6374 - },
6375 - }),
6376 - () => undefined,
6377 - );
6378 - }
6379 - return result;
6380 - },
6381 - [
6382 - environmentId,
6383 - serverThread,
6384 - setThreadInteractionMode,
6385 - setThreadRuntimeMode,
6386 - updateThreadMetadata,
6387 - ],
6388 - );
6195 + if (input.interactionMode !== serverThread.interactionMode) {
6196 + result = mapAtomCommandResult(
6197 + await setThreadInteractionMode({
6198 + environmentId,
6199 + input: {
6200 + threadId: input.threadId,
6201 + interactionMode: input.interactionMode,
6202 + createdAt: input.createdAt,
6203 + },
6204 + }),
6205 + () => undefined,
6206 + );
6207 + }
6208 + return result;
6209 + };
6210
6211 // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
6212 // thread switches. LegendList fires scroll events with isAtEnd=false while
@@ -6413,7 +6234,7 @@ export default function ChatView(props: ChatViewProps) {
6234 readonly userScrollGeneration: number;
6235 } | null>(null);
6236 const anchorScrollRestoreFrameRef = useRef<number | null>(null);
6416 - const cancelTimelineLiveFollowForUserNavigation = useCallback(() => {
6237 + const cancelTimelineLiveFollowForUserNavigation = () => {
6238 cancelPositionRestoreRef.current?.();
6239 anchorUserScrollGenerationRef.current += 1;
6240 const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
@@ -6453,14 +6274,17 @@ export default function ChatView(props: ChatViewProps) {
6274 scrollNode.scrollTop = currentScrollTop;
6275 }
6276 }
6456 - }, []);
6457 - const cancelTimelineLiveFollowForUserNavigationRef = useRef(
6277 + };
6278 + const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(
6279 cancelTimelineLiveFollowForUserNavigation,
6280 );
6281 + const cancelTimelineLiveFollowForUserNavigationRef = useRef(
6282 + cancelTimelineLiveFollowForUserNavigationStable,
6283 + );
6284 useEffect(() => {
6285 cancelTimelineLiveFollowForUserNavigationRef.current =
6462 - cancelTimelineLiveFollowForUserNavigation;
6463 - }, [cancelTimelineLiveFollowForUserNavigation]);
6286 + cancelTimelineLiveFollowForUserNavigationStable;
6287 + }, [cancelTimelineLiveFollowForUserNavigationStable]);
6288 useEffect(() => {
6289 const previous = observedTimelineActivityRef.current;
6290 const dispatchedUserItem =
@@ -6498,13 +6322,13 @@ export default function ChatView(props: ChatViewProps) {
6322 setShowScrollToBottom(false);
6323 setTimelineAnchor({ threadKey: activeThreadKey, messageId });
6324 }, [activeActivityRun, activeThreadKey, isServerThread, serverProjection, threadStatus]);
6501 - const timelineRealContentOverflowsViewport = useCallback(
6502 - (list?: LegendListRef | null) =>
6503 - timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
6504 - composerInset: composerTimelineInset,
6505 - anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
6506 - }),
6507 - [composerTimelineInset],
6325 + const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>
6326 + timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {
6327 + composerInset: composerTimelineInset,
6328 + anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
6329 + });
6330 + const timelineRealContentOverflowsViewportStable = useStableCallback(
6331 + timelineRealContentOverflowsViewport,
6332 );
6333 const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(
6334 null,
@@ -6512,8 +6336,11 @@ export default function ChatView(props: ChatViewProps) {
6336 const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {
6337 timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";
6338 composerRef.current?.collapseForTimelineScrollKey(key);
6515 - if ((key === "PageUp" && timelineRealContentOverflowsViewport()) || !isTimelineAtLogicalEnd()) {
6516 - cancelTimelineLiveFollowForUserNavigation();
6339 + if (
6340 + (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||
6341 + !isTimelineAtLogicalEndStable()
6342 + ) {
6343 + cancelTimelineLiveFollowForUserNavigationStable();
6344 }
6345 });
6346 useEffect(() => {
@@ -6531,18 +6358,21 @@ export default function ChatView(props: ChatViewProps) {
6358 }
6359 };
6360 }, [composerOverlayElement]);
6534 - const onComposerPageScrollKeyDown = useCallback((key: PageScrollKey) => {
6361 + const onComposerPageScrollKeyDown = (key: PageScrollKey) => {
6362 pageScrollControllerRef.current?.handleKeyDown(key);
6536 - }, []);
6537 - const onComposerPageScrollKeyUp = useCallback((key: string) => {
6363 + };
6364 + const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown);
6365 + const onComposerPageScrollKeyUp = (key: string) => {
6366 pageScrollControllerRef.current?.handleKeyUp(key);
6539 - }, []);
6540 - const onComposerPageScrollRelease = useCallback(() => {
6367 + };
6368 + const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp);
6369 + const onComposerPageScrollRelease = () => {
6370 pageScrollControllerRef.current?.releaseActiveKey();
6542 - }, []);
6371 + };
6372 + const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);
6373 // Live-follow stays active after send/thread-open until an actual list scroll
6374 // gesture opts out.
6545 - const scrollToEnd = useCallback((animated = false) => {
6375 + const scrollToEnd = (animated: boolean = false) => {
6376 cancelPositionRestoreRef.current?.();
6377 isAtEndRef.current = true;
6378 timelineScrollModeRef.current = "following-end";
@@ -6558,7 +6388,8 @@ export default function ChatView(props: ChatViewProps) {
6388 requestAnimationFrame(() => {
6389 void legendListRef.current?.scrollToEnd?.({ animated });
6390 });
6561 - }, []);
6391 + };
6392 + const scrollToEndStable = useStableCallback(scrollToEnd);
6393 useEffect(() => {
6394 let removeListeners: (() => void) | null = null;
6395 let frame: number | null = null;
@@ -6583,7 +6414,7 @@ export default function ChatView(props: ChatViewProps) {
6414 // while pinned at the end produces no scroll event, never re-arms,
6415 // and streaming silently stops following. Underflowing content can't
6416 // scroll at all, so nothing there should break follow.
6586 - const contentScrollsUp = () => timelineRealContentOverflowsViewport();
6417 + const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();
6418 // The follow re-arm band, not the strict flag: streaming growth makes
6419 // isAtEnd flicker false for a frame before the follow scroll catches
6420 // up, and a gesture landing in that window while still pinned would
@@ -6679,7 +6510,7 @@ export default function ChatView(props: ChatViewProps) {
6510 handleManualNavigation();
6511 }
6512 composerRef.current?.collapseForTimelineScrollKey(event.key);
6682 - if (isTimelineAtLogicalEnd()) {
6513 + if (isTimelineAtLogicalEndStable()) {
6514 composerRef.current?.restoreAfterTimelineReachedEnd();
6515 }
6516 break;
@@ -6713,9 +6544,9 @@ export default function ChatView(props: ChatViewProps) {
6544 }
6545 removeListeners?.();
6546 };
6716 - }, [activeThread?.id, isTimelineAtLogicalEnd, timelineRealContentOverflowsViewport]);
6547 + }, [activeThread?.id, isTimelineAtLogicalEndStable, timelineRealContentOverflowsViewportStable]);
6548
6718 - const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
6549 + const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
6550 if (pendingTimelineAnchorRef.current === messageId) {
6551 pendingTimelineAnchorRef.current = null;
6552 }
@@ -6764,8 +6595,9 @@ export default function ChatView(props: ChatViewProps) {
6595 });
6596 };
6597 requestAnimationFrame(() => positionAnchor(12));
6767 - }, []);
6768 - const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
6598 + };
6599 + const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);
6600 + const onTimelineAnchorSizeChanged = (messageId: MessageId) => {
6601 if (settledTimelineAnchorRef.current !== messageId) {
6602 return;
6603 }
@@ -6805,13 +6637,15 @@ export default function ChatView(props: ChatViewProps) {
6637 }
6638 }
6639 });
6808 - }, []);
6640 + };
6641 + const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged);
6642
6810 - const onToolOutputCollapsedAtEnd = useCallback(() => {
6643 + const onToolOutputCollapsedAtEnd = () => {
6644 composerRef.current?.restoreAfterTimelineReachedEnd();
6812 - }, [composerRef]);
6645 + };
6646 + const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);
6647
6814 - const onIsAtEndChange = useCallback((isAtEnd: boolean) => {
6648 + const onIsAtEndChange = (isAtEnd: boolean) => {
6649 if (
6650 !isAtEnd &&
6651 liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current
@@ -6841,7 +6675,8 @@ export default function ChatView(props: ChatViewProps) {
6675 liveFollowUserScrollGenerationRef.current = null;
6676 showScrollDebouncer.current.maybeExecute();
6677 }
6844 - }, []);
6678 + };
6679 + const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);
6680
6681 useLayoutEffect(() => {
6682 if (timelineScrollModeRef.current !== "anchoring-new-turn") return;
@@ -6853,11 +6688,11 @@ export default function ChatView(props: ChatViewProps) {
6688 timelineEntries,
6689 })
6690 ) {
6856 - scrollToEnd();
6691 + scrollToEndStable();
6692 }
6693 }, [
6694 activeRunningTurnId,
6860 - scrollToEnd,
6695 + scrollToEndStable,
6696 timelineAnchorMessageId,
6697 timelineEntries,
6698 timelineLiveFollowEnabled,
@@ -6885,12 +6720,12 @@ export default function ChatView(props: ChatViewProps) {
6720 useEffect(() => {
6721 if (!activeThread?.id || terminalUiState.terminalOpen) return;
6722 const frame = window.requestAnimationFrame(() => {
6888 - focusComposer();
6723 + focusComposerStable();
6724 });
6725 return () => {
6726 window.cancelAnimationFrame(frame);
6727 };
6893 - }, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]);
6728 + }, [activeThread?.id, focusComposerStable, terminalUiState.terminalOpen]);
6729
6730 // Tabbing back into the app lands focus wherever it last was, often the right panel or the
6731 // body. Put it in the composer unless something that takes typing already holds it. The
@@ -6910,7 +6745,7 @@ export default function ChatView(props: ChatViewProps) {
6745 frame = null;
6746 // A full-screen app owns the page; refocusing the composer would close it.
6747 if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return;
6913 - if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposer();
6748 + if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposerStable();
6749 });
6750 });
6751 };
@@ -6919,7 +6754,7 @@ export default function ChatView(props: ChatViewProps) {
6754 window.removeEventListener("focus", onWindowFocus);
6755 if (frame !== null) window.cancelAnimationFrame(frame);
6756 };
6922 - }, [activeThread?.id, focusComposer, isMobileViewport, terminalUiState.terminalOpen]);
6757 + }, [activeThread?.id, focusComposerStable, isMobileViewport, terminalUiState.terminalOpen]);
6758
6759 useEffect(() => {
6760 if (!activeThread?.id) return;
@@ -6940,7 +6775,7 @@ export default function ChatView(props: ChatViewProps) {
6775 for (const removedMessage of removedMessages) {
6776 const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
6777 if (previewUrls.length > 0) {
6943 - handoffAttachmentPreviews(removedMessage.id, previewUrls);
6778 + handoffAttachmentPreviewsStable(removedMessage.id, previewUrls);
6779 continue;
6780 }
6781 revokeUserMessagePreviewUrls(removedMessage);
@@ -6952,7 +6787,7 @@ export default function ChatView(props: ChatViewProps) {
6787 activeMessageCount,
6788 activeThread?.id,
6789 serverAcknowledgedUserMessageIds,
6955 - handoffAttachmentPreviews,
6790 + handoffAttachmentPreviewsStable,
6791 optimisticUserMessages,
6792 ]);
6793
@@ -6970,9 +6805,10 @@ export default function ChatView(props: ChatViewProps) {
6805 setExpandedImage(null);
6806 }, [resetLocalDispatch, threadId]);
6807
6973 - const closeExpandedImage = useCallback(() => {
6808 + const closeExpandedImage = () => {
6809 setExpandedImage(null);
6975 - }, []);
6810 + };
6811 + const closeExpandedImageStable = useStableCallback(closeExpandedImage);
6812
6813 const activeWorktreePath = activeThread?.worktreePath ?? null;
6814 const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({
@@ -7017,87 +6853,86 @@ export default function ChatView(props: ChatViewProps) {
6853 : null,
6854 [activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
6855 );
7020 - const publishComposerOverlayHeight = useCallback(
7021 - (height: number) => {
7022 - const nextHeight = Math.ceil(height);
7023 - if (nextHeight <= 0) return;
7024 - const isResting = overlayComposerIsResting({
7025 - composerMounted: composerMountedRef.current,
7026 - composerReportedResting: composerRestingRef.current,
7027 - });
7028 - const modelStrip = composerOverlayElement?.querySelector<HTMLElement>(
7029 - '[data-composer-model-strip="true"]',
7030 - );
7031 - // The model-only strip disappears on expansion; counting it again would
7032 - // add 32px of timeline padding as soon as the empty composer collapses.
7033 - const restingOnlyHeight =
7034 - modelStrip && isResting
7035 - ? Math.max(
7036 - 0,
7037 - modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop),
7038 - )
7039 - : 0;
7040 - const nextInset = resolveComposerTimelineInset({
7041 - currentInset: composerTimelineInsetRef.current,
7042 - overlayHeight: nextHeight,
7043 - isResting,
7044 - restingOnlyHeight,
7045 - });
7046 - if (composerTimelineInsetRef.current !== nextInset) {
7047 - composerTimelineInsetRef.current = nextInset;
7048 - setComposerTimelineInset(nextInset);
7049 - }
7050 - const mainSurface = composerOverlayElement?.querySelector<HTMLElement>(
7051 - '[data-chat-composer-main-surface="true"]',
7052 - );
7053 - const button = composerOverlayElement?.parentElement?.querySelector<HTMLElement>(
7054 - 'button[aria-label="Scroll to end"]',
7055 - );
7056 - const clearance =
7057 - composerOverlayElement && mainSurface && button
7058 - ? resolveScrollToEndClearance({
7059 - overlayHeight: nextHeight,
7060 - mainSurfaceTop: mainSurface.getBoundingClientRect().top,
7061 - button: button.getBoundingClientRect(),
7062 - attachments: Array.from(
7063 - composerOverlayElement.querySelectorAll<HTMLElement>(
7064 - '[data-composer-banner-surface="attached"]',
7065 - ),
7066 - (element) => element.getBoundingClientRect(),
6856 + const publishComposerOverlayHeight = (height: number) => {
6857 + const nextHeight = Math.ceil(height);
6858 + if (nextHeight <= 0) return;
6859 + const isResting = overlayComposerIsResting({
6860 + composerMounted: composerMountedRef.current,
6861 + composerReportedResting: composerRestingRef.current,
6862 + });
6863 + const modelStrip = composerOverlayElement?.querySelector<HTMLElement>(
6864 + '[data-composer-model-strip="true"]',
6865 + );
6866 + // The model-only strip disappears on expansion; counting it again would
6867 + // add 32px of timeline padding as soon as the empty composer collapses.
6868 + const restingOnlyHeight =
6869 + modelStrip && isResting
6870 + ? Math.max(
6871 + 0,
6872 + modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop),
6873 + )
6874 + : 0;
6875 + const nextInset = resolveComposerTimelineInset({
6876 + currentInset: composerTimelineInsetRef.current,
6877 + overlayHeight: nextHeight,
6878 + isResting,
6879 + restingOnlyHeight,
6880 + });
6881 + if (composerTimelineInsetRef.current !== nextInset) {
6882 + composerTimelineInsetRef.current = nextInset;
6883 + setComposerTimelineInset(nextInset);
6884 + }
6885 + const mainSurface = composerOverlayElement?.querySelector<HTMLElement>(
6886 + '[data-chat-composer-main-surface="true"]',
6887 + );
6888 + const button = composerOverlayElement?.parentElement?.querySelector<HTMLElement>(
6889 + 'button[aria-label="Scroll to end"]',
6890 + );
6891 + const clearance =
6892 + composerOverlayElement && mainSurface && button
6893 + ? resolveScrollToEndClearance({
6894 + overlayHeight: nextHeight,
6895 + mainSurfaceTop: mainSurface.getBoundingClientRect().top,
6896 + button: button.getBoundingClientRect(),
6897 + attachments: Array.from(
6898 + composerOverlayElement.querySelectorAll<HTMLElement>(
6899 + '[data-composer-banner-surface="attached"]',
6900 ),
7068 - })
7069 - : nextHeight;
7070 - setScrollToEndClearance(clearance);
7071 - },
7072 - [composerOverlayElement],
7073 - );
6901 + (element) => element.getBoundingClientRect(),
6902 + ),
6903 + })
6904 + : nextHeight;
6905 + setScrollToEndClearance(clearance);
6906 + };
6907 + const publishComposerOverlayHeightStable = useStableCallback(publishComposerOverlayHeight);
6908 // The composer reports its resting flag from a layout effect, which runs
6909 // before this component's own layout effects and before any resize
6910 // observation, so every measurement below sees the flag for its layout.
6911 // Only the flag is stored here: the stored height still belongs to the
6912 // previous layout, and the composer publishes the new layout's height
6913 // itself once it has measured it.
7080 - const onComposerRestingChange = useCallback((resting: boolean) => {
6914 + const onComposerRestingChange = (resting: boolean) => {
6915 composerRestingRef.current = resting;
7082 - }, []);
6916 + };
6917 + const onComposerRestingChangeStable = useStableCallback(onComposerRestingChange);
6918 // A held reservation belongs to the previous thread's draft. Rebuild it from
6919 // this thread's overlay so a tall draft elsewhere does not pad this one.
6920 useLayoutEffect(() => {
6921 if (!composerOverlayElement) return;
6922 composerTimelineInsetRef.current = 0;
7088 - publishComposerOverlayHeight(composerOverlayElement.getBoundingClientRect().height);
7089 - }, [activeThreadKey, composerOverlayElement, publishComposerOverlayHeight]);
6923 + publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
6924 + }, [activeThreadKey, composerOverlayElement, publishComposerOverlayHeightStable]);
6925
6926 useLayoutEffect(() => {
6927 if (!composerOverlayElement) return;
6928
6929 const updateHeight = () => {
7095 - publishComposerOverlayHeight(composerOverlayElement.getBoundingClientRect().height);
6930 + publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
6931 };
6932
6933 updateHeight();
6934 return observeResize(composerOverlayElement, updateHeight);
7100 - }, [composerOverlayElement, publishComposerOverlayHeight, showScrollToBottom]);
6935 + }, [composerOverlayElement, publishComposerOverlayHeightStable, showScrollToBottom]);
6936 // Swapping the composer for the status bar (or back) changes what the
6937 // overlay holds, so rebuild the reservation from the new content.
6938 useLayoutEffect(() => {
@@ -7105,8 +6940,8 @@ export default function ChatView(props: ChatViewProps) {
6940 composerMountedRef.current = composerMounted;
6941 if (!composerOverlayElement) return;
6942 composerTimelineInsetRef.current = 0;
7108 - publishComposerOverlayHeight(composerOverlayElement.getBoundingClientRect().height);
7109 - }, [composerMounted, composerOverlayElement, publishComposerOverlayHeight]);
6943 + publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
6944 + }, [composerMounted, composerOverlayElement, publishComposerOverlayHeightStable]);
6945 const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef);
6946 const activeThreadReferenceCopyTarget = useMemo(
6947 () =>
@@ -7126,7 +6961,7 @@ export default function ChatView(props: ChatViewProps) {
6961 openPanelPullRequestUrl,
6962 ],
6963 );
7129 - const copyActiveThreadReference = useCallback(() => {
6964 + const copyActiveThreadReference = () => {
6965 const target = activeThreadReferenceCopyTarget;
6966 if (target === null) return;
6967 void writeTextToClipboard(target.value, target.clipboardTarget).then(
@@ -7149,7 +6984,8 @@ export default function ChatView(props: ChatViewProps) {
6984 );
6985 },
6986 );
7152 - }, [activeThreadReferenceCopyTarget]);
6987 + };
6988 + const copyActiveThreadReferenceStable = useStableCallback(copyActiveThreadReference);
6989 const pullRequestPanelTarget = activeThread
6990 ? threadPullRequestPanelTarget({
6991 projectId: activeThread.projectId,
@@ -7158,11 +6994,12 @@ export default function ChatView(props: ChatViewProps) {
6994 branchPullRequest: activeThreadShell?.branchPullRequest ?? activeThread.branchPullRequest,
6995 })
6996 : null;
7161 - const addPullRequestSurface = useCallback(() => {
6997 + const addPullRequestSurface = () => {
6998 if (!supportsPullRequests || activeThreadRef === null || pullRequestPanelTarget === null)
6999 return;
7000 useRightPanelStore.getState().openPullRequest(activeThreadRef, pullRequestPanelTarget);
7165 - }, [activeThreadRef, pullRequestPanelTarget, supportsPullRequests]);
7001 + };
7002 + const addPullRequestSurfaceStable = useStableCallback(addPullRequestSurface);
7003 const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null;
7004 const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
7005 const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
@@ -7189,10 +7026,11 @@ export default function ChatView(props: ChatViewProps) {
7026 ? threadWokeAt(activeThreadShell, { now: new Date().toISOString() })
7027 : null;
7028 const acknowledgeThreadWoke = useAcknowledgeThreadWoke();
7192 - const acknowledgeActiveThreadWoke = useCallback(() => {
7029 + const acknowledgeActiveThreadWoke = () => {
7030 if (activeThreadRef === null || activeThreadWokeAt === null) return;
7031 acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt);
7195 - }, [acknowledgeThreadWoke, activeThreadRef, activeThreadWokeAt]);
7032 + };
7033 + const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke);
7034 // Mirror of the sidebar's Woke pill for the open thread. Same watermark as
7035 // the sidebar, so an acknowledgement from any device hides it.
7036 const activeThreadLocalVisitedAt = useUiStateStore((store) =>
@@ -7237,7 +7075,7 @@ export default function ChatView(props: ChatViewProps) {
7075 // must never clear (or re-enable) thread B's button.
7076 const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
7077 const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
7240 - const handleUnsettleActiveThread = useCallback(async () => {
7078 + const handleUnsettleActiveThread = async () => {
7079 if (
7080 !activeThreadRef ||
7081 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
@@ -7263,13 +7101,14 @@ export default function ChatView(props: ChatViewProps) {
7101 } finally {
7102 setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
7103 }
7266 - }, [activeThreadRef, unsettleThreadMutation]);
7104 + };
7105 + const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread);
7106 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
7107 reportFailure: false,
7108 });
7109 const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
7110 const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
7272 - const handleUnsnoozeActiveThread = useCallback(async () => {
7111 + const handleUnsnoozeActiveThread = async () => {
7112 if (
7113 !activeThreadRef ||
7114 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
@@ -7309,7 +7148,8 @@ export default function ChatView(props: ChatViewProps) {
7148 } finally {
7149 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
7150 }
7312 - }, [activeThreadRef, activeThreadShell, unsnoozeThreadMutation, updateThreadMetadata]);
7151 + };
7152 + const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
7153 const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
7154 const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
7155 // Once revealed for a given mismatch, the banner stays mounted until the
@@ -7343,7 +7183,7 @@ export default function ChatView(props: ChatViewProps) {
7183 return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;
7184 });
7185 }, [activeBranchMismatchKey, showBranchMismatchBanner]);
7346 - const handleSwitchCheckoutToThread = useCallback(async () => {
7186 + const handleSwitchCheckoutToThread = async () => {
7187 if (!canWriteSourceControl) return;
7188 if (
7189 !activeProjectCwd ||
@@ -7403,18 +7243,7 @@ export default function ChatView(props: ChatViewProps) {
7243 gitStatusQuery.refresh();
7244 setIsRestoringThreadBranch(false);
7245 scheduleComposerFocus();
7406 - }, [
7407 - canWriteSourceControl,
7408 - activeProjectCwd,
7409 - activeThread,
7410 - environmentId,
7411 - gitStatusQuery,
7412 - isRestoringThreadBranch,
7413 - localCheckoutBranchMismatch,
7414 - scheduleComposerFocus,
7415 - switchGitRef,
7416 - updateThreadMetadata,
7417 - ]);
7246 + };
7247 // The stack renders items[0] front-most and tucks the rest behind hover, so
7248 // ordering is priority: system banners, then the branch-mismatch notice,
7249 // and the informational parked-thread banner last — it must never cover another.
@@ -7426,7 +7255,7 @@ export default function ChatView(props: ChatViewProps) {
7255 const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
7256 const isStoppingBackgroundWork =
7257 stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
7429 - const handleStopBackgroundWork = useCallback(async () => {
7258 + const handleStopBackgroundWork = async () => {
7259 if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
7260 return;
7261 const requestKey = `${environmentId}:${activeThread.id}`;
@@ -7447,16 +7276,15 @@ export default function ChatView(props: ChatViewProps) {
7276 );
7277 }
7278 }
7450 - }, [activeThread, environmentId, interruptThreadTurn, setThreadError]);
7451 - const onOpenRelatedThread = useCallback(
7452 - (threadId: ThreadId) => {
7453 - void navigate({
7454 - to: "/$environmentId/$threadId",
7455 - params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
7456 - });
7457 - },
7458 - [environmentId, navigate],
7459 - );
7279 + };
7280 + const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork);
7281 + const onOpenRelatedThread = (threadId: ThreadId) => {
7282 + void navigate({
7283 + to: "/$environmentId/$threadId",
7284 + params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
7285 + });
7286 + };
7287 + const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
7288 const childThreadInputs = useChildThreadInputs(activeThreadRef);
7289 const childInputBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
7290 const first = childThreadInputs[0];
@@ -7473,7 +7301,7 @@ export default function ChatView(props: ChatViewProps) {
7301 <Fragment key={child.id}>
7302 {index > 0 ? " " : null}
7303 <span className="whitespace-nowrap">
7476 - <InlineButton tone="muted" onClick={() => onOpenRelatedThread(child.id)}>
7304 + <InlineButton tone="muted" onClick={() => onOpenRelatedThreadStable(child.id)}>
7305 {child.title}
7306 </InlineButton>
7307 {index < childThreadInputs.length - 1 ? "," : null}
@@ -7481,7 +7309,7 @@ export default function ChatView(props: ChatViewProps) {
7309 </Fragment>
7310 )),
7311 actions: (
7484 - <Button size="xs" variant="ghost" onClick={() => onOpenRelatedThread(first.id)}>
7312 + <Button size="xs" variant="ghost" onClick={() => onOpenRelatedThreadStable(first.id)}>
7313 {first.hasPendingApprovals ? "Open approval" : "Open question"}
7314 </Button>
7315 ),
@@ -7489,95 +7317,78 @@ export default function ChatView(props: ChatViewProps) {
7317 }, [
7318 childThreadInputs,
7319 activePendingApproval,
7492 - activePendingUserInput,
7493 - activeThreadShell?.hasPendingUserInput,
7494 - onOpenRelatedThread,
7495 - ]);
7496 -
7497 - // Commands such as /compact and /goal clear run as their own turn. The draft
7498 - // and its attachments stay local.
7499 - const sendStandaloneCommand = useCallback(
7500 - async (text: string, failureMessage: string) => {
7501 - if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
7502 - const context = composerRef.current?.getSendContext();
7503 - if (!context?.providerAvailable) return;
7504 -
7505 - const threadId = activeThread.id;
7506 - const messageId = newMessageId();
7507 - const createdAt = new Date().toISOString();
7508 - sendInFlightRef.current = true;
7509 - beginLocalDispatch();
7510 - setThreadError(threadId, null);
7511 - setOptimisticUserMessages((messages) => [
7512 - ...messages,
7513 - {
7514 - id: messageId,
7515 - role: "user",
7516 - text,
7517 - runId: null,
7518 - createdAt,
7519 - updatedAt: createdAt,
7520 - streaming: false,
7521 - },
7522 - ]);
7523 - scrollToEnd();
7524 - try {
7525 - const settingsResult = await persistThreadSettingsForNextTurn({
7526 - threadId,
7527 - createdAt,
7528 - ...(localCheckoutBranchMismatch
7529 - ? { branch: localCheckoutBranchMismatch.currentBranch }
7530 - : {}),
7531 - runtimeMode,
7532 - interactionMode: context.interactionMode,
7533 - });
7534 - const result =
7535 - settingsResult._tag === "Failure"
7536 - ? settingsResult
7537 - : await startThreadTurn({
7538 - environmentId,
7539 - input: {
7540 - threadId,
7541 - message: { messageId, role: "user", text, attachments: [] },
7542 - modelSelection: context.selectedModelSelection,
7543 - runtimeMode,
7544 - interactionMode: context.interactionMode,
7545 - createdAt,
7546 - },
7547 - });
7548 - if (result._tag === "Failure") {
7549 - setOptimisticUserMessages((messages) =>
7550 - messages.filter((message) => message.id !== messageId),
7551 - );
7552 - resetLocalDispatch();
7553 - if (!isAtomCommandInterrupted(result)) {
7554 - const error = squashAtomCommandFailure(result);
7555 - setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
7556 - }
7557 - } else {
7558 - clearUsageLimitsFor(routeThreadKey);
7320 + activePendingUserInput,
7321 + activeThreadShell?.hasPendingUserInput,
7322 + onOpenRelatedThreadStable,
7323 + ]);
7324 +
7325 + // Commands such as /compact and /goal clear run as their own turn. The draft
7326 + // and its attachments stay local.
7327 + const sendStandaloneCommand = async (text: string, failureMessage: string) => {
7328 + if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
7329 + const context = composerRef.current?.getSendContext();
7330 + if (!context?.providerAvailable) return;
7331 +
7332 + const threadId = activeThread.id;
7333 + const messageId = newMessageId();
7334 + const createdAt = new Date().toISOString();
7335 + sendInFlightRef.current = true;
7336 + beginLocalDispatch();
7337 + setThreadError(threadId, null);
7338 + setOptimisticUserMessages((messages) => [
7339 + ...messages,
7340 + {
7341 + id: messageId,
7342 + role: "user",
7343 + text,
7344 + runId: null,
7345 + createdAt,
7346 + updatedAt: createdAt,
7347 + streaming: false,
7348 + },
7349 + ]);
7350 + scrollToEnd();
7351 + try {
7352 + const settingsResult = await persistThreadSettingsForNextTurn({
7353 + threadId,
7354 + createdAt,
7355 + ...(localCheckoutBranchMismatch
7356 + ? { branch: localCheckoutBranchMismatch.currentBranch }
7357 + : {}),
7358 + runtimeMode,
7359 + interactionMode: context.interactionMode,
7360 + });
7361 + const result =
7362 + settingsResult._tag === "Failure"
7363 + ? settingsResult
7364 + : await startThreadTurn({
7365 + environmentId,
7366 + input: {
7367 + threadId,
7368 + message: { messageId, role: "user", text, attachments: [] },
7369 + modelSelection: context.selectedModelSelection,
7370 + runtimeMode,
7371 + interactionMode: context.interactionMode,
7372 + createdAt,
7373 + },
7374 + });
7375 + if (result._tag === "Failure") {
7376 + setOptimisticUserMessages((messages) =>
7377 + messages.filter((message) => message.id !== messageId),
7378 + );
7379 + resetLocalDispatch();
7380 + if (!isAtomCommandInterrupted(result)) {
7381 + const error = squashAtomCommandFailure(result);
7382 + setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
7383 }
7560 - } finally {
7561 - sendInFlightRef.current = false;
7384 + } else {
7385 + clearUsageLimitsFor(routeThreadKey);
7386 }
7563 - },
7564 - [
7565 - activeThread,
7566 - beginLocalDispatch,
7567 - clientSettingsHydrated,
7568 - composerRef,
7569 - environmentId,
7570 - localCheckoutBranchMismatch,
7571 - persistThreadSettingsForNextTurn,
7572 - resetLocalDispatch,
7573 - routeThreadKey,
7574 - runtimeMode,
7575 - scrollToEnd,
7576 - sendInFlightRef,
7577 - setThreadError,
7578 - startThreadTurn,
7579 - ],
7580 - );
7387 + } finally {
7388 + sendInFlightRef.current = false;
7389 + }
7390 + };
7391 + const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
7392 // A native /goal keeps the agent working across turns. Stop pauses a Codex
7393 // goal; once the thread is idle the row offers the native follow-ups.
7394 const activeGoal = activeThreadShell?.goal ?? null;
@@ -7601,7 +7412,9 @@ export default function ChatView(props: ChatViewProps) {
7412 <Button
7413 size="xs"
7414 variant="ghost"
7604 - onClick={() => void sendStandaloneCommand("/goal resume", "Failed to resume goal.")}
7415 + onClick={() =>
7416 + void sendStandaloneCommandStable("/goal resume", "Failed to resume goal.")
7417 + }
7418 >
7419 Resume
7420 </Button>
@@ -7609,14 +7422,14 @@ export default function ChatView(props: ChatViewProps) {
7422 <Button
7423 size="xs"
7424 variant="ghost"
7612 - onClick={() => void sendStandaloneCommand("/goal clear", "Failed to clear goal.")}
7425 + onClick={() => void sendStandaloneCommandStable("/goal clear", "Failed to clear goal.")}
7426 >
7427 Clear
7428 </Button>
7429 </>
7430 ),
7431 };
7619 - }, [activeGoal, activeThread, isWorking, sendStandaloneCommand]);
7432 + }, [activeGoal, activeThread, isWorking, sendStandaloneCommandStable]);
7433
7434 const backgroundWorkBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
7435 const presentation = presentPendingBackgroundWork(activeBackgroundTasks);
@@ -7659,7 +7472,7 @@ export default function ChatView(props: ChatViewProps) {
7472 <InlineButton
7473 tone="muted"
7474 aria-label={`Open subagent ${item.label}`}
7662 - onClick={() => onOpenRelatedThread(childThreadId)}
7475 + onClick={() => onOpenRelatedThreadStable(childThreadId)}
7476 >
7477 {item.label}
7478 </InlineButton>
@@ -7674,7 +7487,7 @@ export default function ChatView(props: ChatViewProps) {
7487 size="xs"
7488 variant="ghost"
7489 disabled={!canOperateThread || isStoppingBackgroundWork}
7677 - onClick={() => void handleStopBackgroundWork()}
7490 + onClick={() => void handleStopBackgroundWorkStable()}
7491 >
7492 {isStoppingBackgroundWork ? "Stopping..." : "Stop"}
7493 </Button>
@@ -7684,9 +7497,9 @@ export default function ChatView(props: ChatViewProps) {
7497 activeBackgroundTasks,
7498 activeThread,
7499 canOperateThread,
7687 - handleStopBackgroundWork,
7500 + handleStopBackgroundWorkStable,
7501 isStoppingBackgroundWork,
7689 - onOpenRelatedThread,
7502 + onOpenRelatedThreadStable,
7503 ]);
7504 // Settled, snoozed, and woke are thread state, not composer actions: each
7505 // gets one quiet line after the last message instead of a banner. A woken
@@ -7707,7 +7520,7 @@ export default function ChatView(props: ChatViewProps) {
7520 }
7521 actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
7522 actionDisabled={!canOperateThread || isUnsnoozing}
7710 - onAction={() => void handleUnsnoozeActiveThread()}
7523 + onAction={() => void handleUnsnoozeActiveThreadStable()}
7524 />
7525 ) : activeThreadSettled ? (
7526 <ThreadStatusLine
@@ -7719,26 +7532,26 @@ export default function ChatView(props: ChatViewProps) {
7532 }
7533 actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
7534 actionDisabled={!canOperateThread || isUnsettling}
7722 - onAction={() => void handleUnsettleActiveThread()}
7535 + onAction={() => void handleUnsettleActiveThreadStable()}
7536 />
7537 ) : activeThreadWokeVisible ? (
7538 <ThreadStatusLine
7539 icon={<AlarmClockIcon />}
7540 label="Woke from snooze"
7541 actionLabel="Dismiss"
7729 - onAction={acknowledgeActiveThreadWoke}
7542 + onAction={acknowledgeActiveThreadWokeStable}
7543 />
7544 ) : null;
7545 }, [
7733 - acknowledgeActiveThreadWoke,
7546 + acknowledgeActiveThreadWokeStable,
7547 activeThreadSettled,
7548 activeThreadShell?.settledAt,
7549 activeThreadShell?.snoozedUntil,
7550 activeThreadSnoozed,
7551 activeThreadWokeVisible,
7552 canOperateThread,
7740 - handleUnsettleActiveThread,
7741 - handleUnsnoozeActiveThread,
7553 + handleUnsettleActiveThreadStable,
7554 + handleUnsnoozeActiveThreadStable,
7555 isUnsettling,
7556 isUnsnoozing,
7557 nowMinute,
@@ -7815,7 +7628,7 @@ export default function ChatView(props: ChatViewProps) {
7628 () => new Set(),
7629 );
7630 const keepFullHistory = fullHistoryThreadKeys.has(routeThreadKey);
7818 - const setKeepFullHistory = useCallback((threadKey: string, keep: boolean) => {
7631 + const setKeepFullHistory = (threadKey: string, keep: boolean) => {
7632 setFullHistoryThreadKeys((current) => {
7633 if (current.has(threadKey) === keep) return current;
7634 const next = new Set(current);
@@ -7823,23 +7636,18 @@ export default function ChatView(props: ChatViewProps) {
7636 else next.delete(threadKey);
7637 return next;
7638 });
7826 - }, []);
7827 - const toggleKeepFullHistory = useCallback(
7828 - () => setKeepFullHistory(routeThreadKey, !keepFullHistory),
7829 - [keepFullHistory, routeThreadKey, setKeepFullHistory],
7830 - );
7831 - const handleRestoreThreadBranch = useCallback(() => {
7639 + };
7640 + const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory);
7641 + const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory);
7642 + const handleRestoreThreadBranch = () => {
7643 if (!canWriteSourceControl) return;
7644 if (gitStatusQuery.data?.hasWorkingTreeChanges) {
7645 setBranchRestoreConfirmOpen(true);
7646 return;
7647 }
7648 void handleSwitchCheckoutToThread();
7838 - }, [
7839 - canWriteSourceControl,
7840 - gitStatusQuery.data?.hasWorkingTreeChanges,
7841 - handleSwitchCheckoutToThread,
7842 - ]);
7649 + };
7650 + const handleRestoreThreadBranchStable = useStableCallback(handleRestoreThreadBranch);
7651 const feedbackBannerItems = useMemo(
7652 () =>
7653 feedbackSubmissions.flatMap((submission) => {
@@ -7929,7 +7737,7 @@ export default function ChatView(props: ChatViewProps) {
7737 size="xs"
7738 variant="ghost"
7739 disabled={!canWriteSourceControl || isRestoringThreadBranch}
7932 - onClick={handleRestoreThreadBranch}
7740 + onClick={handleRestoreThreadBranchStable}
7741 >
7742 {isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
7743 </Button>
@@ -7948,7 +7756,7 @@ export default function ChatView(props: ChatViewProps) {
7756 canWriteSourceControl,
7757 feedbackBannerItems,
7758 limitRecoveryBanner,
7951 - handleRestoreThreadBranch,
7759 + handleRestoreThreadBranchStable,
7760 isRestoringThreadBranch,
7761 backgroundWorkBannerItem,
7762 childInputBannerItem,
@@ -8028,7 +7836,7 @@ export default function ChatView(props: ChatViewProps) {
7836 } else if (previous && !current) {
7837 terminalUiOpenByThreadRef.current[activeThreadKey] = current;
7838 const frame = window.requestAnimationFrame(() => {
8031 - focusComposer();
7839 + focusComposerStable();
7840 });
7841 return () => {
7842 window.cancelAnimationFrame(frame);
@@ -8036,31 +7844,31 @@ export default function ChatView(props: ChatViewProps) {
7844 }
7845
7846 terminalUiOpenByThreadRef.current[activeThreadKey] = current;
8039 - }, [activeThreadKey, focusComposer, terminalUiState.terminalOpen]);
8040 -
8041 - const getShortcutContext = useCallback(
8042 - (eventTarget: EventTarget | null = document.activeElement) => ({
8043 - terminalFocus: getTerminalFocusOwner() !== null,
8044 - terminalOpen: Boolean(terminalUiState.terminalOpen),
8045 - previewFocus: isPreviewFocused(),
8046 - previewOpen: previewPanelOpen,
8047 - editableFocus: isEditableFocused(eventTarget),
8048 - modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
8049 - composerFocus: document.activeElement?.getAttribute("data-testid") === "composer-editor",
8050 - draftThreadRoute: routeKind === "draft",
8051 - turnRunning: phase === "running",
8052 - isWeb: !isElectron,
8053 - isDesktop: isElectron,
8054 - }),
8055 - [composerRef, previewPanelOpen, terminalUiState.terminalOpen, routeKind, phase],
8056 - );
7847 + }, [activeThreadKey, focusComposerStable, terminalUiState.terminalOpen]);
7848 +
7849 + const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({
7850 + terminalFocus: getTerminalFocusOwner() !== null,
7851 + terminalOpen: Boolean(terminalUiState.terminalOpen),
7852 + previewFocus: isPreviewFocused(),
7853 + previewOpen: previewPanelOpen,
7854 + editableFocus: isEditableFocused(eventTarget),
7855 + modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
7856 + composerFocus: document.activeElement?.getAttribute("data-testid") === "composer-editor",
7857 + draftThreadRoute: routeKind === "draft",
7858 + turnRunning: phase === "running",
7859 + isWeb: !isElectron,
7860 + isDesktop: isElectron,
7861 + });
7862 + const getShortcutContextStable = useStableCallback(getShortcutContext);
7863 const timelineSkills = activeProviderStatus
7864 ? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)
7865 : EMPTY_PROVIDER_SKILLS;
7866 const threadFindControlsRef = useRef<ThreadFindControls | null>(null);
7867 const [isThreadFindActive, setIsThreadFindActive] = useState(false);
8062 - const openThreadFind = useCallback(() => threadFindControlsRef.current?.open(), []);
8063 - const closeThreadFind = useCallback(() => threadFindControlsRef.current?.close(), []);
7868 + const openThreadFind = () => threadFindControlsRef.current?.open();
7869 + const openThreadFindStable = useStableCallback(openThreadFind);
7870 + const closeThreadFind = () => threadFindControlsRef.current?.close();
7871 + const closeThreadFindStable = useStableCallback(closeThreadFind);
7872
7873 useEffect(() => {
7874 const handler = (event: globalThis.KeyboardEvent) => {
@@ -8081,7 +7889,7 @@ export default function ChatView(props: ChatViewProps) {
7889 if (event.defaultPrevented && terminalFocusOwner === null) {
7890 return;
7891 }
8084 - const shortcutContext = getShortcutContext(event.target);
7892 + const shortcutContext = getShortcutContextStable(event.target);
7893
7894 if (
7895 !shortcutContext.terminalFocus &&
@@ -8103,7 +7911,7 @@ export default function ChatView(props: ChatViewProps) {
7911 if (command === "thread.copyReference") {
7912 event.preventDefault();
7913 event.stopPropagation();
8106 - if (!event.repeat) copyActiveThreadReference();
7914 + if (!event.repeat) copyActiveThreadReferenceStable();
7915 return;
7916 }
7917
@@ -8113,7 +7921,7 @@ export default function ChatView(props: ChatViewProps) {
7921 event.stopPropagation();
7922 if (!isServerThread || !activeThreadRef || !supportsSettlement) return;
7923 if (activeThreadSettled) {
8116 - void handleUnsettleActiveThread();
7924 + void handleUnsettleActiveThreadStable();
7925 return;
7926 }
7927 // Same as the sidebar Settle button: settle, then open the next thread.
@@ -8159,7 +7967,7 @@ export default function ChatView(props: ChatViewProps) {
7967 if (!terminalUiState.terminalOpen && !canReadTerminal && !canOperateTerminal) return;
7968 event.preventDefault();
7969 event.stopPropagation();
8162 - toggleTerminalVisibility();
7970 + toggleTerminalVisibilityStable();
7971 return;
7972 }
7973
@@ -8167,28 +7975,28 @@ export default function ChatView(props: ChatViewProps) {
7975 if (command === "chat.find" && isServerThread && serverConfig?.threadFind === true) {
7976 event.preventDefault();
7977 event.stopPropagation();
8170 - openThreadFind();
7978 + openThreadFindStable();
7979 return;
7980 }
7981
7982 if (command === "rightPanel.toggle") {
7983 event.preventDefault();
7984 event.stopPropagation();
8177 - toggleRightPanel();
7985 + toggleRightPanelStable();
7986 return;
7987 }
7988
7989 if (command === "rightPanel.toggleMaximized") {
7990 event.preventDefault();
7991 event.stopPropagation();
8184 - if (!event.repeat) toggleRightPanelMaximized();
7992 + if (!event.repeat) toggleRightPanelMaximizedStable();
7993 return;
7994 }
7995
7996 if (command === "threadPanel.toggle") {
7997 event.preventDefault();
7998 event.stopPropagation();
8191 - toggleThreadPanel();
7999 + toggleThreadPanelStable();
8000 return;
8001 }
8002
@@ -8198,7 +8006,7 @@ export default function ChatView(props: ChatViewProps) {
8006 if (!activeRightPanelSurface) return;
8007 event.preventDefault();
8008 event.stopPropagation();
8201 - if (!event.repeat) closeRightPanelSurface(activeRightPanelSurface);
8009 + if (!event.repeat) closeRightPanelSurfaceStable(activeRightPanelSurface);
8010 return;
8011 }
8012
@@ -8209,13 +8017,13 @@ export default function ChatView(props: ChatViewProps) {
8017 event.preventDefault();
8018 event.stopPropagation();
8019 if (terminalFocusOwner === "right-panel") {
8212 - splitPanelTerminal();
8020 + splitPanelTerminalStable();
8021 return;
8022 }
8023 if (!terminalUiState.terminalOpen) {
8216 - setTerminalOpen(true);
8024 + setTerminalOpenStable(true);
8025 }
8218 - splitTerminal();
8026 + splitTerminalStable();
8027 return;
8028 }
8029
@@ -8226,13 +8034,13 @@ export default function ChatView(props: ChatViewProps) {
8034 event.preventDefault();
8035 event.stopPropagation();
8036 if (terminalFocusOwner === "right-panel") {
8229 - splitPanelTerminal("vertical");
8037 + splitPanelTerminalStable("vertical");
8038 return;
8039 }
8040 if (!terminalUiState.terminalOpen) {
8233 - setTerminalOpen(true);
8041 + setTerminalOpenStable(true);
8042 }
8235 - splitTerminal("vertical");
8043 + splitTerminalStable("vertical");
8044 return;
8045 }
8046
@@ -8243,11 +8051,11 @@ export default function ChatView(props: ChatViewProps) {
8051 event.preventDefault();
8052 event.stopPropagation();
8053 if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") {
8246 - requestClosePanelTerminal(activeRightPanelSurface.activeTerminalId);
8054 + requestClosePanelTerminalStable(activeRightPanelSurface.activeTerminalId);
8055 return;
8056 }
8057 if (!terminalUiState.terminalOpen) return;
8250 - requestCloseTerminal(terminalUiState.activeTerminalId);
8058 + requestCloseTerminalStable(terminalUiState.activeTerminalId);
8059 return;
8060 }
8061
@@ -8258,20 +8066,20 @@ export default function ChatView(props: ChatViewProps) {
8066 event.preventDefault();
8067 event.stopPropagation();
8068 if (terminalFocusOwner === "right-panel") {
8261 - addTerminalSurface();
8069 + addTerminalSurfaceStable();
8070 return;
8071 }
8072 if (!terminalUiState.terminalOpen) {
8265 - setTerminalOpen(true);
8073 + setTerminalOpenStable(true);
8074 }
8267 - createNewTerminal();
8075 + createNewTerminalStable();
8076 return;
8077 }
8078
8079 if (command === "diff.toggle") {
8080 event.preventDefault();
8081 event.stopPropagation();
8274 - onToggleDiff();
8082 + onToggleDiffStable();
8083 return;
8084 }
8085
@@ -8305,7 +8113,7 @@ export default function ChatView(props: ChatViewProps) {
8113 (env) => env.environmentId === currentId,
8114 );
8115 const next = logicalProjectEnvironments[(index + 1) % logicalProjectEnvironments.length];
8308 - if (next) onEnvironmentChange(next.environmentId);
8116 + if (next) onEnvironmentChangeStable(next.environmentId);
8117 return;
8118 }
8119
@@ -8348,7 +8156,7 @@ export default function ChatView(props: ChatViewProps) {
8156 event.preventDefault();
8157 event.stopPropagation();
8158 if (event.repeat) return;
8351 - void onInterrupt();
8159 + void onInterruptStable();
8160 return;
8161 }
8162
@@ -8358,7 +8166,7 @@ export default function ChatView(props: ChatViewProps) {
8166 if (!script) return;
8167 event.preventDefault();
8168 event.stopPropagation();
8361 - void runProjectScript(script);
8169 + void runProjectScriptStable(script);
8170 };
8171 const dismissFind = (event: KeyboardEvent) => {
8172 if (
@@ -8370,11 +8178,11 @@ export default function ChatView(props: ChatViewProps) {
8178 isCommandPaletteOpen()
8179 )
8180 return;
8373 - const context = getShortcutContext(event.target);
8181 + const context = getShortcutContextStable(event.target);
8182 if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return;
8183 event.preventDefault();
8376 - closeThreadFind();
8377 - focusComposer();
8184 + closeThreadFindStable();
8185 + focusComposerStable();
8186 };
8187 window.addEventListener("keydown", handler, true);
8188 window.addEventListener("keydown", dismissFind);
@@ -8388,7 +8196,7 @@ export default function ChatView(props: ChatViewProps) {
8196 activeProjectScripts,
8197 canReadTerminal,
8198 canOperateTerminal,
8391 - addTerminalSurface,
8199 + addTerminalSurfaceStable,
8200 activeThreadRef,
8201 activeThreadPinned,
8202 activeThreadSettled,
@@ -8396,51 +8204,51 @@ export default function ChatView(props: ChatViewProps) {
8204 terminalUiState.terminalOpen,
8205 terminalUiState.activeTerminalId,
8206 activeThreadId,
8399 - closeRightPanelSurface,
8400 - requestCloseTerminal,
8401 - requestClosePanelTerminal,
8402 - createNewTerminal,
8403 - setTerminalOpen,
8404 - runProjectScript,
8405 - splitTerminal,
8406 - splitPanelTerminal,
8207 + closeRightPanelSurfaceStable,
8208 + requestCloseTerminalStable,
8209 + requestClosePanelTerminalStable,
8210 + createNewTerminalStable,
8211 + setTerminalOpenStable,
8212 + runProjectScriptStable,
8213 + splitTerminalStable,
8214 + splitPanelTerminalStable,
8215 keybindings,
8216 scriptKeybindings,
8409 - handleUnsettleActiveThread,
8217 + handleUnsettleActiveThreadStable,
8218 isServerThread,
8219 serverConfig?.threadFind,
8412 - onInterrupt,
8413 - onToggleDiff,
8220 + onInterruptStable,
8221 + onToggleDiffStable,
8222 pinThread,
8223 settleThread,
8224 supportsPinning,
8225 supportsSettlement,
8226 confirmAndUnpinThread,
8419 - copyActiveThreadReference,
8420 - getShortcutContext,
8421 - openThreadFind,
8422 - closeThreadFind,
8227 + copyActiveThreadReferenceStable,
8228 + getShortcutContextStable,
8229 + openThreadFindStable,
8230 + closeThreadFindStable,
8231 isThreadFindActive,
8424 - toggleRightPanel,
8425 - toggleRightPanelMaximized,
8426 - toggleThreadPanel,
8427 - toggleTerminalVisibility,
8232 + toggleRightPanelStable,
8233 + toggleRightPanelMaximizedStable,
8234 + toggleThreadPanelStable,
8235 + toggleTerminalVisibilityStable,
8236 composerRef,
8237 draftId,
8238 environmentId,
8239 envLocked,
8240 hasMultipleEnvironments,
8241 logicalProjectEnvironments,
8434 - onEnvironmentChange,
8242 + onEnvironmentChangeStable,
8243 ]);
8244
8245 // A focused desktop browser page forwards these chords as menu actions.
8246 useEffect(() => {
8247 return window.desktopBridge?.onMenuAction((action) => {
8440 - if (action === "rightPanel.toggle") toggleRightPanel();
8441 - else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximized();
8248 + if (action === "rightPanel.toggle") toggleRightPanelStable();
8249 + else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximizedStable();
8250 });
8443 - }, [toggleRightPanel, toggleRightPanelMaximized]);
8251 + }, [toggleRightPanelStable, toggleRightPanelMaximizedStable]);
8252
8253 // Paste-to-focus: the resting composer blurs on a click into the timeline,
8254 // so a paste that follows has no editable target and would be dropped.
@@ -8490,266 +8298,233 @@ export default function ChatView(props: ChatViewProps) {
8298 setPendingRevert(null);
8299 }
8300
8493 - const onRevertToTurnCount = useCallback(
8494 - async (turnCount: number, messageId: MessageId, restoreFiles?: boolean) => {
8495 - const localApi = readLocalApi();
8496 - if (
8497 - !localApi ||
8498 - !activeThread ||
8499 - isRevertingCheckpoint ||
8500 - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
8501 - )
8502 - return;
8503 - const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId);
8504 - const message = sourceMessage
8505 - ? {
8506 - id: sourceMessage.id,
8507 - role: sourceMessage.role,
8508 - text: sourceMessage.text,
8509 - attachments: sourceMessage.attachments,
8510 - context: sourceMessage.context,
8511 - runId: sourceMessage.runId,
8512 - streaming: false,
8513 - createdAt: DateTime.formatIso(sourceMessage.createdAt),
8514 - updatedAt: DateTime.formatIso(sourceMessage.updatedAt),
8515 - }
8516 - : undefined;
8517 - if (!message || message.role !== "user") return;
8301 + const onRevertToTurnCount = async (
8302 + turnCount: number,
8303 + messageId: MessageId,
8304 + restoreFiles?: boolean,
8305 + ) => {
8306 + const localApi = readLocalApi();
8307 + if (
8308 + !localApi ||
8309 + !activeThread ||
8310 + isRevertingCheckpoint ||
8311 + !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
8312 + )
8313 + return;
8314 + const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId);
8315 + const message = sourceMessage
8316 + ? {
8317 + id: sourceMessage.id,
8318 + role: sourceMessage.role,
8319 + text: sourceMessage.text,
8320 + attachments: sourceMessage.attachments,
8321 + context: sourceMessage.context,
8322 + runId: sourceMessage.runId,
8323 + streaming: false,
8324 + createdAt: DateTime.formatIso(sourceMessage.createdAt),
8325 + updatedAt: DateTime.formatIso(sourceMessage.updatedAt),
8326 + }
8327 + : undefined;
8328 + if (!message || message.role !== "user") return;
8329
8519 - if (!supportsConversationRollback) {
8520 - setThreadError(
8521 - activeThread.id,
8522 - "This provider does not support reverting conversation history. Start a new thread instead.",
8523 - );
8524 - return;
8330 + if (!supportsConversationRollback) {
8331 + setThreadError(
8332 + activeThread.id,
8333 + "This provider does not support reverting conversation history. Start a new thread instead.",
8334 + );
8335 + return;
8336 + }
8337 + if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
8338 + setThreadError(
8339 + activeThread.id,
8340 + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
8341 + );
8342 + return;
8343 + }
8344 + if (phase === "running" || isSendBusy || isConnecting) {
8345 + setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
8346 + return;
8347 + }
8348 + if (restoreFiles === undefined) {
8349 + setPendingRevert({ turnCount, messageId, routeThreadKey });
8350 + return;
8351 + }
8352 +
8353 + useComposerDraftStore.setState((store) => ({
8354 + rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
8355 + }));
8356 + setThreadError(activeThread.id, null);
8357 + try {
8358 + if (composerRef.current?.hasPendingAttachments()) {
8359 + throw new Error("Wait for attachments to finish preparing before rewinding.");
8360 }
8526 - if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
8527 - setThreadError(
8528 - activeThread.id,
8529 - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
8361 + const connection = readPreparedConnection(environmentId);
8362 + if (!connection) throw new Error("The environment is not connected.");
8363 + const files = await prepareRevertedMessageAttachments({
8364 + message,
8365 + environmentId,
8366 + httpBaseUrl: connection.httpBaseUrl,
8367 + createAssetUrl: createAttachmentAssetUrl,
8368 + });
8369 + const store = useComposerDraftStore.getState();
8370 + const draft = store.getComposerDraft(composerDraftTarget);
8371 + if (
8372 + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
8373 + PROVIDER_SEND_TURN_MAX_ATTACHMENTS
8374 + ) {
8375 + throw new Error(
8376 + "Make room for this message's attachments in the composer before rewinding.",
8377 );
8531 - return;
8532 - }
8533 - if (phase === "running" || isSendBusy || isConnecting) {
8534 - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
8535 - return;
8536 - }
8537 - if (restoreFiles === undefined) {
8538 - setPendingRevert({ turnCount, messageId, routeThreadKey });
8539 - return;
8378 }
8541 -
8542 - useComposerDraftStore.setState((store) => ({
8543 - rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
8544 - }));
8545 - setThreadError(activeThread.id, null);
8546 - try {
8547 - if (composerRef.current?.hasPendingAttachments()) {
8548 - throw new Error("Wait for attachments to finish preparing before rewinding.");
8549 - }
8550 - const connection = readPreparedConnection(environmentId);
8551 - if (!connection) throw new Error("The environment is not connected.");
8552 - const files = await prepareRevertedMessageAttachments({
8553 - message,
8379 + const commandId = CommandId.make(randomUUID());
8380 + await waitForRevertedMessage(routeThreadRef, messageId, turnCount, commandId, async () => {
8381 + const result = await revertThreadCheckpoint({
8382 environmentId,
8555 - httpBaseUrl: connection.httpBaseUrl,
8556 - createAssetUrl: createAttachmentAssetUrl,
8557 - });
8558 - const store = useComposerDraftStore.getState();
8559 - const draft = store.getComposerDraft(composerDraftTarget);
8560 - if (
8561 - (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
8562 - PROVIDER_SEND_TURN_MAX_ATTACHMENTS
8563 - ) {
8564 - throw new Error(
8565 - "Make room for this message's attachments in the composer before rewinding.",
8566 - );
8567 - }
8568 - const commandId = CommandId.make(randomUUID());
8569 - await waitForRevertedMessage(routeThreadRef, messageId, turnCount, commandId, async () => {
8570 - const result = await revertThreadCheckpoint({
8571 - environmentId,
8572 - input: { commandId, threadId: activeThread.id, turnCount, restoreFiles },
8573 - });
8574 - if (result._tag === "Failure") throw squashAtomCommandFailure(result);
8383 + input: { commandId, threadId: activeThread.id, turnCount, restoreFiles },
8384 });
8576 - const currentPrompt = store.getComposerDraft(composerDraftTarget)?.prompt ?? "";
8577 - const restoredPrompt = recallableComposerPrompt(message.text);
8578 - const nextPrompt =
8579 - restoredPrompt.length === 0
8580 - ? currentPrompt
8581 - : currentPrompt.length > 0
8582 - ? `${currentPrompt}\n\n${restoredPrompt}`
8583 - : restoredPrompt;
8584 - store.setPrompt(composerDraftTarget, nextPrompt);
8585 - const images: ComposerImageAttachment[] = [];
8586 - const restoredFiles: ComposerFileAttachment[] = [];
8587 - files.forEach((file, index) => {
8588 - const attachment = {
8589 - id: randomUUID(),
8590 - name: file.name,
8591 - mimeType: file.type,
8592 - sizeBytes: file.size,
8593 - file,
8594 - };
8595 - if (message.attachments?.[index]?.type === "image") {
8596 - images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
8597 - } else {
8598 - restoredFiles.push({ ...attachment, type: "file" });
8599 - }
8600 - });
8601 - store.addImages(composerDraftTarget, images, { allowDuplicates: true });
8602 - store.addFiles(composerDraftTarget, restoredFiles, { allowDuplicates: true });
8603 - if (currentRouteThreadKeyRef.current === routeThreadKey) {
8604 - promptRef.current = nextPrompt;
8605 - composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
8606 - requestAnimationFrame(() => {
8607 - if (currentRouteThreadKeyRef.current === routeThreadKey)
8608 - composerRef.current?.focusAtEnd();
8609 - });
8385 + if (result._tag === "Failure") throw squashAtomCommandFailure(result);
8386 + });
8387 + const currentPrompt = store.getComposerDraft(composerDraftTarget)?.prompt ?? "";
8388 + const restoredPrompt = recallableComposerPrompt(message.text);
8389 + const nextPrompt =
8390 + restoredPrompt.length === 0
8391 + ? currentPrompt
8392 + : currentPrompt.length > 0
8393 + ? `${currentPrompt}\n\n${restoredPrompt}`
8394 + : restoredPrompt;
8395 + store.setPrompt(composerDraftTarget, nextPrompt);
8396 + const images: ComposerImageAttachment[] = [];
8397 + const restoredFiles: ComposerFileAttachment[] = [];
8398 + files.forEach((file, index) => {
8399 + const attachment = {
8400 + id: randomUUID(),
8401 + name: file.name,
8402 + mimeType: file.type,
8403 + sizeBytes: file.size,
8404 + file,
8405 + };
8406 + if (message.attachments?.[index]?.type === "image") {
8407 + images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
8408 + } else {
8409 + restoredFiles.push({ ...attachment, type: "file" });
8410 }
8611 - } catch (error) {
8612 - setThreadError(
8613 - activeThread.id,
8614 - error instanceof Error ? error.message : "Failed to revert thread state.",
8615 - );
8616 - } finally {
8617 - useComposerDraftStore.setState((store) => {
8618 - const remaining = new Set(store.rewindingThreadKeys);
8619 - remaining.delete(routeThreadKey);
8620 - return { rewindingThreadKeys: remaining };
8621 - });
8622 - }
8623 - },
8624 - [
8625 - activeThread,
8626 - activeEnvironmentUnavailable,
8627 - activeEnvironmentUnavailableLabel,
8628 - composerDraftTarget,
8629 - composerRef,
8630 - createAttachmentAssetUrl,
8631 - environmentId,
8632 - isConnecting,
8633 - isRevertingCheckpoint,
8634 - isSendBusy,
8635 - phase,
8636 - revertThreadCheckpoint,
8637 - routeThreadKey,
8638 - routeThreadRef,
8639 - setThreadError,
8640 - supportsConversationRollback,
8641 - serverProjection,
8642 - ],
8643 - );
8644 -
8645 - const onRollbackCheckpoint = useCallback(
8646 - async (input: { readonly checkpointId: string; readonly scopeId: string }) => {
8647 - if (!activeThread || isRevertingCheckpoint) return;
8648 - if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
8649 - setThreadError(
8650 - activeThread.id,
8651 - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
8652 - );
8653 - return;
8654 - }
8655 - if (phase === "running" || isSendBusy || isConnecting) {
8656 - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
8657 - return;
8658 - }
8659 - const localApi = readLocalApi();
8660 - const confirmed =
8661 - localApi == null
8662 - ? window.confirm("Roll back this thread to the selected checkpoint?")
8663 - : await localApi.dialogs.confirm(
8664 - "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.",
8665 - );
8666 - if (!confirmed) return;
8667 -
8668 - useComposerDraftStore.setState((store) => ({
8669 - rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
8670 - }));
8671 - setThreadError(activeThread.id, null);
8672 - const result = await revertThreadCheckpoint({
8673 - environmentId,
8674 - input: {
8675 - threadId: activeThread.id,
8676 - checkpointId: input.checkpointId,
8677 - scopeId: input.scopeId,
8678 - },
8411 });
8680 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
8681 - const error = squashAtomCommandFailure(result);
8682 - setThreadError(
8683 - activeThread.id,
8684 - error instanceof Error ? error.message : "Failed to revert thread state.",
8685 - );
8412 + store.addImages(composerDraftTarget, images, { allowDuplicates: true });
8413 + store.addFiles(composerDraftTarget, restoredFiles, { allowDuplicates: true });
8414 + if (currentRouteThreadKeyRef.current === routeThreadKey) {
8415 + promptRef.current = nextPrompt;
8416 + composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
8417 + requestAnimationFrame(() => {
8418 + if (currentRouteThreadKeyRef.current === routeThreadKey)
8419 + composerRef.current?.focusAtEnd();
8420 + });
8421 }
8422 + } catch (error) {
8423 + setThreadError(
8424 + activeThread.id,
8425 + error instanceof Error ? error.message : "Failed to revert thread state.",
8426 + );
8427 + } finally {
8428 useComposerDraftStore.setState((store) => {
8429 const remaining = new Set(store.rewindingThreadKeys);
8430 remaining.delete(routeThreadKey);
8431 return { rewindingThreadKeys: remaining };
8432 });
8692 - },
8693 - [
8694 - activeEnvironmentUnavailable,
8695 - activeEnvironmentUnavailableLabel,
8696 - activeThread,
8433 + }
8434 + };
8435 + const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount);
8436 +
8437 + const onRollbackCheckpoint = async (input: {
8438 + readonly checkpointId: string;
8439 + readonly scopeId: string;
8440 + }) => {
8441 + if (!activeThread || isRevertingCheckpoint) return;
8442 + if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {
8443 + setThreadError(
8444 + activeThread.id,
8445 + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,
8446 + );
8447 + return;
8448 + }
8449 + if (phase === "running" || isSendBusy || isConnecting) {
8450 + setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
8451 + return;
8452 + }
8453 + const localApi = readLocalApi();
8454 + const confirmed =
8455 + localApi == null
8456 + ? window.confirm("Roll back this thread to the selected checkpoint?")
8457 + : await localApi.dialogs.confirm(
8458 + "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.",
8459 + );
8460 + if (!confirmed) return;
8461 +
8462 + useComposerDraftStore.setState((store) => ({
8463 + rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
8464 + }));
8465 + setThreadError(activeThread.id, null);
8466 + const result = await revertThreadCheckpoint({
8467 environmentId,
8698 - isConnecting,
8699 - isRevertingCheckpoint,
8700 - isSendBusy,
8701 - phase,
8702 - revertThreadCheckpoint,
8703 - setThreadError,
8704 - ],
8705 - );
8468 + input: {
8469 + threadId: activeThread.id,
8470 + checkpointId: input.checkpointId,
8471 + scopeId: input.scopeId,
8472 + },
8473 + });
8474 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
8475 + const error = squashAtomCommandFailure(result);
8476 + setThreadError(
8477 + activeThread.id,
8478 + error instanceof Error ? error.message : "Failed to revert thread state.",
8479 + );
8480 + }
8481 + useComposerDraftStore.setState((store) => {
8482 + const remaining = new Set(store.rewindingThreadKeys);
8483 + remaining.delete(routeThreadKey);
8484 + return { rewindingThreadKeys: remaining };
8485 + });
8486 + };
8487
8707 - const onForkFromRun = useCallback(
8708 - async (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => {
8709 - if (!activeThread || activeEnvironmentUnavailable) return;
8710 - const targetThreadId = newThreadId();
8711 - const targetThreadRef = scopeThreadRef(environmentId, targetThreadId);
8712 - const result = await forkThreadFromRun({
8713 - environmentId,
8714 - input: {
8715 - sourceThreadId: input.sourceThreadId,
8716 - targetThreadId,
8717 - runId: input.runId,
8718 - title: `${activeThread.title} fork`,
8719 - },
8720 - });
8721 - if (result._tag === "Failure") {
8722 - if (!isAtomCommandInterrupted(result)) {
8723 - const error = squashAtomCommandFailure(result);
8724 - setThreadError(
8725 - activeThread.id,
8726 - error instanceof Error ? error.message : "Failed to fork this response.",
8727 - );
8728 - }
8729 - return;
8730 - }
8731 - const targetThreadReady = await waitForThreadShell(targetThreadRef);
8732 - if (!targetThreadReady) {
8488 + const onForkFromRun = async (input: {
8489 + readonly sourceThreadId: ThreadId;
8490 + readonly runId: RunId;
8491 + }) => {
8492 + if (!activeThread || activeEnvironmentUnavailable) return;
8493 + const targetThreadId = newThreadId();
8494 + const targetThreadRef = scopeThreadRef(environmentId, targetThreadId);
8495 + const result = await forkThreadFromRun({
8496 + environmentId,
8497 + input: {
8498 + sourceThreadId: input.sourceThreadId,
8499 + targetThreadId,
8500 + runId: input.runId,
8501 + title: `${activeThread.title} fork`,
8502 + },
8503 + });
8504 + if (result._tag === "Failure") {
8505 + if (!isAtomCommandInterrupted(result)) {
8506 + const error = squashAtomCommandFailure(result);
8507 setThreadError(
8508 activeThread.id,
8735 - "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.",
8509 + error instanceof Error ? error.message : "Failed to fork this response.",
8510 );
8737 - return;
8511 }
8739 - await navigate({
8740 - to: "/$environmentId/$threadId",
8741 - params: buildThreadRouteParams(targetThreadRef),
8742 - });
8743 - },
8744 - [
8745 - activeEnvironmentUnavailable,
8746 - activeThread,
8747 - environmentId,
8748 - forkThreadFromRun,
8749 - navigate,
8750 - setThreadError,
8751 - ],
8752 - );
8512 + return;
8513 + }
8514 + const targetThreadReady = await waitForThreadShell(targetThreadRef);
8515 + if (!targetThreadReady) {
8516 + setThreadError(
8517 + activeThread.id,
8518 + "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.",
8519 + );
8520 + return;
8521 + }
8522 + await navigate({
8523 + to: "/$environmentId/$threadId",
8524 + params: buildThreadRouteParams(targetThreadRef),
8525 + });
8526 + };
8527 + const onForkFromRunStable = useStableCallback(onForkFromRun);
8528 const onCompactContext = () => {
8529 if (compactDisabled) return;

This file is too large to show in full.

apps/web/src/components/chat/ChatComposer.tsx
+1196 -1446
@@ -1154,6 +1154,7 @@ import {
1154 import { searchProviderSkills } from "../../providerSkillSearch";
1155 import { useDelayedStatus } from "../../hooks/useDelayedStatus";
1156 import { useMediaQuery } from "../../hooks/useMediaQuery";
1157 +import { useStableCallback } from "../../hooks/useStableCallback";
1158 import { usePanelAnimationSettings } from "../../panelAnimations";
1159 import { useAtomCommand } from "../../state/use-atom-command";
1160 import { readEnvironmentScope } from "../../state/session";
@@ -3005,27 +3006,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3006 // ------------------------------------------------------------------
3007 // Provider traits UI
3008 // ------------------------------------------------------------------
3008 - const setPromptFromTraits = useCallback(
3009 - (nextPrompt: string) => {
3010 - if (nextPrompt === promptRef.current) {
3011 - scheduleComposerFocus();
3012 - return;
3013 - }
3014 - promptRef.current = nextPrompt;
3015 - setComposerDraftPrompt(composerDraftTarget, nextPrompt);
3016 - const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);
3017 - setComposerCursor(nextCursor);
3018 - setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length));
3009 + const setPromptFromTraits = (nextPrompt: string) => {
3010 + if (nextPrompt === promptRef.current) {
3011 scheduleComposerFocus();
3020 - },
3021 - [
3022 - composerDraftTarget,
3023 - promptRef,
3024 - scheduleComposerFocus,
3025 - setComposerDraftPrompt,
3026 - setComposerTrigger,
3027 - ],
3028 - );
3012 + return;
3013 + }
3014 + promptRef.current = nextPrompt;
3015 + setComposerDraftPrompt(composerDraftTarget, nextPrompt);
3016 + const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);
3017 + setComposerCursor(nextCursor);
3018 + setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length));
3019 + scheduleComposerFocus();
3020 + };
3021 + const setPromptFromTraitsStable = useStableCallback(setPromptFromTraits);
3022
3023 const providerTraitsMenuContent = renderProviderTraitsMenuContent({
3024 provider: selectedProvider,
@@ -3037,7 +3030,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3030 modelOptions: composerModelOptions?.[selectedInstanceId],
3031 reportedModelSelection,
3032 prompt,
3040 - onPromptChange: setPromptFromTraits,
3033 + onPromptChange: setPromptFromTraitsStable,
3034 planModeEnabled: settings.planModeEnabled,
3035 });
3036 const providerTraitsPickerInput = {
@@ -3050,7 +3043,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3043 modelOptions: composerModelOptions?.[selectedInstanceId],
3044 reportedModelSelection,
3045 prompt,
3053 - onPromptChange: setPromptFromTraits,
3046 + onPromptChange: setPromptFromTraitsStable,
3047 planModeEnabled: settings.planModeEnabled,
3048 isComposerOwned: true,
3049 } satisfies Parameters<typeof renderProviderTraitsPicker>[0];
@@ -3111,66 +3104,39 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3104 // ------------------------------------------------------------------
3105 // Prompt helpers
3106 // ------------------------------------------------------------------
3114 - const setPrompt = useCallback(
3115 - (nextPrompt: string) => {
3116 - setComposerDraftPrompt(composerDraftTarget, nextPrompt);
3117 - },
3118 - [composerDraftTarget, setComposerDraftPrompt],
3119 - );
3107 + const setPrompt = (nextPrompt: string) => {
3108 + setComposerDraftPrompt(composerDraftTarget, nextPrompt);
3109 + };
3110
3121 - const addComposerImage = useCallback(
3122 - (image: ComposerImageAttachment) => addComposerDraftImages(attachmentDraftTarget, [image]),
3123 - [attachmentDraftTarget, addComposerDraftImages],
3124 - );
3111 + const addComposerImage = (image: ComposerImageAttachment) =>
3112 + addComposerDraftImages(attachmentDraftTarget, [image]);
3113
3126 - const addComposerImagesToDraft = useCallback(
3127 - (images: ComposerImageAttachment[]) => addComposerDraftImages(attachmentDraftTarget, images),
3128 - [attachmentDraftTarget, addComposerDraftImages],
3129 - );
3114 + const addComposerImagesToDraft = (images: ComposerImageAttachment[]) =>
3115 + addComposerDraftImages(attachmentDraftTarget, images);
3116
3131 - const addComposerFilesToDraft = useCallback(
3132 - (files: ComposerFileAttachment[]) =>
3133 - addComposerDraftFiles(attachmentDraftTarget, files, {
3134 - appendReference: questionAttachmentTarget === null,
3135 - }),
3136 - [addComposerDraftFiles, attachmentDraftTarget, questionAttachmentTarget],
3137 - );
3117 + const addComposerFilesToDraft = (files: ComposerFileAttachment[]) =>
3118 + addComposerDraftFiles(attachmentDraftTarget, files, {
3119 + appendReference: questionAttachmentTarget === null,
3120 + });
3121
3139 - const removeComposerImageFromDraft = useCallback(
3140 - (imageId: string) => {
3141 - if (questionAttachmentTarget && activePendingIsResponding) return;
3142 - releaseAttachmentUpload(imageId);
3143 - removeComposerDraftImage(attachmentDraftTarget, imageId);
3144 - },
3145 - [
3146 - attachmentDraftTarget,
3147 - questionAttachmentTarget,
3148 - activePendingIsResponding,
3149 - removeComposerDraftImage,
3150 - ],
3151 - );
3122 + const removeComposerImageFromDraft = (imageId: string) => {
3123 + if (questionAttachmentTarget && activePendingIsResponding) return;
3124 + releaseAttachmentUpload(imageId);
3125 + removeComposerDraftImage(attachmentDraftTarget, imageId);
3126 + };
3127
3153 - const removeComposerFileFromDraft = useCallback(
3154 - (fileId: string) => {
3155 - if (questionAttachmentTarget && activePendingIsResponding) return;
3156 - // Release by the draft attachment, not the bare queue key: a hydrated
3157 - // file's upload lives server-side under its persisted attachment id.
3158 - const file = composerFilesRef.current.find((candidate) => candidate.id === fileId);
3159 - if (file) {
3160 - releaseDraftAttachment(file);
3161 - } else {
3162 - releaseAttachmentUpload(fileId);
3163 - }
3164 - removeComposerDraftFile(attachmentDraftTarget, fileId);
3165 - },
3166 - [
3167 - attachmentDraftTarget,
3168 - questionAttachmentTarget,
3169 - activePendingIsResponding,
3170 - composerFilesRef,
3171 - removeComposerDraftFile,
3172 - ],
3173 - );
3128 + const removeComposerFileFromDraft = (fileId: string) => {
3129 + if (questionAttachmentTarget && activePendingIsResponding) return;
3130 + // Release by the draft attachment, not the bare queue key: a hydrated
3131 + // file's upload lives server-side under its persisted attachment id.
3132 + const file = composerFilesRef.current.find((candidate) => candidate.id === fileId);
3133 + if (file) {
3134 + releaseDraftAttachment(file);
3135 + } else {
3136 + releaseAttachmentUpload(fileId);
3137 + }
3138 + removeComposerDraftFile(attachmentDraftTarget, fileId);
3139 + };
3140
3141 const addComposerDraftTerminalContexts = useComposerDraftStore(
3142 (store) => store.addTerminalContexts,
@@ -3181,72 +3147,60 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3147 );
3148 const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts);
3149 const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
3184 - const buildContextClipboardFragment = useCallback(
3185 - (contextIds: ReadonlyArray<string>): string | null => {
3186 - const wanted = new Set(contextIds);
3187 - // An annotation's screenshot is referenced by the annotation record, not by the copied
3188 - // text. Pull it in so the round-trip keeps the image the annotation points at.
3189 - for (const annotation of composerPreviewAnnotations) {
3190 - if (
3191 - wanted.has(previewAnnotationContextId(annotation.id)) &&
3192 - composerImages.some((image) => image.id === annotation.id)
3193 - ) {
3194 - wanted.add(toKindScopedComposerContextId("image", annotation.id));
3195 - }
3150 + const buildContextClipboardFragment = (contextIds: ReadonlyArray<string>): string | null => {
3151 + const wanted = new Set(contextIds);
3152 + // An annotation's screenshot is referenced by the annotation record, not by the copied
3153 + // text. Pull it in so the round-trip keeps the image the annotation points at.
3154 + for (const annotation of composerPreviewAnnotations) {
3155 + if (
3156 + wanted.has(previewAnnotationContextId(annotation.id)) &&
3157 + composerImages.some((image) => image.id === annotation.id)
3158 + ) {
3159 + wanted.add(toKindScopedComposerContextId("image", annotation.id));
3160 }
3197 - const records: ComposerContextRecord[] = [
3198 - ...composerTerminalContexts
3199 - .filter((c) => wanted.has(terminalContextReference(c).contextId))
3200 - .map(terminalContextRecord),
3201 - ...composerThreadContexts.filter((record) => wanted.has(record.contextId)),
3202 - ...composerReviewComments
3203 - .filter((c) => wanted.has(reviewCommentContextId(c.id)))
3204 - .map(reviewCommentContextRecord),
3205 - ...composerPreviewAnnotations
3206 - .filter((a) => wanted.has(previewAnnotationContextId(a.id)))
3207 - .map((annotation) =>
3208 - previewAnnotationContextRecord(annotation, {
3209 - screenshotContextId: composerImages.some((image) => image.id === annotation.id)
3210 - ? annotation.id
3211 - : undefined,
3212 - }),
3213 - ),
3214 - ...[...composerImages, ...composerFiles]
3215 - .filter((attachment) =>
3216 - wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)),
3217 - )
3218 - .flatMap((attachment) => {
3219 - const record = uploadedAttachmentContextRecord(
3220 - attachment,
3221 - uploadsByImageId[attachment.id],
3222 - );
3223 - return record ? [record] : [];
3161 + }
3162 + const records: ComposerContextRecord[] = [
3163 + ...composerTerminalContexts
3164 + .filter((c) => wanted.has(terminalContextReference(c).contextId))
3165 + .map(terminalContextRecord),
3166 + ...composerThreadContexts.filter((record) => wanted.has(record.contextId)),
3167 + ...composerReviewComments
3168 + .filter((c) => wanted.has(reviewCommentContextId(c.id)))
3169 + .map(reviewCommentContextRecord),
3170 + ...composerPreviewAnnotations
3171 + .filter((a) => wanted.has(previewAnnotationContextId(a.id)))
3172 + .map((annotation) =>
3173 + previewAnnotationContextRecord(annotation, {
3174 + screenshotContextId: composerImages.some((image) => image.id === annotation.id)
3175 + ? annotation.id
3176 + : undefined,
3177 }),
3225 - ];
3226 - if (records.length === 0) return null;
3227 - return encodeComposerContextFragment({
3228 - version: 1,
3229 - source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) },
3230 - records,
3231 - });
3232 - },
3233 - [
3234 - activeThread,
3235 - composerFiles,
3236 - composerImages,
3237 - composerPreviewAnnotations,
3238 - composerReviewComments,
3239 - composerTerminalContexts,
3240 - composerThreadContexts,
3241 - environmentId,
3242 - uploadsByImageId,
3243 - ],
3244 - );
3178 + ),
3179 + ...[...composerImages, ...composerFiles]
3180 + .filter((attachment) =>
3181 + wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)),
3182 + )
3183 + .flatMap((attachment) => {
3184 + const record = uploadedAttachmentContextRecord(
3185 + attachment,
3186 + uploadsByImageId[attachment.id],
3187 + );
3188 + return record ? [record] : [];
3189 + }),
3190 + ];
3191 + if (records.length === 0) return null;
3192 + return encodeComposerContextFragment({
3193 + version: 1,
3194 + source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) },
3195 + records,
3196 + });
3197 + };
3198 + const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment);
3199 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });
3200 const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, {
3201 reportFailure: false,
3202 });
3249 - const countReservedAttachments = useCallback(() => {
3203 + const countReservedAttachments = () => {
3204 const questionRequest = pendingUserInputs[0];
3205 const otherQuestionKeys =
3206 questionAttachmentTarget && questionRequest && activeThreadId
@@ -3269,272 +3223,238 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3223 (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) +
3224 countQuestionAttachments(otherQuestionKeys)
3225 );
3272 - }, [
3273 - activeThreadId,
3274 - attachmentDraftTarget,
3275 - attachmentTargetKey,
3276 - environmentId,
3277 - getComposerDraft,
3278 - pendingUserInputs,
3279 - questionAttachmentTarget,
3280 - ]);
3226 + };
3227 + const countReservedAttachmentsStable = useStableCallback(countReservedAttachments);
3228 /**
3229 * Bytes for a pasted image or file come back through the source environment's asset URL
3230 * (the client is the only party that can reach both) and re-enter this draft as a normal
3231 * attachment under a fresh id. The pasted chip is rewritten to that id and reads as
3232 * unresolved until the bytes land; a failed transfer says so and leaves the chip to remove.
3233 */
3287 - const runAttachmentImport = useCallback(
3288 - async (
3289 - record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
3290 - localId: string,
3291 - sourceEnvironmentId: EnvironmentId,
3292 - importTargetKey: string,
3293 - ) => {
3294 - const fail = (reason: string) => {
3295 - toastManager.add({
3296 - type: "error",
3297 - title: `Couldn't bring ${record.name} into this message`,
3298 - description: `${reason} Remove the chip or attach the file again.`,
3299 - });
3300 - };
3301 - const sourceConnection = readPreparedConnection(sourceEnvironmentId);
3302 - if (!sourceConnection) {
3303 - fail("The environment it came from is not connected.");
3304 - return;
3305 - }
3306 - const result = await createAssetUrl({
3307 - environmentId: sourceEnvironmentId,
3308 - input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
3234 + const runAttachmentImport = async (
3235 + record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
3236 + localId: string,
3237 + sourceEnvironmentId: EnvironmentId,
3238 + importTargetKey: string,
3239 + ) => {
3240 + const fail = (reason: string) => {
3241 + toastManager.add({
3242 + type: "error",
3243 + title: `Couldn't bring ${record.name} into this message`,
3244 + description: `${reason} Remove the chip or attach the file again.`,
3245 });
3310 - const url =
3311 - result._tag === "Success"
3312 - ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
3313 - : null;
3314 - if (!url) {
3315 - fail("The original attachment is no longer available.");
3316 - return;
3317 - }
3318 - let blob: Blob;
3319 - try {
3320 - const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
3321 - if (!response.ok) throw new Error(`HTTP ${response.status}`);
3322 - blob = await response.blob();
3323 - } catch {
3324 - fail("Downloading it from the source failed.");
3325 - return;
3326 - }
3327 - const file = new File([blob], record.name, { type: record.mimeType || blob.type });
3328 - // The draft these bytes belong to may have been sent or switched away from while they
3329 - // downloaded. Dropping them here keeps them out of whatever draft is open now.
3330 - if (attachmentTargetKeyRef.current !== importTargetKey) return;
3331 - const replacesFileMarker =
3332 - record.kind === "file" &&
3333 - composerFilesRef.current.some(
3334 - (candidate) =>
3335 - composerFileNeedsReattach(candidate) &&
3336 - composerFileMatchesReattachMarker(candidate, {
3337 - name: record.name,
3338 - mimeType: file.type,
3339 - sizeBytes: file.size,
3340 - }),
3341 - );
3342 - if (
3343 - !replacesFileMarker &&
3344 - (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 &&
3345 - countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS
3346 - ) {
3347 - fail("The attachment limit has been reached.");
3348 - return;
3349 - }
3350 - if (record.kind === "image") {
3351 - const accepted = addComposerImage({
3352 - type: "image",
3246 + };
3247 + const sourceConnection = readPreparedConnection(sourceEnvironmentId);
3248 + if (!sourceConnection) {
3249 + fail("The environment it came from is not connected.");
3250 + return;
3251 + }
3252 + const result = await createAssetUrl({
3253 + environmentId: sourceEnvironmentId,
3254 + input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
3255 + });
3256 + const url =
3257 + result._tag === "Success"
3258 + ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
3259 + : null;
3260 + if (!url) {
3261 + fail("The original attachment is no longer available.");
3262 + return;
3263 + }
3264 + let blob: Blob;
3265 + try {
3266 + const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
3267 + if (!response.ok) throw new Error(`HTTP ${response.status}`);
3268 + blob = await response.blob();
3269 + } catch {
3270 + fail("Downloading it from the source failed.");
3271 + return;
3272 + }
3273 + const file = new File([blob], record.name, { type: record.mimeType || blob.type });
3274 + // The draft these bytes belong to may have been sent or switched away from while they
3275 + // downloaded. Dropping them here keeps them out of whatever draft is open now.
3276 + if (attachmentTargetKeyRef.current !== importTargetKey) return;
3277 + const replacesFileMarker =
3278 + record.kind === "file" &&
3279 + composerFilesRef.current.some(
3280 + (candidate) =>
3281 + composerFileNeedsReattach(candidate) &&
3282 + composerFileMatchesReattachMarker(candidate, {
3283 + name: record.name,
3284 + mimeType: file.type,
3285 + sizeBytes: file.size,
3286 + }),
3287 + );
3288 + if (
3289 + !replacesFileMarker &&
3290 + (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 &&
3291 + countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS
3292 + ) {
3293 + fail("The attachment limit has been reached.");
3294 + return;
3295 + }
3296 + if (record.kind === "image") {
3297 + const accepted = addComposerImage({
3298 + type: "image",
3299 + id: localId,
3300 + name: record.name,
3301 + mimeType: file.type,
3302 + sizeBytes: file.size,
3303 + previewUrl: URL.createObjectURL(file),
3304 + file,
3305 + });
3306 + if (!accepted.includes(localId))
3307 + fail("The draft rejected this attachment (duplicate or attachment limit reached).");
3308 + } else {
3309 + const accepted = addComposerFilesToDraft([
3310 + {
3311 + type: "file",
3312 id: localId,
3313 name: record.name,
3314 mimeType: file.type,
3315 sizeBytes: file.size,
3357 - previewUrl: URL.createObjectURL(file),
3316 file,
3359 - });
3360 - if (!accepted.includes(localId))
3361 - fail("The draft rejected this attachment (duplicate or attachment limit reached).");
3362 - } else {
3363 - const accepted = addComposerFilesToDraft([
3364 - {
3365 - type: "file",
3366 - id: localId,
3367 - name: record.name,
3368 - mimeType: file.type,
3369 - sizeBytes: file.size,
3370 - file,
3371 - },
3372 - ]);
3373 - if (!accepted.includes(localId))
3374 - fail("The draft rejected this attachment (duplicate or attachment limit reached).");
3375 - }
3376 - },
3377 - [
3378 - addComposerFilesToDraft,
3379 - addComposerImage,
3380 - composerFilesRef,
3381 - countReservedAttachments,
3382 - createAssetUrl,
3383 - ],
3384 - );
3385 - const importAttachmentRecord = useCallback(
3386 - async (
3387 - record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
3388 - localId: string,
3389 - sourceEnvironmentId: EnvironmentId,
3390 - ) => {
3391 - // The chip lands in the draft immediately while these bytes are still downloading. Count
3392 - // the transfer against its own draft so a send cannot snapshot a message whose chip has no
3393 - // attachment behind it, and so bytes for an abandoned draft never enter the next one.
3394 - const importTargetKey = attachmentTargetKey;
3395 - pendingDraftWork.begin(importTargetKey);
3396 - try {
3397 - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey);
3398 - } finally {
3399 - pendingDraftWork.end(importTargetKey);
3400 - }
3401 - },
3402 - [attachmentTargetKey, runAttachmentImport],
3403 - );
3317 + },
3318 + ]);
3319 + if (!accepted.includes(localId))
3320 + fail("The draft rejected this attachment (duplicate or attachment limit reached).");
3321 + }
3322 + };
3323 + const importAttachmentRecord = async (
3324 + record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
3325 + localId: string,
3326 + sourceEnvironmentId: EnvironmentId,
3327 + ) => {
3328 + // The chip lands in the draft immediately while these bytes are still downloading. Count
3329 + // the transfer against its own draft so a send cannot snapshot a message whose chip has no
3330 + // attachment behind it, and so bytes for an abandoned draft never enter the next one.
3331 + const importTargetKey = attachmentTargetKey;
3332 + pendingDraftWork.begin(importTargetKey);
3333 + try {
3334 + await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey);
3335 + } finally {
3336 + pendingDraftWork.end(importTargetKey);
3337 + }
3338 + };
3339 /**
3340 * Brings records into this draft (paste, stash restore). Binaries are transferred only
3341 * when `sourceEnvironmentId` is given; the stash restores its own images and files.
3342 */
3408 - const importContextRecords = useCallback(
3409 - (
3410 - records: ReadonlyArray<ComposerContextRecord>,
3411 - sourceEnvironmentId: EnvironmentId | null,
3412 - ): ReadonlyMap<string, string> => {
3413 - const rewritten = new Map<string, string>();
3414 - const dependentAttachmentLocalIds = new Map<string, string>();
3415 - const skippedDependentAttachmentIds = new Set<string>();
3416 - // Resolve annotations before their dependent screenshot records even if a foreign
3417 - // clipboard producer emitted the records in a different order.
3418 - const orderedRecords = records.toSorted((left, right) =>
3419 - left.kind === "preview-annotation" && right.kind !== "preview-annotation"
3420 - ? -1
3421 - : right.kind === "preview-annotation" && left.kind !== "preview-annotation"
3422 - ? 1
3423 - : 0,
3424 - );
3425 - for (const candidate of orderedRecords) {
3426 - // Producer ids fold into context ids, so two different excerpts can collide. Only skip
3427 - // when the draft already holds the same payload; a colliding but different record is
3428 - // re-minted under a fresh id so both survive the paste.
3429 - const record = asKnownContextRecord(candidate);
3430 - if (!record) continue;
3431 - const existing = composerContextImportLookupIds(record).flatMap((contextId) => {
3432 - const found = composerContextRecords.get(contextId);
3433 - return found ? [found] : [];
3434 - })[0];
3435 - const existingRecord =
3436 - existing?.kind === "terminal"
3437 - ? terminalContextRecord(existing.record)
3438 - : existing?.kind === "review-comment"
3439 - ? reviewCommentContextRecord(existing.record)
3440 - : existing?.kind === "preview-annotation"
3441 - ? previewAnnotationContextRecord(existing.record)
3442 - : existing?.kind === "thread"
3443 - ? existing.record
3444 - : existing
3445 - ? (uploadedContextRecordFromDraft(existing) ?? undefined)
3446 - : undefined;
3447 - if (existingRecord && isSameComposerContextPayload(existingRecord, record)) {
3343 + const importContextRecords = (
3344 + records: ReadonlyArray<ComposerContextRecord>,
3345 + sourceEnvironmentId: EnvironmentId | null,
3346 + ): ReadonlyMap<string, string> => {
3347 + const rewritten = new Map<string, string>();
3348 + const dependentAttachmentLocalIds = new Map<string, string>();
3349 + const skippedDependentAttachmentIds = new Set<string>();
3350 + // Resolve annotations before their dependent screenshot records even if a foreign
3351 + // clipboard producer emitted the records in a different order.
3352 + const orderedRecords = records.toSorted((left, right) =>
3353 + left.kind === "preview-annotation" && right.kind !== "preview-annotation"
3354 + ? -1
3355 + : right.kind === "preview-annotation" && left.kind !== "preview-annotation"
3356 + ? 1
3357 + : 0,
3358 + );
3359 + for (const candidate of orderedRecords) {
3360 + // Producer ids fold into context ids, so two different excerpts can collide. Only skip
3361 + // when the draft already holds the same payload; a colliding but different record is
3362 + // re-minted under a fresh id so both survive the paste.
3363 + const record = asKnownContextRecord(candidate);
3364 + if (!record) continue;
3365 + const existing = composerContextImportLookupIds(record).flatMap((contextId) => {
3366 + const found = composerContextRecords.get(contextId);
3367 + return found ? [found] : [];
3368 + })[0];
3369 + const existingRecord =
3370 + existing?.kind === "terminal"
3371 + ? terminalContextRecord(existing.record)
3372 + : existing?.kind === "review-comment"
3373 + ? reviewCommentContextRecord(existing.record)
3374 + : existing?.kind === "preview-annotation"
3375 + ? previewAnnotationContextRecord(existing.record)
3376 + : existing?.kind === "thread"
3377 + ? existing.record
3378 + : existing
3379 + ? (uploadedContextRecordFromDraft(existing) ?? undefined)
3380 + : undefined;
3381 + if (existingRecord && isSameComposerContextPayload(existingRecord, record)) {
3382 + if (record.kind === "preview-annotation" && record.screenshotContextId) {
3383 + skippedDependentAttachmentIds.add(record.screenshotContextId);
3384 + }
3385 + continue;
3386 + }
3387 + const conflicts = existing !== undefined;
3388 + switch (record.kind) {
3389 + case "terminal": {
3390 + const threadId = activeThread?.id ?? activeThreadId;
3391 + if (!threadId) break;
3392 + const imported = terminalContextDraftFromRecord(record, threadId);
3393 + const draft = conflicts ? { ...imported, id: randomUUID() } : imported;
3394 + addComposerDraftTerminalContexts(composerDraftTarget, [draft], {
3395 + appendReference: false,
3396 + });
3397 + rewritten.set(record.contextId, terminalContextReference(draft).contextId);
3398 + break;
3399 + }
3400 + case "review-comment": {
3401 + const imported = reviewCommentFromRecord(record);
3402 + const comment = conflicts ? { ...imported, id: randomUUID() } : imported;
3403 + addComposerDraftReviewComment(composerDraftTarget, comment, {
3404 + appendReference: false,
3405 + });
3406 + rewritten.set(record.contextId, reviewCommentContextId(comment.id));
3407 + break;
3408 + }
3409 + case "element":
3410 + case "preview-annotation": {
3411 + const imported =
3412 + record.kind === "element"
3413 + ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString())
3414 + : previewAnnotationFromRecord(record);
3415 + const annotation = conflicts ? { ...imported, id: randomUUID() } : imported;
3416 if (record.kind === "preview-annotation" && record.screenshotContextId) {
3449 - skippedDependentAttachmentIds.add(record.screenshotContextId);
3417 + dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id);
3418 }
3451 - continue;
3419 + addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, {
3420 + appendReference: false,
3421 + });
3422 + rewritten.set(record.contextId, previewAnnotationContextId(annotation.id));
3423 + break;
3424 }
3453 - const conflicts = existing !== undefined;
3454 - switch (record.kind) {
3455 - case "terminal": {
3456 - const threadId = activeThread?.id ?? activeThreadId;
3457 - if (!threadId) break;
3458 - const imported = terminalContextDraftFromRecord(record, threadId);
3459 - const draft = conflicts ? { ...imported, id: randomUUID() } : imported;
3460 - addComposerDraftTerminalContexts(composerDraftTarget, [draft], {
3461 - appendReference: false,
3462 - });
3463 - rewritten.set(record.contextId, terminalContextReference(draft).contextId);
3464 - break;
3465 - }
3466 - case "review-comment": {
3467 - const imported = reviewCommentFromRecord(record);
3468 - const comment = conflicts ? { ...imported, id: randomUUID() } : imported;
3469 - addComposerDraftReviewComment(composerDraftTarget, comment, {
3470 - appendReference: false,
3471 - });
3472 - rewritten.set(record.contextId, reviewCommentContextId(comment.id));
3473 - break;
3474 - }
3475 - case "element":
3476 - case "preview-annotation": {
3477 - const imported =
3478 - record.kind === "element"
3479 - ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString())
3480 - : previewAnnotationFromRecord(record);
3481 - const annotation = conflicts ? { ...imported, id: randomUUID() } : imported;
3482 - if (record.kind === "preview-annotation" && record.screenshotContextId) {
3483 - dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id);
3484 - }
3485 - addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, {
3486 - appendReference: false,
3487 - });
3488 - rewritten.set(record.contextId, previewAnnotationContextId(annotation.id));
3489 - break;
3490 - }
3491 - case "thread": {
3492 - // The agent can only read threads on its own server; a pasted foreign one is dropped.
3493 - if (record.environmentId !== environmentId) break;
3494 - addComposerDraftThreadContexts(attachmentDraftTarget, [record], {
3495 - appendReference: false,
3496 - });
3425 + case "thread": {
3426 + // The agent can only read threads on its own server; a pasted foreign one is dropped.
3427 + if (record.environmentId !== environmentId) break;
3428 + addComposerDraftThreadContexts(attachmentDraftTarget, [record], {
3429 + appendReference: false,
3430 + });
3431 + rewritten.set(record.contextId, record.contextId);
3432 + break;
3433 + }
3434 + case "image":
3435 + case "file": {
3436 + if (skippedDependentAttachmentIds.has(record.contextId)) break;
3437 + if (sourceEnvironmentId === null && !conflicts) {
3438 rewritten.set(record.contextId, record.contextId);
3439 break;
3440 }
3500 - case "image":
3501 - case "file": {
3502 - if (skippedDependentAttachmentIds.has(record.contextId)) break;
3503 - if (sourceEnvironmentId === null && !conflicts) {
3504 - rewritten.set(record.contextId, record.contextId);
3505 - break;
3506 - }
3507 - if (sourceEnvironmentId === null) break;
3508 - const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID();
3509 - rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId));
3510 - void importAttachmentRecord(record, localId, sourceEnvironmentId);
3511 - break;
3512 - }
3513 - default:
3514 - break;
3441 + if (sourceEnvironmentId === null) break;
3442 + const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID();
3443 + rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId));
3444 + void importAttachmentRecord(record, localId, sourceEnvironmentId);
3445 + break;
3446 }
3447 + default:
3448 + break;
3449 }
3517 - return rewritten;
3518 - },
3519 - [
3520 - activeThread,
3521 - activeThreadId,
3522 - addComposerDraftPreviewAnnotation,
3523 - addComposerDraftReviewComment,
3524 - addComposerDraftTerminalContexts,
3525 - addComposerDraftThreadContexts,
3526 - composerContextRecords,
3527 - attachmentDraftTarget,
3528 - composerDraftTarget,
3529 - environmentId,
3530 - importAttachmentRecord,
3531 - ],
3532 - );
3533 - const importContextFragment = useCallback(
3534 - (fragment: ComposerContextClipboardFragment): ReadonlyMap<string, string> =>
3535 - importContextRecords(fragment.records, fragment.source.environmentId),
3536 - [importContextRecords],
3537 - );
3450 + }
3451 + return rewritten;
3452 + };
3453 + const importContextFragment = (
3454 + fragment: ComposerContextClipboardFragment,
3455 + ): ReadonlyMap<string, string> =>
3456 + importContextRecords(fragment.records, fragment.source.environmentId);
3457 + const importContextFragmentStable = useStableCallback(importContextFragment);
3458
3459 // ------------------------------------------------------------------
3460 // Sync refs back to parent
@@ -3797,7 +3717,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3717 // ------------------------------------------------------------------
3718 // Callbacks: prompt change
3719 // ------------------------------------------------------------------
3800 - const expandComposerForEditorChange = useCallback(() => {
3720 + const expandComposerForEditorChange = () => {
3721 // Editor changes win over the momentum tail of the active scroll gesture.
3722 suppressActiveComposerScrollGesture(
3723 composerScrollGestureRef.current,
@@ -3805,7 +3725,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3725 COMPOSER_SCROLL_GESTURE_RESET_MS,
3726 );
3727 setIsComposerScrollCollapsed(false);
3808 - }, [setIsComposerScrollCollapsed]);
3728 + };
3729 + const expandComposerForEditorChangeStable = useStableCallback(expandComposerForEditorChange);
3730
3731 /**
3732 * Payloads for chips the prompt no longer references. History undo restores the
@@ -3822,260 +3743,216 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3743 previewAnnotations: new Map(),
3744 });
3745
3825 - const onPromptChange = useCallback(
3826 - (
3827 - nextPrompt: string,
3828 - nextCursor: number,
3829 - expandedCursor: number,
3830 - cursorAdjacentToMention: boolean,
3831 - contextIds: string[],
3832 - ) => {
3833 - expandComposerForEditorChange();
3834 - if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) {
3835 - if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return;
3836 - setComposerCursor(nextCursor);
3837 - setComposerTrigger(
3838 - cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
3839 - );
3840 - onChangeActivePendingUserInputCustomAnswer(
3841 - activePendingProgress.activeQuestion.id,
3842 - nextPrompt,
3843 - nextCursor,
3844 - expandedCursor,
3845 - cursorAdjacentToMention,
3846 - );
3847 - return;
3848 - }
3849 - onTypingGuardDraftChange();
3850 - promptRef.current = nextPrompt;
3851 - setPrompt(nextPrompt);
3852 - // Any edit ends browsing, even one later undone by hand: typing a
3853 - // character and deleting it leaves the text equal to the recall, and
3854 - // ArrowDown must move the caret then, not clear the composer.
3855 - if (promptHistoryPositionRef.current?.recalled !== nextPrompt) {
3856 - promptHistoryPositionRef.current = null;
3857 - }
3858 - const referenced = new Set(contextIds);
3859 - const retained = removedContextPayloadsRef.current;
3860 -
3861 - // An undone delete brings the reference back; restore the payload it points at.
3862 - const liveTerminalIds = new Set<string>(
3863 - composerTerminalContexts.map((context) => terminalContextReference(context).contextId),
3746 + const onPromptChange = (
3747 + nextPrompt: string,
3748 + nextCursor: number,
3749 + expandedCursor: number,
3750 + cursorAdjacentToMention: boolean,
3751 + contextIds: string[],
3752 + ) => {
3753 + expandComposerForEditorChange();
3754 + if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) {
3755 + if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return;
3756 + setComposerCursor(nextCursor);
3757 + setComposerTrigger(
3758 + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
3759 );
3865 - const restoredTerminals = [...referenced].flatMap((contextId) => {
3866 - if (liveTerminalIds.has(contextId)) return [];
3867 - const context = retained.terminals.get(contextId);
3868 - return context ? [context] : [];
3869 - });
3870 - const nextTerminals = [
3871 - ...composerTerminalContexts.filter((context) =>
3872 - referenced.has(terminalContextReference(context).contextId),
3873 - ),
3874 - ...restoredTerminals,
3875 - ];
3876 - for (const context of composerTerminalContexts) {
3877 - const contextId = terminalContextReference(context).contextId;
3878 - if (!referenced.has(contextId)) retained.terminals.set(contextId, context);
3879 - }
3880 - if (
3881 - nextTerminals.length !== composerTerminalContexts.length ||
3882 - restoredTerminals.length > 0
3883 - ) {
3884 - setComposerDraftTerminalContexts(composerDraftTarget, nextTerminals);
3885 - }
3886 -
3887 - const liveThreadIds = new Set<string>(
3888 - composerThreadContexts.map((record) => record.contextId),
3760 + onChangeActivePendingUserInputCustomAnswer(
3761 + activePendingProgress.activeQuestion.id,
3762 + nextPrompt,
3763 + nextCursor,
3764 + expandedCursor,
3765 + cursorAdjacentToMention,
3766 );
3890 - const restoredThreads = [...referenced].flatMap((contextId) => {
3891 - if (liveThreadIds.has(contextId)) return [];
3892 - const record = retained.threads.get(contextId);
3893 - return record ? [record] : [];
3894 - });
3895 - const nextThreads = [
3896 - ...composerThreadContexts.filter((record) => referenced.has(record.contextId)),
3897 - ...restoredThreads,
3898 - ];
3899 - for (const record of composerThreadContexts) {
3900 - if (!referenced.has(record.contextId)) retained.threads.set(record.contextId, record);
3901 - }
3902 - if (nextThreads.length !== composerThreadContexts.length || restoredThreads.length > 0) {
3903 - setComposerDraftThreadContexts(composerDraftTarget, nextThreads);
3904 - }
3767 + return;
3768 + }
3769 + onTypingGuardDraftChange();
3770 + promptRef.current = nextPrompt;
3771 + setPrompt(nextPrompt);
3772 + // Any edit ends browsing, even one later undone by hand: typing a
3773 + // character and deleting it leaves the text equal to the recall, and
3774 + // ArrowDown must move the caret then, not clear the composer.
3775 + if (promptHistoryPositionRef.current?.recalled !== nextPrompt) {
3776 + promptHistoryPositionRef.current = null;
3777 + }
3778 + const referenced = new Set(contextIds);
3779 + const retained = removedContextPayloadsRef.current;
3780
3906 - for (const comment of composerReviewComments) {
3907 - const contextId = reviewCommentContextId(comment.id);
3908 - if (!referenced.has(contextId)) {
3909 - retained.reviewComments.set(contextId, comment);
3910 - removeComposerDraftReviewComment(composerDraftTarget, comment.id);
3911 - }
3781 + // An undone delete brings the reference back; restore the payload it points at.
3782 + const liveTerminalIds = new Set<string>(
3783 + composerTerminalContexts.map((context) => terminalContextReference(context).contextId),
3784 + );
3785 + const restoredTerminals = [...referenced].flatMap((contextId) => {
3786 + if (liveTerminalIds.has(contextId)) return [];
3787 + const context = retained.terminals.get(contextId);
3788 + return context ? [context] : [];
3789 + });
3790 + const nextTerminals = [
3791 + ...composerTerminalContexts.filter((context) =>
3792 + referenced.has(terminalContextReference(context).contextId),
3793 + ),
3794 + ...restoredTerminals,
3795 + ];
3796 + for (const context of composerTerminalContexts) {
3797 + const contextId = terminalContextReference(context).contextId;
3798 + if (!referenced.has(contextId)) retained.terminals.set(contextId, context);
3799 + }
3800 + if (nextTerminals.length !== composerTerminalContexts.length || restoredTerminals.length > 0) {
3801 + setComposerDraftTerminalContexts(composerDraftTarget, nextTerminals);
3802 + }
3803 +
3804 + const liveThreadIds = new Set<string>(composerThreadContexts.map((record) => record.contextId));
3805 + const restoredThreads = [...referenced].flatMap((contextId) => {
3806 + if (liveThreadIds.has(contextId)) return [];
3807 + const record = retained.threads.get(contextId);
3808 + return record ? [record] : [];
3809 + });
3810 + const nextThreads = [
3811 + ...composerThreadContexts.filter((record) => referenced.has(record.contextId)),
3812 + ...restoredThreads,
3813 + ];
3814 + for (const record of composerThreadContexts) {
3815 + if (!referenced.has(record.contextId)) retained.threads.set(record.contextId, record);
3816 + }
3817 + if (nextThreads.length !== composerThreadContexts.length || restoredThreads.length > 0) {
3818 + setComposerDraftThreadContexts(composerDraftTarget, nextThreads);
3819 + }
3820 +
3821 + for (const comment of composerReviewComments) {
3822 + const contextId = reviewCommentContextId(comment.id);
3823 + if (!referenced.has(contextId)) {
3824 + retained.reviewComments.set(contextId, comment);
3825 + removeComposerDraftReviewComment(composerDraftTarget, comment.id);
3826 }
3913 - const liveReviewIds = new Set<string>(
3914 - composerReviewComments.map((comment) => reviewCommentContextId(comment.id)),
3915 - );
3916 - for (const contextId of referenced) {
3917 - if (liveReviewIds.has(contextId)) continue;
3918 - const comment = retained.reviewComments.get(contextId);
3919 - if (comment) {
3920 - addComposerDraftReviewComment(composerDraftTarget, comment, { appendReference: false });
3921 - }
3827 + }
3828 + const liveReviewIds = new Set<string>(
3829 + composerReviewComments.map((comment) => reviewCommentContextId(comment.id)),
3830 + );
3831 + for (const contextId of referenced) {
3832 + if (liveReviewIds.has(contextId)) continue;
3833 + const comment = retained.reviewComments.get(contextId);
3834 + if (comment) {
3835 + addComposerDraftReviewComment(composerDraftTarget, comment, { appendReference: false });
3836 }
3837 + }
3838
3924 - const attachmentChanges = reconcileAttachmentContextReferences({
3925 - referencedContextIds: referenced,
3926 - files: composerFiles,
3927 - images: composerImages,
3928 - previewAnnotations: composerPreviewAnnotations,
3929 - retained: removedAttachmentContextPayloadsRef.current,
3839 + const attachmentChanges = reconcileAttachmentContextReferences({
3840 + referencedContextIds: referenced,
3841 + files: composerFiles,
3842 + images: composerImages,
3843 + previewAnnotations: composerPreviewAnnotations,
3844 + retained: removedAttachmentContextPayloadsRef.current,
3845 + });
3846 + for (const annotationId of attachmentChanges.annotationIdsToRemove) {
3847 + // Keep the upload queue entry alive: undo restores the image that owns it.
3848 + removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId);
3849 + }
3850 + for (const restored of attachmentChanges.annotationsToRestore) {
3851 + if (restored.image) addComposerDraftImages(attachmentDraftTarget, [restored.image]);
3852 + addComposerDraftPreviewAnnotation(composerDraftTarget, restored.annotation, {
3853 + appendReference: false,
3854 });
3931 - for (const annotationId of attachmentChanges.annotationIdsToRemove) {
3932 - // Keep the upload queue entry alive: undo restores the image that owns it.
3933 - removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId);
3934 - }
3935 - for (const restored of attachmentChanges.annotationsToRestore) {
3936 - if (restored.image) addComposerDraftImages(attachmentDraftTarget, [restored.image]);
3937 - addComposerDraftPreviewAnnotation(composerDraftTarget, restored.annotation, {
3938 - appendReference: false,
3939 - });
3940 - }
3941 - for (const fileId of attachmentChanges.filesToRemove) {
3942 - // The retained File and upload are still sendable if the editor restores the chip.
3943 - removeComposerDraftFile(attachmentDraftTarget, fileId);
3944 - }
3945 - if (attachmentChanges.filesToRestore.length > 0) {
3946 - addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore);
3947 - }
3948 - setComposerCursor(nextCursor);
3949 - setComposerTrigger(
3950 - cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
3951 - );
3952 - },
3953 - [
3954 - activePendingProgress?.activeQuestion,
3955 - expandComposerForEditorChange,
3956 - onTypingGuardDraftChange,
3957 - pendingUserInputs.length,
3958 - onChangeActivePendingUserInputCustomAnswer,
3959 - promptRef,
3960 - setPrompt,
3961 - setComposerTrigger,
3962 - composerDraftTarget,
3963 - composerTerminalContexts,
3964 - setComposerDraftTerminalContexts,
3965 - composerThreadContexts,
3966 - setComposerDraftThreadContexts,
3967 - composerReviewComments,
3968 - composerPreviewAnnotations,
3969 - composerImages,
3970 - composerFiles,
3971 - removeComposerDraftReviewComment,
3972 - removeComposerDraftPreviewAnnotation,
3973 - removeComposerDraftFile,
3974 - addComposerDraftReviewComment,
3975 - addComposerDraftPreviewAnnotation,
3976 - addComposerDraftImages,
3977 - addComposerDraftFiles,
3978 - attachmentDraftTarget,
3979 - ],
3980 - );
3855 + }
3856 + for (const fileId of attachmentChanges.filesToRemove) {
3857 + // The retained File and upload are still sendable if the editor restores the chip.
3858 + removeComposerDraftFile(attachmentDraftTarget, fileId);
3859 + }
3860 + if (attachmentChanges.filesToRestore.length > 0) {
3861 + addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore);
3862 + }
3863 + setComposerCursor(nextCursor);
3864 + setComposerTrigger(
3865 + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor),
3866 + );
3867 + };
3868 + const onPromptChangeStable = useStableCallback(onPromptChange);
3869
3870 // ------------------------------------------------------------------
3871 // Callbacks: prompt replacement / menu
3872 // ------------------------------------------------------------------
3985 - const applyPromptReplacement = useCallback(
3986 - (
3987 - rangeStart: number,
3988 - rangeEnd: number,
3989 - replacement: string,
3990 - options?: {
3991 - expectedText?: string;
3992 - expandedCursorAfterReplace?: number;
3993 - focusEditorAfterReplace?: boolean;
3994 - citationComment?: {
3995 - start: number;
3996 - sourceAnchor: AssistantCitationSourceAnchor;
3997 - insertedSpaces: ComposerCitationCommentRequest["insertedSpaces"];
3998 - };
3999 - },
4000 - ): boolean => {
4001 - if (
4002 - activePendingUserInput &&
4003 - activePendingProgress?.activeQuestion?.allowCustomAnswer === false
4004 - ) {
4005 - return false;
4006 - }
4007 - const currentText = promptRef.current;
4008 - const safeStart = Math.max(0, Math.min(currentText.length, rangeStart));
4009 - const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd));
4010 - if (
4011 - options?.expectedText !== undefined &&
4012 - currentText.slice(safeStart, safeEnd) !== options.expectedText
4013 - ) {
4014 - return false;
4015 - }
4016 - const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement);
4017 - const nextCursor = collapseExpandedComposerCursor(
4018 - next.text,
4019 - options?.expandedCursorAfterReplace ?? next.cursor,
4020 - isLiteralPendingAnswer,
4021 - );
4022 - const nextExpandedCursor = expandCollapsedComposerCursor(
3873 + const applyPromptReplacement = (
3874 + rangeStart: number,
3875 + rangeEnd: number,
3876 + replacement: string,
3877 + options?: {
3878 + expectedText?: string;
3879 + expandedCursorAfterReplace?: number;
3880 + focusEditorAfterReplace?: boolean;
3881 + citationComment?: {
3882 + start: number;
3883 + sourceAnchor: AssistantCitationSourceAnchor;
3884 + insertedSpaces: ComposerCitationCommentRequest["insertedSpaces"];
3885 + };
3886 + },
3887 + ): boolean => {
3888 + if (
3889 + activePendingUserInput &&
3890 + activePendingProgress?.activeQuestion?.allowCustomAnswer === false
3891 + ) {
3892 + return false;
3893 + }
3894 + const currentText = promptRef.current;
3895 + const safeStart = Math.max(0, Math.min(currentText.length, rangeStart));
3896 + const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd));
3897 + if (
3898 + options?.expectedText !== undefined &&
3899 + currentText.slice(safeStart, safeEnd) !== options.expectedText
3900 + ) {
3901 + return false;
3902 + }
3903 + const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement);
3904 + const nextCursor = collapseExpandedComposerCursor(
3905 + next.text,
3906 + options?.expandedCursorAfterReplace ?? next.cursor,
3907 + isLiteralPendingAnswer,
3908 + );
3909 + const nextExpandedCursor = expandCollapsedComposerCursor(
3910 + next.text,
3911 + nextCursor,
3912 + isLiteralPendingAnswer,
3913 + );
3914 + if (options?.citationComment) {
3915 + composerEditorRef.current?.requestCitationComment({
3916 + previousValue: currentText,
3917 + value: next.text,
3918 + citationStart: options.citationComment.start,
3919 + sourceAnchor: options.citationComment.sourceAnchor,
3920 + insertedSpaces: options.citationComment.insertedSpaces,
3921 + });
3922 + }
3923 + promptRef.current = next.text;
3924 + const activePendingQuestion = activePendingProgress?.activeQuestion;
3925 + if (activePendingQuestion && activePendingUserInput) {
3926 + onChangeActivePendingUserInputCustomAnswer(
3927 + activePendingQuestion.id,
3928 next.text,
3929 nextCursor,
3930 + nextExpandedCursor,
3931 isLiteralPendingAnswer,
3932 );
4027 - if (options?.citationComment) {
4028 - composerEditorRef.current?.requestCitationComment({
4029 - previousValue: currentText,
4030 - value: next.text,
4031 - citationStart: options.citationComment.start,
4032 - sourceAnchor: options.citationComment.sourceAnchor,
4033 - insertedSpaces: options.citationComment.insertedSpaces,
4034 - });
4035 - }
4036 - promptRef.current = next.text;
4037 - const activePendingQuestion = activePendingProgress?.activeQuestion;
4038 - if (activePendingQuestion && activePendingUserInput) {
4039 - onChangeActivePendingUserInputCustomAnswer(
4040 - activePendingQuestion.id,
4041 - next.text,
4042 - nextCursor,
4043 - nextExpandedCursor,
4044 - isLiteralPendingAnswer,
4045 - );
4046 - } else {
4047 - setPrompt(next.text);
4048 - onTypingGuardDraftChange();
4049 - }
4050 - setComposerCursor(nextCursor);
4051 - setComposerTrigger(
4052 - isLiteralPendingAnswer ? null : detectComposerTrigger(next.text, nextExpandedCursor),
4053 - );
4054 - if (options?.focusEditorAfterReplace !== false) {
4055 - window.requestAnimationFrame(() => {
4056 - // Type-to-focus routes only the first key through here; once the
4057 - // controlled update focuses the editor, later keys land natively.
4058 - // Skip the deferred caret placement when the draft has moved on,
4059 - // or it drags the caret back behind what was typed since.
4060 - if (promptRef.current !== next.text) return;
4061 - composerEditorRef.current?.focusAt(nextCursor);
4062 - });
4063 - }
4064 - return true;
4065 - },
4066 - [
4067 - activePendingProgress?.activeQuestion,
4068 - activePendingUserInput,
4069 - isLiteralPendingAnswer,
4070 - onChangeActivePendingUserInputCustomAnswer,
4071 - onTypingGuardDraftChange,
4072 - promptRef,
4073 - setPrompt,
4074 - setComposerTrigger,
4075 - ],
4076 - );
3933 + } else {
3934 + setPrompt(next.text);
3935 + onTypingGuardDraftChange();
3936 + }
3937 + setComposerCursor(nextCursor);
3938 + setComposerTrigger(
3939 + isLiteralPendingAnswer ? null : detectComposerTrigger(next.text, nextExpandedCursor),
3940 + );
3941 + if (options?.focusEditorAfterReplace !== false) {
3942 + window.requestAnimationFrame(() => {
3943 + // Type-to-focus routes only the first key through here; once the
3944 + // controlled update focuses the editor, later keys land natively.
3945 + // Skip the deferred caret placement when the draft has moved on,
3946 + // or it drags the caret back behind what was typed since.
3947 + if (promptRef.current !== next.text) return;
3948 + composerEditorRef.current?.focusAt(nextCursor);
3949 + });
3950 + }
3951 + return true;
3952 + };
3953 + const applyPromptReplacementStable = useStableCallback(applyPromptReplacement);
3954
4078 - const readComposerSnapshot = useCallback((): {
3955 + const readComposerSnapshot = (): {
3956 value: string;
3957 cursor: number;
3958 expandedCursor: number;
@@ -4095,9 +3972,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3972 ),
3973 contextIds: isLiteralPendingAnswer ? [] : collectInlineContextIds(promptRef.current),
3974 };
4098 - }, [composerCursor, isLiteralPendingAnswer, promptRef]);
3975 + };
3976 + const readComposerSnapshotStable = useStableCallback(readComposerSnapshot);
3977
4100 - const resolveActiveComposerTrigger = useCallback((): {
3978 + const resolveActiveComposerTrigger = (): {
3979 snapshot: { value: string; cursor: number; expandedCursor: number };
3980 trigger: ComposerTrigger | null;
3981 } => {
@@ -4108,200 +3986,167 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3986 ? null
3987 : resolveComposerTrigger(detectComposerTrigger(snapshot.value, snapshot.expandedCursor)),
3988 };
4111 - }, [isLiteralPendingAnswer, readComposerSnapshot, resolveComposerTrigger]);
3989 + };
3990
3991 const { onUsageLimitsCommand } = props;
4114 - const onSelectComposerItem = useCallback(
4115 - (item: ComposerCommandItem) => {
4116 - if (composerSelectLockRef.current) return;
4117 - composerSelectLockRef.current = true;
4118 - window.requestAnimationFrame(() => {
4119 - composerSelectLockRef.current = false;
3992 + const onSelectComposerItem = (item: ComposerCommandItem) => {
3993 + if (composerSelectLockRef.current) return;
3994 + composerSelectLockRef.current = true;
3995 + window.requestAnimationFrame(() => {
3996 + composerSelectLockRef.current = false;
3997 + });
3998 + const { snapshot, trigger } = resolveActiveComposerTrigger();
3999 + if (!trigger) return;
4000 + if (item.type === "path") {
4001 + const replacement = `${serializeComposerFileLink(item.path)} `;
4002 + const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4003 + snapshot.value,
4004 + trigger.rangeEnd,
4005 + replacement,
4006 + );
4007 + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, {
4008 + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd),
4009 });
4121 - const { snapshot, trigger } = resolveActiveComposerTrigger();
4122 - if (!trigger) return;
4123 - if (item.type === "path") {
4124 - const replacement = `${serializeComposerFileLink(item.path)} `;
4125 - const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4126 - snapshot.value,
4127 - trigger.rangeEnd,
4128 - replacement,
4129 - );
4130 - const applied = applyPromptReplacement(
4131 - trigger.rangeStart,
4132 - replacementRangeEnd,
4133 - replacement,
4134 - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
4135 - );
4136 - if (applied) {
4137 - setComposerHighlightedItemId(null);
4138 - }
4139 - return;
4010 + if (applied) {
4011 + setComposerHighlightedItemId(null);
4012 }
4141 - if (item.type === "slash-command") {
4142 - if (item.command === "model") {
4143 - const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
4144 - expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
4145 - focusEditorAfterReplace: false,
4146 - });
4147 - if (applied) {
4148 - setComposerHighlightedItemId(null);
4149 - setIsComposerModelPickerOpen(true);
4150 - }
4151 - return;
4152 - }
4153 - if (!planModeUiEnabled) return;
4154 - void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
4013 + return;
4014 + }
4015 + if (item.type === "slash-command") {
4016 + if (item.command === "model") {
4017 const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
4018 expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
4019 + focusEditorAfterReplace: false,
4020 });
4021 if (applied) {
4022 setComposerHighlightedItemId(null);
4023 + setIsComposerModelPickerOpen(true);
4024 }
4025 return;
4026 }
4163 - if (item.type === "provider-slash-command") {
4164 - if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) {
4165 - const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
4166 - expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
4167 - focusEditorAfterReplace: false,
4168 - });
4169 - if (applied) {
4170 - setComposerHighlightedItemId(null);
4171 - onUsageLimitsCommand();
4172 - }
4173 - return;
4174 - }
4175 - const replacement = `/${item.command.name} `;
4176 - const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4177 - snapshot.value,
4178 - trigger.rangeEnd,
4179 - replacement,
4180 - );
4181 - const applied = applyPromptReplacement(
4182 - trigger.rangeStart,
4183 - replacementRangeEnd,
4184 - replacement,
4185 - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
4186 - );
4187 - if (applied) {
4188 - setComposerHighlightedItemId(null);
4189 - }
4190 - return;
4027 + if (!planModeUiEnabled) return;
4028 + void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");
4029 + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
4030 + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
4031 + });
4032 + if (applied) {
4033 + setComposerHighlightedItemId(null);
4034 }
4192 - if (item.type === "skill") {
4193 - const replacement = `$${item.skill.name} `;
4194 - const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4195 - snapshot.value,
4196 - trigger.rangeEnd,
4197 - replacement,
4198 - );
4199 - const applied = applyPromptReplacement(
4200 - trigger.rangeStart,
4201 - replacementRangeEnd,
4202 - replacement,
4203 - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
4204 - );
4035 + return;
4036 + }
4037 + if (item.type === "provider-slash-command") {
4038 + if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) {
4039 + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
4040 + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
4041 + focusEditorAfterReplace: false,
4042 + });
4043 if (applied) {
4044 setComposerHighlightedItemId(null);
4045 + onUsageLimitsCommand();
4046 }
4047 return;
4048 }
4210 - if (item.type === "pull-request") {
4211 - if (
4212 - trigger.kind !== "pull-request" ||
4213 - !composerMenuItemsRef.current.some((candidate) => candidate.id === item.id)
4214 - ) {
4215 - return;
4216 - }
4217 - const comment = buildPullRequestReferenceContext(item.pullRequest);
4218 - const replacement = `${formatInlineContextReference(
4219 - reviewCommentContextReference(comment),
4220 - )} `;
4221 - const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4222 - snapshot.value,
4223 - trigger.rangeEnd,
4224 - replacement,
4225 - );
4226 - const applied = applyPromptReplacement(
4227 - trigger.rangeStart,
4228 - replacementRangeEnd,
4229 - replacement,
4230 - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
4231 - );
4232 - if (applied) {
4233 - addComposerDraftReviewComment(composerDraftTarget, comment, {
4234 - appendReference: false,
4235 - });
4236 - setComposerHighlightedItemId(null);
4237 - }
4238 - return;
4049 + const replacement = `/${item.command.name} `;
4050 + const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4051 + snapshot.value,
4052 + trigger.rangeEnd,
4053 + replacement,
4054 + );
4055 + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, {
4056 + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd),
4057 + });
4058 + if (applied) {
4059 + setComposerHighlightedItemId(null);
4060 }
4240 - if (item.type === "thread") {
4241 - if (trigger.kind !== "path") return;
4242 - const shell = readThreadShell(item.thread);
4243 - if (!shell) return;
4244 - const record = threadContextRecord(item.thread, shell.title);
4245 - const replacement = `${formatInlineContextReference(threadContextReference(record))} `;
4246 - const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4247 - snapshot.value,
4248 - trigger.rangeEnd,
4249 - replacement,
4250 - );
4251 - const applied = applyPromptReplacement(
4252 - trigger.rangeStart,
4253 - replacementRangeEnd,
4254 - replacement,
4255 - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) },
4256 - );
4257 - if (applied) {
4258 - addComposerDraftThreadContexts(attachmentDraftTarget, [record], {
4259 - appendReference: false,
4260 - });
4261 - setComposerHighlightedItemId(null);
4262 - }
4061 + return;
4062 + }
4063 + if (item.type === "skill") {
4064 + const replacement = `$${item.skill.name} `;
4065 + const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4066 + snapshot.value,
4067 + trigger.rangeEnd,
4068 + replacement,
4069 + );
4070 + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, {
4071 + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd),
4072 + });
4073 + if (applied) {
4074 + setComposerHighlightedItemId(null);
4075 + }
4076 + return;
4077 + }
4078 + if (item.type === "pull-request") {
4079 + if (
4080 + trigger.kind !== "pull-request" ||
4081 + !composerMenuItemsRef.current.some((candidate) => candidate.id === item.id)
4082 + ) {
4083 return;
4084 }
4265 - },
4266 - [
4267 - addComposerDraftReviewComment,
4268 - addComposerDraftThreadContexts,
4269 - applyPromptReplacement,
4270 - attachmentDraftTarget,
4271 - composerDraftTarget,
4272 - handleInteractionModeChange,
4273 - planModeUiEnabled,
4274 - onUsageLimitsCommand,
4275 - resolveActiveComposerTrigger,
4276 - ],
4277 - );
4085 + const comment = buildPullRequestReferenceContext(item.pullRequest);
4086 + const replacement = `${formatInlineContextReference(
4087 + reviewCommentContextReference(comment),
4088 + )} `;
4089 + const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4090 + snapshot.value,
4091 + trigger.rangeEnd,
4092 + replacement,
4093 + );
4094 + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, {
4095 + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd),
4096 + });
4097 + if (applied) {
4098 + addComposerDraftReviewComment(composerDraftTarget, comment, {
4099 + appendReference: false,
4100 + });
4101 + setComposerHighlightedItemId(null);
4102 + }
4103 + return;
4104 + }
4105 + if (item.type === "thread") {
4106 + if (trigger.kind !== "path") return;
4107 + const shell = readThreadShell(item.thread);
4108 + if (!shell) return;
4109 + const record = threadContextRecord(item.thread, shell.title);
4110 + const replacement = `${formatInlineContextReference(threadContextReference(record))} `;
4111 + const replacementRangeEnd = extendReplacementRangeForTrailingSpace(
4112 + snapshot.value,
4113 + trigger.rangeEnd,
4114 + replacement,
4115 + );
4116 + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, {
4117 + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd),
4118 + });
4119 + if (applied) {
4120 + addComposerDraftThreadContexts(attachmentDraftTarget, [record], {
4121 + appendReference: false,
4122 + });
4123 + setComposerHighlightedItemId(null);
4124 + }
4125 + return;
4126 + }
4127 + };
4128 + const onSelectComposerItemStable = useStableCallback(onSelectComposerItem);
4129
4279 - const onComposerMenuItemHighlighted = useCallback(
4280 - (itemId: string | null) => {
4281 - setComposerHighlightedItemId(itemId);
4282 - setComposerHighlightedSearchKey(composerMenuSearchKey);
4283 - },
4284 - [composerMenuSearchKey],
4285 - );
4130 + const onComposerMenuItemHighlighted = (itemId: string | null) => {
4131 + setComposerHighlightedItemId(itemId);
4132 + setComposerHighlightedSearchKey(composerMenuSearchKey);
4133 + };
4134 + const onComposerMenuItemHighlightedStable = useStableCallback(onComposerMenuItemHighlighted);
4135
4287 - const nudgeComposerMenuHighlight = useCallback(
4288 - (key: "ArrowDown" | "ArrowUp") => {
4289 - if (composerMenuItems.length === 0) return;
4290 - const highlightedIndex = composerMenuItems.findIndex(
4291 - (item) => item.id === composerHighlightedItemId,
4292 - );
4293 - const normalizedIndex =
4294 - highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0;
4295 - const offset = key === "ArrowDown" ? 1 : -1;
4296 - const nextIndex =
4297 - (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length;
4298 - const nextItem = composerMenuItems[nextIndex];
4299 - setComposerHighlightedItemId(nextItem?.id ?? null);
4300 - },
4301 - [composerHighlightedItemId, composerMenuItems],
4302 - );
4136 + const nudgeComposerMenuHighlight = (key: "ArrowDown" | "ArrowUp") => {
4137 + if (composerMenuItems.length === 0) return;
4138 + const highlightedIndex = composerMenuItems.findIndex(
4139 + (item) => item.id === composerHighlightedItemId,
4140 + );
4141 + const normalizedIndex = highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0;
4142 + const offset = key === "ArrowDown" ? 1 : -1;
4143 + const nextIndex =
4144 + (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length;
4145 + const nextItem = composerMenuItems[nextIndex];
4146 + setComposerHighlightedItemId(nextItem?.id ?? null);
4147 + };
4148
4304 - const blurMobileComposerAfterSend = useCallback(() => {
4149 + const blurMobileComposerAfterSend = () => {
4150 if (!isMobileViewport) return;
4151 if (composerBlurFrameRef.current !== null) {
4152 window.cancelAnimationFrame(composerBlurFrameRef.current);
@@ -4312,9 +4157,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4157 activeElement.blur();
4158 }
4159 setIsComposerFocused(false);
4315 - }, [isMobileViewport, setIsComposerFocused]);
4160 + };
4161
4317 - const shouldBlurMobileComposerOnSubmit = useCallback(() => {
4162 + const shouldBlurMobileComposerOnSubmit = () => {
4163 if (!isMobileViewport) return false;
4164 if (
4165 isSendBusy ||
@@ -4330,120 +4175,87 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4175 return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
4176 }
4177 return showPlanFollowUpPrompt || composerSendState.hasSendableContent;
4333 - }, [
4334 - activePendingProgress,
4335 - activePendingResolvedAnswers,
4336 - composerSendState.hasSendableContent,
4337 - environmentUnavailable,
4338 - isConnecting,
4339 - isMobileViewport,
4340 - isSendBusy,
4341 - isSendDisabled,
4342 - noProviderAvailable,
4343 - phase,
4344 - showPlanFollowUpPrompt,
4345 - ]);
4178 + };
4179
4347 - const submitComposer = useCallback(
4348 - (
4349 - event?: { preventDefault: () => void },
4350 - dispatchMode?: ComposerDispatchMode,
4351 - submissionIntent?: ComposerSubmissionIntent,
4352 - ) => {
4353 - if (
4354 - noProviderAvailable ||
4355 - isSendDisabled ||
4356 - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
4357 - ) {
4358 - event?.preventDefault();
4359 - return;
4360 - }
4361 - // A send while a pasted image is still compressing would strand that
4362 - // image: the turn snapshot wouldn't include it, and it would surface
4363 - // in the *next* draft instead. Only oversized images hit this — small
4364 - // files clear the pending counter within a microtask.
4365 - if (
4366 - activeThreadId &&
4367 - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0
4368 - ) {
4369 - event?.preventDefault();
4370 - toastManager.add({
4371 - type: "info",
4372 - title: "Still compressing a pasted image.",
4373 - description: "Send again once its thumbnail appears.",
4374 - });
4375 - return;
4376 - }
4377 - // A pasted chip's bytes arrive over the network, so the same hazard applies for longer:
4378 - // sending now would snapshot a chip with no attachment behind it.
4379 - if (pendingDraftWork.has(attachmentTargetKey)) {
4380 - event?.preventDefault();
4381 - toastManager.add({
4382 - type: "info",
4383 - title: "Still bringing attached context into this message.",
4384 - description: "Send again once its chip resolves.",
4385 - });
4386 - return;
4387 - }
4388 - const submission = submitComposerDraft({
4389 - prompt: promptRef.current,
4390 - submissionTarget: activePendingProgress ? "pending-user-input" : "provider-turn",
4391 - event,
4392 - onSend: (sendEvent) => {
4393 - // ChatView reports its final composed-input preflight through the
4394 - // composer handle before its first asynchronous send step.
4395 - providerInputRejectedRef.current = false;
4396 - onSend(
4397 - sendEvent,
4398 - dispatchMode ??
4399 - resolveComposerDispatchMode({
4400 - running: phase === "running",
4401 - alternateModifier: false,
4402 - activeTurnDefault: settings.followUpBehavior,
4403 - }),
4404 - submissionIntent,
4405 - );
4406 - return !providerInputRejectedRef.current;
4407 - },
4180 + const submitComposer = (
4181 + event?: { preventDefault: () => void },
4182 + dispatchMode?: ComposerDispatchMode,
4183 + submissionIntent?: ComposerSubmissionIntent,
4184 + ) => {
4185 + if (
4186 + noProviderAvailable ||
4187 + isSendDisabled ||
4188 + !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
4189 + ) {
4190 + event?.preventDefault();
4191 + return;
4192 + }
4193 + // A send while a pasted image is still compressing would strand that
4194 + // image: the turn snapshot wouldn't include it, and it would surface
4195 + // in the *next* draft instead. Only oversized images hit this — small
4196 + // files clear the pending counter within a microtask.
4197 + if (activeThreadId && (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0) {
4198 + event?.preventDefault();
4199 + toastManager.add({
4200 + type: "info",
4201 + title: "Still compressing a pasted image.",
4202 + description: "Send again once its thumbnail appears.",
4203 });
4409 - setComposerSubmissionError(submission.validationMessage);
4410 - if (!submission.didDispatch) return;
4411 - onTypingGuardSend();
4412 - if (shouldBlurMobileComposerOnSubmit()) {
4413 - blurMobileComposerAfterSend();
4414 - }
4415 - },
4416 - [
4417 - activeThreadId,
4418 - activePendingProgress,
4419 - attachmentTargetKey,
4420 - onTypingGuardSend,
4421 - blurMobileComposerAfterSend,
4422 - environmentId,
4423 - isSendDisabled,
4424 - noProviderAvailable,
4425 - onSend,
4426 - settings.followUpBehavior,
4427 - phase,
4428 - promptRef,
4429 - shouldBlurMobileComposerOnSubmit,
4430 - ],
4431 - );
4432 - const handleSubmitMessage = useCallback(
4433 - (event: React.MouseEvent<HTMLButtonElement>) => {
4434 - event.preventDefault();
4435 - submitComposer(
4436 - event,
4437 - resolveComposerDispatchMode({
4438 - running: phase === "running",
4439 - alternateModifier: event.metaKey || event.ctrlKey,
4440 - activeTurnDefault: settings.followUpBehavior,
4441 - }),
4442 - );
4443 - },
4444 - [phase, settings.followUpBehavior, submitComposer],
4445 - );
4446 - const submitCitationAndSend = useCallback(() => {
4204 + return;
4205 + }
4206 + // A pasted chip's bytes arrive over the network, so the same hazard applies for longer:
4207 + // sending now would snapshot a chip with no attachment behind it.
4208 + if (pendingDraftWork.has(attachmentTargetKey)) {
4209 + event?.preventDefault();
4210 + toastManager.add({
4211 + type: "info",
4212 + title: "Still bringing attached context into this message.",
4213 + description: "Send again once its chip resolves.",
4214 + });
4215 + return;
4216 + }
4217 + const submission = submitComposerDraft({
4218 + prompt: promptRef.current,
4219 + submissionTarget: activePendingProgress ? "pending-user-input" : "provider-turn",
4220 + event,
4221 + onSend: (sendEvent) => {
4222 + // ChatView reports its final composed-input preflight through the
4223 + // composer handle before its first asynchronous send step.
4224 + providerInputRejectedRef.current = false;
4225 + onSend(
4226 + sendEvent,
4227 + dispatchMode ??
4228 + resolveComposerDispatchMode({
4229 + running: phase === "running",
4230 + alternateModifier: false,
4231 + activeTurnDefault: settings.followUpBehavior,
4232 + }),
4233 + submissionIntent,
4234 + );
4235 + return !providerInputRejectedRef.current;
4236 + },
4237 + });
4238 + setComposerSubmissionError(submission.validationMessage);
4239 + if (!submission.didDispatch) return;
4240 + onTypingGuardSend();
4241 + if (shouldBlurMobileComposerOnSubmit()) {
4242 + blurMobileComposerAfterSend();
4243 + }
4244 + };
4245 + const submitComposerStable = useStableCallback(submitComposer);
4246 + const handleSubmitMessage = (event: React.MouseEvent<HTMLButtonElement>) => {
4247 + event.preventDefault();
4248 + submitComposer(
4249 + event,
4250 + resolveComposerDispatchMode({
4251 + running: phase === "running",
4252 + alternateModifier: event.metaKey || event.ctrlKey,
4253 + activeTurnDefault: settings.followUpBehavior,
4254 + }),
4255 + );
4256 + };
4257 + const handleSubmitMessageStable = useStableCallback(handleSubmitMessage);
4258 + const submitCitationAndSend = () => {
4259 submitComposer(
4260 undefined,
4261 resolveComposerDispatchMode({
@@ -4452,18 +4264,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4264 activeTurnDefault: settings.followUpBehavior,
4265 }),
4266 );
4455 - }, [phase, settings.followUpBehavior, submitComposer]);
4267 + };
4268 + const submitCitationAndSendStable = useStableCallback(submitCitationAndSend);
4269 // A question or approval took the editor while a citation comment was
4270 // unsaved. Keep the comment in the prompt that comes back afterward.
4458 - const saveCitationDraftToPrompt = useCallback(
4459 - (replacedValue: string, savedValue: string) => {
4460 - if (replacedValue !== prompt) return;
4461 - if (promptRef.current === replacedValue) promptRef.current = savedValue;
4462 - setPrompt(savedValue);
4463 - },
4464 - [prompt, promptRef, setPrompt],
4465 - );
4466 - const compactThreadContext = useCallback(() => {
4271 + const saveCitationDraftToPrompt = (replacedValue: string, savedValue: string) => {
4272 + if (replacedValue !== prompt) return;
4273 + if (promptRef.current === replacedValue) promptRef.current = savedValue;
4274 + setPrompt(savedValue);
4275 + };
4276 + const saveCitationDraftToPromptStable = useStableCallback(saveCitationDraftToPrompt);
4277 + const compactThreadContext = () => {
4278 if (
4279 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
4280 compactDisabled ||
@@ -4478,20 +4289,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4289 return;
4290 }
4291 onCompactContext();
4481 - }, [
4482 - activePendingApproval,
4483 - activeThreadId,
4484 - compactDisabled,
4485 - composerDraftTarget,
4486 - environmentId,
4487 - isConnecting,
4488 - isSendBusy,
4489 - noProviderAvailable,
4490 - onCompactContext,
4491 - pendingUserInputs.length,
4492 - phase,
4493 - ]);
4494 - const expandMobileComposer = useCallback(() => {
4292 + };
4293 + const compactThreadContextStable = useStableCallback(compactThreadContext);
4294 + const expandMobileComposer = () => {
4295 if (composerBlurFrameRef.current !== null) {
4296 window.cancelAnimationFrame(composerBlurFrameRef.current);
4297 composerBlurFrameRef.current = null;
@@ -4512,7 +4312,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4312 mobileComposerExpandInFlightRef.current = false;
4313 });
4314 });
4515 - }, [setIsComposerFocused]);
4315 + };
4316 + const expandMobileComposerStable = useStableCallback(expandMobileComposer);
4317
4318 // ------------------------------------------------------------------
4319 // Prompt history (ArrowUp / ArrowDown)
@@ -4530,68 +4331,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4331 promptHistoryPositionRef.current = null;
4332 }, [promptHistoryTargetKey]);
4333
4533 - const replacePromptFromHistory = useCallback(
4534 - (nextPrompt: string) => {
4535 - promptRef.current = nextPrompt;
4536 - setComposerDraftPrompt(composerDraftTarget, nextPrompt);
4537 - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
4538 - setComposerTrigger(null);
4539 - setComposerHighlightedItemId(null);
4540 - },
4541 - [composerDraftTarget, promptRef, setComposerDraftPrompt, setComposerTrigger],
4542 - );
4334 + const replacePromptFromHistory = (nextPrompt: string) => {
4335 + promptRef.current = nextPrompt;
4336 + setComposerDraftPrompt(composerDraftTarget, nextPrompt);
4337 + setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
4338 + setComposerTrigger(null);
4339 + setComposerHighlightedItemId(null);
4340 + };
4341
4544 - const navigatePromptHistory = useCallback(
4545 - (direction: "backward" | "forward", event: KeyboardEvent): boolean => {
4546 - if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
4547 - return false;
4548 - }
4549 - if (isComposerApprovalState || pendingUserInputs.length > 0) return false;
4550 - // A composer holding an image, file, picked element, preview
4551 - // annotation, or review comment is not empty. Recalling text into it
4552 - // would send the old prompt with the new context, which is never what
4553 - // ArrowUp meant.
4554 - if (
4555 - composerImagesRef.current.length > 0 ||
4556 - composerFilesRef.current.length > 0 ||
4557 - composerTerminalContextsRef.current.length > 0 ||
4558 - composerPreviewAnnotations.length > 0 ||
4559 - composerReviewComments.length > 0
4560 - ) {
4561 - return false;
4562 - }
4563 - // A typed draft with no active recall can never step, so skip the
4564 - // layout read and the entry build for that common case.
4565 - if (promptHistoryPositionRef.current === null && promptRef.current.length > 0) {
4566 - return false;
4567 - }
4568 - const editor = composerEditorRef.current;
4569 - if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) {
4570 - return false;
4571 - }
4572 - const step = stepComposerPromptHistory({
4573 - direction,
4574 - entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current),
4575 - position: promptHistoryPositionRef.current,
4576 - currentPrompt: promptRef.current,
4577 - });
4578 - if (!step) return false;
4579 - promptHistoryPositionRef.current = step.position;
4580 - replacePromptFromHistory(step.prompt);
4581 - return true;
4582 - },
4583 - [
4584 - composerTerminalContextsRef,
4585 - composerFilesRef,
4586 - composerImagesRef,
4587 - composerPreviewAnnotations.length,
4588 - composerReviewComments.length,
4589 - isComposerApprovalState,
4590 - pendingUserInputs.length,
4591 - promptRef,
4592 - replacePromptFromHistory,
4593 - ],
4594 - );
4342 + const navigatePromptHistory = (
4343 + direction: "backward" | "forward",
4344 + event: KeyboardEvent,
4345 + ): boolean => {
4346 + if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
4347 + return false;
4348 + }
4349 + if (isComposerApprovalState || pendingUserInputs.length > 0) return false;
4350 + // A composer holding an image, file, picked element, preview
4351 + // annotation, or review comment is not empty. Recalling text into it
4352 + // would send the old prompt with the new context, which is never what
4353 + // ArrowUp meant.
4354 + if (
4355 + composerImagesRef.current.length > 0 ||
4356 + composerFilesRef.current.length > 0 ||
4357 + composerTerminalContextsRef.current.length > 0 ||
4358 + composerPreviewAnnotations.length > 0 ||
4359 + composerReviewComments.length > 0
4360 + ) {
4361 + return false;
4362 + }
4363 + // A typed draft with no active recall can never step, so skip the
4364 + // layout read and the entry build for that common case.
4365 + if (promptHistoryPositionRef.current === null && promptRef.current.length > 0) {
4366 + return false;
4367 + }
4368 + const editor = composerEditorRef.current;
4369 + if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) {
4370 + return false;
4371 + }
4372 + const step = stepComposerPromptHistory({
4373 + direction,
4374 + entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current),
4375 + position: promptHistoryPositionRef.current,
4376 + currentPrompt: promptRef.current,
4377 + });
4378 + if (!step) return false;
4379 + promptHistoryPositionRef.current = step.position;
4380 + replacePromptFromHistory(step.prompt);
4381 + return true;
4382 + };
4383
4384 // ------------------------------------------------------------------
4385 // Callbacks: command key
@@ -4701,7 +4489,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4489 }, []);
4490
4491 /** Briefly highlight the badge so the save registers without a flourish. */
4704 - const pulseStashBadge = useCallback(() => {
4492 + const pulseStashBadge = () => {
4493 stashPulseKeyRef.current += 1;
4494 setStashPulse({ key: stashPulseKeyRef.current, active: true });
4495 if (stashPulseTimeoutRef.current !== null) {
@@ -4711,334 +4499,318 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4499 stashPulseTimeoutRef.current = null;
4500 setStashPulse((current) => ({ ...current, active: false }));
4501 }, 1200);
4714 - }, []);
4715 -
4716 - const restoreStashEntry = useCallback(
4717 - async (menuEntry: PromptStashEntry) => {
4718 - const filesToVerify = menuEntry.files ?? [];
4719 - if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
4720 - toastManager.add({
4721 - type: "error",
4722 - title: "Stashed files belong to another environment",
4723 - description: "Restore this prompt in the environment that received its files.",
4724 - });
4725 - return;
4726 - }
4727 - setIsStashMenuOpen(false);
4502 + };
4503
4729 - // The server sweeps pending uploads after 24 hours, so ask before
4730 - // reattaching. An expired upload restores as a needs-reattach row
4731 - // instead of a reference the next send would fail to verify. Verify
4732 - // BEFORE taking: the take removes the entry from durable storage, and a
4733 - // tab closed during this await must still find it there after reload.
4734 - const verifications = await Promise.all(
4735 - filesToVerify.map((file) =>
4736 - verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }),
4737 - ),
4738 - );
4739 - const expiredAttachmentIds = new Set(
4740 - filesToVerify
4741 - .filter((_, index) => verifications[index]?.status === "missing")
4742 - .map((file) => file.attachmentId),
4743 - );
4504 + const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
4505 + const filesToVerify = menuEntry.files ?? [];
4506 + if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
4507 + toastManager.add({
4508 + type: "error",
4509 + title: "Stashed files belong to another environment",
4510 + description: "Restore this prompt in the environment that received its files.",
4511 + });
4512 + return;
4513 + }
4514 + setIsStashMenuOpen(false);
4515
4745 - // A thread switch during the verify await would mix the new thread's
4746 - // prompt with this invocation's captured target. Nothing was taken yet,
4747 - // so abort and leave the entry restorable where the user now is.
4748 - if (
4749 - isRevertingCheckpointRef.current ||
4750 - composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
4751 - ) {
4752 - return;
4753 - }
4516 + // The server sweeps pending uploads after 24 hours, so ask before
4517 + // reattaching. An expired upload restores as a needs-reattach row
4518 + // instead of a reference the next send would fail to verify. Verify
4519 + // BEFORE taking: the take removes the entry from durable storage, and a
4520 + // tab closed during this await must still find it there after reload.
4521 + const verifications = await Promise.all(
4522 + filesToVerify.map((file) =>
4523 + verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }),
4524 + ),
4525 + );
4526 + const expiredAttachmentIds = new Set(
4527 + filesToVerify
4528 + .filter((_, index) => verifications[index]?.status === "missing")
4529 + .map((file) => file.attachmentId),
4530 + );
4531
4755 - // The take is also the double-activation guard (click + Enter): the
4756 - // second caller finds the entry gone and stops here.
4757 - const { entry, durable } = takeStashEntry(menuEntry.id);
4758 - if (!entry) return;
4759 - if (!durable) {
4760 - toastManager.add({
4761 - type: "warning",
4762 - title: "Restored prompt may reappear in the stash",
4763 - description:
4764 - "Browser storage rejected the update, so this entry could still be there after a reload.",
4765 - data: { hideCopyButton: true },
4766 - });
4767 - }
4532 + // A thread switch during the verify await would mix the new thread's
4533 + // prompt with this invocation's captured target. Nothing was taken yet,
4534 + // so abort and leave the entry restorable where the user now is.
4535 + if (
4536 + isRevertingCheckpointRef.current ||
4537 + composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
4538 + ) {
4539 + return;
4540 + }
4541
4769 - const rewrittenContextIds = entry.records
4770 - ? importContextRecords(entry.records, null)
4771 - : new Map<string, string>();
4772 - const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => {
4773 - const contextId = rewrittenContextIds.get(reference.contextId);
4774 - return contextId
4775 - ? formatInlineContextReference({
4776 - ...reference,
4777 - contextId,
4778 - kind: reference.kind === "element" ? "preview-annotation" : reference.kind,
4779 - })
4780 - : reference.source;
4542 + // The take is also the double-activation guard (click + Enter): the
4543 + // second caller finds the entry gone and stops here.
4544 + const { entry, durable } = takeStashEntry(menuEntry.id);
4545 + if (!entry) return;
4546 + if (!durable) {
4547 + toastManager.add({
4548 + type: "warning",
4549 + title: "Restored prompt may reappear in the stash",
4550 + description:
4551 + "Browser storage rejected the update, so this entry could still be there after a reload.",
4552 + data: { hideCopyButton: true },
4553 });
4782 - const currentPrompt = promptRef.current;
4783 - // An image-only stash must not append blank lines to whatever is
4784 - // already in the composer.
4785 - const nextPrompt =
4786 - restoredPrompt.length === 0
4787 - ? currentPrompt
4788 - : currentPrompt.trim().length
4789 - ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}`
4790 - : restoredPrompt;
4791 - let promptChanged = nextPrompt !== currentPrompt;
4792 - if (promptChanged) {
4793 - promptRef.current = nextPrompt;
4794 - setComposerDraftPrompt(composerDraftTarget, nextPrompt);
4795 - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
4796 - setComposerTrigger(null);
4797 - }
4554 + }
4555
4799 - let unrestoredFileNames: string[] = [];
4800 - const expiredFileNames: string[] = [];
4801 - let restoredFileCount = 0;
4802 - const stashedFiles = entry.files ?? [];
4803 - if (stashedFiles.length > 0) {
4804 - const composerFilesNow = composerFilesRef.current;
4805 - const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
4806 - const retainedUploadIds = new Set(
4807 - composerFilesNow.flatMap((file) =>
4808 - file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
4809 - ),
4810 - );
4811 - const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey));
4812 - const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach);
4813 - const restoredMarkerIds = new Set<string>();
4814 - const duplicateFiles: PersistedComposerFileAttachment[] = [];
4815 - const markerReplacements: ComposerFileAttachment[] = [];
4816 - const appendedFiles: ComposerFileAttachment[] = [];
4817 - for (const file of stashedFiles) {
4818 - const expired = expiredAttachmentIds.has(file.attachmentId);
4819 - const key = composerFileDedupKey(file);
4820 - const restored: ComposerFileAttachment = {
4821 - type: "file",
4822 - id: file.id,
4823 - name: file.name,
4824 - mimeType: file.mimeType,
4825 - sizeBytes: file.sizeBytes,
4826 - file: null,
4827 - ...(file.source ? { source: file.source } : {}),
4828 - // An expired upload carries no ids, so it hydrates as a
4829 - // needs-reattach row and the "Attach again" flow takes over.
4830 - ...(expired
4831 - ? {}
4832 - : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }),
4833 - };
4834 - if (existingFileIds.has(file.id)) {
4835 - if (!expired && !retainedUploadIds.has(file.attachmentId)) {
4836 - duplicateFiles.push(file);
4837 - }
4838 - continue;
4839 - }
4840 - const reattachMarker = reattachMarkers.find(
4841 - (marker) =>
4842 - !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file),
4843 - );
4844 - if (reattachMarker) {
4845 - restoredMarkerIds.add(reattachMarker.id);
4846 - existingFileIds.add(file.id);
4847 - existingFileKeys.add(key);
4848 - if (expired) {
4849 - expiredFileNames.push(file.name);
4850 - } else {
4851 - retainedUploadIds.add(file.attachmentId);
4852 - markerReplacements.push(restored);
4853 - }
4854 - continue;
4855 - }
4856 - if (existingFileKeys.has(key)) {
4857 - if (!expired && !retainedUploadIds.has(file.attachmentId)) {
4858 - duplicateFiles.push(file);
4859 - }
4860 - continue;
4556 + const rewrittenContextIds = entry.records
4557 + ? importContextRecords(entry.records, null)
4558 + : new Map<string, string>();
4559 + const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => {
4560 + const contextId = rewrittenContextIds.get(reference.contextId);
4561 + return contextId
4562 + ? formatInlineContextReference({
4563 + ...reference,
4564 + contextId,
4565 + kind: reference.kind === "element" ? "preview-annotation" : reference.kind,
4566 + })
4567 + : reference.source;
4568 + });
4569 + const currentPrompt = promptRef.current;
4570 + // An image-only stash must not append blank lines to whatever is
4571 + // already in the composer.
4572 + const nextPrompt =
4573 + restoredPrompt.length === 0
4574 + ? currentPrompt
4575 + : currentPrompt.trim().length
4576 + ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}`
4577 + : restoredPrompt;
4578 + let promptChanged = nextPrompt !== currentPrompt;
4579 + if (promptChanged) {
4580 + promptRef.current = nextPrompt;
4581 + setComposerDraftPrompt(composerDraftTarget, nextPrompt);
4582 + setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length));
4583 + setComposerTrigger(null);
4584 + }
4585 +
4586 + let unrestoredFileNames: string[] = [];
4587 + const expiredFileNames: string[] = [];
4588 + let restoredFileCount = 0;
4589 + const stashedFiles = entry.files ?? [];
4590 + if (stashedFiles.length > 0) {
4591 + const composerFilesNow = composerFilesRef.current;
4592 + const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
4593 + const retainedUploadIds = new Set(
4594 + composerFilesNow.flatMap((file) =>
4595 + file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
4596 + ),
4597 + );
4598 + const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey));
4599 + const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach);
4600 + const restoredMarkerIds = new Set<string>();
4601 + const duplicateFiles: PersistedComposerFileAttachment[] = [];
4602 + const markerReplacements: ComposerFileAttachment[] = [];
4603 + const appendedFiles: ComposerFileAttachment[] = [];
4604 + for (const file of stashedFiles) {
4605 + const expired = expiredAttachmentIds.has(file.attachmentId);
4606 + const key = composerFileDedupKey(file);
4607 + const restored: ComposerFileAttachment = {
4608 + type: "file",
4609 + id: file.id,
4610 + name: file.name,
4611 + mimeType: file.mimeType,
4612 + sizeBytes: file.sizeBytes,
4613 + file: null,
4614 + ...(file.source ? { source: file.source } : {}),
4615 + // An expired upload carries no ids, so it hydrates as a
4616 + // needs-reattach row and the "Attach again" flow takes over.
4617 + ...(expired
4618 + ? {}
4619 + : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }),
4620 + };
4621 + if (existingFileIds.has(file.id)) {
4622 + if (!expired && !retainedUploadIds.has(file.attachmentId)) {
4623 + duplicateFiles.push(file);
4624 }
4625 + continue;
4626 + }
4627 + const reattachMarker = reattachMarkers.find(
4628 + (marker) =>
4629 + !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file),
4630 + );
4631 + if (reattachMarker) {
4632 + restoredMarkerIds.add(reattachMarker.id);
4633 existingFileIds.add(file.id);
4634 existingFileKeys.add(key);
4635 if (expired) {
4636 expiredFileNames.push(file.name);
4637 } else {
4638 retainedUploadIds.add(file.attachmentId);
4639 + markerReplacements.push(restored);
4640 }
4869 - appendedFiles.push(restored);
4641 + continue;
4642 }
4871 - const capacity = remainingComposerAttachmentSlots(
4872 - composerImagesRef.current.length + composerFilesNow.length,
4873 - pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
4874 - );
4875 - // Marker replacements reuse their marker's slot; only appended files
4876 - // consume capacity.
4877 - const filesToAppend = appendedFiles.slice(0, capacity);
4878 - const skippedFiles = appendedFiles.slice(capacity);
4879 - unrestoredFileNames = skippedFiles.map((file) => file.name);
4880 - // A non-durable take can resurrect the stash entry after a reload;
4881 - // deleting these uploads would leave it pointing at nothing.
4882 - if (durable) {
4883 - for (const file of duplicateFiles) {
4643 + if (existingFileKeys.has(key)) {
4644 + if (!expired && !retainedUploadIds.has(file.attachmentId)) {
4645 + duplicateFiles.push(file);
4646 + }
4647 + continue;
4648 + }
4649 + existingFileIds.add(file.id);
4650 + existingFileKeys.add(key);
4651 + if (expired) {
4652 + expiredFileNames.push(file.name);
4653 + } else {
4654 + retainedUploadIds.add(file.attachmentId);
4655 + }
4656 + appendedFiles.push(restored);
4657 + }
4658 + const capacity = remainingComposerAttachmentSlots(
4659 + composerImagesRef.current.length + composerFilesNow.length,
4660 + pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
4661 + );
4662 + // Marker replacements reuse their marker's slot; only appended files
4663 + // consume capacity.
4664 + const filesToAppend = appendedFiles.slice(0, capacity);
4665 + const skippedFiles = appendedFiles.slice(capacity);
4666 + unrestoredFileNames = skippedFiles.map((file) => file.name);
4667 + // A non-durable take can resurrect the stash entry after a reload;
4668 + // deleting these uploads would leave it pointing at nothing.
4669 + if (durable) {
4670 + for (const file of duplicateFiles) {
4671 + releasePersistedAttachmentUpload({
4672 + id: file.id,
4673 + environmentId,
4674 + attachmentId: file.attachmentId,
4675 + });
4676 + }
4677 + for (const file of skippedFiles) {
4678 + if (file.uploadedAttachmentId) {
4679 releasePersistedAttachmentUpload({
4680 id: file.id,
4681 environmentId,
4887 - attachmentId: file.attachmentId,
4682 + attachmentId: file.uploadedAttachmentId,
4683 });
4684 }
4890 - for (const file of skippedFiles) {
4891 - if (file.uploadedAttachmentId) {
4892 - releasePersistedAttachmentUpload({
4893 - id: file.id,
4894 - environmentId,
4895 - attachmentId: file.uploadedAttachmentId,
4896 - });
4897 - }
4898 - }
4685 }
4900 - const restoredFiles = [...markerReplacements, ...filesToAppend];
4901 - if (restoredFiles.length > 0) {
4902 - addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true });
4903 - const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt;
4904 - if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) {
4905 - promptRef.current = restoredFilePrompt;
4906 - setComposerCursor(
4907 - collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length),
4908 - );
4909 - setComposerTrigger(null);
4910 - promptChanged = true;
4911 - }
4912 - restoredFileCount = filesToAppend.length;
4686 + }
4687 + const restoredFiles = [...markerReplacements, ...filesToAppend];
4688 + if (restoredFiles.length > 0) {
4689 + addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true });
4690 + const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt;
4691 + if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) {
4692 + promptRef.current = restoredFilePrompt;
4693 + setComposerCursor(
4694 + collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length),
4695 + );
4696 + setComposerTrigger(null);
4697 + promptChanged = true;
4698 }
4699 + restoredFileCount = filesToAppend.length;
4700 }
4701 + }
4702
4916 - let unrestoredImageNames: string[] = [];
4917 - if (entry.attachments.length > 0) {
4918 - const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
4919 - // The draft store also dedupes by mimeType+sizeBytes+name, so filter
4920 - // on the same key here. Counting a duplicate against capacity would
4921 - // burn a slot the store then refuses to fill, pushing a genuinely
4922 - // unique image into the overflow list for nothing.
4923 - const existingDedupKeys = new Set(
4924 - composerImagesRef.current.map(
4925 - (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
4703 + let unrestoredImageNames: string[] = [];
4704 + if (entry.attachments.length > 0) {
4705 + const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
4706 + // The draft store also dedupes by mimeType+sizeBytes+name, so filter
4707 + // on the same key here. Counting a duplicate against capacity would
4708 + // burn a slot the store then refuses to fill, pushing a genuinely
4709 + // unique image into the overflow list for nothing.
4710 + const existingDedupKeys = new Set(
4711 + composerImagesRef.current.map(
4712 + (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
4713 + ),
4714 + );
4715 + const capacity = remainingComposerAttachmentSlots(
4716 + composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
4717 + pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
4718 + );
4719 + const pending = entry.attachments.filter(
4720 + (attachment) =>
4721 + !existingIds.has(attachment.id) &&
4722 + !existingDedupKeys.has(
4723 + `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`,
4724 ),
4927 - );
4928 - const capacity = remainingComposerAttachmentSlots(
4929 - composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
4930 - pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
4931 - );
4932 - const pending = entry.attachments.filter(
4933 - (attachment) =>
4934 - !existingIds.has(attachment.id) &&
4935 - !existingDedupKeys.has(
4936 - `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`,
4937 - ),
4938 - );
4939 - // Anything past the attachment limit cannot be restored. The entry is
4940 - // already out of the queue, so report the overflow by name instead of
4941 - // discarding it silently.
4942 - unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name);
4943 - const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity));
4944 - if (restoredImages.length > 0) {
4945 - addComposerDraftImages(composerDraftTarget, restoredImages);
4946 - }
4725 + );
4726 + // Anything past the attachment limit cannot be restored. The entry is
4727 + // already out of the queue, so report the overflow by name instead of
4728 + // discarding it silently.
4729 + unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name);
4730 + const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity));
4731 + if (restoredImages.length > 0) {
4732 + addComposerDraftImages(composerDraftTarget, restoredImages);
4733 }
4734 + }
4735
4949 - // Deliberately no model/provider restore: the stash exists to carry a
4950 - // prompt across threads and providers, so whatever the composer has
4951 - // selected right now stays selected.
4952 -
4953 - // Each cause gets its own sentence so "too large" is never blamed for a
4954 - // file that actually failed to decode, or for one the composer simply
4955 - // had no room to take back.
4956 - const missingImageReasons: string[] = [];
4957 - if (entry.droppedImageNames.length > 0) {
4958 - missingImageReasons.push(
4959 - `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
4960 - );
4961 - }
4962 - if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
4963 - missingImageReasons.push(
4964 - `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
4965 - );
4966 - }
4967 - if (unrestoredImageNames.length > 0) {
4968 - missingImageReasons.push(
4969 - `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
4970 - );
4971 - }
4972 - if (unrestoredFileNames.length > 0) {
4973 - missingImageReasons.push(
4974 - `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
4975 - );
4976 - }
4977 - if (expiredFileNames.length > 0) {
4978 - missingImageReasons.push(
4979 - `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`,
4980 - );
4981 - }
4982 - if (missingImageReasons.length > 0) {
4983 - toastManager.add({
4984 - type: "warning",
4985 - title: "Some attachments were not restored",
4986 - description: missingImageReasons.join(" "),
4987 - });
4988 - }
4736 + // Deliberately no model/provider restore: the stash exists to carry a
4737 + // prompt across threads and providers, so whatever the composer has
4738 + // selected right now stays selected.
4739 +
4740 + // Each cause gets its own sentence so "too large" is never blamed for a
4741 + // file that actually failed to decode, or for one the composer simply
4742 + // had no room to take back.
4743 + const missingImageReasons: string[] = [];
4744 + if (entry.droppedImageNames.length > 0) {
4745 + missingImageReasons.push(
4746 + `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
4747 + );
4748 + }
4749 + if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
4750 + missingImageReasons.push(
4751 + `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
4752 + );
4753 + }
4754 + if (unrestoredImageNames.length > 0) {
4755 + missingImageReasons.push(
4756 + `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
4757 + );
4758 + }
4759 + if (unrestoredFileNames.length > 0) {
4760 + missingImageReasons.push(
4761 + `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
4762 + );
4763 + }
4764 + if (expiredFileNames.length > 0) {
4765 + missingImageReasons.push(
4766 + `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`,
4767 + );
4768 + }
4769 + if (missingImageReasons.length > 0) {
4770 + toastManager.add({
4771 + type: "warning",
4772 + title: "Some attachments were not restored",
4773 + description: missingImageReasons.join(" "),
4774 + });
4775 + }
4776
4990 - // Only yank the caret to the end when text was actually inserted;
4991 - // restoring images alone should leave the user where they were typing.
4992 - if (promptChanged) {
4993 - window.requestAnimationFrame(() => {
4994 - composerEditorRef.current?.focusAtEnd();
4995 - });
4996 - }
4997 - },
4998 - [
4999 - addComposerDraftFiles,
5000 - addComposerDraftImages,
5001 - composerDraftTarget,
5002 - composerFilesRef,
5003 - composerImagesRef,
5004 - environmentId,
5005 - promptRef,
5006 - setComposerDraftPrompt,
5007 - setComposerTrigger,
5008 - takeStashEntry,
5009 - importContextRecords,
5010 - ],
5011 - );
4777 + // Only yank the caret to the end when text was actually inserted;
4778 + // restoring images alone should leave the user where they were typing.
4779 + if (promptChanged) {
4780 + window.requestAnimationFrame(() => {
4781 + composerEditorRef.current?.focusAtEnd();
4782 + });
4783 + }
4784 + };
4785 + const restoreStashEntryStable = useStableCallback(restoreStashEntry);
4786
5013 - const deleteStashEntry = useCallback(
5014 - (entry: PromptStashEntry) => {
5015 - const { entry: removed, durable } = takeStashEntry(entry.id);
5016 - if (!stashQueue.some((candidate) => candidate.id !== entry.id)) {
5017 - setIsStashMenuOpen(false);
5018 - }
5019 - if (durable && removed) {
5020 - for (const file of removed.files ?? []) {
5021 - releasePersistedAttachmentUpload({
5022 - id: file.id,
5023 - environmentId: file.environmentId,
5024 - attachmentId: file.attachmentId,
5025 - });
5026 - }
5027 - }
5028 - if (!durable) {
5029 - toastManager.add({
5030 - type: "warning",
5031 - title: "Stash entry may come back",
5032 - description:
5033 - "Browser storage rejected the delete, so this prompt could reappear after a reload.",
5034 - data: { hideCopyButton: true },
4787 + const deleteStashEntry = (entry: PromptStashEntry) => {
4788 + const { entry: removed, durable } = takeStashEntry(entry.id);
4789 + if (!stashQueue.some((candidate) => candidate.id !== entry.id)) {
4790 + setIsStashMenuOpen(false);
4791 + }
4792 + if (durable && removed) {
4793 + for (const file of removed.files ?? []) {
4794 + releasePersistedAttachmentUpload({
4795 + id: file.id,
4796 + environmentId: file.environmentId,
4797 + attachmentId: file.attachmentId,
4798 });
4799 }
5037 - },
5038 - [stashQueue, takeStashEntry],
5039 - );
4800 + }
4801 + if (!durable) {
4802 + toastManager.add({
4803 + type: "warning",
4804 + title: "Stash entry may come back",
4805 + description:
4806 + "Browser storage rejected the delete, so this prompt could reappear after a reload.",
4807 + data: { hideCopyButton: true },
4808 + });
4809 + }
4810 + };
4811 + const deleteStashEntryStable = useStableCallback(deleteStashEntry);
4812
5041 - const stashCurrentPrompt = useCallback(async () => {
4813 + const stashCurrentPrompt = async () => {
4814 // Stashing clears the draft. A pasted attachment still downloading would then land in the
4815 // emptied composer instead of travelling with the entry it belongs to.
4816 if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
@@ -5264,38 +5036,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5036 // snapshot's ⌘S until the composer remounts.
5037 stashInFlightRef.current.delete(snapshotKey);
5038 }
5267 - }, [
5268 - clearComposerDraftPromptAndImages,
5269 - clearComposerDraftTerminalContexts,
5270 - setComposerDraftPrompt,
5271 - setComposerTrigger,
5272 - composerDraftTarget,
5273 - composerFilesRef,
5274 - composerImagesRef,
5275 - composerTerminalContextsRef,
5276 - composerReviewComments,
5277 - composerPreviewAnnotations,
5278 - removeComposerDraftReviewComment,
5279 - removeComposerDraftPreviewAnnotation,
5280 - environmentId,
5281 - finalizeStashEntryImages,
5282 - promptRef,
5283 - pulseStashBadge,
5284 - restoreStashEntry,
5285 - stashEntryToQueue,
5286 - ]);
5039 + };
5040 + const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
5041
5288 - const toggleStashMenu = useCallback(() => {
5042 + const toggleStashMenu = () => {
5043 if (isComposerCollapsedMobile) {
5044 expandMobileComposer();
5045 setIsStashMenuOpen(true);
5046 return;
5047 }
5048 setIsStashMenuOpen((open) => !open);
5295 - }, [expandMobileComposer, isComposerCollapsedMobile]);
5296 - const toggleTasksDrawer = useCallback(() => {
5049 + };
5050 + const toggleStashMenuStable = useStableCallback(toggleStashMenu);
5051 + const toggleTasksDrawer = () => {
5052 setIsTasksDrawerOpen((open) => !open);
5298 - }, []);
5053 + };
5054 + const toggleTasksDrawerStable = useStableCallback(toggleTasksDrawer);
5055 const hasBannerItems = props.bannerItems.length > 0;
5056 const hasBlockingComposerTopDrawer =
5057 activePendingApproval !== null || pendingUserInputs.length > 0;
@@ -5308,7 +5064,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5064 const inlineTasksBadge = showInlineTasksBadge ? (
5065 <ComposerTasksBadge
5066 expanded={false}
5311 - onToggle={toggleTasksDrawer}
5067 + onToggle={toggleTasksDrawerStable}
5068 placement="inline"
5069 progress={activeTasksProgress}
5070 steps={activeTaskSteps}
@@ -5793,7 +5549,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5549 ) : !hasBlockingComposerTopDrawer && activeTasksProgress && activeTaskSteps ? (
5550 <ComposerTasksContent
5551 expanded={isTasksDrawerOpen}
5796 - onToggle={toggleTasksDrawer}
5552 + onToggle={toggleTasksDrawerStable}
5553 progress={activeTasksProgress}
5554 steps={activeTaskSteps}
5555 />
@@ -5862,7 +5618,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5618 if (isComposerApprovalState || projectSelectionRequired || activePendingProgress !== null) {
5619 return;
5620 }
5865 - void stashCurrentPrompt();
5621 + void stashCurrentPromptStable();
5622 };
5623 window.addEventListener("keydown", handler, true);
5624 return () => window.removeEventListener("keydown", handler, true);
@@ -5873,7 +5629,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5629 keybindings,
5630 pendingUserInputs.length,
5631 projectSelectionRequired,
5876 - stashCurrentPrompt,
5632 + stashCurrentPromptStable,
5633 isRevertingCheckpoint,
5634 terminalOpen,
5635 ]);
@@ -6261,94 +6017,81 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6017 event.stopPropagation();
6018 };
6019
6264 - const insertComposerText = useCallback(
6265 - (
6266 - text: string,
6267 - position: "cursor" | "end",
6268 - options?: {
6269 - ensureLeadingBoundary?: boolean;
6270 - citationCommentAnchor?: AssistantCitationSourceAnchor;
6271 - clipboardData?: DataTransfer;
6272 - },
6273 - ): boolean => {
6274 - if (
6275 - text.length === 0 ||
6276 - isConnecting ||
6277 - isComposerApprovalState ||
6278 - pendingUserInputs.length > 0 ||
6279 - projectSelectionRequired ||
6280 - (options?.citationCommentAnchor && !composerEditorRef.current)
6281 - ) {
6282 - return false;
6283 - }
6284 - if (options?.clipboardData) {
6285 - text = importPastedComposerText(options.clipboardData, importContextFragment);
6286 - }
6287 - const prompt = promptRef.current;
6288 - const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length;
6289 - const needsLeadingSpace =
6290 - (options?.ensureLeadingBoundary ?? false) &&
6291 - cursor > 0 &&
6292 - !/\s/.test(prompt[cursor - 1] ?? "");
6293 - const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text);
6294 - return applyPromptReplacement(
6295 - cursor,
6296 - rangeEnd,
6297 - needsLeadingSpace ? ` ${text}` : text,
6298 - options?.citationCommentAnchor
6299 - ? {
6300 - citationComment: {
6301 - start: cursor + (needsLeadingSpace ? 1 : 0),
6302 - sourceAnchor: options.citationCommentAnchor,
6303 - // An existing space after the cursor is consumed and re-emitted, so it stays.
6304 - insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor },
6305 - },
6306 - focusEditorAfterReplace: false,
6307 - }
6308 - : undefined,
6309 - );
6310 - },
6311 - [
6312 - applyPromptReplacement,
6313 - isComposerApprovalState,
6314 - isConnecting,
6315 - pendingUserInputs.length,
6316 - projectSelectionRequired,
6317 - promptRef,
6318 - readComposerSnapshot,
6319 - importContextFragment,
6320 - ],
6321 - );
6322 -
6323 - const insertComposerTextAtEnd = useCallback<ChatComposerHandle["insertTextAtEnd"]>(
6324 - (text, options) => {
6325 - const inserted = insertComposerText(text, "end", options);
6326 - if (inserted && isComposerCollapsedMobile) {
6327 - // The expanded editor is hidden at phone widths, so its scheduled
6328 - // focus cannot expand the composer by itself. Reveal it before the
6329 - // focus frame runs to preserve type-to-focus and external inserts.
6330 - expandMobileComposer();
6331 - }
6332 - return inserted;
6020 + const insertComposerText = (
6021 + text: string,
6022 + position: "cursor" | "end",
6023 + options?: {
6024 + ensureLeadingBoundary?: boolean;
6025 + citationCommentAnchor?: AssistantCitationSourceAnchor;
6026 + clipboardData?: DataTransfer;
6027 },
6334 - [expandMobileComposer, insertComposerText, isComposerCollapsedMobile],
6335 - );
6028 + ): boolean => {
6029 + if (
6030 + text.length === 0 ||
6031 + isConnecting ||
6032 + isComposerApprovalState ||
6033 + pendingUserInputs.length > 0 ||
6034 + projectSelectionRequired ||
6035 + (options?.citationCommentAnchor && !composerEditorRef.current)
6036 + ) {
6037 + return false;
6038 + }
6039 + if (options?.clipboardData) {
6040 + text = importPastedComposerText(options.clipboardData, importContextFragment);
6041 + }
6042 + const prompt = promptRef.current;
6043 + const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length;
6044 + const needsLeadingSpace =
6045 + (options?.ensureLeadingBoundary ?? false) &&
6046 + cursor > 0 &&
6047 + !/\s/.test(prompt[cursor - 1] ?? "");
6048 + const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text);
6049 + return applyPromptReplacement(
6050 + cursor,
6051 + rangeEnd,
6052 + needsLeadingSpace ? ` ${text}` : text,
6053 + options?.citationCommentAnchor
6054 + ? {
6055 + citationComment: {
6056 + start: cursor + (needsLeadingSpace ? 1 : 0),
6057 + sourceAnchor: options.citationCommentAnchor,
6058 + // An existing space after the cursor is consumed and re-emitted, so it stays.
6059 + insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor },
6060 + },
6061 + focusEditorAfterReplace: false,
6062 + }
6063 + : undefined,
6064 + );
6065 + };
6066 + const insertComposerTextStable = useStableCallback(insertComposerText);
6067 +
6068 + const insertComposerTextAtEnd: ChatComposerHandle["insertTextAtEnd"] = (text, options) => {
6069 + const inserted = insertComposerText(text, "end", options);
6070 + if (inserted && isComposerCollapsedMobile) {
6071 + // The expanded editor is hidden at phone widths, so its scheduled
6072 + // focus cannot expand the composer by itself. Reveal it before the
6073 + // focus frame runs to preserve type-to-focus and external inserts.
6074 + expandMobileComposer();
6075 + }
6076 + return inserted;
6077 + };
6078 + const insertComposerTextAtEndStable = useStableCallback(insertComposerTextAtEnd);
6079
6080 // Context produced by other panels (diff comments, preview picks) asks the store to place
6081 // its chip; while this composer is mounted for the draft, that means the caret.
6339 - const insertContextReferencesAtCaret = useCallback(
6340 - (references: ReadonlyArray<ComposerContextReference>): boolean =>
6341 - insertComposerText(`${references.map(formatInlineContextReference).join(" ")} `, "cursor", {
6342 - ensureLeadingBoundary: true,
6343 - }),
6344 - [insertComposerText],
6345 - );
6082 + const insertContextReferencesAtCaret = (
6083 + references: ReadonlyArray<ComposerContextReference>,
6084 + ): boolean =>
6085 + insertComposerText(`${references.map(formatInlineContextReference).join(" ")} `, "cursor", {
6086 + ensureLeadingBoundary: true,
6087 + });
6088 + const insertContextReferencesAtCaretStable = useStableCallback(insertContextReferencesAtCaret);
6089 const setContextInsertionHandler = useComposerDraftStore(
6090 (store) => store.setContextInsertionHandler,
6091 );
6092 useEffect(() => {
6350 - return setContextInsertionHandler(composerDraftTarget, insertContextReferencesAtCaret);
6351 - }, [composerDraftTarget, insertContextReferencesAtCaret, setContextInsertionHandler]);
6093 + return setContextInsertionHandler(composerDraftTarget, insertContextReferencesAtCaretStable);
6094 + }, [composerDraftTarget, insertContextReferencesAtCaretStable, setContextInsertionHandler]);
6095
6096 // File-tree drags land as mentions. Handled in the capture phase so the
6097 // editor never sees the drop; the load-bearing rules (native stop, "move"
@@ -6380,7 +6123,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6123 await importComposerThreadAttachment({
6124 targetKey,
6125 pendingImports: pendingThreadImportsRef.current,
6383 - countReservedAttachments,
6126 + countReservedAttachments: countReservedAttachmentsStable,
6127 load: async () => {
6128 const result = await loadThreadTranscript({
6129 environmentId: ref.environmentId,
@@ -6443,12 +6186,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6186 const text = `${records
6187 .map((record) => formatInlineContextReference(threadContextReference(record)))
6188 .join(" ")} `;
6446 - const snapshot = readComposerSnapshot();
6189 + const snapshot = readComposerSnapshotStable();
6190 const cursor = snapshot.expandedCursor;
6191 const leadingSpace = cursor > 0 && !/\s/.test(snapshot.value[cursor - 1] ?? "");
6192 const inserted =
6193 canAnswer &&
6451 - applyPromptReplacement(
6194 + applyPromptReplacementStable(
6195 cursor,
6196 extendReplacementRangeForTrailingSpace(snapshot.value, cursor, text),
6197 leadingSpace ? ` ${text}` : text,
@@ -6464,7 +6207,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6207 addComposerDraftThreadContexts(questionAttachmentTarget, records, {
6208 appendReference: false,
6209 });
6467 - if (isComposerCollapsedMobile) expandMobileComposer();
6210 + if (isComposerCollapsedMobile) expandMobileComposerStable();
6211 } else {
6212 addComposerDraftThreadContexts(composerDraftTarget, records);
6213 }
@@ -6490,15 +6233,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6233 window.addEventListener("dragend", onWindowDragEnd);
6234 return () => window.removeEventListener("dragend", onWindowDragEnd);
6235 }, [isDragOverComposer]);
6493 - const handleInterruptPrimaryAction = useCallback(() => {
6236 + const handleInterruptPrimaryAction = () => {
6237 void onInterrupt();
6495 - }, [onInterrupt]);
6496 - const handleImplementPlanInNewThreadPrimaryAction = useCallback(() => {
6238 + };
6239 + const handleInterruptPrimaryActionStable = useStableCallback(handleInterruptPrimaryAction);
6240 + const handleImplementPlanInNewThreadPrimaryAction = () => {
6241 void onImplementPlanInNewThread();
6498 - }, [onImplementPlanInNewThread]);
6242 + };
6243 + const handleImplementPlanInNewThreadPrimaryActionStable = useStableCallback(
6244 + handleImplementPlanInNewThreadPrimaryAction,
6245 + );
6246 // The phone composer collapses when the editor loses focus. Desktop only
6247 // rests on a timeline scroll, so losing focus there changes nothing.
6501 - const scheduleComposerCollapseCheck = useCallback(() => {
6248 + const scheduleComposerCollapseCheck = () => {
6249 if (!isMobileViewport || mobileComposerExpandInFlightRef.current) {
6250 return;
6251 }
@@ -6525,7 +6272,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6272 }
6273 setIsComposerFocused(false);
6274 });
6528 - }, [isMobileViewport, setIsComposerFocused]);
6275 + };
6276
6277 useEffect(() => {
6278 return () => {
@@ -6544,7 +6291,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6291 // ------------------------------------------------------------------
6292 // Imperative handle
6293 // ------------------------------------------------------------------
6547 - const openModelPicker = useCallback(() => {
6294 + const openModelPicker = () => {
6295 if (composerControlsHidden) {
6296 if (composerBlurFrameRef.current !== null) {
6297 window.cancelAnimationFrame(composerBlurFrameRef.current);
@@ -6554,7 +6301,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6301 setIsComposerFocused(true);
6302 }
6303 setIsComposerModelPickerOpen(true);
6557 - }, [composerControlsHidden, setIsComposerFocused, setIsComposerScrollCollapsed]);
6304 + };
6305 + const openModelPickerStable = useStableCallback(openModelPicker);
6306
6307 useImperativeHandle(
6308 composerRef,
@@ -6610,7 +6358,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6358 });
6359 continue;
6360 }
6613 - insertComposerTextAtEnd(`${serializeComposerFileLink(path)} `, {
6361 + insertComposerTextAtEndStable(`${serializeComposerFileLink(path)} `, {
6362 ensureLeadingBoundary: true,
6363 });
6364 }
@@ -6619,7 +6367,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6367 hasPendingAttachments: () =>
6368 (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0 ||
6369 pendingDraftWork.has(attachmentTargetKey),
6622 - insertTextAtEnd: insertComposerTextAtEnd,
6370 + insertTextAtEnd: insertComposerTextAtEndStable,
6371 pasteTextAtEnd: (text: string, options) => {
6372 const bypassAutoAttachment =
6373 options?.bypassAutoAttachment === true ||
@@ -6638,17 +6386,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6386 return true;
6387 },
6388 citeAssistantText: (citation, sourceAnchor) =>
6641 - insertComposerText(
6389 + insertComposerTextStable(
6390 formatAssistantCitationForComposer(citation, citation.comment),
6391 "cursor",
6392 { ensureLeadingBoundary: true, citationCommentAnchor: sourceAnchor },
6393 ),
6646 - openModelPicker,
6394 + openModelPicker: openModelPickerStable,
6395 toggleModelPicker: () => {
6396 if (isComposerModelPickerOpen) {
6397 setIsComposerModelPickerOpen(false);
6398 } else {
6651 - openModelPicker();
6399 + openModelPickerStable();
6400 }
6401 },
6402 openControl: (command) => {
@@ -6673,14 +6421,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6421 trigger.focus({ preventScroll: true });
6422 trigger.click();
6423 },
6676 - compactContext: compactThreadContext,
6424 + compactContext: compactThreadContextStable,
6425 isModelPickerOpen: () => isComposerModelPickerOpen,
6426 isCaretAtStart: () => {
6427 const range = composerEditorRef.current?.readSelectionRange();
6428 return range !== undefined && range.start === 0 && range.end === 0;
6429 },
6430 readSnapshot: () => {
6683 - return readComposerSnapshot();
6431 + return readComposerSnapshotStable();
6432 },
6433 resetCursorState: (options?: {
6434 cursor?: number;
@@ -6706,7 +6454,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6454 },
6455 addTerminalContext: (selection: TerminalContextSelection) => {
6456 if (!activeThread || isChoiceOnlyPendingQuestion || isLiteralPendingAnswer) return;
6709 - const snapshot = readComposerSnapshot();
6457 + const snapshot = readComposerSnapshotStable();
6458 const context = {
6459 id: randomUUID(),
6460 threadId: activeThread.id,
@@ -6787,8 +6535,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6535 activePendingProgress,
6536 composerTerminalContexts,
6537 insertComposerDraftTerminalContext,
6790 - insertComposerText,
6791 - insertComposerTextAtEnd,
6538 + insertComposerTextStable,
6539 + insertComposerTextAtEndStable,
6540 promptRef,
6541 composerImagesRef,
6542 composerFilesRef,
@@ -6804,10 +6552,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6552 isLiteralPendingAnswer,
6553 pendingUserInputs.length,
6554 projectSelectionRequired,
6807 - applyPromptReplacement,
6555 + applyPromptReplacementStable,
6556 isComposerModelPickerOpen,
6809 - openModelPicker,
6810 - readComposerSnapshot,
6557 + openModelPickerStable,
6558 + readComposerSnapshotStable,
6559 resetComposerTrigger,
6560 setComposerTrigger,
6561 selectedModel,
@@ -6823,7 +6571,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6571 selectedProviderModels,
6572 interactionMode,
6573 planModeUiEnabled,
6826 - compactThreadContext,
6574 + compactThreadContextStable,
6575 restoreAfterTimelineReachedEnd,
6576 getTimelineScrollableNode,
6577 isTimelineAtLogicalEnd,
@@ -6836,7 +6584,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6584 return (
6585 <form
6586 ref={composerFormRef}
6839 - onSubmit={submitComposer}
6587 + onSubmit={submitComposerStable}
6588 onPointerDownCapture={(event) => {
6589 const target = event.target;
6590 if (isInsideRestingComposerControlScope(target)) return;
@@ -7039,7 +6787,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6787 !activePendingProgress?.activeQuestion?.multiSelect && "px-3 py-2",
6788 )}
6789 onPointerDown={(event) => event.preventDefault()}
7042 - onClick={expandMobileComposer}
6790 + onClick={expandMobileComposerStable}
6791 aria-label="Write custom answer"
6792 >
6793 {activePendingProgress?.customAnswer || "Write custom answer"}
@@ -7066,9 +6814,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6814 hasSendableContent={false}
6815 preserveComposerFocusOnPointerDown
6816 onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
7069 - onInterrupt={handleInterruptPrimaryAction}
6817 + onInterrupt={handleInterruptPrimaryActionStable}
6818 onImplementPlanInNewThread={
7071 - handleImplementPlanInNewThreadPrimaryAction
6819 + handleImplementPlanInNewThreadPrimaryActionStable
6820 }
6821 />
6822 ) : null}
@@ -7086,7 +6834,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6834 activeTasksProgress &&
6835 activeTaskSteps ? (
6836 <ComposerTasksDrawer
7089 - onCollapse={toggleTasksDrawer}
6837 + onCollapse={toggleTasksDrawerStable}
6838 progress={activeTasksProgress}
6839 steps={activeTaskSteps}
6840 />
@@ -7095,7 +6843,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6843 <ComposerBanner.Attachment>
6844 <ComposerTasksBadge
6845 expanded={false}
7098 - onToggle={toggleTasksDrawer}
6846 + onToggle={toggleTasksDrawerStable}
6847 progress={activeTasksProgress}
6848 steps={activeTaskSteps}
6849 />
@@ -7108,7 +6856,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6856 menuOpen={isStashMenuOpen}
6857 pulseKey={stashPulse.key}
6858 pulsing={stashPulse.active}
7111 - onToggleMenu={toggleStashMenu}
6859 + onToggleMenu={toggleStashMenuStable}
6860 />
6861 ) : null}
6862 </ComposerBanner.Dock>
@@ -7145,7 +6893,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6893 : "text-placeholder",
6894 )}
6895 onPointerDown={(event) => event.preventDefault()}
7148 - onClick={isChoiceOnlyPendingQuestion ? undefined : expandMobileComposer}
6896 + onClick={isChoiceOnlyPendingQuestion ? undefined : expandMobileComposerStable}
6897 disabled={isChoiceOnlyPendingQuestion}
6898 aria-label="Expand composer"
6899 >
@@ -7215,8 +6963,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6963 modelPickerOpen: false,
6964 },
6965 })}
7218 - onRestore={restoreStashEntry}
7219 - onDelete={deleteStashEntry}
6966 + onRestore={restoreStashEntryStable}
6967 + onDelete={deleteStashEntryStable}
6968 onClose={() => setIsStashMenuOpen(false)}
6969 />
6970 </ComposerCommandMenuLayer>
@@ -7241,8 +6989,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6989 triggerKind={composerTriggerKind}
6990 emptyStateText={composerMenuEmptyState}
6991 activeItemId={activeComposerMenuItem?.id ?? null}
7244 - onHighlightedItemChange={onComposerMenuItemHighlighted}
7245 - onSelect={onSelectComposerItem}
6992 + onHighlightedItemChange={onComposerMenuItemHighlightedStable}
6993 + onSelect={onSelectComposerItemStable}
6994 />
6995 </ComposerCommandMenuLayer>
6996 )}
@@ -7682,8 +7430,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7430 }
7431 cursor={composerCursor}
7432 contextRecords={composerContextRecords}
7685 - buildContextClipboardFragment={buildContextClipboardFragment}
7686 - importContextFragment={importContextFragment}
7433 + buildContextClipboardFragment={buildContextClipboardFragmentStable}
7434 + importContextFragment={importContextFragmentStable}
7435 skills={selectedProviderSkills}
7436 containerClassName={cn(isComposerResting && "min-w-0 flex-1")}
7437 className={cn(
@@ -7696,14 +7444,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7444 isComposerResting &&
7445 "flex items-center overflow-hidden whitespace-nowrap leading-8",
7446 )}
7699 - onChange={onPromptChange}
7700 - onVisibleSelectionChange={expandComposerForEditorChange}
7447 + onChange={onPromptChangeStable}
7448 + onVisibleSelectionChange={expandComposerForEditorChangeStable}
7449 onCommandKeyDown={onComposerCommandKey}
7450 onPageScrollKeyDown={onPageScrollKeyDown}
7451 onPageScrollKeyUp={onPageScrollKeyUp}
7452 onPageScrollRelease={onPageScrollRelease}
7705 - onCitationSubmitAndSend={submitCitationAndSend}
7706 - onCitationDraftSave={saveCitationDraftToPrompt}
7453 + onCitationSubmitAndSend={submitCitationAndSendStable}
7454 + onCitationDraftSave={saveCitationDraftToPromptStable}
7455 onPaste={onComposerPaste}
7456 placeholder={
7457 isComposerApprovalState
@@ -7757,8 +7505,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7505 hasSendableContent={false}
7506 preserveComposerFocusOnPointerDown
7507 onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
7760 - onInterrupt={handleInterruptPrimaryAction}
7761 - onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
7508 + onInterrupt={handleInterruptPrimaryActionStable}
7509 + onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryActionStable}
7510 />
7511 </div>
7512 ) : null}
@@ -7884,11 +7632,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7632 canResume={showResumeAction}
7633 preserveComposerFocusOnPointerDown={isMobileViewport || isComposerResting}
7634 isEditingQueuedMessage={isEditingQueuedMessage}
7887 - onSubmitMessage={handleSubmitMessage}
7635 + onSubmitMessage={handleSubmitMessageStable}
7636 onResume={onResume}
7637 onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
7890 - onInterrupt={handleInterruptPrimaryAction}
7891 - onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
7638 + onInterrupt={handleInterruptPrimaryActionStable}
7639 + onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryActionStable}
7640 compactBeforeSendTokens={props.resumeCompactionTokens}
7641 keepFullHistory={props.keepFullHistory}
7642 onToggleKeepFullHistory={props.onToggleKeepFullHistory}
@@ -7896,7 +7644,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7644 compactDisabled || noProviderAvailable || isSendBusy || isConnecting
7645 }
7646 compactDisabledReason={resolvedCompactDisabledReason}
7899 - {...(compactCommandAvailable ? { onCompactContext: compactThreadContext } : {})}
7647 + {...(compactCommandAvailable
7648 + ? { onCompactContext: compactThreadContextStable }
7649 + : {})}
7650 />
7651 </div>
7652 </div>
docs/internals/web-ui.md
+16
@@ -37,3 +37,19 @@ The composer banners are the reference.
37 Build new UI the same way. Compose or extend a component instead of copying its markup and classes.
38 When a call site repeats a treatment another one already uses, make it a variant or a slot on the
39 shared component. A new composer banner or notice uses the `ComposerBanner` slots.
40 +
41 +## Handlers in large components
42 +
43 +V8 gives every closure created in one render a single shared scope. A memoized handler keeps
44 +the scope of the render that created it, and that scope holds the other memoized values of that
45 +render. When handlers in one component change at different times, each keeps an older scope that
46 +holds older handlers, and old renders, with their server config and thread data, stay in memory
47 +for as long as the component is mounted. React Compiler's memoized closures do the same.
48 +
49 +In large, long-lived components such as `ChatView` and `ChatComposer`, write handlers as plain
50 +functions and wrap them with [`useStableCallback`](../../apps/web/src/hooks/useStableCallback.ts)
51 +only where they leave the component: props, hook dependency arrays, and effect or memo bodies.
52 +Calls inside the component keep the plain function, so work that resumes after an `await` still
53 +acts on the render it started in. A function that a child calls during render, or after an
54 +`await`, comes from a module-level factory memoized on its inputs, so its closure keeps only
55 +those inputs.