@devries-cameron20 / t3code-1 / commits / 22fd2aca1f
Fork 0

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

refactor(web): the composer's layout and provider hooks live in their own files (#23042)

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

Julius Marminge committed Oct 21, 2026 at 13:23 UTC 22fd2aca1fcfc4d9d45fa7352796dc6a8d8b95a6
7 files changed +987 -944
apps/web/src/components/chat/ChatComposer.tsx
+6 -944
@@ -41,7 +41,6 @@ import {
41 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
42 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
43 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
44 - PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
44 } from "@t3tools/contracts";
45 import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
46 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
@@ -67,7 +66,6 @@ import {
66 useLayoutEffect,
67 useRef,
68 useState,
70 - useSyncExternalStore,
69 } from "react";
70 import { createPortal, flushSync } from "react-dom";
71 import {
@@ -91,7 +89,6 @@ import {
89 getAntigravitySendBlockReason,
90 readFileAsDataUrl,
91 resolveComposerInteractionMode,
94 - resolveComposerProviderSelection,
92 threadShellHasStarted,
93 } from "../ChatView.logic";
94 import {
@@ -116,8 +113,6 @@ import {
113 hydrateImagesFromPersisted,
114 useComposerDraftStore,
115 useComposerThreadDraft,
119 - deriveEffectiveComposerModelState,
120 - useComposerDraftModelState,
116 } from "../../composerDraftStore";
117 import {
118 MAX_STASH_ENTRIES,
@@ -189,13 +184,10 @@ import {
184 toKindScopedComposerContextId,
185 } from "@t3tools/shared/composerContextReferences";
186 import {
192 - resolveRestingComposerControlsLayout,
193 - shouldAnimateComposerRestingTransition,
187 shouldUseCompactComposerPrimaryActions,
188 shouldUseCompactComposerFooter,
189 shouldUseRestingComposerLayout,
190 } from "../composerFooterLayout";
198 -import { measureRestingComposerControls } from "./restingComposerControlsMeasurement";
191 import {
192 type ComposerCitationCommentRequest,
193 type ComposerPromptEditorHandle,
@@ -285,7 +277,6 @@ import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
277 import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic";
278 import {
279 getComposerPromptInjectionState,
288 - getComposerProviderState,
280 getComposerReasoningStep,
281 renderProviderTraitsMenuContent,
282 renderProviderTraitsPicker,
@@ -301,11 +292,6 @@ import {
292 buildExpandedImagePreview,
293 type ExpandedImagePreview,
294 } from "./ExpandedImagePreview";
304 -import {
305 - getPendingSnapShotAnimations,
306 - pendingSnapShotAnimationIdsForTarget,
307 - subscribeToPendingSnapShotAnimations,
308 -} from "../../lib/snapShotAnimation";
295 import { resizeSnapShotSource } from "../../lib/snapShotSource";
296 import { cn, isMacPlatform, randomUUID } from "~/lib/utils";
297 import {
@@ -329,631 +315,14 @@ import {
315 } from "./composerScrollGesture";
316 import { observeResize } from "~/lib/observeResize";
317
332 -type ComposerCommandMenuPosition = {
333 - bottom: number;
334 - left: number;
335 - maxHeight: number;
336 - width: number;
337 -};
338 -
318 const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
319
320 const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24;
321 const COMPOSER_SCROLL_GESTURE_RESET_MS = 120;
343 -const COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS = 50;
344 -const COMPOSER_RESTING_TRANSITION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
345 -const COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX = 4;
346 -
347 -function useComposerRestingTransition(
348 - isCollapsed: boolean,
349 - isResting: boolean,
350 - restingControlsRef: React.RefObject<HTMLDivElement | null>,
351 - onOverlayHeightChange: (height: number) => void,
352 - animationsActive: boolean,
353 - animationDurationMs: number,
354 -) {
355 - const elementRef = useRef<HTMLDivElement>(null);
356 - const isCollapsedRef = useRef(isCollapsed);
357 - const previousCollapsedRef = useRef(isCollapsed);
358 - const previousRestingRef = useRef(isResting);
359 - const previousHeightRef = useRef<number | null>(null);
360 - const previousModelStripHeightRef = useRef<number | null>(null);
361 - const previousContentOffsetsRef = useRef<{
362 - promptFromTop: number | null;
363 - promptHeight: number | null;
364 - actionFromBottom: number | null;
365 - controlsFromBottom: number | null;
366 - controlsFromLeft: number | null;
367 - surfaceBottomInset: number | null;
368 - }>({
369 - promptFromTop: null,
370 - promptHeight: null,
371 - actionFromBottom: null,
372 - controlsFromBottom: null,
373 - controlsFromLeft: null,
374 - surfaceBottomInset: null,
375 - });
376 - const animationRef = useRef<Animation | null>(null);
377 - const animationTargetHeightRef = useRef<number | null>(null);
378 - const contentAnimationsRef = useRef<Animation[]>([]);
379 - const stateChangeAnimationsRef = useRef<Animation[]>([]);
380 - const pinnedOverlayRef = useRef<HTMLElement | null>(null);
381 - const transitionCleanupTimeoutRef = useRef<number | null>(null);
382 - const transitionLayoutRequestRef = useRef(0);
383 - const hasCompletedInitialLayoutRef = useRef(false);
384 -
385 - const clearOverlayPin = () => {
386 - // The overlay belongs to the chat view and outlives this composer, so it
387 - // is remembered from pin time rather than re-resolved through a ref that
388 - // React may already have detached during unmount.
389 - const overlay = pinnedOverlayRef.current;
390 - pinnedOverlayRef.current = null;
391 - overlay?.style.removeProperty("height");
392 - overlay?.style.removeProperty("display");
393 - overlay?.style.removeProperty("flex-direction");
394 - overlay?.style.removeProperty("justify-content");
395 - };
396 -
397 - const clearTransitionStyles = () => {
398 - const element = elementRef.current;
399 - const footer = element?.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
400 - element?.style.removeProperty("overflow");
401 - element?.style.removeProperty("clip-path");
402 - element?.style.removeProperty("overflow-clip-margin");
403 - element
404 - ?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]')
405 - ?.style.removeProperty("height");
406 - footer?.style.removeProperty("position");
407 - footer?.style.removeProperty("top");
408 - footer?.style.removeProperty("bottom");
409 - footer?.style.removeProperty("left");
410 - footer?.style.removeProperty("right");
411 - footer?.style.removeProperty("height");
412 - const shell = element?.closest<HTMLElement>('[data-slot="composer-shell"]');
413 - shell?.removeAttribute("data-model-strip-transition");
414 - const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
415 - for (const property of [
416 - "position",
417 - "top",
418 - "visibility",
419 - "height",
420 - "min-height",
421 - "padding-top",
422 - "align-items",
423 - "z-index",
424 - "pointer-events",
425 - ]) {
426 - modelStrip?.style.removeProperty(property);
427 - }
428 - clearOverlayPin();
429 - };
430 -
431 - useLayoutEffect(() => {
432 - isCollapsedRef.current = isCollapsed;
433 - });
434 -
435 - const transitionToCurrentGeometry = (stateChanged: boolean) => {
436 - const element = elementRef.current;
437 - const surface = element?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]');
438 - if (!element || !surface) return;
439 -
440 - const nextIsCollapsed = isCollapsedRef.current;
441 -
442 - const visibleTransitionElement = (selector: string) =>
443 - Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
444 - (candidate) => candidate.getClientRects().length > 0,
445 - ) ?? null;
446 - const prompt = visibleTransitionElement(
447 - '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
448 - );
449 - const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]');
450 - const footer = element.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
451 - const continuousControls =
452 - element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true";
453 - const controls = nextIsCollapsed
454 - ? restingControlsRef.current
455 - : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
456 -
457 - const shell = element.closest<HTMLElement>('[data-slot="composer-shell"]');
458 - const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
459 - const interruptedStripHeight =
460 - animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null;
461 - const interruptedAnimation = animationRef.current;
462 - const interruptedPromptTop = interruptedAnimation
463 - ? (prompt?.getBoundingClientRect().top ?? null)
464 - : null;
465 - const interruptedActionTop = interruptedAnimation
466 - ? (action?.getBoundingClientRect().top ?? null)
467 - : null;
468 - const interruptedControlsLeft = interruptedAnimation
469 - ? (controls?.getBoundingClientRect().left ?? null)
470 - : null;
471 - const interruptedControlsTop = interruptedAnimation
472 - ? (controls?.getBoundingClientRect().top ?? null)
473 - : null;
474 - const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null;
475 - const interruptedTargetHeight = animationTargetHeightRef.current;
476 - const interruptedCurrentTime =
477 - typeof interruptedAnimation?.currentTime === "number"
478 - ? interruptedAnimation.currentTime
479 - : null;
480 - const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration;
481 - if (transitionCleanupTimeoutRef.current !== null) {
482 - window.clearTimeout(transitionCleanupTimeoutRef.current);
483 - transitionCleanupTimeoutRef.current = null;
484 - }
485 - interruptedAnimation?.cancel();
486 - animationRef.current = null;
487 - for (const animation of contentAnimationsRef.current) animation.cancel();
488 - contentAnimationsRef.current = [];
489 - if (stateChanged) {
490 - for (const animation of stateChangeAnimationsRef.current) animation.cancel();
491 - stateChangeAnimationsRef.current = [];
492 - }
493 - clearTransitionStyles();
494 -
495 - const nextRect = element.getBoundingClientRect();
496 - const nextHeight = nextRect.height;
497 - const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null;
498 - // The chat view resize-observes the overlay to place the timeline
499 - // inset, the scroll-to-end pill, and the mini player. Publishing the
500 - // destination height here turns that feedback into one update instead
501 - // of a ChatView re-render on every animation frame.
502 - const overlay = element.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
503 - const overlayRect = overlay?.getBoundingClientRect();
504 - const overlayHeight = overlayRect?.height ?? null;
505 - if (overlayHeight !== null) {
506 - onOverlayHeightChange(overlayHeight);
507 - }
508 - const nextPromptRect = prompt?.getBoundingClientRect() ?? null;
509 - const nextPromptTop = nextPromptRect?.top ?? null;
510 - const nextActionTop = action?.getBoundingClientRect().top ?? null;
511 - const nextControlsRect = controls?.getBoundingClientRect() ?? null;
512 - const nextControlsTop = nextControlsRect?.top ?? null;
513 - const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1;
514 - const previousHeight = interruptedHeight ?? previousHeightRef.current;
515 - const targetChanged =
516 - interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5;
517 - const shouldAnimate = shouldAnimateComposerRestingTransition({
518 - hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current,
519 - stateChanged,
520 - hasInterruptedAnimation: interruptedHeight !== null,
521 - });
522 -
523 - if (
524 - shouldAnimate &&
525 - animationsActive &&
526 - previousHeight !== null &&
527 - Math.abs(previousHeight - nextHeight) >= 0.5
528 - ) {
529 - const remainingDuration =
530 - typeof interruptedDuration === "number" && interruptedCurrentTime !== null
531 - ? Math.max(1, interruptedDuration - interruptedCurrentTime)
532 - : animationDurationMs;
533 - const duration =
534 - interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs;
535 - element.style.overflow = "clip";
536 - if (modelStrip) {
537 - const controlsClearance = Math.max(
538 - nextModelStripHeight ?? 0,
539 - previousModelStripHeightRef.current ?? 0,
540 - );
541 - element.style.overflowClipMargin = `${controlsClearance}px`;
542 - element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`;
543 - }
544 - surface.style.height = "100%";
545 -
546 - if (overlay && overlayHeight !== null) {
547 - overlay.style.height = `${String(overlayHeight)}px`;
548 - overlay.style.display = "flex";
549 - overlay.style.flexDirection = "column";
550 - overlay.style.justifyContent = "flex-end";
551 - pinnedOverlayRef.current = overlay;
552 - }
553 -
554 - if (footer) {
555 - footer.style.position = "absolute";
556 - footer.style.top = "auto";
557 - footer.style.bottom = `${String(footerBottom)}px`;
558 - footer.style.height = "3rem";
559 - if (nextIsCollapsed) {
560 - footer.style.left = "auto";
561 - footer.style.right = "1px";
562 - } else {
563 - footer.style.left = "1px";
564 - footer.style.right = "1px";
565 - }
566 - }
567 -
568 - let stripAnimation: Animation | null = null;
569 - if (modelStrip) {
570 - const stripHeight = modelStrip.getBoundingClientRect().height;
571 - const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop);
572 - const fromHeight =
573 - interruptedStripHeight ??
574 - (previousCollapsedRef.current
575 - ? (previousModelStripHeightRef.current ?? stripHeight)
576 - : stripOverlap);
577 - const toHeight = nextIsCollapsed ? stripHeight : stripOverlap;
578 - modelStrip.style.position = "relative";
579 - modelStrip.style.top = "auto";
580 - modelStrip.style.visibility = "visible";
581 - modelStrip.style.minHeight = "0";
582 - modelStrip.style.paddingTop = "0";
583 - modelStrip.style.alignItems = "flex-end";
584 - modelStrip.style.pointerEvents = "none";
585 - modelStrip.style.zIndex = "20";
586 - shell?.setAttribute("data-model-strip-transition", "true");
587 - stripAnimation = modelStrip.animate(
588 - [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }],
589 - { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" },
590 - );
591 - }
592 -
593 - const animation = element.animate(
594 - [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }],
595 - {
596 - duration,
597 - easing: COMPOSER_RESTING_TRANSITION_EASING,
598 - fill: "both",
599 - },
600 - );
601 - animationRef.current = animation;
602 - animationTargetHeightRef.current = nextHeight;
603 -
604 - const animatedRect = element.getBoundingClientRect();
605 - const previousBottom =
606 - overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null
607 - ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset
608 - : animatedRect.bottom;
609 - const bottomShift = previousBottom - animatedRect.bottom;
610 - const previousPromptTop =
611 - interruptedPromptTop ??
612 - (previousContentOffsetsRef.current.promptFromTop === null
613 - ? null
614 - : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop);
615 - const previousActionTop =
616 - interruptedActionTop ??
617 - (previousContentOffsetsRef.current.actionFromBottom === null
618 - ? null
619 - : previousBottom - previousContentOffsetsRef.current.actionFromBottom);
620 - const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : [];
621 - const animateContentPosition = (
622 - content: HTMLElement | null,
623 - previousTop: number | null,
624 - previousLeft: number | null = null,
625 - ) => {
626 - if (!content || previousTop === null) return;
627 - const rect = content.getBoundingClientRect();
628 - const offset = previousTop - rect.top;
629 - const offsetX = previousLeft === null ? 0 : previousLeft - rect.left;
630 - if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return;
631 - contentAnimations.push(
632 - content.animate(
633 - [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }],
634 - {
635 - duration,
636 - easing: COMPOSER_RESTING_TRANSITION_EASING,
637 - },
638 - ),
639 - );
640 - };
641 - animateContentPosition(prompt, previousPromptTop);
642 - animateContentPosition(action, previousActionTop);
643 - if (continuousControls) {
644 - const previousControlsTop =
645 - interruptedControlsTop ??
646 - (previousContentOffsetsRef.current.controlsFromBottom === null
647 - ? null
648 - : previousBottom - previousContentOffsetsRef.current.controlsFromBottom);
649 - const previousControlsLeft =
650 - interruptedControlsLeft ??
651 - (previousContentOffsetsRef.current.controlsFromLeft === null
652 - ? null
653 - : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft);
654 - animateContentPosition(controls, previousControlsTop, previousControlsLeft);
655 - }
656 - contentAnimationsRef.current = contentAnimations;
657 -
658 - if (stateChanged) {
659 - const stateChangeAnimations: Animation[] = [];
660 -
661 - const previousPromptHeight = previousContentOffsetsRef.current.promptHeight;
662 - if (
663 - !nextIsCollapsed &&
664 - prompt &&
665 - nextPromptRect &&
666 - previousPromptHeight !== null &&
667 - nextPromptRect.height - previousPromptHeight >= 0.5
668 - ) {
669 - const hiddenHeight = nextPromptRect.height - previousPromptHeight;
670 - stateChangeAnimations.push(
671 - prompt.animate(
672 - [
673 - { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` },
674 - { clipPath: "inset(0 0 0 0)" },
675 - ],
676 - {
677 - duration,
678 - easing: COMPOSER_RESTING_TRANSITION_EASING,
679 - },
680 - ),
681 - );
682 - }
683 -
684 - const arrivingControls = nextIsCollapsed
685 - ? restingControlsRef.current
686 - : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
687 - if (arrivingControls && !continuousControls) {
688 - const drift = nextIsCollapsed
689 - ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX
690 - : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX;
691 - stateChangeAnimations.push(
692 - arrivingControls.animate(
693 - [
694 - { opacity: 0, transform: `translateY(${String(drift)}px)` },
695 - { opacity: 1, transform: "none" },
696 - ],
697 - {
698 - duration: nextIsCollapsed ? duration : duration / 2,
699 - delay: nextIsCollapsed ? 0 : duration / 2,
700 - fill: "backwards",
701 - easing: COMPOSER_RESTING_TRANSITION_EASING,
702 - },
703 - ),
704 - );
705 - }
706 -
707 - const arrivingImagePreviews = nextIsCollapsed
708 - ? Array.from(
709 - element.querySelectorAll<HTMLElement>('[data-chat-composer-resting-images="true"]'),
710 - )
711 - : Array.from(
712 - element.querySelectorAll<HTMLElement>('[data-chat-composer-expanded-image="true"]'),
713 - );
714 - for (const imagePreview of arrivingImagePreviews) {
715 - stateChangeAnimations.push(
716 - imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], {
717 - duration: nextIsCollapsed ? duration : duration / 2,
718 - delay: nextIsCollapsed ? 0 : duration / 2,
719 - fill: "backwards",
720 - easing: COMPOSER_RESTING_TRANSITION_EASING,
721 - }),
722 - );
723 - }
724 - stateChangeAnimationsRef.current = stateChangeAnimations;
725 - }
726 -
727 - const finishTransition = (cancelAnimations: boolean) => {
728 - if (animationRef.current !== animation) return;
729 - if (transitionCleanupTimeoutRef.current !== null) {
730 - window.clearTimeout(transitionCleanupTimeoutRef.current);
731 - transitionCleanupTimeoutRef.current = null;
732 - }
733 - if (cancelAnimations) {
734 - animation.cancel();
735 - for (const contentAnimation of contentAnimationsRef.current) {
736 - contentAnimation.cancel();
737 - }
738 - for (const stateChangeAnimation of stateChangeAnimationsRef.current) {
739 - stateChangeAnimation.cancel();
740 - }
741 - }
742 - animationRef.current = null;
743 - animationTargetHeightRef.current = null;
744 - contentAnimationsRef.current = [];
745 - stateChangeAnimationsRef.current = [];
746 - animation.cancel();
747 - stripAnimation?.cancel();
748 - clearTransitionStyles();
749 - };
750 - void animation.finished.catch(() => undefined).then(() => finishTransition(false));
751 - // A suspended document timeline can leave `finished` pending while
752 - // these measurement styles remain active. Wall-clock cleanup makes
753 - // the natural layout the eventual source of truth in that case.
754 - transitionCleanupTimeoutRef.current = window.setTimeout(
755 - () => finishTransition(true),
756 - duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS,
757 - );
758 - } else {
759 - animationTargetHeightRef.current = null;
760 - }
761 -
762 - previousCollapsedRef.current = nextIsCollapsed;
763 - previousHeightRef.current = nextHeight;
764 - previousModelStripHeightRef.current = nextModelStripHeight;
765 - previousContentOffsetsRef.current = {
766 - promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top,
767 - promptHeight: nextPromptRect?.height ?? null,
768 - actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop,
769 - controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop,
770 - controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left,
771 - surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null,
772 - };
773 - };
774 -
775 - useLayoutEffect(() => {
776 - const requestId = transitionLayoutRequestRef.current + 1;
777 - transitionLayoutRequestRef.current = requestId;
778 - const stateChanged = previousCollapsedRef.current !== isCollapsed;
779 - // A non-Git context strip enters or leaves flow through ChatView state in
780 - // an earlier layout effect. Let React flush that parent update before the
781 - // FLIP reads its destination geometry, while still running before paint.
782 - queueMicrotask(() => {
783 - if (transitionLayoutRequestRef.current !== requestId) return;
784 - transitionToCurrentGeometry(stateChanged);
785 - });
786 - return () => {
787 - if (transitionLayoutRequestRef.current === requestId) {
788 - transitionLayoutRequestRef.current += 1;
789 - }
790 - };
791 - }, [isCollapsed, transitionToCurrentGeometry]);
792 -
793 - useLayoutEffect(() => {
794 - if (previousRestingRef.current === isResting) return;
795 - previousRestingRef.current = isResting;
796 - if (animationRef.current) return;
797 - const overlay = elementRef.current?.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
798 - if (overlay) onOverlayHeightChange(overlay.getBoundingClientRect().height);
799 - }, [isResting, onOverlayHeightChange]);
800 -
801 - useLayoutEffect(() => {
802 - const element = elementRef.current;
803 - if (!element) return;
804 -
805 - const body = element.querySelector<HTMLElement>('[data-chat-composer-body="true"]');
806 - return observeResize(body ? [element, body] : element, (entries) => {
807 - if (animationRef.current) {
808 - if (body && entries.some((entry) => entry.target === body)) {
809 - transitionToCurrentGeometry(false);
810 - }
811 - return;
812 - }
813 - const elementRect = element.getBoundingClientRect();
814 - const visibleTransitionElement = (selector: string) =>
815 - Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
816 - (candidate) => candidate.getClientRects().length > 0,
817 - ) ?? null;
818 - const promptRect = visibleTransitionElement(
819 - '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
820 - )?.getBoundingClientRect();
821 - const actionTop = visibleTransitionElement(
822 - '[data-chat-composer-transition-actions="true"]',
823 - )?.getBoundingClientRect().top;
824 - const controlsRect = (
825 - isCollapsedRef.current
826 - ? restingControlsRef.current
827 - : visibleTransitionElement('[data-chat-composer-controls="left"]')
828 - )?.getBoundingClientRect();
829 - previousHeightRef.current = elementRect.height;
830 - previousContentOffsetsRef.current = {
831 - promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top,
832 - promptHeight: promptRect?.height ?? null,
833 - actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop,
834 - controlsFromBottom:
835 - controlsRect === undefined ? null : elementRect.bottom - controlsRect.top,
836 - controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left,
837 - surfaceBottomInset:
838 - (element
839 - .closest<HTMLElement>('[data-chat-composer-overlay="true"]')
840 - ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom,
841 - };
842 - });
843 - }, [restingControlsRef, transitionToCurrentGeometry]);
844 -
845 - useEffect(() => {
846 - hasCompletedInitialLayoutRef.current = true;
847 - return () => {
848 - if (transitionCleanupTimeoutRef.current !== null) {
849 - window.clearTimeout(transitionCleanupTimeoutRef.current);
850 - transitionCleanupTimeoutRef.current = null;
851 - }
852 - animationRef.current?.cancel();
853 - animationRef.current = null;
854 - animationTargetHeightRef.current = null;
855 - for (const animation of contentAnimationsRef.current) animation.cancel();
856 - contentAnimationsRef.current = [];
857 - for (const animation of stateChangeAnimationsRef.current) animation.cancel();
858 - stateChangeAnimationsRef.current = [];
859 - clearTransitionStyles();
860 - };
861 - }, [clearTransitionStyles]);
862 -
863 - return elementRef;
864 -}
865 -
866 -function composerCommandMenuPositionsEqual(
867 - a: ComposerCommandMenuPosition,
868 - b: ComposerCommandMenuPosition,
869 -): boolean {
870 - return (
871 - a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width
872 - );
873 -}
874 -
875 -function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) {
876 - const [position, setPosition] = useState<ComposerCommandMenuPosition | null>(null);
877 -
878 - useLayoutEffect(() => {
879 - const anchor = props.anchor;
880 - if (!anchor) return;
881 -
882 - const updatePosition = () => {
883 - const form = anchor.closest<HTMLElement>('[data-chat-composer-form="true"]');
884 - const mainSurface = form?.querySelector<HTMLElement>(
885 - '[data-chat-composer-main-surface="true"]',
886 - );
887 - const rect = (mainSurface ?? form ?? anchor).getBoundingClientRect();
888 - const rootFontSizePx =
889 - Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16;
890 - const drawerInsetRem = Number.parseFloat(
891 - window.getComputedStyle(form ?? anchor).getPropertyValue("--chat-composer-drawer-inset"),
892 - );
893 - const drawerInset = drawerInsetRem * rootFontSizePx;
894 - const width = rect.width - drawerInset * 2;
895 - if (width <= 0) {
896 - setPosition(null);
897 - return;
898 - }
899 - const composerOverlap = rootFontSizePx + 1;
900 - const next = {
901 - bottom: window.innerHeight - rect.top - composerOverlap,
902 - left: rect.left + drawerInset,
903 - maxHeight: Math.max(96, rect.top - 24 + composerOverlap),
904 - width,
905 - };
906 - setPosition((current) =>
907 - current && composerCommandMenuPositionsEqual(current, next) ? current : next,
908 - );
909 - };
910 -
911 - updatePosition();
912 - window.addEventListener("resize", updatePosition);
913 - window.addEventListener("scroll", updatePosition, true);
914 -
915 - const observed: Element[] = [anchor];
916 - for (let element = anchor.parentElement; element; element = element.parentElement) {
917 - observed.push(element);
918 - }
919 - const stopObserving = observeResize(observed, updatePosition);
920 -
921 - return () => {
922 - stopObserving();
923 - window.removeEventListener("resize", updatePosition);
924 - window.removeEventListener("scroll", updatePosition, true);
925 - };
926 - }, [props.anchor]);
927 -
928 - if (!props.anchor || !position) return null;
929 -
930 - return createPortal(
931 - <div
932 - className="pointer-events-auto fixed z-40 flex flex-col"
933 - data-composer-drawer-layer="true"
934 - style={{
935 - bottom: position.bottom,
936 - left: position.left,
937 - maxHeight: position.maxHeight,
938 - width: position.width,
939 - }}
940 - >
941 - {props.children}
942 - </div>,
943 - document.body,
944 - );
945 -}
322 import { toastManager } from "../ui/toast";
323 import { CircleAlertIcon, PlayIcon, ShieldIcon } from "lucide-react";
324 import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";
325 import { hasProviderSetup } from "./ProviderStatusBanner";
950 -import {
951 - applyProviderInstanceSettings,
952 - deriveProviderInstanceEntries,
953 - NO_PROVIDER_MODEL_SELECTION,
954 - sortProviderInstanceEntries,
955 - type ProviderInstanceEntry,
956 -} from "../../providerInstances";
326 import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
327 import type { UnifiedSettings } from "@t3tools/contracts/settings";
328 import {
@@ -981,8 +350,6 @@ import {
350 } from "@t3tools/client-runtime/state/composer-dispatch";
351 import type { ContextWindowSnapshot } from "../../lib/contextWindow";
352 import {
984 - hasCompleteProviderWorkspaceSnapshot,
985 - hasCurrentProviderWorkspaceSnapshot,
353 resolveProviderSkillsForCwd,
354 resolveProviderSlashCommandsForCwd,
355 } from "@t3tools/client-runtime/providerSkills";
@@ -993,10 +360,13 @@ import { useStableCallback } from "../../hooks/useStableCallback";
360 import { usePanelAnimationSettings } from "../../panelAnimations";
361 import { useAtomCommand } from "../../state/use-atom-command";
362 import { readEnvironmentScope } from "../../state/session";
996 -import { serverEnvironment } from "../../state/server";
363 import type { ReviewCommentContext } from "../../reviewCommentContext";
998 -
999 -const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
364 +import { useComposerRestingTransition } from "./useComposerRestingTransition";
365 +import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer";
366 +import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout";
367 +import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh";
368 +import { useComposerProviderModel } from "./useComposerProviderModel";
369 +import { useComposerImageGroups } from "./useComposerImageGroups";
370
371 /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */
372 function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
@@ -1025,83 +395,6 @@ const extendReplacementRangeForTrailingSpace = (
395 return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd;
396 };
397
1028 -function useRestingComposerControlsLayout(host: HTMLDivElement | null, useControlsAsHost = false) {
1029 - const [controls, setControls] = useState<HTMLDivElement | null>(null);
1030 - const controlsRef = useRef<HTMLDivElement>(null);
1031 - const attachControls = (element: HTMLDivElement | null) => {
1032 - controlsRef.current = element;
1033 - setControls(element);
1034 - };
1035 - const [layout, setLayout] = useState<{
1036 - hiddenCount: number;
1037 - iconOnlyCount?: number;
1038 - visible: boolean;
1039 - }>({ hiddenCount: 0, visible: true });
1040 -
1041 - const measure = () => {
1042 - const currentHost = useControlsAsHost ? controls : host;
1043 - if (currentHost === null || !controls) return;
1044 -
1045 - const measurement = measureRestingComposerControls(controls);
1046 - if (!measurement) return;
1047 - const style = getComputedStyle(currentHost);
1048 - const hostWidth =
1049 - currentHost.clientWidth -
1050 - (Number.parseFloat(style.paddingInlineStart) || 0) -
1051 - (Number.parseFloat(style.paddingInlineEnd) || 0);
1052 -
1053 - setLayout((current) => {
1054 - const next = resolveRestingComposerControlsLayout({
1055 - ...measurement,
1056 - hostWidth,
1057 - previous: current,
1058 - });
1059 - return next.hiddenCount === current.hiddenCount &&
1060 - next.iconOnlyCount === current.iconOnlyCount &&
1061 - next.visible === current.visible
1062 - ? current
1063 - : next;
1064 - });
1065 - };
1066 -
1067 - useLayoutEffect(() => {
1068 - const currentHost = useControlsAsHost ? controls : host;
1069 - if (!currentHost || !controls) return;
1070 - let stopObserving = () => {};
1071 - const observeControls = () => {
1072 - stopObserving();
1073 - stopObserving = observeResize(
1074 - [
1075 - currentHost,
1076 - controls,
1077 - ...controls.querySelectorAll<HTMLElement>(
1078 - "[data-resting-block], [data-composer-control-label], [data-chat-provider-model-picker-label]",
1079 - ),
1080 - ],
1081 - measure,
1082 - );
1083 - measure();
1084 - };
1085 - observeControls();
1086 - const mutations = new MutationObserver(observeControls);
1087 - mutations.observe(controls, { childList: true, subtree: true, characterData: true });
1088 - document.fonts.addEventListener("loadingdone", measure);
1089 - return () => {
1090 - stopObserving();
1091 - mutations.disconnect();
1092 - document.fonts.removeEventListener("loadingdone", measure);
1093 - };
1094 - }, [host, controls, useControlsAsHost, measure]);
1095 -
1096 - return {
1097 - controlsRef,
1098 - attachControls,
1099 - hiddenBlockCount: layout.hiddenCount,
1100 - iconOnlyBlockCount: layout.iconOnlyCount ?? 0,
1101 - controlsVisible: layout.visible,
1102 - };
1103 -}
1104 -
398 const runtimeModeOptions = runtimeModes.map((mode) => ({ mode, ...runtimeModeConfig[mode] }));
399
400 export interface ChatComposerHandle {
@@ -1330,237 +623,6 @@ export interface ChatComposerProps {
623 onFileOpen: (attachment: ChatFileAttachment) => void;
624 }
625
1333 -/**
1334 - * Keeps the selected provider's workspace snapshot fresh for the composer's
1335 - * cwd. Returns a check to run when the user types.
1336 - */
1337 -function useProviderWorkspaceSnapshotRefresh(input: {
1338 - readonly environmentId: EnvironmentId;
1339 - readonly gitCwd: string | null;
1340 - readonly selectedProviderEntry: ProviderInstanceEntry | undefined;
1341 - readonly selectedProviderStatus: ServerProvider | null;
1342 -}) {
1343 - const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input;
1344 - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
1345 - reportFailure: false,
1346 - });
1347 - // The last scan this composer asked for. A request inside the TTL is not
1348 - // repeated, so a client clock ahead of the server's cannot loop rescans.
1349 - const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
1350 - const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
1351 - key: string;
1352 - notBefore: number;
1353 - } | null>(null);
1354 - const workspaceRefreshScopeKey =
1355 - gitCwd && selectedProviderEntry
1356 - ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`
1357 - : null;
1358 - const workspaceSlashCommandsPending =
1359 - selectedProviderStatus?.workspaceSnapshots?.some(
1360 - (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true,
1361 - ) ?? false;
1362 - useEffect(() => {
1363 - if (
1364 - !workspaceSlashCommandsPending ||
1365 - !workspaceRefreshRetry ||
1366 - workspaceRefreshRetry.key !== workspaceRefreshScopeKey
1367 - )
1368 - return;
1369 - const timeout = setTimeout(
1370 - () => {
1371 - setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
1372 - },
1373 - Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
1374 - );
1375 - return () => clearTimeout(timeout);
1376 - }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
1377 - // Losing a snapshot (the server dropped it) lifts both the TTL and the retry
1378 - // cooldown so the next check rescans at once.
1379 - const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd);
1380 - const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot);
1381 - const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0);
1382 - if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) {
1383 - setHadWorkspaceSnapshot(hasWorkspaceSnapshot);
1384 - if (!hasWorkspaceSnapshot) {
1385 - setWorkspaceSnapshotLossCount((count) => count + 1);
1386 - setWorkspaceRefreshRetry(null);
1387 - }
1388 - }
1389 - const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount);
1390 - const refreshWorkspaceSnapshotIfStale = (
1391 - now: number,
1392 - key: string | null,
1393 - retry: { key: string; notBefore: number } | null,
1394 - snapshotLossCount: number,
1395 - ) => {
1396 - if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) {
1397 - lastWorkspaceSnapshotLossRef.current = snapshotLossCount;
1398 - workspaceRefreshKeyRef.current = null;
1399 - }
1400 - if (key === null || !gitCwd || !selectedProviderEntry) return;
1401 - const lastRequest = workspaceRefreshKeyRef.current;
1402 - if (
1403 - lastRequest?.key === key &&
1404 - now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
1405 - )
1406 - return;
1407 - // A pending retry needs no clearing here: its cooldown lapses long before the TTL.
1408 - if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return;
1409 - if (retry?.key === key && now < retry.notBefore) return;
1410 - const request = { key, requestedAt: now };
1411 - workspaceRefreshKeyRef.current = request;
1412 - const retryLater = () => {
1413 - if (workspaceRefreshKeyRef.current !== request) return;
1414 - workspaceRefreshKeyRef.current = null;
1415 - setWorkspaceRefreshRetry({
1416 - key,
1417 - notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
1418 - });
1419 - };
1420 - void refreshProviders({
1421 - environmentId,
1422 - input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
1423 - }).then((result) => {
1424 - const refreshedSnapshot =
1425 - result._tag === "Success" &&
1426 - hasCompleteProviderWorkspaceSnapshot(
1427 - result.value.providers.find(
1428 - (provider) => provider.instanceId === selectedProviderEntry.instanceId,
1429 - ),
1430 - gitCwd,
1431 - );
1432 - if (!refreshedSnapshot) retryLater();
1433 - }, retryLater);
1434 - };
1435 - const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale);
1436 - useEffect(() => {
1437 - refreshWorkspaceSnapshotOnChange(
1438 - Date.now(),
1439 - workspaceRefreshScopeKey,
1440 - workspaceRefreshRetry,
1441 - workspaceSnapshotLossCount,
1442 - );
1443 - }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]);
1444 - return useStableCallback(() =>
1445 - refreshWorkspaceSnapshotIfStale(
1446 - Date.now(),
1447 - workspaceRefreshScopeKey,
1448 - workspaceRefreshRetry,
1449 - workspaceSnapshotLossCount,
1450 - ),
1451 - );
1452 -}
1453 -
1454 -const NO_PROVIDER_MODELS: ServerProvider["models"] = [];
1455 -
1456 -/**
1457 - * The provider instances the composer offers, which one is selected, and the model and options
1458 - * the draft resolves to on it. The draft store is read first so every derivation follows the only
1459 - * hook here; in the composer body they would straddle its later hooks and lose their cache.
1460 - */
1461 -function useComposerProviderModel(
1462 - input: Omit<Parameters<typeof resolveComposerProviderSelection>[0], "entries"> & {
1463 - readonly providerStatuses: ReadonlyArray<ServerProvider>;
1464 - readonly settings: UnifiedSettings;
1465 - readonly activeProjectId: ProjectId | null;
1466 - readonly threadRef: ScopedThreadRef | DraftId;
1467 - readonly threadModelSelection: ModelSelection | null | undefined;
1468 - readonly projectModelSelection: ModelSelection | null | undefined;
1469 - readonly promptInjectionState: ReturnType<typeof getComposerPromptInjectionState>;
1470 - },
1471 -) {
1472 - const {
1473 - providerStatuses,
1474 - settings,
1475 - activeProjectId,
1476 - threadRef,
1477 - threadModelSelection,
1478 - projectModelSelection,
1479 - promptInjectionState,
1480 - candidateInstanceIds,
1481 - lockedProvider,
1482 - lockedInstanceId,
1483 - } = input;
1484 - const draftModelState = useComposerDraftModelState(threadRef);
1485 - const providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry> = sortProviderInstanceEntries(
1486 - applyProviderInstanceSettings(
1487 - deriveProviderInstanceEntries(providerStatuses),
1488 - settings,
1489 - activeProjectId,
1490 - ),
1491 - );
1492 - const selection = resolveComposerProviderSelection({
1493 - entries: providerInstanceEntries,
1494 - candidateInstanceIds,
1495 - lockedProvider,
1496 - lockedInstanceId,
1497 - });
1498 - const selectedInstanceId =
1499 - selection.selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId;
1500 - const selectedProvider: ProviderDriverKind =
1501 - selection.selectedProviderEntry?.driverKind ?? selection.requestedDriverKind;
1502 - const modelState = deriveEffectiveComposerModelState({
1503 - draft: draftModelState,
1504 - providers: providerStatuses,
1505 - selectedProvider,
1506 - selectedInstanceId,
1507 - threadModelSelection,
1508 - projectModelSelection,
1509 - settings,
1510 - });
1511 - const selectedProviderModels = selection.selectedProviderEntry?.models ?? NO_PROVIDER_MODELS;
1512 - const composerProviderState = getComposerProviderState({
1513 - provider: selectedProvider,
1514 - model: modelState.selectedModel,
1515 - models: selectedProviderModels,
1516 - promptInjectionState,
1517 - modelOptions: modelState.modelOptions?.[selectedInstanceId],
1518 - planModeEnabled: settings.planModeEnabled,
1519 - });
1520 - return {
1521 - providerInstanceEntries,
1522 - ...selection,
1523 - selectedInstanceId,
1524 - selectedProvider,
1525 - selectedProviderModels,
1526 - composerModelOptions: modelState.modelOptions,
1527 - selectedModel: modelState.selectedModel,
1528 - composerProviderState,
1529 - };
1530 -}
1531 -
1532 -/**
1533 - * Follows the SnapShots still animating into this draft and splits the draft's images into
1534 - * pending SnapShots and standalone images.
1535 - */
1536 -function useComposerImageGroups(
1537 - composerDraftTarget: ScopedThreadRef | DraftId,
1538 - composerImages: ReadonlyArray<ComposerImageAttachment>,
1539 - composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>,
1540 -) {
1541 - const pendingSnapShotAnimations = useSyncExternalStore(
1542 - subscribeToPendingSnapShotAnimations,
1543 - getPendingSnapShotAnimations,
1544 - getPendingSnapShotAnimations,
1545 - );
1546 - const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget(
1547 - pendingSnapShotAnimations,
1548 - composerDraftTarget,
1549 - );
1550 - const previewAnnotationIds = new Set(
1551 - composerPreviewAnnotations.map((annotation) => annotation.id),
1552 - );
1553 - return {
1554 - pendingSnapShotAnimations,
1555 - pendingSnapShotIds,
1556 - pendingSnapShotIdSet: new Set(pendingSnapShotIds),
1557 - uncommittedSnapShotIds: pendingSnapShotIds.filter(
1558 - (id) => !composerImages.some((image) => image.id === id),
1559 - ),
1560 - standaloneComposerImages: composerImages.filter((image) => !previewAnnotationIds.has(image.id)),
1561 - };
1562 -}
1563 -
626 const NO_PROVIDER_SKILLS: ServerProvider["skills"] = [];
627 const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = [];
628
apps/web/src/components/chat/ComposerCommandMenuLayer.tsx new
+94
@@ -0,0 +1,94 @@
1 +import { type ReactNode, useLayoutEffect, useState } from "react";
2 +import { createPortal } from "react-dom";
3 +import { observeResize } from "~/lib/observeResize";
4 +
5 +type ComposerCommandMenuPosition = {
6 + bottom: number;
7 + left: number;
8 + maxHeight: number;
9 + width: number;
10 +};
11 +
12 +function composerCommandMenuPositionsEqual(
13 + a: ComposerCommandMenuPosition,
14 + b: ComposerCommandMenuPosition,
15 +): boolean {
16 + return (
17 + a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width
18 + );
19 +}
20 +
21 +export function ComposerCommandMenuLayer(props: {
22 + anchor: HTMLElement | null;
23 + children: ReactNode;
24 +}) {
25 + const [position, setPosition] = useState<ComposerCommandMenuPosition | null>(null);
26 +
27 + useLayoutEffect(() => {
28 + const anchor = props.anchor;
29 + if (!anchor) return;
30 +
31 + const updatePosition = () => {
32 + const form = anchor.closest<HTMLElement>('[data-chat-composer-form="true"]');
33 + const mainSurface = form?.querySelector<HTMLElement>(
34 + '[data-chat-composer-main-surface="true"]',
35 + );
36 + const rect = (mainSurface ?? form ?? anchor).getBoundingClientRect();
37 + const rootFontSizePx =
38 + Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16;
39 + const drawerInsetRem = Number.parseFloat(
40 + window.getComputedStyle(form ?? anchor).getPropertyValue("--chat-composer-drawer-inset"),
41 + );
42 + const drawerInset = drawerInsetRem * rootFontSizePx;
43 + const width = rect.width - drawerInset * 2;
44 + if (width <= 0) {
45 + setPosition(null);
46 + return;
47 + }
48 + const composerOverlap = rootFontSizePx + 1;
49 + const next = {
50 + bottom: window.innerHeight - rect.top - composerOverlap,
51 + left: rect.left + drawerInset,
52 + maxHeight: Math.max(96, rect.top - 24 + composerOverlap),
53 + width,
54 + };
55 + setPosition((current) =>
56 + current && composerCommandMenuPositionsEqual(current, next) ? current : next,
57 + );
58 + };
59 +
60 + updatePosition();
61 + window.addEventListener("resize", updatePosition);
62 + window.addEventListener("scroll", updatePosition, true);
63 +
64 + const observed: Element[] = [anchor];
65 + for (let element = anchor.parentElement; element; element = element.parentElement) {
66 + observed.push(element);
67 + }
68 + const stopObserving = observeResize(observed, updatePosition);
69 +
70 + return () => {
71 + stopObserving();
72 + window.removeEventListener("resize", updatePosition);
73 + window.removeEventListener("scroll", updatePosition, true);
74 + };
75 + }, [props.anchor]);
76 +
77 + if (!props.anchor || !position) return null;
78 +
79 + return createPortal(
80 + <div
81 + className="pointer-events-auto fixed z-40 flex flex-col"
82 + data-composer-drawer-layer="true"
83 + style={{
84 + bottom: position.bottom,
85 + left: position.left,
86 + maxHeight: position.maxHeight,
87 + width: position.width,
88 + }}
89 + >
90 + {props.children}
91 + </div>,
92 + document.body,
93 + );
94 +}
apps/web/src/components/chat/useComposerImageGroups.ts new
+40
@@ -0,0 +1,40 @@
1 +import { type ComposerImageAttachment, type DraftId } from "../../composerDraftStore";
2 +import { type ScopedThreadRef } from "@t3tools/contracts";
3 +import {
4 + getPendingSnapShotAnimations,
5 + pendingSnapShotAnimationIdsForTarget,
6 + subscribeToPendingSnapShotAnimations,
7 +} from "../../lib/snapShotAnimation";
8 +import { useSyncExternalStore } from "react";
9 +
10 +/**
11 + * Follows the SnapShots still animating into this draft and splits the draft's images into
12 + * pending SnapShots and standalone images.
13 + */
14 +export function useComposerImageGroups(
15 + composerDraftTarget: ScopedThreadRef | DraftId,
16 + composerImages: ReadonlyArray<ComposerImageAttachment>,
17 + composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>,
18 +) {
19 + const pendingSnapShotAnimations = useSyncExternalStore(
20 + subscribeToPendingSnapShotAnimations,
21 + getPendingSnapShotAnimations,
22 + getPendingSnapShotAnimations,
23 + );
24 + const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget(
25 + pendingSnapShotAnimations,
26 + composerDraftTarget,
27 + );
28 + const previewAnnotationIds = new Set(
29 + composerPreviewAnnotations.map((annotation) => annotation.id),
30 + );
31 + return {
32 + pendingSnapShotAnimations,
33 + pendingSnapShotIds,
34 + pendingSnapShotIdSet: new Set(pendingSnapShotIds),
35 + uncommittedSnapShotIds: pendingSnapShotIds.filter(
36 + (id) => !composerImages.some((image) => image.id === id),
37 + ),
38 + standaloneComposerImages: composerImages.filter((image) => !previewAnnotationIds.has(image.id)),
39 + };
40 +}
apps/web/src/components/chat/useComposerProviderModel.ts new
+100
@@ -0,0 +1,100 @@
1 +import {
2 + type DraftId,
3 + deriveEffectiveComposerModelState,
4 + useComposerDraftModelState,
5 +} from "../../composerDraftStore";
6 +import {
7 + type ModelSelection,
8 + type ProjectId,
9 + ProviderDriverKind,
10 + type ScopedThreadRef,
11 + type ServerProvider,
12 +} from "@t3tools/contracts";
13 +import {
14 + NO_PROVIDER_MODEL_SELECTION,
15 + type ProviderInstanceEntry,
16 + applyProviderInstanceSettings,
17 + deriveProviderInstanceEntries,
18 + sortProviderInstanceEntries,
19 +} from "../../providerInstances";
20 +import { type UnifiedSettings } from "@t3tools/contracts/settings";
21 +import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState";
22 +import { resolveComposerProviderSelection } from "../ChatView.logic";
23 +
24 +const NO_PROVIDER_MODELS: ServerProvider["models"] = [];
25 +
26 +/**
27 + * The provider instances the composer offers, which one is selected, and the model and options
28 + * the draft resolves to on it. The draft store is read first so every derivation follows the only
29 + * hook here; in the composer body they would straddle its later hooks and lose their cache.
30 + */
31 +export function useComposerProviderModel(
32 + input: Omit<Parameters<typeof resolveComposerProviderSelection>[0], "entries"> & {
33 + readonly providerStatuses: ReadonlyArray<ServerProvider>;
34 + readonly settings: UnifiedSettings;
35 + readonly activeProjectId: ProjectId | null;
36 + readonly threadRef: ScopedThreadRef | DraftId;
37 + readonly threadModelSelection: ModelSelection | null | undefined;
38 + readonly projectModelSelection: ModelSelection | null | undefined;
39 + readonly promptInjectionState: ReturnType<typeof getComposerPromptInjectionState>;
40 + },
41 +) {
42 + const {
43 + providerStatuses,
44 + settings,
45 + activeProjectId,
46 + threadRef,
47 + threadModelSelection,
48 + projectModelSelection,
49 + promptInjectionState,
50 + candidateInstanceIds,
51 + lockedProvider,
52 + lockedInstanceId,
53 + } = input;
54 + const draftModelState = useComposerDraftModelState(threadRef);
55 + const providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry> = sortProviderInstanceEntries(
56 + applyProviderInstanceSettings(
57 + deriveProviderInstanceEntries(providerStatuses),
58 + settings,
59 + activeProjectId,
60 + ),
61 + );
62 + const selection = resolveComposerProviderSelection({
63 + entries: providerInstanceEntries,
64 + candidateInstanceIds,
65 + lockedProvider,
66 + lockedInstanceId,
67 + });
68 + const selectedInstanceId =
69 + selection.selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId;
70 + const selectedProvider: ProviderDriverKind =
71 + selection.selectedProviderEntry?.driverKind ?? selection.requestedDriverKind;
72 + const modelState = deriveEffectiveComposerModelState({
73 + draft: draftModelState,
74 + providers: providerStatuses,
75 + selectedProvider,
76 + selectedInstanceId,
77 + threadModelSelection,
78 + projectModelSelection,
79 + settings,
80 + });
81 + const selectedProviderModels = selection.selectedProviderEntry?.models ?? NO_PROVIDER_MODELS;
82 + const composerProviderState = getComposerProviderState({
83 + provider: selectedProvider,
84 + model: modelState.selectedModel,
85 + models: selectedProviderModels,
86 + promptInjectionState,
87 + modelOptions: modelState.modelOptions?.[selectedInstanceId],
88 + planModeEnabled: settings.planModeEnabled,
89 + });
90 + return {
91 + providerInstanceEntries,
92 + ...selection,
93 + selectedInstanceId,
94 + selectedProvider,
95 + selectedProviderModels,
96 + composerModelOptions: modelState.modelOptions,
97 + selectedModel: modelState.selectedModel,
98 + composerProviderState,
99 + };
100 +}
apps/web/src/components/chat/useComposerRestingTransition.ts new
+526
@@ -0,0 +1,526 @@
1 +import { observeResize } from "~/lib/observeResize";
2 +import { shouldAnimateComposerRestingTransition } from "../composerFooterLayout";
3 +import { useEffect, useLayoutEffect, useRef } from "react";
4 +
5 +const COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS = 50;
6 +const COMPOSER_RESTING_TRANSITION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
7 +const COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX = 4;
8 +
9 +export function useComposerRestingTransition(
10 + isCollapsed: boolean,
11 + isResting: boolean,
12 + restingControlsRef: React.RefObject<HTMLDivElement | null>,
13 + onOverlayHeightChange: (height: number) => void,
14 + animationsActive: boolean,
15 + animationDurationMs: number,
16 +) {
17 + const elementRef = useRef<HTMLDivElement>(null);
18 + const isCollapsedRef = useRef(isCollapsed);
19 + const previousCollapsedRef = useRef(isCollapsed);
20 + const previousRestingRef = useRef(isResting);
21 + const previousHeightRef = useRef<number | null>(null);
22 + const previousModelStripHeightRef = useRef<number | null>(null);
23 + const previousContentOffsetsRef = useRef<{
24 + promptFromTop: number | null;
25 + promptHeight: number | null;
26 + actionFromBottom: number | null;
27 + controlsFromBottom: number | null;
28 + controlsFromLeft: number | null;
29 + surfaceBottomInset: number | null;
30 + }>({
31 + promptFromTop: null,
32 + promptHeight: null,
33 + actionFromBottom: null,
34 + controlsFromBottom: null,
35 + controlsFromLeft: null,
36 + surfaceBottomInset: null,
37 + });
38 + const animationRef = useRef<Animation | null>(null);
39 + const animationTargetHeightRef = useRef<number | null>(null);
40 + const contentAnimationsRef = useRef<Animation[]>([]);
41 + const stateChangeAnimationsRef = useRef<Animation[]>([]);
42 + const pinnedOverlayRef = useRef<HTMLElement | null>(null);
43 + const transitionCleanupTimeoutRef = useRef<number | null>(null);
44 + const transitionLayoutRequestRef = useRef(0);
45 + const hasCompletedInitialLayoutRef = useRef(false);
46 +
47 + const clearOverlayPin = () => {
48 + // The overlay belongs to the chat view and outlives this composer, so it
49 + // is remembered from pin time rather than re-resolved through a ref that
50 + // React may already have detached during unmount.
51 + const overlay = pinnedOverlayRef.current;
52 + pinnedOverlayRef.current = null;
53 + overlay?.style.removeProperty("height");
54 + overlay?.style.removeProperty("display");
55 + overlay?.style.removeProperty("flex-direction");
56 + overlay?.style.removeProperty("justify-content");
57 + };
58 +
59 + const clearTransitionStyles = () => {
60 + const element = elementRef.current;
61 + const footer = element?.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
62 + element?.style.removeProperty("overflow");
63 + element?.style.removeProperty("clip-path");
64 + element?.style.removeProperty("overflow-clip-margin");
65 + element
66 + ?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]')
67 + ?.style.removeProperty("height");
68 + footer?.style.removeProperty("position");
69 + footer?.style.removeProperty("top");
70 + footer?.style.removeProperty("bottom");
71 + footer?.style.removeProperty("left");
72 + footer?.style.removeProperty("right");
73 + footer?.style.removeProperty("height");
74 + const shell = element?.closest<HTMLElement>('[data-slot="composer-shell"]');
75 + shell?.removeAttribute("data-model-strip-transition");
76 + const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
77 + for (const property of [
78 + "position",
79 + "top",
80 + "visibility",
81 + "height",
82 + "min-height",
83 + "padding-top",
84 + "align-items",
85 + "z-index",
86 + "pointer-events",
87 + ]) {
88 + modelStrip?.style.removeProperty(property);
89 + }
90 + clearOverlayPin();
91 + };
92 +
93 + useLayoutEffect(() => {
94 + isCollapsedRef.current = isCollapsed;
95 + });
96 +
97 + const transitionToCurrentGeometry = (stateChanged: boolean) => {
98 + const element = elementRef.current;
99 + const surface = element?.querySelector<HTMLElement>('[data-chat-composer-surface="true"]');
100 + if (!element || !surface) return;
101 +
102 + const nextIsCollapsed = isCollapsedRef.current;
103 +
104 + const visibleTransitionElement = (selector: string) =>
105 + Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
106 + (candidate) => candidate.getClientRects().length > 0,
107 + ) ?? null;
108 + const prompt = visibleTransitionElement(
109 + '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
110 + );
111 + const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]');
112 + const footer = element.querySelector<HTMLElement>('[data-chat-composer-footer="true"]');
113 + const continuousControls =
114 + element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true";
115 + const controls = nextIsCollapsed
116 + ? restingControlsRef.current
117 + : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
118 +
119 + const shell = element.closest<HTMLElement>('[data-slot="composer-shell"]');
120 + const modelStrip = shell?.querySelector<HTMLElement>('[data-composer-model-strip="true"]');
121 + const interruptedStripHeight =
122 + animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null;
123 + const interruptedAnimation = animationRef.current;
124 + const interruptedPromptTop = interruptedAnimation
125 + ? (prompt?.getBoundingClientRect().top ?? null)
126 + : null;
127 + const interruptedActionTop = interruptedAnimation
128 + ? (action?.getBoundingClientRect().top ?? null)
129 + : null;
130 + const interruptedControlsLeft = interruptedAnimation
131 + ? (controls?.getBoundingClientRect().left ?? null)
132 + : null;
133 + const interruptedControlsTop = interruptedAnimation
134 + ? (controls?.getBoundingClientRect().top ?? null)
135 + : null;
136 + const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null;
137 + const interruptedTargetHeight = animationTargetHeightRef.current;
138 + const interruptedCurrentTime =
139 + typeof interruptedAnimation?.currentTime === "number"
140 + ? interruptedAnimation.currentTime
141 + : null;
142 + const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration;
143 + if (transitionCleanupTimeoutRef.current !== null) {
144 + window.clearTimeout(transitionCleanupTimeoutRef.current);
145 + transitionCleanupTimeoutRef.current = null;
146 + }
147 + interruptedAnimation?.cancel();
148 + animationRef.current = null;
149 + for (const animation of contentAnimationsRef.current) animation.cancel();
150 + contentAnimationsRef.current = [];
151 + if (stateChanged) {
152 + for (const animation of stateChangeAnimationsRef.current) animation.cancel();
153 + stateChangeAnimationsRef.current = [];
154 + }
155 + clearTransitionStyles();
156 +
157 + const nextRect = element.getBoundingClientRect();
158 + const nextHeight = nextRect.height;
159 + const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null;
160 + // The chat view resize-observes the overlay to place the timeline
161 + // inset, the scroll-to-end pill, and the mini player. Publishing the
162 + // destination height here turns that feedback into one update instead
163 + // of a ChatView re-render on every animation frame.
164 + const overlay = element.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
165 + const overlayRect = overlay?.getBoundingClientRect();
166 + const overlayHeight = overlayRect?.height ?? null;
167 + if (overlayHeight !== null) {
168 + onOverlayHeightChange(overlayHeight);
169 + }
170 + const nextPromptRect = prompt?.getBoundingClientRect() ?? null;
171 + const nextPromptTop = nextPromptRect?.top ?? null;
172 + const nextActionTop = action?.getBoundingClientRect().top ?? null;
173 + const nextControlsRect = controls?.getBoundingClientRect() ?? null;
174 + const nextControlsTop = nextControlsRect?.top ?? null;
175 + const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1;
176 + const previousHeight = interruptedHeight ?? previousHeightRef.current;
177 + const targetChanged =
178 + interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5;
179 + const shouldAnimate = shouldAnimateComposerRestingTransition({
180 + hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current,
181 + stateChanged,
182 + hasInterruptedAnimation: interruptedHeight !== null,
183 + });
184 +
185 + if (
186 + shouldAnimate &&
187 + animationsActive &&
188 + previousHeight !== null &&
189 + Math.abs(previousHeight - nextHeight) >= 0.5
190 + ) {
191 + const remainingDuration =
192 + typeof interruptedDuration === "number" && interruptedCurrentTime !== null
193 + ? Math.max(1, interruptedDuration - interruptedCurrentTime)
194 + : animationDurationMs;
195 + const duration =
196 + interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs;
197 + element.style.overflow = "clip";
198 + if (modelStrip) {
199 + const controlsClearance = Math.max(
200 + nextModelStripHeight ?? 0,
201 + previousModelStripHeightRef.current ?? 0,
202 + );
203 + element.style.overflowClipMargin = `${controlsClearance}px`;
204 + element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`;
205 + }
206 + surface.style.height = "100%";
207 +
208 + if (overlay && overlayHeight !== null) {
209 + overlay.style.height = `${String(overlayHeight)}px`;
210 + overlay.style.display = "flex";
211 + overlay.style.flexDirection = "column";
212 + overlay.style.justifyContent = "flex-end";
213 + pinnedOverlayRef.current = overlay;
214 + }
215 +
216 + if (footer) {
217 + footer.style.position = "absolute";
218 + footer.style.top = "auto";
219 + footer.style.bottom = `${String(footerBottom)}px`;
220 + footer.style.height = "3rem";
221 + if (nextIsCollapsed) {
222 + footer.style.left = "auto";
223 + footer.style.right = "1px";
224 + } else {
225 + footer.style.left = "1px";
226 + footer.style.right = "1px";
227 + }
228 + }
229 +
230 + let stripAnimation: Animation | null = null;
231 + if (modelStrip) {
232 + const stripHeight = modelStrip.getBoundingClientRect().height;
233 + const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop);
234 + const fromHeight =
235 + interruptedStripHeight ??
236 + (previousCollapsedRef.current
237 + ? (previousModelStripHeightRef.current ?? stripHeight)
238 + : stripOverlap);
239 + const toHeight = nextIsCollapsed ? stripHeight : stripOverlap;
240 + modelStrip.style.position = "relative";
241 + modelStrip.style.top = "auto";
242 + modelStrip.style.visibility = "visible";
243 + modelStrip.style.minHeight = "0";
244 + modelStrip.style.paddingTop = "0";
245 + modelStrip.style.alignItems = "flex-end";
246 + modelStrip.style.pointerEvents = "none";
247 + modelStrip.style.zIndex = "20";
248 + shell?.setAttribute("data-model-strip-transition", "true");
249 + stripAnimation = modelStrip.animate(
250 + [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }],
251 + { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" },
252 + );
253 + }
254 +
255 + const animation = element.animate(
256 + [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }],
257 + {
258 + duration,
259 + easing: COMPOSER_RESTING_TRANSITION_EASING,
260 + fill: "both",
261 + },
262 + );
263 + animationRef.current = animation;
264 + animationTargetHeightRef.current = nextHeight;
265 +
266 + const animatedRect = element.getBoundingClientRect();
267 + const previousBottom =
268 + overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null
269 + ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset
270 + : animatedRect.bottom;
271 + const bottomShift = previousBottom - animatedRect.bottom;
272 + const previousPromptTop =
273 + interruptedPromptTop ??
274 + (previousContentOffsetsRef.current.promptFromTop === null
275 + ? null
276 + : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop);
277 + const previousActionTop =
278 + interruptedActionTop ??
279 + (previousContentOffsetsRef.current.actionFromBottom === null
280 + ? null
281 + : previousBottom - previousContentOffsetsRef.current.actionFromBottom);
282 + const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : [];
283 + const animateContentPosition = (
284 + content: HTMLElement | null,
285 + previousTop: number | null,
286 + previousLeft: number | null = null,
287 + ) => {
288 + if (!content || previousTop === null) return;
289 + const rect = content.getBoundingClientRect();
290 + const offset = previousTop - rect.top;
291 + const offsetX = previousLeft === null ? 0 : previousLeft - rect.left;
292 + if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return;
293 + contentAnimations.push(
294 + content.animate(
295 + [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }],
296 + {
297 + duration,
298 + easing: COMPOSER_RESTING_TRANSITION_EASING,
299 + },
300 + ),
301 + );
302 + };
303 + animateContentPosition(prompt, previousPromptTop);
304 + animateContentPosition(action, previousActionTop);
305 + if (continuousControls) {
306 + const previousControlsTop =
307 + interruptedControlsTop ??
308 + (previousContentOffsetsRef.current.controlsFromBottom === null
309 + ? null
310 + : previousBottom - previousContentOffsetsRef.current.controlsFromBottom);
311 + const previousControlsLeft =
312 + interruptedControlsLeft ??
313 + (previousContentOffsetsRef.current.controlsFromLeft === null
314 + ? null
315 + : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft);
316 + animateContentPosition(controls, previousControlsTop, previousControlsLeft);
317 + }
318 + contentAnimationsRef.current = contentAnimations;
319 +
320 + if (stateChanged) {
321 + const stateChangeAnimations: Animation[] = [];
322 +
323 + const previousPromptHeight = previousContentOffsetsRef.current.promptHeight;
324 + if (
325 + !nextIsCollapsed &&
326 + prompt &&
327 + nextPromptRect &&
328 + previousPromptHeight !== null &&
329 + nextPromptRect.height - previousPromptHeight >= 0.5
330 + ) {
331 + const hiddenHeight = nextPromptRect.height - previousPromptHeight;
332 + stateChangeAnimations.push(
333 + prompt.animate(
334 + [
335 + { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` },
336 + { clipPath: "inset(0 0 0 0)" },
337 + ],
338 + {
339 + duration,
340 + easing: COMPOSER_RESTING_TRANSITION_EASING,
341 + },
342 + ),
343 + );
344 + }
345 +
346 + const arrivingControls = nextIsCollapsed
347 + ? restingControlsRef.current
348 + : element.querySelector<HTMLElement>('[data-chat-composer-controls="left"]');
349 + if (arrivingControls && !continuousControls) {
350 + const drift = nextIsCollapsed
351 + ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX
352 + : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX;
353 + stateChangeAnimations.push(
354 + arrivingControls.animate(
355 + [
356 + { opacity: 0, transform: `translateY(${String(drift)}px)` },
357 + { opacity: 1, transform: "none" },
358 + ],
359 + {
360 + duration: nextIsCollapsed ? duration : duration / 2,
361 + delay: nextIsCollapsed ? 0 : duration / 2,
362 + fill: "backwards",
363 + easing: COMPOSER_RESTING_TRANSITION_EASING,
364 + },
365 + ),
366 + );
367 + }
368 +
369 + const arrivingImagePreviews = nextIsCollapsed
370 + ? Array.from(
371 + element.querySelectorAll<HTMLElement>('[data-chat-composer-resting-images="true"]'),
372 + )
373 + : Array.from(
374 + element.querySelectorAll<HTMLElement>('[data-chat-composer-expanded-image="true"]'),
375 + );
376 + for (const imagePreview of arrivingImagePreviews) {
377 + stateChangeAnimations.push(
378 + imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], {
379 + duration: nextIsCollapsed ? duration : duration / 2,
380 + delay: nextIsCollapsed ? 0 : duration / 2,
381 + fill: "backwards",
382 + easing: COMPOSER_RESTING_TRANSITION_EASING,
383 + }),
384 + );
385 + }
386 + stateChangeAnimationsRef.current = stateChangeAnimations;
387 + }
388 +
389 + const finishTransition = (cancelAnimations: boolean) => {
390 + if (animationRef.current !== animation) return;
391 + if (transitionCleanupTimeoutRef.current !== null) {
392 + window.clearTimeout(transitionCleanupTimeoutRef.current);
393 + transitionCleanupTimeoutRef.current = null;
394 + }
395 + if (cancelAnimations) {
396 + animation.cancel();
397 + for (const contentAnimation of contentAnimationsRef.current) {
398 + contentAnimation.cancel();
399 + }
400 + for (const stateChangeAnimation of stateChangeAnimationsRef.current) {
401 + stateChangeAnimation.cancel();
402 + }
403 + }
404 + animationRef.current = null;
405 + animationTargetHeightRef.current = null;
406 + contentAnimationsRef.current = [];
407 + stateChangeAnimationsRef.current = [];
408 + animation.cancel();
409 + stripAnimation?.cancel();
410 + clearTransitionStyles();
411 + };
412 + void animation.finished.catch(() => undefined).then(() => finishTransition(false));
413 + // A suspended document timeline can leave `finished` pending while
414 + // these measurement styles remain active. Wall-clock cleanup makes
415 + // the natural layout the eventual source of truth in that case.
416 + transitionCleanupTimeoutRef.current = window.setTimeout(
417 + () => finishTransition(true),
418 + duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS,
419 + );
420 + } else {
421 + animationTargetHeightRef.current = null;
422 + }
423 +
424 + previousCollapsedRef.current = nextIsCollapsed;
425 + previousHeightRef.current = nextHeight;
426 + previousModelStripHeightRef.current = nextModelStripHeight;
427 + previousContentOffsetsRef.current = {
428 + promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top,
429 + promptHeight: nextPromptRect?.height ?? null,
430 + actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop,
431 + controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop,
432 + controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left,
433 + surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null,
434 + };
435 + };
436 +
437 + useLayoutEffect(() => {
438 + const requestId = transitionLayoutRequestRef.current + 1;
439 + transitionLayoutRequestRef.current = requestId;
440 + const stateChanged = previousCollapsedRef.current !== isCollapsed;
441 + // A non-Git context strip enters or leaves flow through ChatView state in
442 + // an earlier layout effect. Let React flush that parent update before the
443 + // FLIP reads its destination geometry, while still running before paint.
444 + queueMicrotask(() => {
445 + if (transitionLayoutRequestRef.current !== requestId) return;
446 + transitionToCurrentGeometry(stateChanged);
447 + });
448 + return () => {
449 + if (transitionLayoutRequestRef.current === requestId) {
450 + transitionLayoutRequestRef.current += 1;
451 + }
452 + };
453 + }, [isCollapsed, transitionToCurrentGeometry]);
454 +
455 + useLayoutEffect(() => {
456 + if (previousRestingRef.current === isResting) return;
457 + previousRestingRef.current = isResting;
458 + if (animationRef.current) return;
459 + const overlay = elementRef.current?.closest<HTMLElement>('[data-chat-composer-overlay="true"]');
460 + if (overlay) onOverlayHeightChange(overlay.getBoundingClientRect().height);
461 + }, [isResting, onOverlayHeightChange]);
462 +
463 + useLayoutEffect(() => {
464 + const element = elementRef.current;
465 + if (!element) return;
466 +
467 + const body = element.querySelector<HTMLElement>('[data-chat-composer-body="true"]');
468 + return observeResize(body ? [element, body] : element, (entries) => {
469 + if (animationRef.current) {
470 + if (body && entries.some((entry) => entry.target === body)) {
471 + transitionToCurrentGeometry(false);
472 + }
473 + return;
474 + }
475 + const elementRect = element.getBoundingClientRect();
476 + const visibleTransitionElement = (selector: string) =>
477 + Array.from(element.querySelectorAll<HTMLElement>(selector)).find(
478 + (candidate) => candidate.getClientRects().length > 0,
479 + ) ?? null;
480 + const promptRect = visibleTransitionElement(
481 + '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]',
482 + )?.getBoundingClientRect();
483 + const actionTop = visibleTransitionElement(
484 + '[data-chat-composer-transition-actions="true"]',
485 + )?.getBoundingClientRect().top;
486 + const controlsRect = (
487 + isCollapsedRef.current
488 + ? restingControlsRef.current
489 + : visibleTransitionElement('[data-chat-composer-controls="left"]')
490 + )?.getBoundingClientRect();
491 + previousHeightRef.current = elementRect.height;
492 + previousContentOffsetsRef.current = {
493 + promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top,
494 + promptHeight: promptRect?.height ?? null,
495 + actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop,
496 + controlsFromBottom:
497 + controlsRect === undefined ? null : elementRect.bottom - controlsRect.top,
498 + controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left,
499 + surfaceBottomInset:
500 + (element
501 + .closest<HTMLElement>('[data-chat-composer-overlay="true"]')
502 + ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom,
503 + };
504 + });
505 + }, [restingControlsRef, transitionToCurrentGeometry]);
506 +
507 + useEffect(() => {
508 + hasCompletedInitialLayoutRef.current = true;
509 + return () => {
510 + if (transitionCleanupTimeoutRef.current !== null) {
511 + window.clearTimeout(transitionCleanupTimeoutRef.current);
512 + transitionCleanupTimeoutRef.current = null;
513 + }
514 + animationRef.current?.cancel();
515 + animationRef.current = null;
516 + animationTargetHeightRef.current = null;
517 + for (const animation of contentAnimationsRef.current) animation.cancel();
518 + contentAnimationsRef.current = [];
519 + for (const animation of stateChangeAnimationsRef.current) animation.cancel();
520 + stateChangeAnimationsRef.current = [];
521 + clearTransitionStyles();
522 + };
523 + }, [clearTransitionStyles]);
524 +
525 + return elementRef;
526 +}
apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts new
+137
@@ -0,0 +1,137 @@
1 +import {
2 + type EnvironmentId,
3 + PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
4 + type ServerProvider,
5 +} from "@t3tools/contracts";
6 +import { type ProviderInstanceEntry } from "../../providerInstances";
7 +import {
8 + hasCompleteProviderWorkspaceSnapshot,
9 + hasCurrentProviderWorkspaceSnapshot,
10 +} from "@t3tools/client-runtime/providerSkills";
11 +import { serverEnvironment } from "../../state/server";
12 +import { useAtomCommand } from "../../state/use-atom-command";
13 +import { useEffect, useEffectEvent, useRef, useState } from "react";
14 +import { useStableCallback } from "../../hooks/useStableCallback";
15 +
16 +const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
17 +
18 +/**
19 + * Keeps the selected provider's workspace snapshot fresh for the composer's
20 + * cwd. Returns a check to run when the user types.
21 + */
22 +export function useProviderWorkspaceSnapshotRefresh(input: {
23 + readonly environmentId: EnvironmentId;
24 + readonly gitCwd: string | null;
25 + readonly selectedProviderEntry: ProviderInstanceEntry | undefined;
26 + readonly selectedProviderStatus: ServerProvider | null;
27 +}) {
28 + const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input;
29 + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
30 + reportFailure: false,
31 + });
32 + // The last scan this composer asked for. A request inside the TTL is not
33 + // repeated, so a client clock ahead of the server's cannot loop rescans.
34 + const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null);
35 + const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{
36 + key: string;
37 + notBefore: number;
38 + } | null>(null);
39 + const workspaceRefreshScopeKey =
40 + gitCwd && selectedProviderEntry
41 + ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}`
42 + : null;
43 + const workspaceSlashCommandsPending =
44 + selectedProviderStatus?.workspaceSnapshots?.some(
45 + (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true,
46 + ) ?? false;
47 + useEffect(() => {
48 + if (
49 + !workspaceSlashCommandsPending ||
50 + !workspaceRefreshRetry ||
51 + workspaceRefreshRetry.key !== workspaceRefreshScopeKey
52 + )
53 + return;
54 + const timeout = setTimeout(
55 + () => {
56 + setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current));
57 + },
58 + Math.max(0, workspaceRefreshRetry.notBefore - Date.now()),
59 + );
60 + return () => clearTimeout(timeout);
61 + }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]);
62 + // Losing a snapshot (the server dropped it) lifts both the TTL and the retry
63 + // cooldown so the next check rescans at once.
64 + const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd);
65 + const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot);
66 + const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0);
67 + if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) {
68 + setHadWorkspaceSnapshot(hasWorkspaceSnapshot);
69 + if (!hasWorkspaceSnapshot) {
70 + setWorkspaceSnapshotLossCount((count) => count + 1);
71 + setWorkspaceRefreshRetry(null);
72 + }
73 + }
74 + const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount);
75 + const refreshWorkspaceSnapshotIfStale = (
76 + now: number,
77 + key: string | null,
78 + retry: { key: string; notBefore: number } | null,
79 + snapshotLossCount: number,
80 + ) => {
81 + if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) {
82 + lastWorkspaceSnapshotLossRef.current = snapshotLossCount;
83 + workspaceRefreshKeyRef.current = null;
84 + }
85 + if (key === null || !gitCwd || !selectedProviderEntry) return;
86 + const lastRequest = workspaceRefreshKeyRef.current;
87 + if (
88 + lastRequest?.key === key &&
89 + now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS
90 + )
91 + return;
92 + // A pending retry needs no clearing here: its cooldown lapses long before the TTL.
93 + if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return;
94 + if (retry?.key === key && now < retry.notBefore) return;
95 + const request = { key, requestedAt: now };
96 + workspaceRefreshKeyRef.current = request;
97 + const retryLater = () => {
98 + if (workspaceRefreshKeyRef.current !== request) return;
99 + workspaceRefreshKeyRef.current = null;
100 + setWorkspaceRefreshRetry({
101 + key,
102 + notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
103 + });
104 + };
105 + void refreshProviders({
106 + environmentId,
107 + input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd },
108 + }).then((result) => {
109 + const refreshedSnapshot =
110 + result._tag === "Success" &&
111 + hasCompleteProviderWorkspaceSnapshot(
112 + result.value.providers.find(
113 + (provider) => provider.instanceId === selectedProviderEntry.instanceId,
114 + ),
115 + gitCwd,
116 + );
117 + if (!refreshedSnapshot) retryLater();
118 + }, retryLater);
119 + };
120 + const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale);
121 + useEffect(() => {
122 + refreshWorkspaceSnapshotOnChange(
123 + Date.now(),
124 + workspaceRefreshScopeKey,
125 + workspaceRefreshRetry,
126 + workspaceSnapshotLossCount,
127 + );
128 + }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]);
129 + return useStableCallback(() =>
130 + refreshWorkspaceSnapshotIfStale(
131 + Date.now(),
132 + workspaceRefreshScopeKey,
133 + workspaceRefreshRetry,
134 + workspaceSnapshotLossCount,
135 + ),
136 + );
137 +}
apps/web/src/components/chat/useRestingComposerControlsLayout.ts new
+84
@@ -0,0 +1,84 @@
1 +import { measureRestingComposerControls } from "./restingComposerControlsMeasurement";
2 +import { observeResize } from "~/lib/observeResize";
3 +import { resolveRestingComposerControlsLayout } from "../composerFooterLayout";
4 +import { useLayoutEffect, useRef, useState } from "react";
5 +
6 +export function useRestingComposerControlsLayout(
7 + host: HTMLDivElement | null,
8 + useControlsAsHost = false,
9 +) {
10 + const [controls, setControls] = useState<HTMLDivElement | null>(null);
11 + const controlsRef = useRef<HTMLDivElement>(null);
12 + const attachControls = (element: HTMLDivElement | null) => {
13 + controlsRef.current = element;
14 + setControls(element);
15 + };
16 + const [layout, setLayout] = useState<{
17 + hiddenCount: number;
18 + iconOnlyCount?: number;
19 + visible: boolean;
20 + }>({ hiddenCount: 0, visible: true });
21 +
22 + const measure = () => {
23 + const currentHost = useControlsAsHost ? controls : host;
24 + if (currentHost === null || !controls) return;
25 +
26 + const measurement = measureRestingComposerControls(controls);
27 + if (!measurement) return;
28 + const style = getComputedStyle(currentHost);
29 + const hostWidth =
30 + currentHost.clientWidth -
31 + (Number.parseFloat(style.paddingInlineStart) || 0) -
32 + (Number.parseFloat(style.paddingInlineEnd) || 0);
33 +
34 + setLayout((current) => {
35 + const next = resolveRestingComposerControlsLayout({
36 + ...measurement,
37 + hostWidth,
38 + previous: current,
39 + });
40 + return next.hiddenCount === current.hiddenCount &&
41 + next.iconOnlyCount === current.iconOnlyCount &&
42 + next.visible === current.visible
43 + ? current
44 + : next;
45 + });
46 + };
47 +
48 + useLayoutEffect(() => {
49 + const currentHost = useControlsAsHost ? controls : host;
50 + if (!currentHost || !controls) return;
51 + let stopObserving = () => {};
52 + const observeControls = () => {
53 + stopObserving();
54 + stopObserving = observeResize(
55 + [
56 + currentHost,
57 + controls,
58 + ...controls.querySelectorAll<HTMLElement>(
59 + "[data-resting-block], [data-composer-control-label], [data-chat-provider-model-picker-label]",
60 + ),
61 + ],
62 + measure,
63 + );
64 + measure();
65 + };
66 + observeControls();
67 + const mutations = new MutationObserver(observeControls);
68 + mutations.observe(controls, { childList: true, subtree: true, characterData: true });
69 + document.fonts.addEventListener("loadingdone", measure);
70 + return () => {
71 + stopObserving();
72 + mutations.disconnect();
73 + document.fonts.removeEventListener("loadingdone", measure);
74 + };
75 + }, [host, controls, useControlsAsHost, measure]);
76 +
77 + return {
78 + controlsRef,
79 + attachControls,
80 + hiddenBlockCount: layout.hiddenCount,
81 + iconOnlyBlockCount: layout.iconOnlyCount ?? 0,
82 + controlsVisible: layout.visible,
83 + };
84 +}