The best way to control Claude Code, Codex and more from any computer or phone
perf(web): ChatComposer compiles with no manual memoization (#20397)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 17:43 UTC
e925fe754e8e4707626d94f74d25f6eb6735a30e
2 files changed
+839
-895
apps/web/reactCompiledFiles.ts
+1
@@ -7,6 +7,7 @@
7
export const REACT_COMPILED_FILES = [
8
"apps/web/src/components/PersistentThreadTerminals.tsx",
9
"apps/web/src/components/Sidebar.tsx",
10
+ "apps/web/src/components/chat/ChatComposer.tsx",
11
"apps/web/src/components/chat/usePendingThreadRequests.ts",
12
"apps/web/src/components/chat/composerFocusRedirect.ts",
13
"apps/web/src/components/chat/useChatShortcuts.ts",
apps/web/src/components/chat/ChatComposer.tsx
+838
-895
@@ -21,7 +21,6 @@ import {
21
changeQuestionAttachmentPreparation,
22
} from "../../questionAttachments";
23
import type {
24
- ApprovalRequestId,
24
KeybindingCommand,
25
AssistantCitation,
26
ChatAttachment as ContractChatAttachment,
@@ -53,7 +52,7 @@ import {
52
PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
53
} from "@t3tools/contracts";
54
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
56
-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
55
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
56
import * as Schema from "effect/Schema";
57
import {
58
isPasteAsTextShortcut,
@@ -69,13 +68,11 @@ import {
68
memo,
69
type ComponentProps,
70
type ReactNode,
72
- useCallback,
71
useEffect,
72
useEffectEvent,
73
useId,
74
useImperativeHandle,
75
useLayoutEffect,
78
- useMemo,
76
useRef,
77
useState,
78
useSyncExternalStore,
@@ -362,13 +359,10 @@ import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
359
import { observeResize } from "~/lib/observeResize";
360
361
function ComposerVideoThumbnail({ file }: { file: File }) {
365
- const setVideo = useCallback(
366
- (video: HTMLVideoElement | null) => {
367
- if (!video) return;
368
- return attachVideoThumbnail(video, file);
369
- },
370
- [file],
371
- );
362
+ const setVideo = (video: HTMLVideoElement | null) => {
363
+ if (!video) return;
364
+ return attachVideoThumbnail(video, file);
365
+ };
366
367
return (
368
<video
@@ -480,7 +474,7 @@ function useComposerRestingTransition(
474
const transitionLayoutRequestRef = useRef(0);
475
const hasCompletedInitialLayoutRef = useRef(false);
476
483
- const clearOverlayPin = useCallback(() => {
477
+ const clearOverlayPin = () => {
478
// The overlay belongs to the chat view and outlives this composer, so it
479
// is remembered from pin time rather than re-resolved through a ref that
480
// React may already have detached during unmount.
@@ -490,9 +484,9 @@ function useComposerRestingTransition(
484
overlay?.style.removeProperty("display");
485
overlay?.style.removeProperty("flex-direction");
486
overlay?.style.removeProperty("justify-content");
493
- }, []);
487
+ };
488
495
- const clearTransitionStyles = useCallback(() => {
489
+ const clearTransitionStyles = () => {
490
const element = elementRef.current;
491
const footer = element?.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
492
element?.style.removeProperty("overflow");
@@ -524,361 +518,351 @@ function useComposerRestingTransition(
518
modelStrip?.style.removeProperty(property);
519
}
520
clearOverlayPin();
527
- }, [clearOverlayPin]);
521
+ };
522
529
- isCollapsedRef.current = isCollapsed;
523
+ useLayoutEffect(() => {
524
+ isCollapsedRef.current = isCollapsed;
525
+ });
526
531
- const transitionToCurrentGeometry = useCallback(
532
- (stateChanged: boolean) => {
533
- const element = elementRef.current;
534
- const surface = element?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]');
535
- if (!element || !surface) return;
527
+ const transitionToCurrentGeometry = (stateChanged: boolean) => {
528
+ const element = elementRef.current;
529
+ const surface = element?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]');
530
+ if (!element || !surface) return;
531
537
- const nextIsCollapsed = isCollapsedRef.current;
532
+ const nextIsCollapsed = isCollapsedRef.current;
533
539
- const visibleTransitionElement = (selector: string) =>
540
- Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
541
- (candidate) => candidate.getClientRects().length > 0,
542
- ) ?? null;
543
- const prompt = visibleTransitionElement(
544
- '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
545
- );
546
- const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]');
547
- const footer = element.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
548
- const continuousControls =
549
- element.dataset.inlineRestingControls === "true" ||
550
- element.dataset.modelOnlyStrip === "true";
551
- const controls = nextIsCollapsed
552
- ? restingControlsRef.current
553
- : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
554
-
555
- const shell = element.closest<HTMLElement>('[data-slot="composer-shell"]');
556
- const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
557
- const interruptedStripHeight =
558
- animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null;
559
- const interruptedAnimation = animationRef.current;
560
- const interruptedPromptTop = interruptedAnimation
561
- ? (prompt?.getBoundingClientRect().top ?? null)
562
- : null;
563
- const interruptedActionTop = interruptedAnimation
564
- ? (action?.getBoundingClientRect().top ?? null)
565
- : null;
566
- const interruptedControlsLeft = interruptedAnimation
567
- ? (controls?.getBoundingClientRect().left ?? null)
568
- : null;
569
- const interruptedControlsTop = interruptedAnimation
570
- ? (controls?.getBoundingClientRect().top ?? null)
571
- : null;
572
- const interruptedHeight = interruptedAnimation
573
- ? element.getBoundingClientRect().height
534
+ const visibleTransitionElement = (selector: string) =>
535
+ Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
536
+ (candidate) => candidate.getClientRects().length > 0,
537
+ ) ?? null;
538
+ const prompt = visibleTransitionElement(
539
+ '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
540
+ );
541
+ const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]');
542
+ const footer = element.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
543
+ const continuousControls =
544
+ element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true";
545
+ const controls = nextIsCollapsed
546
+ ? restingControlsRef.current
547
+ : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
548
+
549
+ const shell = element.closest<HTMLElement>('[data-slot="composer-shell"]');
550
+ const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
551
+ const interruptedStripHeight =
552
+ animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null;
553
+ const interruptedAnimation = animationRef.current;
554
+ const interruptedPromptTop = interruptedAnimation
555
+ ? (prompt?.getBoundingClientRect().top ?? null)
556
+ : null;
557
+ const interruptedActionTop = interruptedAnimation
558
+ ? (action?.getBoundingClientRect().top ?? null)
559
+ : null;
560
+ const interruptedControlsLeft = interruptedAnimation
561
+ ? (controls?.getBoundingClientRect().left ?? null)
562
+ : null;
563
+ const interruptedControlsTop = interruptedAnimation
564
+ ? (controls?.getBoundingClientRect().top ?? null)
565
+ : null;
566
+ const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null;
567
+ const interruptedTargetHeight = animationTargetHeightRef.current;
568
+ const interruptedCurrentTime =
569
+ typeof interruptedAnimation?.currentTime === "number"
570
+ ? interruptedAnimation.currentTime
571
: null;
575
- const interruptedTargetHeight = animationTargetHeightRef.current;
576
- const interruptedCurrentTime =
577
- typeof interruptedAnimation?.currentTime === "number"
578
- ? interruptedAnimation.currentTime
579
- : null;
580
- const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration;
581
- if (transitionCleanupTimeoutRef.current !== null) {
582
- window.clearTimeout(transitionCleanupTimeoutRef.current);
583
- transitionCleanupTimeoutRef.current = null;
584
- }
585
- interruptedAnimation?.cancel();
586
- animationRef.current = null;
587
- for (const animation of contentAnimationsRef.current) animation.cancel();
588
- contentAnimationsRef.current = [];
589
- if (stateChanged) {
590
- for (const animation of stateChangeAnimationsRef.current) animation.cancel();
591
- stateChangeAnimationsRef.current = [];
592
- }
593
- clearTransitionStyles();
572
+ const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration;
573
+ if (transitionCleanupTimeoutRef.current !== null) {
574
+ window.clearTimeout(transitionCleanupTimeoutRef.current);
575
+ transitionCleanupTimeoutRef.current = null;
576
+ }
577
+ interruptedAnimation?.cancel();
578
+ animationRef.current = null;
579
+ for (const animation of contentAnimationsRef.current) animation.cancel();
580
+ contentAnimationsRef.current = [];
581
+ if (stateChanged) {
582
+ for (const animation of stateChangeAnimationsRef.current) animation.cancel();
583
+ stateChangeAnimationsRef.current = [];
584
+ }
585
+ clearTransitionStyles();
586
+
587
+ const nextRect = element.getBoundingClientRect();
588
+ const nextHeight = nextRect.height;
589
+ const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null;
590
+ // The chat view resize-observes the overlay to place the timeline
591
+ // inset, the scroll-to-end pill, and the mini player. Publishing the
592
+ // destination height here turns that feedback into one update instead
593
+ // of a ChatView re-render on every animation frame.
594
+ const overlay = element.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
595
+ const overlayRect = overlay?.getBoundingClientRect();
596
+ const overlayHeight = overlayRect?.height ?? null;
597
+ if (overlayHeight !== null) {
598
+ onOverlayHeightChange(overlayHeight);
599
+ }
600
+ const nextPromptRect = prompt?.getBoundingClientRect() ?? null;
601
+ const nextPromptTop = nextPromptRect?.top ?? null;
602
+ const nextActionTop = action?.getBoundingClientRect().top ?? null;
603
+ const nextControlsRect = controls?.getBoundingClientRect() ?? null;
604
+ const nextControlsTop = nextControlsRect?.top ?? null;
605
+ const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1;
606
+ const previousHeight = interruptedHeight ?? previousHeightRef.current;
607
+ const targetChanged =
608
+ interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5;
609
+ const shouldAnimate = shouldAnimateComposerRestingTransition({
610
+ hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current,
611
+ stateChanged,
612
+ hasInterruptedAnimation: interruptedHeight !== null,
613
+ });
614
595
- const nextRect = element.getBoundingClientRect();
596
- const nextHeight = nextRect.height;
597
- const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null;
598
- // The chat view resize-observes the overlay to place the timeline
599
- // inset, the scroll-to-end pill, and the mini player. Publishing the
600
- // destination height here turns that feedback into one update instead
601
- // of a ChatView re-render on every animation frame.
602
- const overlay = element.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
603
- const overlayRect = overlay?.getBoundingClientRect();
604
- const overlayHeight = overlayRect?.height ?? null;
605
- if (overlayHeight !== null) {
606
- onOverlayHeightChange(overlayHeight);
615
+ if (
616
+ shouldAnimate &&
617
+ animationsActive &&
618
+ previousHeight !== null &&
619
+ Math.abs(previousHeight - nextHeight) >= 0.5
620
+ ) {
621
+ const remainingDuration =
622
+ typeof interruptedDuration === "number" && interruptedCurrentTime !== null
623
+ ? Math.max(1, interruptedDuration - interruptedCurrentTime)
624
+ : animationDurationMs;
625
+ const duration =
626
+ interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs;
627
+ element.style.overflow = "clip";
628
+ if (modelStrip) {
629
+ const controlsClearance = Math.max(
630
+ nextModelStripHeight ?? 0,
631
+ previousModelStripHeightRef.current ?? 0,
632
+ );
633
+ element.style.overflowClipMargin = `${controlsClearance}px`;
634
+ element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`;
635
+ }
636
+ surface.style.height = "100%";
637
+
638
+ if (overlay && overlayHeight !== null) {
639
+ overlay.style.height = `${String(overlayHeight)}px`;
640
+ overlay.style.display = "flex";
641
+ overlay.style.flexDirection = "column";
642
+ overlay.style.justifyContent = "flex-end";
643
+ pinnedOverlayRef.current = overlay;
644
}
608
- const nextPromptRect = prompt?.getBoundingClientRect() ?? null;
609
- const nextPromptTop = nextPromptRect?.top ?? null;
610
- const nextActionTop = action?.getBoundingClientRect().top ?? null;
611
- const nextControlsRect = controls?.getBoundingClientRect() ?? null;
612
- const nextControlsTop = nextControlsRect?.top ?? null;
613
- const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1;
614
- const previousHeight = interruptedHeight ?? previousHeightRef.current;
615
- const targetChanged =
616
- interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5;
617
- const shouldAnimate = shouldAnimateComposerRestingTransition({
618
- hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current,
619
- stateChanged,
620
- hasInterruptedAnimation: interruptedHeight !== null,
621
- });
622
-
623
- if (
624
- shouldAnimate &&
625
- animationsActive &&
626
- previousHeight !== null &&
627
- Math.abs(previousHeight - nextHeight) >= 0.5
628
- ) {
629
- const remainingDuration =
630
- typeof interruptedDuration === "number" && interruptedCurrentTime !== null
631
- ? Math.max(1, interruptedDuration - interruptedCurrentTime)
632
- : animationDurationMs;
633
- const duration =
634
- interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs;
635
- element.style.overflow = "clip";
636
- if (modelStrip) {
637
- const controlsClearance = Math.max(
638
- nextModelStripHeight ?? 0,
639
- previousModelStripHeightRef.current ?? 0,
640
- );
641
- element.style.overflowClipMargin = `${controlsClearance}px`;
642
- element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`;
643
- }
644
- surface.style.height = "100%";
645
-
646
- if (overlay && overlayHeight !== null) {
647
- overlay.style.height = `${String(overlayHeight)}px`;
648
- overlay.style.display = "flex";
649
- overlay.style.flexDirection = "column";
650
- overlay.style.justifyContent = "flex-end";
651
- pinnedOverlayRef.current = overlay;
652
- }
645
654
- if (footer) {
655
- footer.style.position = "absolute";
656
- footer.style.top = "auto";
657
- footer.style.bottom = `${String(footerBottom)}px`;
658
- footer.style.height = "3rem";
659
- if (nextIsCollapsed) {
660
- footer.style.left = "auto";
661
- footer.style.right = "1px";
662
- } else {
663
- footer.style.left = "1px";
664
- footer.style.right = "1px";
665
- }
646
+ if (footer) {
647
+ footer.style.position = "absolute";
648
+ footer.style.top = "auto";
649
+ footer.style.bottom = `${String(footerBottom)}px`;
650
+ footer.style.height = "3rem";
651
+ if (nextIsCollapsed) {
652
+ footer.style.left = "auto";
653
+ footer.style.right = "1px";
654
+ } else {
655
+ footer.style.left = "1px";
656
+ footer.style.right = "1px";
657
}
658
+ }
659
668
- let stripAnimation: Animation | null = null;
669
- if (modelStrip) {
670
- const stripHeight = modelStrip.getBoundingClientRect().height;
671
- const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop);
672
- const fromHeight =
673
- interruptedStripHeight ??
674
- (previousCollapsedRef.current
675
- ? (previousModelStripHeightRef.current ?? stripHeight)
676
- : stripOverlap);
677
- const toHeight = nextIsCollapsed ? stripHeight : stripOverlap;
678
- modelStrip.style.position = "relative";
679
- modelStrip.style.top = "auto";
680
- modelStrip.style.visibility = "visible";
681
- modelStrip.style.minHeight = "0";
682
- modelStrip.style.paddingTop = "0";
683
- modelStrip.style.alignItems = "flex-end";
684
- modelStrip.style.pointerEvents = "none";
685
- modelStrip.style.zIndex = "20";
686
- shell?.setAttribute("data-model-strip-transition", "true");
687
- stripAnimation = modelStrip.animate(
688
- [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }],
689
- { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" },
690
- );
691
- }
660
+ let stripAnimation: Animation | null = null;
661
+ if (modelStrip) {
662
+ const stripHeight = modelStrip.getBoundingClientRect().height;
663
+ const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop);
664
+ const fromHeight =
665
+ interruptedStripHeight ??
666
+ (previousCollapsedRef.current
667
+ ? (previousModelStripHeightRef.current ?? stripHeight)
668
+ : stripOverlap);
669
+ const toHeight = nextIsCollapsed ? stripHeight : stripOverlap;
670
+ modelStrip.style.position = "relative";
671
+ modelStrip.style.top = "auto";
672
+ modelStrip.style.visibility = "visible";
673
+ modelStrip.style.minHeight = "0";
674
+ modelStrip.style.paddingTop = "0";
675
+ modelStrip.style.alignItems = "flex-end";
676
+ modelStrip.style.pointerEvents = "none";
677
+ modelStrip.style.zIndex = "20";
678
+ shell?.setAttribute("data-model-strip-transition", "true");
679
+ stripAnimation = modelStrip.animate(
680
+ [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }],
681
+ { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" },
682
+ );
683
+ }
684
693
- const animation = element.animate(
694
- [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }],
695
- {
696
- duration,
697
- easing: COMPOSER_RESTING_TRANSITION_EASING,
698
- fill: "both",
699
- },
685
+ const animation = element.animate(
686
+ [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }],
687
+ {
688
+ duration,
689
+ easing: COMPOSER_RESTING_TRANSITION_EASING,
690
+ fill: "both",
691
+ },
692
+ );
693
+ animationRef.current = animation;
694
+ animationTargetHeightRef.current = nextHeight;
695
+
696
+ const animatedRect = element.getBoundingClientRect();
697
+ const previousBottom =
698
+ overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null
699
+ ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset
700
+ : animatedRect.bottom;
701
+ const bottomShift = previousBottom - animatedRect.bottom;
702
+ const previousPromptTop =
703
+ interruptedPromptTop ??
704
+ (previousContentOffsetsRef.current.promptFromTop === null
705
+ ? null
706
+ : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop);
707
+ const previousActionTop =
708
+ interruptedActionTop ??
709
+ (previousContentOffsetsRef.current.actionFromBottom === null
710
+ ? null
711
+ : previousBottom - previousContentOffsetsRef.current.actionFromBottom);
712
+ const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : [];
713
+ const animateContentPosition = (
714
+ content: HTMLElement | null,
715
+ previousTop: number | null,
716
+ previousLeft: number | null = null,
717
+ ) => {
718
+ if (!content || previousTop === null) return;
719
+ const rect = content.getBoundingClientRect();
720
+ const offset = previousTop - rect.top;
721
+ const offsetX = previousLeft === null ? 0 : previousLeft - rect.left;
722
+ if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return;
723
+ contentAnimations.push(
724
+ content.animate(
725
+ [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }],
726
+ {
727
+ duration,
728
+ easing: COMPOSER_RESTING_TRANSITION_EASING,
729
+ },
730
+ ),
731
);
701
- animationRef.current = animation;
702
- animationTargetHeightRef.current = nextHeight;
703
-
704
- const animatedRect = element.getBoundingClientRect();
705
- const previousBottom =
706
- overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null
707
- ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset
708
- : animatedRect.bottom;
709
- const bottomShift = previousBottom - animatedRect.bottom;
710
- const previousPromptTop =
711
- interruptedPromptTop ??
712
- (previousContentOffsetsRef.current.promptFromTop === null
732
+ };
733
+ animateContentPosition(prompt, previousPromptTop);
734
+ animateContentPosition(action, previousActionTop);
735
+ if (continuousControls) {
736
+ const previousControlsTop =
737
+ interruptedControlsTop ??
738
+ (previousContentOffsetsRef.current.controlsFromBottom === null
739
? null
714
- : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop);
715
- const previousActionTop =
716
- interruptedActionTop ??
717
- (previousContentOffsetsRef.current.actionFromBottom === null
740
+ : previousBottom - previousContentOffsetsRef.current.controlsFromBottom);
741
+ const previousControlsLeft =
742
+ interruptedControlsLeft ??
743
+ (previousContentOffsetsRef.current.controlsFromLeft === null
744
? null
719
- : previousBottom - previousContentOffsetsRef.current.actionFromBottom);
720
- const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : [];
721
- const animateContentPosition = (
722
- content: HTMLElement | null,
723
- previousTop: number | null,
724
- previousLeft: number | null = null,
725
- ) => {
726
- if (!content || previousTop === null) return;
727
- const rect = content.getBoundingClientRect();
728
- const offset = previousTop - rect.top;
729
- const offsetX = previousLeft === null ? 0 : previousLeft - rect.left;
730
- if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return;
731
- contentAnimations.push(
732
- content.animate(
733
- [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }],
745
+ : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft);
746
+ animateContentPosition(controls, previousControlsTop, previousControlsLeft);
747
+ }
748
+ contentAnimationsRef.current = contentAnimations;
749
+
750
+ if (stateChanged) {
751
+ const stateChangeAnimations: Animation[] = [];
752
+
753
+ const previousPromptHeight = previousContentOffsetsRef.current.promptHeight;
754
+ if (
755
+ !nextIsCollapsed &&
756
+ prompt &&
757
+ nextPromptRect &&
758
+ previousPromptHeight !== null &&
759
+ nextPromptRect.height - previousPromptHeight >= 0.5
760
+ ) {
761
+ const hiddenHeight = nextPromptRect.height - previousPromptHeight;
762
+ stateChangeAnimations.push(
763
+ prompt.animate(
764
+ [
765
+ { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` },
766
+ { clipPath: "inset(0 0 0 0)" },
767
+ ],
768
{
769
duration,
770
easing: COMPOSER_RESTING_TRANSITION_EASING,
771
},
772
),
773
);
740
- };
741
- animateContentPosition(prompt, previousPromptTop);
742
- animateContentPosition(action, previousActionTop);
743
- if (continuousControls) {
744
- const previousControlsTop =
745
- interruptedControlsTop ??
746
- (previousContentOffsetsRef.current.controlsFromBottom === null
747
- ? null
748
- : previousBottom - previousContentOffsetsRef.current.controlsFromBottom);
749
- const previousControlsLeft =
750
- interruptedControlsLeft ??
751
- (previousContentOffsetsRef.current.controlsFromLeft === null
752
- ? null
753
- : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft);
754
- animateContentPosition(controls, previousControlsTop, previousControlsLeft);
774
}
756
- contentAnimationsRef.current = contentAnimations;
757
-
758
- if (stateChanged) {
759
- const stateChangeAnimations: Animation[] = [];
760
-
761
- const previousPromptHeight = previousContentOffsetsRef.current.promptHeight;
762
- if (
763
- !nextIsCollapsed &&
764
- prompt &&
765
- nextPromptRect &&
766
- previousPromptHeight !== null &&
767
- nextPromptRect.height - previousPromptHeight >= 0.5
768
- ) {
769
- const hiddenHeight = nextPromptRect.height - previousPromptHeight;
770
- stateChangeAnimations.push(
771
- prompt.animate(
772
- [
773
- { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` },
774
- { clipPath: "inset(0 0 0 0)" },
775
- ],
776
- {
777
- duration,
778
- easing: COMPOSER_RESTING_TRANSITION_EASING,
779
- },
780
- ),
781
- );
782
- }
783
-
784
- const arrivingControls = nextIsCollapsed
785
- ? restingControlsRef.current
786
- : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
787
- if (arrivingControls && !continuousControls) {
788
- const drift = nextIsCollapsed
789
- ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX
790
- : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX;
791
- stateChangeAnimations.push(
792
- arrivingControls.animate(
793
- [
794
- { opacity: 0, transform: `translateY(${String(drift)}px)` },
795
- { opacity: 1, transform: "none" },
796
- ],
797
- {
798
- duration: nextIsCollapsed ? duration : duration / 2,
799
- delay: nextIsCollapsed ? 0 : duration / 2,
800
- fill: "backwards",
801
- easing: COMPOSER_RESTING_TRANSITION_EASING,
802
- },
803
- ),
804
- );
805
- }
775
807
- const arrivingImagePreviews = nextIsCollapsed
808
- ? Array.from(
809
- element.querySelectorAll<HTMLElement>('[data-chat-composer-resting-images="true"]'),
810
- )
811
- : Array.from(
812
- element.querySelectorAll<HTMLElement>('[data-chat-composer-expanded-image="true"]'),
813
- );
814
- for (const imagePreview of arrivingImagePreviews) {
815
- stateChangeAnimations.push(
816
- imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], {
776
+ const arrivingControls = nextIsCollapsed
777
+ ? restingControlsRef.current
778
+ : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
779
+ if (arrivingControls && !continuousControls) {
780
+ const drift = nextIsCollapsed
781
+ ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX
782
+ : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX;
783
+ stateChangeAnimations.push(
784
+ arrivingControls.animate(
785
+ [
786
+ { opacity: 0, transform: `translateY(${String(drift)}px)` },
787
+ { opacity: 1, transform: "none" },
788
+ ],
789
+ {
790
duration: nextIsCollapsed ? duration : duration / 2,
791
delay: nextIsCollapsed ? 0 : duration / 2,
792
fill: "backwards",
793
easing: COMPOSER_RESTING_TRANSITION_EASING,
821
- }),
794
+ },
795
+ ),
796
+ );
797
+ }
798
+
799
+ const arrivingImagePreviews = nextIsCollapsed
800
+ ? Array.from(
801
+ element.querySelectorAll<HTMLElement>('[data-chat-composer-resting-images="true"]'),
802
+ )
803
+ : Array.from(
804
+ element.querySelectorAll<HTMLElement>('[data-chat-composer-expanded-image="true"]'),
805
);
823
- }
824
- stateChangeAnimationsRef.current = stateChangeAnimations;
806
+ for (const imagePreview of arrivingImagePreviews) {
807
+ stateChangeAnimations.push(
808
+ imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], {
809
+ duration: nextIsCollapsed ? duration : duration / 2,
810
+ delay: nextIsCollapsed ? 0 : duration / 2,
811
+ fill: "backwards",
812
+ easing: COMPOSER_RESTING_TRANSITION_EASING,
813
+ }),
814
+ );
815
}
816
+ stateChangeAnimationsRef.current = stateChangeAnimations;
817
+ }
818
827
- const finishTransition = (cancelAnimations: boolean) => {
828
- if (animationRef.current !== animation) return;
829
- if (transitionCleanupTimeoutRef.current !== null) {
830
- window.clearTimeout(transitionCleanupTimeoutRef.current);
831
- transitionCleanupTimeoutRef.current = null;
819
+ const finishTransition = (cancelAnimations: boolean) => {
820
+ if (animationRef.current !== animation) return;
821
+ if (transitionCleanupTimeoutRef.current !== null) {
822
+ window.clearTimeout(transitionCleanupTimeoutRef.current);
823
+ transitionCleanupTimeoutRef.current = null;
824
+ }
825
+ if (cancelAnimations) {
826
+ animation.cancel();
827
+ for (const contentAnimation of contentAnimationsRef.current) {
828
+ contentAnimation.cancel();
829
}
833
- if (cancelAnimations) {
834
- animation.cancel();
835
- for (const contentAnimation of contentAnimationsRef.current) {
836
- contentAnimation.cancel();
837
- }
838
- for (const stateChangeAnimation of stateChangeAnimationsRef.current) {
839
- stateChangeAnimation.cancel();
840
- }
830
+ for (const stateChangeAnimation of stateChangeAnimationsRef.current) {
831
+ stateChangeAnimation.cancel();
832
}
842
- animationRef.current = null;
843
- animationTargetHeightRef.current = null;
844
- contentAnimationsRef.current = [];
845
- stateChangeAnimationsRef.current = [];
846
- animation.cancel();
847
- stripAnimation?.cancel();
848
- clearTransitionStyles();
849
- };
850
- void animation.finished.catch(() => undefined).then(() => finishTransition(false));
851
- // A suspended document timeline can leave `finished` pending while
852
- // these measurement styles remain active. Wall-clock cleanup makes
853
- // the natural layout the eventual source of truth in that case.
854
- transitionCleanupTimeoutRef.current = window.setTimeout(
855
- () => finishTransition(true),
856
- duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS,
857
- );
858
- } else {
833
+ }
834
+ animationRef.current = null;
835
animationTargetHeightRef.current = null;
860
- }
861
-
862
- previousCollapsedRef.current = nextIsCollapsed;
863
- previousHeightRef.current = nextHeight;
864
- previousModelStripHeightRef.current = nextModelStripHeight;
865
- previousContentOffsetsRef.current = {
866
- promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top,
867
- promptHeight: nextPromptRect?.height ?? null,
868
- actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop,
869
- controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop,
870
- controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left,
871
- surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null,
836
+ contentAnimationsRef.current = [];
837
+ stateChangeAnimationsRef.current = [];
838
+ animation.cancel();
839
+ stripAnimation?.cancel();
840
+ clearTransitionStyles();
841
};
873
- },
874
- [
875
- animationDurationMs,
876
- animationsActive,
877
- clearTransitionStyles,
878
- onOverlayHeightChange,
879
- restingControlsRef,
880
- ],
881
- );
842
+ void animation.finished.catch(() => undefined).then(() => finishTransition(false));
843
+ // A suspended document timeline can leave `finished` pending while
844
+ // these measurement styles remain active. Wall-clock cleanup makes
845
+ // the natural layout the eventual source of truth in that case.
846
+ transitionCleanupTimeoutRef.current = window.setTimeout(
847
+ () => finishTransition(true),
848
+ duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS,
849
+ );
850
+ } else {
851
+ animationTargetHeightRef.current = null;
852
+ }
853
+
854
+ previousCollapsedRef.current = nextIsCollapsed;
855
+ previousHeightRef.current = nextHeight;
856
+ previousModelStripHeightRef.current = nextModelStripHeight;
857
+ previousContentOffsetsRef.current = {
858
+ promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top,
859
+ promptHeight: nextPromptRect?.height ?? null,
860
+ actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop,
861
+ controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop,
862
+ controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left,
863
+ surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null,
864
+ };
865
+ };
866
867
useLayoutEffect(() => {
868
const requestId = transitionLayoutRequestRef.current + 1;
@@ -985,10 +969,7 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
969
970
useLayoutEffect(() => {
971
const anchor = props.anchor;
988
- if (!anchor) {
989
- setPosition(null);
990
- return;
991
- }
972
+ if (!anchor) return;
973
974
const updatePosition = () => {
975
const form = anchor.closest<HTMLElement>('[data-chat-composer-form="true"]');
@@ -1036,7 +1017,7 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
1017
};
1018
}, [props.anchor]);
1019
1039
- if (!position) return null;
1020
+ if (!props.anchor || !position) return null;
1021
1022
return createPortal(
1023
<div
@@ -1059,7 +1040,6 @@ import { Select, SelectItem, SelectPopup, SelectValue } from "../ui/select";
1040
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
1041
import { toastManager } from "../ui/toast";
1042
import {
1062
- FileIcon,
1043
BotIcon,
1044
CircleAlertIcon,
1045
PaperclipIcon,
@@ -1123,6 +1103,22 @@ import type { ReviewCommentContext } from "../../reviewCommentContext";
1103
1104
const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
1105
1106
+/** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */
1107
+function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
1108
+ const armed = Date.now() <= deadline.current;
1109
+ deadline.current = 0;
1110
+ return armed;
1111
+}
1112
+
1113
+async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
1114
+ try {
1115
+ const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
1116
+ return response.ok ? await response.blob() : null;
1117
+ } catch {
1118
+ return null;
1119
+ }
1120
+}
1121
+
1122
const extendReplacementRangeForTrailingSpace = (
1123
text: string,
1124
rangeEnd: number,
@@ -1137,20 +1133,18 @@ const extendReplacementRangeForTrailingSpace = (
1133
function useRestingComposerControlsLayout(host: HTMLDivElement | null, useControlsAsHost = false) {
1134
const [controls, setControls] = useState<HTMLDivElement | null>(null);
1135
const controlsRef = useRef<HTMLDivElement>(null);
1140
- const attachControls = useCallback((element: HTMLDivElement | null) => {
1136
+ const attachControls = (element: HTMLDivElement | null) => {
1137
controlsRef.current = element;
1138
setControls(element);
1143
- }, []);
1144
- const hostRef = useRef(host);
1145
- hostRef.current = host;
1139
+ };
1140
const [layout, setLayout] = useState<{
1141
hiddenCount: number;
1142
iconOnlyCount?: number;
1143
visible: boolean;
1144
}>({ hiddenCount: 0, visible: true });
1145
1152
- const measure = useCallback(() => {
1153
- const currentHost = useControlsAsHost ? controls : hostRef.current;
1146
+ const measure = () => {
1147
+ const currentHost = useControlsAsHost ? controls : host;
1148
if (currentHost === null || !controls) return;
1149
1150
const measurement = measureRestingComposerControls(controls);
@@ -1173,10 +1167,9 @@ function useRestingComposerControlsLayout(host: HTMLDivElement | null, useContro
1167
? current
1168
: next;
1169
});
1176
- }, [controls, useControlsAsHost]);
1170
+ };
1171
1178
- useLayoutEffect(measure, [measure, host]);
1179
- useEffect(() => {
1172
+ useLayoutEffect(() => {
1173
const currentHost = useControlsAsHost ? controls : host;
1174
if (!currentHost || !controls) return;
1175
let stopObserving = () => {};
@@ -1648,6 +1641,213 @@ export interface ChatComposerProps {
1641
onFileOpen: (attachment: ChatFileAttachment) => void;
1642
}
1643
1644
+/**
1645
+ * Keeps the selected provider's workspace snapshot fresh for the composer's
1646
+ * cwd. Returns a check to run when the user types.
1647
+ */
1648
+function useProviderWorkspaceSnapshotRefresh(input: {
1649
+ readonly environmentId: EnvironmentId;
1650
+ readonly gitCwd: string | null;
1651
+ readonly selectedProviderEntry: ProviderInstanceEntry | undefined;
1652
+ readonly selectedProviderStatus: ServerProvider | null;
1653
+}) {
1654
+ const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input;
1655
+ const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
1656
+ reportFailure: false,
1657
+ });
1658
+ // The last scan this composer asked for. A request inside the TTL is not
1659
+ // repeated, so a client clock ahead of the server's cannot loop rescans.
1660
+ const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
1661
+ const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
1662
+ key: string;
1663
+ notBefore: number;
1664
+ } | null>(null);
1665
+ const workspaceRefreshScopeKey =
1666
+ gitCwd && selectedProviderEntry
1667
+ ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`
1668
+ : null;
1669
+ const workspaceSlashCommandsPending =
1670
+ selectedProviderStatus?.workspaceSnapshots?.some(
1671
+ (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true,
1672
+ ) ?? false;
1673
+ useEffect(() => {
1674
+ if (
1675
+ !workspaceSlashCommandsPending ||
1676
+ !workspaceRefreshRetry ||
1677
+ workspaceRefreshRetry.key !== workspaceRefreshScopeKey
1678
+ )
1679
+ return;
1680
+ const timeout = setTimeout(
1681
+ () => {
1682
+ setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
1683
+ },
1684
+ Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
1685
+ );
1686
+ return () => clearTimeout(timeout);
1687
+ }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
1688
+ // Losing a snapshot (the server dropped it) lifts both the TTL and the retry
1689
+ // cooldown so the next check rescans at once.
1690
+ const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd);
1691
+ const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot);
1692
+ const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0);
1693
+ if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) {
1694
+ setHadWorkspaceSnapshot(hasWorkspaceSnapshot);
1695
+ if (!hasWorkspaceSnapshot) {
1696
+ setWorkspaceSnapshotLossCount((count) => count + 1);
1697
+ setWorkspaceRefreshRetry(null);
1698
+ }
1699
+ }
1700
+ const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount);
1701
+ const refreshWorkspaceSnapshotIfStale = (
1702
+ now: number,
1703
+ key: string | null,
1704
+ retry: { key: string; notBefore: number } | null,
1705
+ snapshotLossCount: number,
1706
+ ) => {
1707
+ if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) {
1708
+ lastWorkspaceSnapshotLossRef.current = snapshotLossCount;
1709
+ workspaceRefreshKeyRef.current = null;
1710
+ }
1711
+ if (key === null || !gitCwd || !selectedProviderEntry) return;
1712
+ const lastRequest = workspaceRefreshKeyRef.current;
1713
+ if (
1714
+ lastRequest?.key === key &&
1715
+ now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
1716
+ )
1717
+ return;
1718
+ // A pending retry needs no clearing here: its cooldown lapses long before the TTL.
1719
+ if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return;
1720
+ if (retry?.key === key && now < retry.notBefore) return;
1721
+ const request = { key, requestedAt: now };
1722
+ workspaceRefreshKeyRef.current = request;
1723
+ const retryLater = () => {
1724
+ if (workspaceRefreshKeyRef.current !== request) return;
1725
+ workspaceRefreshKeyRef.current = null;
1726
+ setWorkspaceRefreshRetry({
1727
+ key,
1728
+ notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
1729
+ });
1730
+ };
1731
+ void refreshProviders({
1732
+ environmentId,
1733
+ input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
1734
+ }).then((result) => {
1735
+ const refreshedSnapshot =
1736
+ result._tag === "Success" &&
1737
+ hasCompleteProviderWorkspaceSnapshot(
1738
+ result.value.providers.find(
1739
+ (provider) => provider.instanceId === selectedProviderEntry.instanceId,
1740
+ ),
1741
+ gitCwd,
1742
+ );
1743
+ if (!refreshedSnapshot) retryLater();
1744
+ }, retryLater);
1745
+ };
1746
+ const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale);
1747
+ useEffect(() => {
1748
+ refreshWorkspaceSnapshotOnChange(
1749
+ Date.now(),
1750
+ workspaceRefreshScopeKey,
1751
+ workspaceRefreshRetry,
1752
+ workspaceSnapshotLossCount,
1753
+ );
1754
+ }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]);
1755
+ return useStableCallback(() =>
1756
+ refreshWorkspaceSnapshotIfStale(
1757
+ Date.now(),
1758
+ workspaceRefreshScopeKey,
1759
+ workspaceRefreshRetry,
1760
+ workspaceSnapshotLossCount,
1761
+ ),
1762
+ );
1763
+}
1764
+
1765
+/**
1766
+ * The provider instances the composer offers and which one is selected.
1767
+ * A hook so its results reach the composer frozen: they are passed to plain
1768
+ * functions across later hook calls, which would otherwise keep the compiler
1769
+ * from caching them.
1770
+ */
1771
+function useComposerProviderSelection(
1772
+ input: Omit<Parameters<typeof resolveComposerProviderSelection>[0], "entries"> & {
1773
+ readonly providerStatuses: ReadonlyArray<ServerProvider>;
1774
+ readonly settings: UnifiedSettings;
1775
+ readonly activeProjectId: ProjectId | null;
1776
+ },
1777
+) {
1778
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1779
+ "use memo";
1780
+ const { providerStatuses, settings, activeProjectId, ...selection } = input;
1781
+ const providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry> = sortProviderInstanceEntries(
1782
+ applyProviderInstanceSettings(
1783
+ deriveProviderInstanceEntries(providerStatuses),
1784
+ settings,
1785
+ activeProjectId,
1786
+ ),
1787
+ );
1788
+ return {
1789
+ providerInstanceEntries,
1790
+ ...resolveComposerProviderSelection({ ...selection, entries: providerInstanceEntries }),
1791
+ };
1792
+}
1793
+
1794
+function useModelOptionsByInstance(
1795
+ settings: UnifiedSettings,
1796
+ entries: ReadonlyArray<ProviderInstanceEntry>,
1797
+ selectedInstanceId: ProviderInstanceId,
1798
+ selectedModel: string | null,
1799
+): ReadonlyMap<ProviderInstanceId, ReadonlyArray<AppModelOption>> {
1800
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1801
+ "use memo";
1802
+ const out = new Map<ProviderInstanceId, ReadonlyArray<AppModelOption>>();
1803
+ for (const entry of entries) {
1804
+ out.set(
1805
+ entry.instanceId,
1806
+ getAppModelOptionsForInstance(
1807
+ settings,
1808
+ entry,
1809
+ entry.instanceId === selectedInstanceId ? selectedModel : null,
1810
+ ),
1811
+ );
1812
+ }
1813
+ return out;
1814
+}
1815
+
1816
+/** Splits the draft's images into pending SnapShots and standalone images. */
1817
+function useComposerImageGroups(
1818
+ pendingSnapShotAnimations: ReturnType<typeof getPendingSnapShotAnimations>,
1819
+ composerDraftTarget: ScopedThreadRef | DraftId,
1820
+ composerImages: ReadonlyArray<ComposerImageAttachment>,
1821
+ composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>,
1822
+) {
1823
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1824
+ "use memo";
1825
+ const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget(
1826
+ pendingSnapShotAnimations,
1827
+ composerDraftTarget,
1828
+ );
1829
+ const previewAnnotationIds = new Set(
1830
+ composerPreviewAnnotations.map((annotation) => annotation.id),
1831
+ );
1832
+ return {
1833
+ pendingSnapShotIds,
1834
+ pendingSnapShotIdSet: new Set(pendingSnapShotIds),
1835
+ uncommittedSnapShotIds: pendingSnapShotIds.filter(
1836
+ (id) => !composerImages.some((image) => image.id === id),
1837
+ ),
1838
+ standaloneComposerImages: composerImages.filter((image) => !previewAnnotationIds.has(image.id)),
1839
+ };
1840
+}
1841
+
1842
+const NO_PROVIDER_SKILLS: ServerProvider["skills"] = [];
1843
+const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = [];
1844
+
1845
+function useComposerProviderState(input: Parameters<typeof getComposerProviderState>[0]) {
1846
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1847
+ "use memo";
1848
+ return getComposerProviderState(input);
1849
+}
1850
+
1851
export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {
1852
const {
1853
composerDraftTarget,
@@ -1783,7 +1983,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1983
const isEditingQueuedMessage = editingQueuedAttachments !== null;
1984
const composerDraft = useComposerThreadDraft(composerDraftTarget);
1985
const composerDraftTargetKeyRef = useRef("");
1786
- composerDraftTargetKeyRef.current = composerDraftTargetKey;
1986
+ useLayoutEffect(() => {
1987
+ composerDraftTargetKeyRef.current = composerDraftTargetKey;
1988
+ });
1989
const questionAttachmentTarget =
1990
pendingUserInputs[0] && activePendingProgress?.activeQuestion
1991
? questionAttachmentDraftId(
@@ -1799,12 +2001,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2001
// An import that finishes after a draft change must compare against the draft open *now*, not
2002
// the one captured in the closure that started it.
2003
const attachmentTargetKeyRef = useRef(attachmentTargetKey);
1802
- attachmentTargetKeyRef.current = attachmentTargetKey;
2004
+ useLayoutEffect(() => {
2005
+ attachmentTargetKeyRef.current = attachmentTargetKey;
2006
+ });
2007
const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts);
2008
const prompt = composerDraft.prompt;
2009
const composerImages = attachmentDraft.images;
2010
const composerFiles = attachmentDraft.files;
1807
- const inlineFileIdSet = useMemo(() => {
2011
+ const inlineFileIdSet = (() => {
2012
if (questionAttachmentTarget) return new Set<string>();
2013
const contextIds = new Set(collectInlineContextIds(prompt));
2014
return new Set(
@@ -1812,7 +2016,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2016
.filter((file) => contextIds.has(toKindScopedComposerContextId("file", file.id)))
2017
.map((file) => file.id),
2018
);
1815
- }, [composerFiles, prompt, questionAttachmentTarget]);
2019
+ })();
2020
const composerVideos = composerFiles.filter((file) =>
2021
isPreviewableComposerVideo(file, environmentId),
2022
);
@@ -1830,90 +2034,64 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2034
getPendingSnapShotAnimations,
2035
getPendingSnapShotAnimations,
2036
);
1833
- const pendingSnapShotIds = useMemo(
1834
- () => pendingSnapShotAnimationIdsForTarget(pendingSnapShotAnimations, composerDraftTarget),
1835
- [composerDraftTarget, pendingSnapShotAnimations],
1836
- );
1837
- const pendingSnapShotIdSet = useMemo(() => new Set(pendingSnapShotIds), [pendingSnapShotIds]);
1838
- const uncommittedSnapShotIds = pendingSnapShotIds.filter(
1839
- (id) => !composerImages.some((image) => image.id === id),
2037
+ const {
2038
+ pendingSnapShotIds,
2039
+ pendingSnapShotIdSet,
2040
+ uncommittedSnapShotIds,
2041
+ standaloneComposerImages,
2042
+ } = useComposerImageGroups(
2043
+ pendingSnapShotAnimations,
2044
+ composerDraftTarget,
2045
+ composerImages,
2046
+ composerPreviewAnnotations,
2047
);
1841
- const standaloneComposerImages = useMemo(() => {
1842
- const previewAnnotationIds = new Set(
1843
- composerPreviewAnnotations.map((annotation) => annotation.id),
1844
- );
1845
- return composerImages.filter((image) => !previewAnnotationIds.has(image.id));
1846
- }, [composerImages, composerPreviewAnnotations]);
2048
const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds;
2049
const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
2050
const openPrLink = useOpenPrLink(routeThreadRef);
2051
const [previewFileId, setPreviewFileId] = useState<string | null>(null);
2052
const previewFile = composerFiles.find((file) => file.id === previewFileId);
1852
- const composerContextActions = useMemo(
1853
- () => ({
1854
- environmentId,
1855
- cwd: gitCwd ?? undefined,
1856
- expandImage: (imageId: string) => {
1857
- const preview = buildExpandedImagePreview(composerImages, imageId);
1858
- if (preview) onExpandImage(preview);
1859
- },
1860
- openFile: setPreviewFileId,
1861
- openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path),
1862
- expandVideo: (fileId: string) => {
1863
- const file = composerFiles.find((candidate) => candidate.id === fileId);
1864
- if (!file || !isVideoAttachment(file)) return;
1865
- const localPreview = buildExpandedImagePreview([file], file.id);
1866
- if (localPreview) {
1867
- onExpandImage(localPreview);
1868
- return;
1869
- }
1870
- if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) {
1871
- return;
1872
- }
1873
- const persistedPreview = buildAttachmentVideoPreview(environmentId, {
1874
- type: "file",
1875
- id: file.uploadedAttachmentId,
1876
- name: file.name,
1877
- mimeType: file.mimeType,
1878
- sizeBytes: file.sizeBytes,
1879
- });
1880
- if (persistedPreview) onExpandImage(persistedPreview);
1881
- },
1882
- openPullRequest: (event: React.MouseEvent<HTMLElement>, url: string) => {
1883
- openPrLink(event, url);
1884
- },
1885
- }),
1886
- [
1887
- composerFiles,
1888
- composerImages,
1889
- gitCwd,
1890
- environmentId,
1891
- onExpandImage,
1892
- openPrLink,
1893
- routeThreadRef,
1894
- ],
1895
- );
1896
- const composerContextRecords = useMemo(
1897
- () =>
1898
- composerContextRecordsFromDraft({
1899
- terminalContexts: composerTerminalContexts,
1900
- reviewComments: composerReviewComments,
1901
- previewAnnotations: composerPreviewAnnotations,
1902
- threadContexts: composerThreadContexts,
1903
- images: composerImages,
1904
- files: composerFiles,
1905
- uploadsByImageId,
1906
- }),
1907
- [
1908
- composerFiles,
1909
- composerImages,
1910
- composerPreviewAnnotations,
1911
- composerReviewComments,
1912
- composerTerminalContexts,
1913
- composerThreadContexts,
1914
- uploadsByImageId,
1915
- ],
1916
- );
2053
+ const composerContextActions = {
2054
+ environmentId,
2055
+ cwd: gitCwd ?? undefined,
2056
+ expandImage: (imageId: string) => {
2057
+ const preview = buildExpandedImagePreview(composerImages, imageId);
2058
+ if (preview) onExpandImage(preview);
2059
+ },
2060
+ openFile: setPreviewFileId,
2061
+ openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path),
2062
+ expandVideo: (fileId: string) => {
2063
+ const file = composerFiles.find((candidate) => candidate.id === fileId);
2064
+ if (!file || !isVideoAttachment(file)) return;
2065
+ const localPreview = buildExpandedImagePreview([file], file.id);
2066
+ if (localPreview) {
2067
+ onExpandImage(localPreview);
2068
+ return;
2069
+ }
2070
+ if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) {
2071
+ return;
2072
+ }
2073
+ const persistedPreview = buildAttachmentVideoPreview(environmentId, {
2074
+ type: "file",
2075
+ id: file.uploadedAttachmentId,
2076
+ name: file.name,
2077
+ mimeType: file.mimeType,
2078
+ sizeBytes: file.sizeBytes,
2079
+ });
2080
+ if (persistedPreview) onExpandImage(persistedPreview);
2081
+ },
2082
+ openPullRequest: (event: React.MouseEvent<HTMLElement>, url: string) => {
2083
+ openPrLink(event, url);
2084
+ },
2085
+ };
2086
+ const composerContextRecords = composerContextRecordsFromDraft({
2087
+ terminalContexts: composerTerminalContexts,
2088
+ reviewComments: composerReviewComments,
2089
+ previewAnnotations: composerPreviewAnnotations,
2090
+ threadContexts: composerThreadContexts,
2091
+ images: composerImages,
2092
+ files: composerFiles,
2093
+ uploadsByImageId,
2094
+ });
2095
const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length;
2096
const fileStagingLimit = fileAttachmentStagingLimit({
2097
attachmentUploadsCapabilityKnown,
@@ -2057,46 +2235,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2235
uploadsByImageId,
2236
]);
2237
2060
- const providerInstanceEntries = useMemo<ReadonlyArray<ProviderInstanceEntry>>(
2061
- () =>
2062
- sortProviderInstanceEntries(
2063
- applyProviderInstanceSettings(
2064
- deriveProviderInstanceEntries(providerStatuses),
2065
- settings,
2066
- activeProjectId,
2067
- ),
2068
- ),
2069
- [providerStatuses, settings, activeProjectId],
2070
- );
2071
- const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
2238
const {
2239
+ providerInstanceEntries,
2240
selectedProviderEntry,
2241
requestedDriverKind,
2242
lockedContinuationGroupKey,
2243
unavailableProviderInstanceId,
2077
- } = useMemo(
2078
- () =>
2079
- resolveComposerProviderSelection({
2080
- entries: providerInstanceEntries,
2081
- candidateInstanceIds: [
2082
- selectedProviderByThreadId,
2083
- activeThread?.runtime?.providerInstanceId,
2084
- activeThreadModelSelection?.instanceId,
2085
- activeProjectDefaultModelSelection?.instanceId,
2086
- ],
2087
- lockedProvider,
2088
- lockedInstanceId:
2089
- activeThread?.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId,
2090
- }),
2091
- [
2092
- activeProjectDefaultModelSelection?.instanceId,
2244
+ } = useComposerProviderSelection({
2245
+ providerStatuses,
2246
+ settings,
2247
+ activeProjectId,
2248
+ candidateInstanceIds: [
2249
+ composerDraft.activeProvider ?? null,
2250
activeThread?.runtime?.providerInstanceId,
2251
activeThreadModelSelection?.instanceId,
2095
- selectedProviderByThreadId,
2096
- lockedProvider,
2097
- providerInstanceEntries,
2252
+ activeProjectDefaultModelSelection?.instanceId,
2253
],
2099
- );
2254
+ lockedProvider,
2255
+ lockedInstanceId:
2256
+ activeThread?.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId,
2257
+ });
2258
const selectedInstanceId =
2259
selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId;
2260
const noProviderAvailable =
@@ -2145,145 +2303,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2303
: (attachmentBlockReason ??
2304
(multipleModelSelections === null ? providerSendBlockReason : null)));
2305
const isSendDisabled = sendDisabledReason !== null;
2148
- const selectedProviderStatus = useMemo(
2149
- () => selectedProviderEntry?.snapshot ?? null,
2150
- [selectedProviderEntry],
2151
- );
2306
+ const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null;
2307
const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry);
2153
- const selectedProviderSkills = useMemo(
2154
- () =>
2155
- selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd) : [],
2156
- [gitCwd, selectedProviderStatus],
2157
- );
2158
- const selectedProviderSlashCommands = useMemo(
2159
- () =>
2160
- selectedProviderStatus
2161
- ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd)
2162
- : [],
2163
- [gitCwd, selectedProviderStatus],
2164
- );
2165
- const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
2166
- reportFailure: false,
2167
- });
2168
- // The last scan this composer asked for. A request inside the TTL is not
2169
- // repeated, so a client clock ahead of the server's cannot loop rescans.
2170
- const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
2171
- const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
2172
- key: string;
2173
- notBefore: number;
2174
- } | null>(null);
2175
- const workspaceRefreshScopeKey =
2176
- gitCwd && selectedProviderEntry
2177
- ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`
2178
- : null;
2179
- const workspaceSlashCommandsPending =
2180
- selectedProviderStatus?.workspaceSnapshots?.some(
2181
- (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true,
2182
- ) ?? false;
2183
- useEffect(() => {
2184
- if (
2185
- !workspaceSlashCommandsPending ||
2186
- !workspaceRefreshRetry ||
2187
- workspaceRefreshRetry.key !== workspaceRefreshScopeKey
2188
- )
2189
- return;
2190
- const timeout = setTimeout(
2191
- () => {
2192
- setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
2193
- },
2194
- Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
2195
- );
2196
- return () => clearTimeout(timeout);
2197
- }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
2198
- const hadWorkspaceSnapshotRef = useRef(false);
2199
- useEffect(() => {
2200
- const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(
2201
- selectedProviderStatus,
2202
- gitCwd,
2203
- );
2204
- if (hadWorkspaceSnapshotRef.current && !hasWorkspaceSnapshot) {
2205
- workspaceRefreshKeyRef.current = null;
2206
- setWorkspaceRefreshRetry(null);
2207
- }
2208
- hadWorkspaceSnapshotRef.current = hasWorkspaceSnapshot;
2209
- }, [gitCwd, selectedProviderStatus]);
2210
- useEffect(() => {
2211
- if (!gitCwd || !selectedProviderEntry) return;
2212
- const key = `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`;
2213
- const now = Date.now();
2214
- const lastRequest = workspaceRefreshKeyRef.current;
2215
- if (
2216
- lastRequest?.key === key &&
2217
- now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
2218
- )
2219
- return;
2220
- if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) {
2221
- setWorkspaceRefreshRetry(null);
2222
- return;
2223
- }
2224
- const retry = workspaceRefreshRetry;
2225
- if (retry?.key === key && now < retry.notBefore) return;
2226
- const request = { key, requestedAt: now };
2227
- workspaceRefreshKeyRef.current = request;
2228
- const retryLater = () => {
2229
- if (workspaceRefreshKeyRef.current !== request) return;
2230
- workspaceRefreshKeyRef.current = null;
2231
- setWorkspaceRefreshRetry({
2232
- key,
2233
- notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
2234
- });
2235
- };
2236
- void refreshProviders({
2237
- environmentId,
2238
- input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
2239
- }).then((result) => {
2240
- const hasWorkspaceSnapshot =
2241
- result._tag === "Success" &&
2242
- hasCompleteProviderWorkspaceSnapshot(
2243
- result.value.providers.find(
2244
- (provider) => provider.instanceId === selectedProviderEntry.instanceId,
2245
- ),
2246
- gitCwd,
2247
- );
2248
- if (!hasWorkspaceSnapshot) retryLater();
2249
- }, retryLater);
2250
- }, [
2308
+ const selectedProviderSkills = selectedProviderStatus
2309
+ ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd)
2310
+ : NO_PROVIDER_SKILLS;
2311
+ const selectedProviderSlashCommands = selectedProviderStatus
2312
+ ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd)
2313
+ : NO_PROVIDER_SLASH_COMMANDS;
2314
+ const refreshWorkspaceSnapshotOnTyping = useProviderWorkspaceSnapshotRefresh({
2315
environmentId,
2316
gitCwd,
2253
- prompt,
2254
- refreshProviders,
2317
selectedProviderEntry,
2256
- workspaceRefreshRetry,
2257
- ]);
2258
- const selectedProviderModels = useMemo<ReadonlyArray<ServerProvider["models"][number]>>(
2259
- () => selectedProviderEntry?.models ?? [],
2260
- [selectedProviderEntry],
2261
- );
2318
+ selectedProviderStatus,
2319
+ });
2320
+ const selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]> =
2321
+ selectedProviderEntry?.models ?? [];
2322
2263
- const composerPromptInjectionState = useMemo(
2264
- () => getComposerPromptInjectionState(prompt),
2265
- [prompt],
2266
- );
2267
- const composerProviderState = useMemo(
2268
- () =>
2269
- getComposerProviderState({
2270
- provider: selectedProvider,
2271
- model: selectedModel,
2272
- models: selectedProviderModels,
2273
- promptInjectionState: composerPromptInjectionState,
2274
- modelOptions: composerModelOptions?.[selectedInstanceId],
2275
- planModeEnabled: settings.planModeEnabled,
2276
- }),
2277
- [
2278
- composerModelOptions,
2279
- composerPromptInjectionState,
2280
- selectedInstanceId,
2281
- selectedModel,
2282
- selectedProvider,
2283
- selectedProviderModels,
2284
- settings.planModeEnabled,
2285
- ],
2286
- );
2323
+ const composerPromptInjectionState = getComposerPromptInjectionState(prompt);
2324
+ const composerProviderState = useComposerProviderState({
2325
+ provider: selectedProvider,
2326
+ model: selectedModel,
2327
+ models: selectedProviderModels,
2328
+ promptInjectionState: composerPromptInjectionState,
2329
+ modelOptions: composerModelOptions?.[selectedInstanceId],
2330
+ planModeEnabled: settings.planModeEnabled,
2331
+ });
2332
2333
const selectedPromptEffort = composerProviderState.promptEffort;
2334
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
@@ -2292,37 +2337,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2337
provider: selectedProviderStatus,
2338
interactionMode: requestedInteractionMode,
2339
});
2295
- const selectedModelSelection = useMemo<ModelSelection>(
2296
- () => createModelSelection(selectedInstanceId, selectedModel, selectedModelOptionsForDispatch),
2297
- [selectedInstanceId, selectedModel, selectedModelOptionsForDispatch],
2340
+ const selectedModelSelection: ModelSelection = createModelSelection(
2341
+ selectedInstanceId,
2342
+ selectedModel,
2343
+ selectedModelOptionsForDispatch,
2344
);
2345
const selectedModelForPicker = selectedModel;
2300
- const modelOptionsByInstance = useMemo<
2301
- ReadonlyMap<ProviderInstanceId, ReadonlyArray<AppModelOption>>
2302
- >(() => {
2303
- const out = new Map<ProviderInstanceId, ReadonlyArray<AppModelOption>>();
2304
- for (const entry of providerInstanceEntries) {
2305
- out.set(
2306
- entry.instanceId,
2307
- getAppModelOptionsForInstance(
2308
- settings,
2309
- entry,
2310
- entry.instanceId === selectedInstanceId ? selectedModelForPicker : null,
2311
- ),
2312
- );
2313
- }
2314
- return out;
2315
- }, [providerInstanceEntries, selectedInstanceId, selectedModelForPicker, settings]);
2316
- const selectedModelForPickerWithCustomFallback = useMemo(() => {
2346
+ const modelOptionsByInstance = useModelOptionsByInstance(
2347
+ settings,
2348
+ providerInstanceEntries,
2349
+ selectedInstanceId,
2350
+ selectedModelForPicker,
2351
+ );
2352
+ const selectedModelForPickerWithCustomFallback = (() => {
2353
const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? [];
2354
return currentOptions.some((option) => option.slug === selectedModelForPicker)
2355
? selectedModelForPicker
2356
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
2321
- }, [modelOptionsByInstance, selectedInstanceId, selectedModelForPicker, selectedProvider]);
2357
+ })();
2358
2323
- const activeThreadModelDisplayName = useMemo(
2324
- () => resolveContextWindowModelDisplayName(activeThreadModelSelection, modelOptionsByInstance),
2325
- [activeThreadModelSelection, modelOptionsByInstance],
2359
+ const activeThreadModelDisplayName = resolveContextWindowModelDisplayName(
2360
+ activeThreadModelSelection,
2361
+ modelOptionsByInstance,
2362
);
2363
const reserveContextWindowMeter = shouldReserveContextWindowMeter({
2364
meterEnabled: settings.contextWindowMeterEnabled,
@@ -2349,7 +2385,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2385
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
2386
const composerSuggestionId = useId();
2387
const composerSuggestionListId = `${composerSuggestionId}-${encodeURIComponent(draftId ?? activeThreadId ?? "new")}-suggestions`;
2352
- const promptHistoryPositionRef = useRef<ComposerPromptHistoryPosition | null>(null);
2388
+ const promptHistoryPositionRef = useRef<{
2389
+ targetKey: string;
2390
+ position: ComposerPromptHistoryPosition;
2391
+ } | null>(null);
2392
const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>(
2393
null,
2394
);
@@ -2409,7 +2448,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2448
const pendingImageCompressionsRef = useRef<Map<string, number>>(new Map());
2449
const pendingThreadImportsRef = useRef<Map<string, number>>(new Map());
2450
const isRevertingCheckpointRef = useRef(isRevertingCheckpoint);
2412
- isRevertingCheckpointRef.current = isRevertingCheckpoint;
2451
+ useLayoutEffect(() => {
2452
+ isRevertingCheckpointRef.current = isRevertingCheckpoint;
2453
+ });
2454
2455
useEffect(() => {
2456
const armPasteAsTextShortcut = () => {
@@ -2454,23 +2495,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2495
};
2496
}, []);
2497
2457
- const composerSendState = useMemo(
2458
- () =>
2459
- deriveComposerSendState({
2460
- prompt,
2461
- imageCount: composerImages.length + composerFiles.length,
2462
- terminalContexts: composerTerminalContexts,
2463
- elementContextCount: composerPreviewAnnotations.length + composerReviewComments.length,
2464
- }),
2465
- [
2466
- composerFiles.length,
2467
- composerImages.length,
2468
- composerPreviewAnnotations.length,
2469
- composerReviewComments.length,
2470
- composerTerminalContexts,
2471
- prompt,
2472
- ],
2473
- );
2498
+ const composerSendState = deriveComposerSendState({
2499
+ prompt,
2500
+ imageCount: composerImages.length + composerFiles.length,
2501
+ terminalContexts: composerTerminalContexts,
2502
+ elementContextCount: composerPreviewAnnotations.length + composerReviewComments.length,
2503
+ });
2504
const composerTriggerKind = composerTrigger?.kind ?? null;
2505
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
2506
const pullRequestTriggerQuery =
@@ -2502,41 +2532,32 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2532
composerPreviewAnnotations.length === 0 &&
2533
composerReviewComments.length === 0;
2534
2505
- const pullRequestListTargets = useMemo(
2506
- () =>
2507
- composerTriggerKind !== "pull-request" ||
2508
- pullRequestProjectId === null ||
2509
- (pullRequestTextQuery !== null && settledPullRequestTextQuery === null)
2510
- ? EMPTY_PULL_REQUEST_LIST_TARGETS
2511
- : [
2512
- {
2513
- environmentId,
2514
- input: {
2515
- state: "all" as const,
2516
- projectId: pullRequestProjectId,
2517
- limit: COMPOSER_PULL_REQUEST_LIST_LIMIT,
2518
- ...(settledPullRequestTextQuery === null
2519
- ? {}
2520
- : { query: settledPullRequestTextQuery }),
2521
- },
2535
+ const pullRequestListTargets =
2536
+ composerTriggerKind !== "pull-request" ||
2537
+ pullRequestProjectId === null ||
2538
+ (pullRequestTextQuery !== null && settledPullRequestTextQuery === null)
2539
+ ? EMPTY_PULL_REQUEST_LIST_TARGETS
2540
+ : [
2541
+ {
2542
+ environmentId,
2543
+ input: {
2544
+ state: "all" as const,
2545
+ projectId: pullRequestProjectId,
2546
+ limit: COMPOSER_PULL_REQUEST_LIST_LIMIT,
2547
+ ...(settledPullRequestTextQuery === null
2548
+ ? {}
2549
+ : { query: settledPullRequestTextQuery }),
2550
},
2523
- ],
2524
- [
2525
- composerTriggerKind,
2526
- environmentId,
2527
- pullRequestProjectId,
2528
- pullRequestTextQuery,
2529
- settledPullRequestTextQuery,
2530
- ],
2531
- );
2551
+ },
2552
+ ];
2553
const pullRequestLookup = usePullRequestList(pullRequestListTargets);
2533
- const pullRequestTriggerNumber = useMemo(() => {
2554
+ const pullRequestTriggerNumber = (() => {
2555
if (composerTrigger?.kind !== "pull-request" || composerTrigger.query.length === 0) {
2556
return null;
2557
}
2558
const number = Number(composerTrigger.query);
2559
return Number.isSafeInteger(number) && number > 0 ? number : null;
2539
- }, [composerTrigger]);
2560
+ })();
2561
const debouncedPullRequestNumber = useDebouncedValue(pullRequestTriggerNumber, 180);
2562
const settledPullRequestNumber =
2563
pullRequestTriggerNumber === debouncedPullRequestNumber ? pullRequestTriggerNumber : null;
@@ -2564,15 +2585,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2585
}),
2586
);
2587
2567
- const linkedPullRequests = useMemo(
2568
- () =>
2569
- pullRequestProjectId === null
2570
- ? []
2571
- : composerPullRequestsFromLinks(threadPullRequests ?? [], pullRequestProjectId),
2572
- [pullRequestProjectId, threadPullRequests],
2573
- );
2588
+ const linkedPullRequests =
2589
+ pullRequestProjectId === null
2590
+ ? []
2591
+ : composerPullRequestsFromLinks(threadPullRequests ?? [], pullRequestProjectId);
2592
2575
- const composerMenuItems = useMemo<ComposerCommandItem[]>(() => {
2593
+ const composerMenuItems = ((): ComposerCommandItem[] => {
2594
if (!composerTrigger) return [];
2595
if (composerTrigger.kind === "path") {
2596
return [
@@ -2725,54 +2743,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2743
}));
2744
}
2745
return [];
2728
- }, [
2729
- activeThreadId,
2730
- compactSlashCommandAvailable,
2731
- composerTrigger,
2732
- environmentId,
2733
- environmentThreadShells,
2734
- exactPullRequestLookup.data,
2735
- linkedPullRequests,
2736
- planModeUiEnabled,
2737
- pullRequestLookup.data,
2738
- pullRequestProjectId,
2739
- pullRequestRepository,
2740
- pullRequestTriggerNumber,
2741
- selectedProvider,
2742
- selectedProviderSkills,
2743
- selectedProviderSlashCommands,
2744
- selectedProviderStatus,
2745
- settings.showSkillsInSlashMenu,
2746
- workspaceEntries.entries,
2747
- ]);
2746
+ })();
2747
2748
const composerMenuOpen = Boolean(composerTrigger);
2749
const composerMenuSearchKey = composerTrigger
2750
? `${composerSuggestionListId}:${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}`
2751
: null;
2753
- const activeComposerMenuItem = useMemo(() => {
2754
- const activeItemId = resolveComposerMenuActiveItemId({
2755
- items: composerMenuItems,
2756
- highlightedItemId: composerHighlightedItemId,
2757
- currentSearchKey: composerMenuSearchKey,
2758
- highlightedSearchKey: composerHighlightedSearchKey,
2759
- });
2760
- return composerMenuItems.find((item) => item.id === activeItemId) ?? null;
2761
- }, [
2762
- composerHighlightedItemId,
2763
- composerHighlightedSearchKey,
2764
- composerMenuItems,
2765
- composerMenuSearchKey,
2766
- ]);
2752
+ const activeComposerMenuItemId = resolveComposerMenuActiveItemId({
2753
+ items: composerMenuItems,
2754
+ highlightedItemId: composerHighlightedItemId,
2755
+ currentSearchKey: composerMenuSearchKey,
2756
+ highlightedSearchKey: composerHighlightedSearchKey,
2757
+ });
2758
+ const activeComposerMenuItem =
2759
+ composerMenuItems.find((item) => item.id === activeComposerMenuItemId) ?? null;
2760
2768
- composerMenuOpenRef.current = composerMenuOpen;
2769
- composerMenuItemsRef.current = composerMenuItems;
2770
- activeComposerMenuItemRef.current = activeComposerMenuItem;
2761
+ useLayoutEffect(() => {
2762
+ composerMenuOpenRef.current = composerMenuOpen;
2763
+ composerMenuItemsRef.current = composerMenuItems;
2764
+ activeComposerMenuItemRef.current = activeComposerMenuItem;
2765
+ });
2766
2772
- const nonPersistedComposerImageIdSet = useMemo(
2773
- () => new Set(nonPersistedComposerImageIds),
2774
- [nonPersistedComposerImageIds],
2775
- );
2767
+ const nonPersistedComposerImageIdSet = new Set(nonPersistedComposerImageIds);
2768
2769
const isComposerApprovalState = activePendingApproval !== null;
2770
const composerSuggestionsVisible = composerMenuOpen && !isComposerApprovalState;
@@ -2792,28 +2784,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2784
(supportsQuestionAttachments &&
2785
activePendingProgress.activeQuestion?.allowCustomAnswer !== false));
2786
const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null;
2795
- const composerFooterActionLayoutKey = useMemo(() => {
2796
- if (activePendingProgress) {
2797
- return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`;
2798
- }
2799
- if (phase === "running") {
2800
- return "running";
2801
- }
2802
- if (showPlanFollowUpPrompt) {
2803
- return prompt.trim().length > 0 ? "plan:refine" : "plan:implement";
2804
- }
2805
- return `idle:${composerSendState.hasSendableContent}:${isSendBusy}:${isConnecting}:${isPreparingWorktree}`;
2806
- }, [
2807
- activePendingIsResponding,
2808
- activePendingProgress,
2809
- composerSendState.hasSendableContent,
2810
- isConnecting,
2811
- isPreparingWorktree,
2812
- isSendBusy,
2813
- phase,
2814
- prompt,
2815
- showPlanFollowUpPrompt,
2816
- ]);
2787
2788
const isComposerMenuLoading =
2789
(composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending) ||
@@ -2824,7 +2794,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2794
pullRequestTextQuery !== debouncedPullRequestTextQuery ||
2795
pullRequestTriggerNumber !== debouncedPullRequestNumber ||
2796
exactPullRequestLookup.isPending));
2827
- const composerMenuEmptyState = useMemo(() => {
2797
+ const composerMenuEmptyState = (() => {
2798
if (composerTriggerKind === "skill") {
2799
return "No skills found. Try / to browse provider commands.";
2800
}
@@ -2845,14 +2815,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2815
return composerTriggerKind === "path"
2816
? "No matching files or folders."
2817
: "No matching command.";
2848
- }, [
2849
- composerTrigger,
2850
- composerTriggerKind,
2851
- pullRequestLookup.data?.errors,
2852
- pullRequestLookup.error,
2853
- pullRequestProjectId,
2854
- pullRequestRepository,
2855
- ]);
2818
+ })();
2819
2820
const setPromptFromTraits = (nextPrompt: string) => {
2821
if (nextPrompt === promptRef.current) {
@@ -2906,30 +2869,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2869
iconOnlyBlockCount: restingControlsIconOnlyBlockCount,
2870
controlsVisible: restingControlsVisible,
2871
} = useRestingComposerControlsLayout(restingControlsHost ?? inlineRestingControlsHost);
2909
- const expandedControlsLayout = useRestingComposerControlsLayout(null, true);
2910
- const pendingPrimaryAction = useMemo(
2911
- () =>
2912
- activePendingProgress
2913
- ? {
2914
- questionIndex: activePendingProgress.questionIndex,
2915
- isLastQuestion: activePendingProgress.isLastQuestion,
2916
- canAdvance:
2917
- activePendingProgress.canAdvance &&
2918
- !attachmentBlockReason &&
2919
- !(questionPreparations[attachmentTargetKey] ?? 0),
2920
- isResponding: activePendingIsResponding,
2921
- isComplete: Boolean(activePendingResolvedAnswers),
2922
- }
2923
- : null,
2924
- [
2925
- activePendingIsResponding,
2926
- activePendingProgress,
2927
- activePendingResolvedAnswers,
2928
- attachmentBlockReason,
2929
- questionPreparations,
2930
- attachmentTargetKey,
2931
- ],
2932
- );
2872
+ const {
2873
+ attachControls: attachExpandedComposerControls,
2874
+ hiddenBlockCount: expandedControlsHiddenBlockCount,
2875
+ iconOnlyBlockCount: expandedControlsIconOnlyBlockCount,
2876
+ } = useRestingComposerControlsLayout(null, true);
2877
+ const pendingPrimaryAction = activePendingProgress
2878
+ ? {
2879
+ questionIndex: activePendingProgress.questionIndex,
2880
+ isLastQuestion: activePendingProgress.isLastQuestion,
2881
+ canAdvance:
2882
+ activePendingProgress.canAdvance &&
2883
+ !attachmentBlockReason &&
2884
+ !(questionPreparations[attachmentTargetKey] ?? 0),
2885
+ isResponding: activePendingIsResponding,
2886
+ isComplete: Boolean(activePendingResolvedAnswers),
2887
+ }
2888
+ : null;
2889
const showResumeAction =
2890
canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage;
2891
const collapsedComposerPrimaryActionDisabled =
@@ -3103,12 +3059,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3059
fail("The original attachment is no longer available.");
3060
return;
3061
}
3106
- let blob: Blob;
3107
- try {
3108
- const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
3109
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
3110
- blob = await response.blob();
3111
- } catch {
3062
+ const blob = await downloadAttachmentBlob(url);
3063
+ if (!blob) {
3064
fail("Downloading it from the source failed.");
3065
return;
3066
}
@@ -3172,11 +3124,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3124
// attachment behind it, and so bytes for an abandoned draft never enter the next one.
3125
const importTargetKey = attachmentTargetKey;
3126
pendingDraftWork.begin(importTargetKey);
3175
- try {
3176
- await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey);
3177
- } finally {
3178
- pendingDraftWork.end(importTargetKey);
3179
- }
3127
+ await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() =>
3128
+ pendingDraftWork.end(importTargetKey),
3129
+ );
3130
};
3131
const importContextRecords = (
3132
records: ReadonlyArray<ComposerContextRecord>,
@@ -3297,20 +3247,27 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3247
useEffect(() => {
3248
if (isLiteralPendingAnswer) return;
3249
promptRef.current = prompt;
3300
- setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing));
3250
}, [isLiteralPendingAnswer, prompt, promptRef]);
3251
+ const [cursorClampedFor, setCursorClampedFor] = useState({ prompt, isLiteralPendingAnswer });
3252
+ if (
3253
+ cursorClampedFor.prompt !== prompt ||
3254
+ cursorClampedFor.isLiteralPendingAnswer !== isLiteralPendingAnswer
3255
+ ) {
3256
+ setCursorClampedFor({ prompt, isLiteralPendingAnswer });
3257
+ if (!isLiteralPendingAnswer) {
3258
+ setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing));
3259
+ }
3260
+ }
3261
3303
- useEffect(() => {
3304
- if (composerSubmissionError === null) return;
3262
+ // A shown length error follows the prompt so it clears once the prompt fits.
3263
+ if (composerSubmissionError !== null) {
3264
const nextError = getComposerPromptLengthValidationMessage(prompt);
3265
if (nextError !== composerSubmissionError) {
3266
setComposerSubmissionError(nextError);
3267
}
3309
- }, [composerSubmissionError, prompt]);
3268
+ }
3269
3311
- useEffect(() => {
3312
- setProviderInputSubmissionError(null);
3313
- }, [
3270
+ const providerInputInputs = [
3271
composerPreviewAnnotations,
3272
composerReviewComments,
3273
composerTerminalContexts,
@@ -3318,7 +3275,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3275
selectedModel,
3276
selectedPromptEffort,
3277
selectedProvider,
3321
- ]);
3278
+ ] as const;
3279
+ const [providerInputValidatedFor, setProviderInputValidatedFor] = useState(providerInputInputs);
3280
+ if (providerInputInputs.some((value, index) => value !== providerInputValidatedFor[index])) {
3281
+ setProviderInputValidatedFor(providerInputInputs);
3282
+ setProviderInputSubmissionError(null);
3283
+ }
3284
3285
useEffect(() => {
3286
composerImagesRef.current = composerImages;
@@ -3332,31 +3294,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3294
composerTerminalContextsRef.current = composerTerminalContexts;
3295
}, [composerTerminalContexts, composerTerminalContextsRef]);
3296
3335
- useEffect(() => {
3336
- if (!composerMenuOpen) {
3337
- setComposerHighlightedItemId(null);
3338
- setComposerHighlightedSearchKey(null);
3339
- return;
3340
- }
3341
- const nextActiveItemId = resolveComposerMenuActiveItemId({
3342
- items: composerMenuItems,
3343
- highlightedItemId: composerHighlightedItemId,
3344
- currentSearchKey: composerMenuSearchKey,
3345
- highlightedSearchKey: composerHighlightedSearchKey,
3346
- });
3347
- setComposerHighlightedItemId((existing) =>
3348
- existing === nextActiveItemId ? existing : nextActiveItemId,
3349
- );
3350
- setComposerHighlightedSearchKey((existing) =>
3351
- existing === composerMenuSearchKey ? existing : composerMenuSearchKey,
3352
- );
3353
- }, [
3354
- composerHighlightedItemId,
3355
- composerHighlightedSearchKey,
3356
- composerMenuItems,
3357
- composerMenuOpen,
3358
- composerMenuSearchKey,
3359
- ]);
3297
+ // The highlight is stored resolved, so keyboard handlers and the next
3298
+ // search compare against the item that is actually shown as active.
3299
+ const resolvedHighlightedItemId = composerMenuOpen ? activeComposerMenuItemId : null;
3300
+ const resolvedHighlightedSearchKey = composerMenuOpen ? composerMenuSearchKey : null;
3301
+ if (composerHighlightedItemId !== resolvedHighlightedItemId) {
3302
+ setComposerHighlightedItemId(resolvedHighlightedItemId);
3303
+ }
3304
+ if (composerHighlightedSearchKey !== resolvedHighlightedSearchKey) {
3305
+ setComposerHighlightedSearchKey(resolvedHighlightedSearchKey);
3306
+ }
3307
3308
const lastSyncedPendingInputRef = useRef<{
3309
requestId: string | null;
@@ -3407,24 +3354,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3354
resetComposerTrigger,
3355
]);
3356
3410
- useEffect(() => {
3357
+ const composerSessionKey = `${draftId ?? ""}:${activeThreadId ?? ""}:${isLiteralPendingAnswer}`;
3358
+ const [shownComposerSessionKey, setShownComposerSessionKey] = useState(composerSessionKey);
3359
+ if (shownComposerSessionKey !== composerSessionKey) {
3360
+ setShownComposerSessionKey(composerSessionKey);
3361
setComposerHighlightedItemId(null);
3362
setComposerHighlightedSearchKey(null);
3363
setComposerSubmissionError(null);
3364
setProviderInputSubmissionError(null);
3415
- const { cursor, trigger } = composerStateAtPromptEnd(promptRef.current, isLiteralPendingAnswer);
3365
+ const pendingAnswer = activePendingProgress?.customAnswer;
3366
+ const { cursor, trigger } = composerStateAtPromptEnd(
3367
+ typeof pendingAnswer === "string" ? pendingAnswer : prompt,
3368
+ isLiteralPendingAnswer,
3369
+ );
3370
setComposerCursor(cursor);
3371
resetComposerTrigger(trigger);
3372
setIsDragOverComposer(false);
3373
setIsComposerScrollCollapsed(false);
3420
- }, [
3421
- draftId,
3422
- activeThreadId,
3423
- isLiteralPendingAnswer,
3424
- promptRef,
3425
- resetComposerTrigger,
3426
- setIsComposerScrollCollapsed,
3427
- ]);
3374
+ }
3375
3376
useLayoutEffect(() => {
3377
const composerForm = composerFormRef.current;
@@ -3460,13 +3407,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3407
previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact,
3408
);
3409
});
3463
- }, [
3464
- activeThreadId,
3465
- composerFooterActionLayoutKey,
3466
- composerFooterHasWideActions,
3467
- isComposerApprovalState,
3468
- isComposerCollapsedMobile,
3469
- ]);
3410
+ }, [composerFooterHasWideActions]);
3411
3412
useEffect(() => {
3413
let cancelled = false;
@@ -3567,6 +3508,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3508
contextIds: string[],
3509
) => {
3510
expandComposerForEditorChange();
3511
+ // Typing is when the menu is about to need skills, so it re-checks a
3512
+ // snapshot that has aged past its TTL.
3513
+ refreshWorkspaceSnapshotOnTyping();
3514
if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) {
3515
if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return;
3516
setComposerCursor(nextCursor);
@@ -3585,7 +3529,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3529
onTypingGuardDraftChange();
3530
promptRef.current = nextPrompt;
3531
setPrompt(nextPrompt);
3588
- if (promptHistoryPositionRef.current?.recalled !== nextPrompt) {
3532
+ if (promptHistoryPositionRef.current?.position.recalled !== nextPrompt) {
3533
promptHistoryPositionRef.current = null;
3534
}
3535
const referenced = new Set(contextIds);
@@ -4119,15 +4063,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4063
// Entries are built on the keypress, not per render: the timeline changes
4064
// on every streamed delta and ArrowUp is rare.
4065
const promptHistoryMessagesRef = useRef(promptHistoryMessages);
4122
- promptHistoryMessagesRef.current = promptHistoryMessages;
4066
+ useLayoutEffect(() => {
4067
+ promptHistoryMessagesRef.current = promptHistoryMessages;
4068
+ });
4069
4070
// The composer persists across threads. A recall from thread A must not
4071
// be treated as active in thread B, where the text-match fallback could
4072
// otherwise turn B's own draft into a browsing position.
4073
const promptHistoryTargetKey = composerTargetKey(composerDraftTarget);
4128
- useEffect(() => {
4129
- promptHistoryPositionRef.current = null;
4130
- }, [promptHistoryTargetKey]);
4074
4075
const replacePromptFromHistory = (nextPrompt: string) => {
4076
promptRef.current = nextPrompt;
@@ -4154,7 +4097,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4097
) {
4098
return false;
4099
}
4157
- if (promptHistoryPositionRef.current === null && promptRef.current.length > 0) {
4100
+ const recalled = promptHistoryPositionRef.current;
4101
+ const position = recalled?.targetKey === promptHistoryTargetKey ? recalled.position : null;
4102
+ if (position === null && promptRef.current.length > 0) {
4103
return false;
4104
}
4105
const editor = composerEditorRef.current;
@@ -4164,11 +4109,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4109
const step = stepComposerPromptHistory({
4110
direction,
4111
entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current),
4167
- position: promptHistoryPositionRef.current,
4112
+ position,
4113
currentPrompt: promptRef.current,
4114
});
4115
if (!step) return false;
4171
- promptHistoryPositionRef.current = step.position;
4116
+ promptHistoryPositionRef.current = step.position
4117
+ ? { targetKey: promptHistoryTargetKey, position: step.position }
4118
+ : null;
4119
replacePromptFromHistory(step.prompt);
4120
return true;
4121
};
@@ -4650,7 +4597,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4597
4598
const stashTarget = composerDraftTarget;
4599
const entryId = randomUUID();
4653
- try {
4600
+ const stashAndEncode = async () => {
4601
// Ordering matters in both directions: writing before clearing means a
4602
// crash or closed tab mid-encode still leaves the prompt recoverable,
4603
// while clearing before the async image work means edits typed during
@@ -4774,9 +4721,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4721
data: { hideCopyButton: true },
4722
});
4723
}
4777
- } finally {
4778
- stashInFlightRef.current.delete(snapshotKey);
4779
- }
4724
+ };
4725
+ await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey));
4726
};
4727
const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt);
4728
@@ -4953,7 +4899,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4899
!hasMultilinePrompt &&
4900
!composerHasExpandedChrome &&
4901
!showInlineTasksBadge;
4956
- composerScrollCollapseEligibleRef.current = canScrollCollapseComposer && !isComposerResting;
4902
+ const composerScrollCollapseEligible = canScrollCollapseComposer && !isComposerResting;
4903
+ useLayoutEffect(() => {
4904
+ composerScrollCollapseEligibleRef.current = composerScrollCollapseEligible;
4905
+ });
4906
4907
useEffect(() => {
4908
if (!canScrollCollapseComposer) {
@@ -5048,7 +4997,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4997
finishScrollGesture();
4998
};
4999
}, [
5051
- activeThreadId,
5000
canTrackComposerScrollGesture,
5001
getTimelineScrollableNode,
5002
isTimelineAtLogicalEnd,
@@ -5057,10 +5005,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5005
5006
const restingHiddenBlockCount = composerControlsCollapsed
5007
? restingControlsHiddenBlockCount
5060
- : expandedControlsLayout.hiddenBlockCount;
5008
+ : expandedControlsHiddenBlockCount;
5009
const iconOnlyBlockCount = composerControlsCollapsed
5010
? restingControlsIconOnlyBlockCount
5063
- : expandedControlsLayout.iconOnlyBlockCount;
5011
+ : expandedControlsIconOnlyBlockCount;
5012
const restingProviderTraitsPicker = renderProviderTraitsPicker({
5013
...providerTraitsPickerInput,
5014
size: composerControlsCollapsed ? "xs" : "sm",
@@ -5295,30 +5243,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5243
const bannerStackItems = activityStackItem
5244
? [activityStackItem, ...props.bannerItems]
5245
: props.bannerItems;
5298
- useEffect(() => {
5299
- if (activeTasksProgress === null || activeTaskSteps === null) {
5300
- setIsTasksDrawerOpen(false);
5301
- }
5302
- }, [activeTaskSteps, activeTasksProgress]);
5303
-
5304
- useEffect(() => {
5305
- if (hasBlockingComposerTopDrawer) {
5306
- setIsTasksDrawerOpen(false);
5307
- }
5308
- }, [hasBlockingComposerTopDrawer]);
5309
-
5310
- useEffect(() => {
5246
+ const [tasksDrawerThreadId, setTasksDrawerThreadId] = useState(activeThreadId);
5247
+ if (
5248
+ isTasksDrawerOpen &&
5249
+ (activeTasksProgress === null ||
5250
+ activeTaskSteps === null ||
5251
+ hasBlockingComposerTopDrawer ||
5252
+ tasksDrawerThreadId !== activeThreadId)
5253
+ ) {
5254
setIsTasksDrawerOpen(false);
5312
- }, [activeThreadId]);
5313
-
5314
- useEffect(() => {
5315
- if (composerMenuOpen) {
5316
- setIsStashMenuOpen(false);
5317
- }
5318
- }, [composerMenuOpen]);
5319
- useEffect(() => {
5320
- setIsStashMenuOpen(false);
5321
- }, [prompt]);
5255
+ }
5256
+ if (tasksDrawerThreadId !== activeThreadId) setTasksDrawerThreadId(activeThreadId);
5257
+
5258
+ const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen });
5259
+ if (
5260
+ stashMenuClosesOn.prompt !== prompt ||
5261
+ stashMenuClosesOn.composerMenuOpen !== composerMenuOpen
5262
+ ) {
5263
+ setStashMenuClosesOn({ prompt, composerMenuOpen });
5264
+ if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
5265
+ }
5266
5267
useEffect(() => {
5268
const handler = (event: globalThis.KeyboardEvent) => {
@@ -5501,7 +5445,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5445
);
5446
if (questionAttachmentTarget)
5447
changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length);
5504
- try {
5448
+ const compressAndStoreImages = async (): Promise<boolean> => {
5449
const nextImages: ComposerImageAttachment[] = [];
5450
let compressionError: string | null = null;
5451
for (const file of acceptedImages) {
@@ -5554,7 +5498,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5498
if (compressionError !== null) {
5499
setThreadError(threadId, compressionError);
5500
}
5557
- } finally {
5501
+ return insertedAny;
5502
+ };
5503
+ return await compressAndStoreImages().finally(() => {
5504
if (questionAttachmentTarget)
5505
changeQuestionAttachmentPreparation(questionAttachmentTarget, -acceptedImages.length);
5506
const remaining =
@@ -5564,8 +5510,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5510
} else {
5511
pendingImageCompressionsRef.current.delete(attachmentTargetKey);
5512
}
5567
- }
5568
- return insertedAny;
5513
+ });
5514
};
5515
5516
const insertAttachmentReferences = (
@@ -5690,8 +5635,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5635
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
5636
const files = Array.from(event.clipboardData.files);
5637
const plainText = event.clipboardData.getData("text/plain");
5693
- const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current;
5694
- pasteAsTextShortcutUntilRef.current = 0;
5638
+ const bypassAutoAttachment = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef);
5639
if (
5640
files.length > 0 &&
5641
activeThreadId &&
@@ -5796,10 +5740,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5740
// editor never sees the drop; the load-bearing rules (native stop, "move"
5741
// effect, no eager focus) live in makeComposerMentionDragHandlers.
5742
const composerMentionDragHandlers = makeComposerMentionDragHandlers({
5799
- insertMentionAtEnd: (text) => insertComposerTextAtEnd(text, { ensureLeadingBoundary: true }),
5743
+ insertMentionAtEnd: (text) =>
5744
+ insertComposerTextAtEndStable(text, { ensureLeadingBoundary: true }),
5745
insertPullRequestAtEnd: (pullRequest) => {
5746
const comment = buildPullRequestReferenceContext(pullRequest);
5802
- const inserted = insertComposerTextAtEnd(
5747
+ const inserted = insertComposerTextAtEndStable(
5748
`${formatInlineContextReference(reviewCommentContextReference(comment))} `,
5749
{ ensureLeadingBoundary: true },
5750
);
@@ -5829,8 +5774,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5774
timeout: 0,
5775
data: { threadRef: routeThreadRef, hideCopyButton: true },
5776
});
5832
- try {
5833
- await importComposerThreadAttachment({
5777
+ const importResult = await settlePromise(() =>
5778
+ importComposerThreadAttachment({
5779
targetKey,
5780
pendingImports: pendingThreadImportsRef.current,
5781
countReservedAttachments: countReservedAttachmentsStable,
@@ -5854,9 +5799,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5799
);
5800
}
5801
},
5857
- });
5858
- } catch (error) {
5859
- if (!isActive()) return;
5802
+ }),
5803
+ );
5804
+ if (importResult._tag === "Failure" && isActive()) {
5805
+ const error = squashAtomCommandFailure(importResult);
5806
toastManager.add({
5807
type: "error",
5808
title: "Unable to read the dropped thread",
@@ -5866,10 +5812,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5812
? "This thread exceeds the attachment size limit. Try a shorter thread."
5813
: "Check that its environment is connected and up to date, then try again.",
5814
});
5869
- } finally {
5870
- toastManager.close(loadingToast);
5871
- pendingDraftWork.end(targetKey);
5815
}
5816
+ toastManager.close(loadingToast);
5817
+ pendingDraftWork.end(targetKey);
5818
},
5819
);
5820
@@ -6074,10 +6019,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6019
pendingDraftWork.has(attachmentTargetKey),
6020
insertTextAtEnd: insertComposerTextAtEndStable,
6021
pasteTextAtEnd: (text: string, options) => {
6077
- const bypassAutoAttachment =
6078
- options?.bypassAutoAttachment === true ||
6079
- Date.now() <= pasteAsTextShortcutUntilRef.current;
6080
- pasteAsTextShortcutUntilRef.current = 0;
6022
+ const shortcutArmed = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef);
6023
+ const bypassAutoAttachment = options?.bypassAutoAttachment === true || shortcutArmed;
6024
const promptLength = promptRef.current.length;
6025
if (
6026
!foldPastedText(text, bypassAutoAttachment, {
@@ -7226,7 +7169,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7169
)}
7170
>
7171
<div
7229
- ref={expandedControlsLayout.attachControls}
7172
+ ref={attachExpandedComposerControls}
7173
data-chat-composer-controls="left"
7174
data-chat-composer-footer-controls="true"
7175
className={cn(