From c19d9977d483f8c661c9ad6bede0f1d8da517d31 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 13:23:38 -0700 Subject: [PATCH 01/83] perf(web): typing no longer re-renders the traits picker or attach button (#23040) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 167 +++++++++--------- apps/web/src/components/chat/TraitsPicker.tsx | 63 ++++--- .../chat/composerProviderState.test.tsx | 10 ++ .../components/chat/composerProviderState.tsx | 15 +- .../settings/ProjectDefaultsSettings.tsx | 2 - .../components/settings/SettingsPanels.tsx | 2 - .../settings/SourceControlWritingSettings.tsx | 4 - 7 files changed, 144 insertions(+), 119 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 106d84fd1257a..18eea30efb314 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -290,6 +290,7 @@ import { renderProviderTraitsMenuContent, renderProviderTraitsPicker, } from "./composerProviderState"; +import { readPromptUltrathink } from "./TraitsPicker"; import { providerSupportsManualCompaction, resolveContextWindowModelDisplayName, @@ -2307,7 +2308,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; - const setPromptFromTraits = (nextPrompt: string) => { + const editPromptFromTraits = (edit: (prompt: string) => string) => { + const currentPrompt = getComposerDraft(composerDraftTarget)?.prompt ?? ""; + const nextPrompt = edit(currentPrompt); + if (nextPrompt === currentPrompt) return; if (nextPrompt === promptRef.current) { scheduleComposerFocus(); return; @@ -2319,7 +2323,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); scheduleComposerFocus(); }; - const setPromptFromTraitsStable = useStableCallback(setPromptFromTraits); + const editPromptFromTraitsStable = useStableCallback(editPromptFromTraits); + const promptUltrathink = readPromptUltrathink(prompt); const providerTraitsMenuContent = renderProviderTraitsMenuContent({ provider: selectedProvider, @@ -2330,8 +2335,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) models: selectedProviderModels, modelOptions: composerModelOptions?.[selectedInstanceId], reportedModelSelection, - prompt, - onPromptChange: setPromptFromTraitsStable, + promptUltrathink, + onPromptEdit: editPromptFromTraitsStable, planModeEnabled: settings.planModeEnabled, }); const providerTraitsPickerInput = { @@ -2343,8 +2348,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) models: selectedProviderModels, modelOptions: composerModelOptions?.[selectedInstanceId], reportedModelSelection, - prompt, - onPromptChange: setPromptFromTraitsStable, + promptUltrathink, + onPromptEdit: editPromptFromTraitsStable, planModeEnabled: settings.planModeEnabled, isComposerOwned: true, } satisfies Parameters[0]; @@ -4736,6 +4741,82 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) terminalOpen, ]); + const insertComposerText = ( + text: string, + position: "cursor" | "end", + options?: { + ensureLeadingBoundary?: boolean; + citationCommentAnchor?: AssistantCitationSourceAnchor; + clipboardData?: DataTransfer; + }, + ): boolean => { + if ( + text.length === 0 || + isConnecting || + activePendingIsResponding || + (pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) || + projectSelectionRequired || + (options?.citationCommentAnchor && !composerEditorRef.current) + ) { + return false; + } + if (options?.clipboardData) { + text = importPastedComposerText(options.clipboardData, importContextFragment); + } + const prompt = promptRef.current; + const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; + const needsLeadingSpace = + (options?.ensureLeadingBoundary ?? false) && + cursor > 0 && + !/\s/.test(prompt[cursor - 1] ?? ""); + const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text); + return applyPromptReplacement( + cursor, + rangeEnd, + needsLeadingSpace ? ` ${text}` : text, + options?.citationCommentAnchor + ? { + citationComment: { + start: cursor + (needsLeadingSpace ? 1 : 0), + sourceAnchor: options.citationCommentAnchor, + insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor }, + }, + focusEditorAfterReplace: false, + } + : undefined, + ); + }; + const insertComposerTextStable = useStableCallback(insertComposerText); + + const insertAttachmentReferences = ( + references: ReadonlyArray, + selection?: { start: number; end: number }, + ): boolean => { + if (references.length === 0) return false; + // Question answers carry attachments beside the answer, never as chips. Falling back to + // the thread prompt here would hide the file behind a reference the question never shows. + if (questionAttachmentTarget) return false; + return insertAttachmentReferencesForDraft({ + target: composerDraftTarget, + liveAttachmentTargetKey: attachmentTargetKeyRef.current, + references, + insertReferences: () => { + if (selection) { + const edit = inlineContextReferenceReplacement(promptRef.current, selection, references); + return applyPromptReplacementStable(edit.start, edit.end, edit.text); + } + const text = references.map(formatInlineContextReference).join(" "); + const inserted = insertComposerTextStable(`${text} `, "cursor", { + ensureLeadingBoundary: true, + }); + if (!inserted) { + setPrompt(ensureInlineContextReferences(promptRef.current, references)); + } + return true; + }, + }); + }; + const addComposerAttachments = async ( files: File[], options?: { @@ -4944,33 +5025,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); }; - const insertAttachmentReferences = ( - references: ReadonlyArray, - selection?: { start: number; end: number }, - ): boolean => { - if (references.length === 0) return false; - // Question answers carry attachments beside the answer, never as chips. Falling back to - // the thread prompt here would hide the file behind a reference the question never shows. - if (questionAttachmentTarget) return false; - return insertAttachmentReferencesForDraft({ - target: composerDraftTarget, - liveAttachmentTargetKey: attachmentTargetKeyRef.current, - references, - insertReferences: () => { - if (selection) { - const edit = inlineContextReferenceReplacement(promptRef.current, selection, references); - return applyPromptReplacement(edit.start, edit.end, edit.text); - } - const text = references.map(formatInlineContextReference).join(" "); - const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true }); - if (!inserted) { - setPrompt(ensureInlineContextReferences(promptRef.current, references)); - } - return true; - }, - }); - }; - const removeComposerImage = (imageId: string) => { const image = composerImagesRef.current.find((candidate) => candidate.id === imageId); const referenced = collectInlineContextIds(promptRef.current).includes( @@ -5075,53 +5129,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) () => resolveActiveComposerTrigger().trigger?.kind === "path", ); - const insertComposerText = ( - text: string, - position: "cursor" | "end", - options?: { - ensureLeadingBoundary?: boolean; - citationCommentAnchor?: AssistantCitationSourceAnchor; - clipboardData?: DataTransfer; - }, - ): boolean => { - if ( - text.length === 0 || - isConnecting || - activePendingIsResponding || - (pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) || - projectSelectionRequired || - (options?.citationCommentAnchor && !composerEditorRef.current) - ) { - return false; - } - if (options?.clipboardData) { - text = importPastedComposerText(options.clipboardData, importContextFragment); - } - const prompt = promptRef.current; - const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; - const needsLeadingSpace = - (options?.ensureLeadingBoundary ?? false) && - cursor > 0 && - !/\s/.test(prompt[cursor - 1] ?? ""); - const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text); - return applyPromptReplacement( - cursor, - rangeEnd, - needsLeadingSpace ? ` ${text}` : text, - options?.citationCommentAnchor - ? { - citationComment: { - start: cursor + (needsLeadingSpace ? 1 : 0), - sourceAnchor: options.citationCommentAnchor, - insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor }, - }, - focusEditorAfterReplace: false, - } - : undefined, - ); - }; - const insertComposerTextStable = useStableCallback(insertComposerText); - const insertComposerTextAtEnd: ChatComposerHandle["insertTextAtEnd"] = (text, options) => { const inserted = insertComposerText(text, "end", options); if (inserted && isComposerCollapsedMobile) { diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index db350ca52f031..00566955e5d40 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -1,7 +1,6 @@ import { buildTraitsTriggerDisplay, getDescriptorStringValue, - getPromptControlledTraits, getTraitSelectChange, replaceDescriptorCurrentValue, selectableProviderOptionChoices, @@ -21,6 +20,7 @@ import { buildProviderOptionSelectionsFromDescriptors, getProviderOptionCurrentLabel, getProviderOptionDescriptors, + isClaudeUltrathinkPrompt, normalizeModelSlug, } from "@t3tools/shared/model"; import { memo } from "react"; @@ -50,6 +50,17 @@ import { useComposerMenuState } from "./useComposerMenuState"; type ProviderOptions = ReadonlyArray; +/** + * All the picker reads from the prompt while rendering. Passing this instead of + * the prompt keeps the picker from re-rendering on every keystroke. + */ +export type PromptUltrathink = "none" | "prefix" | "body"; + +export function readPromptUltrathink(prompt: string): PromptUltrathink { + if (!isClaudeUltrathinkPrompt(prompt)) return "none"; + return isClaudeUltrathinkPrompt(prompt.replace(/^Ultrathink:\s*/i, "")) ? "body" : "prefix"; +} + const SAVED_OPTION_LABELS: Readonly> = { agent: "Agent", effort: "Effort", @@ -108,7 +119,7 @@ function getSelectedTraits( provider: ProviderDriverKind, models: ReadonlyArray, model: string | null | undefined, - prompt: string, + promptUltrathink: PromptUltrathink, modelOptions: ProviderOptions | null | undefined, allowPromptInjectedEffort: boolean, planModeEnabled: boolean, @@ -144,11 +155,11 @@ function getSelectedTraits( const thinkingDescriptor = booleanDescriptors.find((descriptor) => descriptor.id === "thinking") ?? null; - const { ultrathinkPromptControlled, ultrathinkInBodyText } = getPromptControlledTraits( - descriptors, - prompt, - allowPromptInjectedEffort, - ); + const ultrathinkPromptControlled = + allowPromptInjectedEffort && + (primarySelectDescriptor?.promptInjectedValues?.length ?? 0) > 0 && + promptUltrathink !== "none"; + const ultrathinkInBodyText = ultrathinkPromptControlled && promptUltrathink === "body"; const effort = (ultrathinkPromptControlled ? "ultrathink" @@ -186,7 +197,7 @@ function getTraitsSectionVisibility(input: { provider: ProviderDriverKind; models: ReadonlyArray; model: string | null | undefined; - prompt: string; + promptUltrathink?: PromptUltrathink | undefined; modelOptions: ProviderOptions | null | undefined; allowPromptInjectedEffort?: boolean; planModeEnabled: boolean; @@ -195,7 +206,7 @@ function getTraitsSectionVisibility(input: { input.provider, input.models, input.model, - input.prompt, + input.promptUltrathink ?? "none", input.modelOptions, input.allowPromptInjectedEffort ?? true, input.planModeEnabled, @@ -244,7 +255,7 @@ export function getReasoningTraitStep(input: { input.provider, input.models, input.model, - input.prompt, + readPromptUltrathink(input.prompt), input.modelOptions, true, input.planModeEnabled, @@ -291,7 +302,7 @@ export function shouldRenderTraitsControls(input: { provider: ProviderDriverKind; models: ReadonlyArray; model: string | null | undefined; - prompt: string; + promptUltrathink?: PromptUltrathink | undefined; modelOptions: ProviderOptions | null | undefined; allowPromptInjectedEffort?: boolean; planModeEnabled: boolean; @@ -304,8 +315,9 @@ export interface TraitsMenuContentProps { instanceId?: ProviderInstanceId; models: ReadonlyArray; model: string | null | undefined; - prompt: string; - onPromptChange: (prompt: string) => void; + promptUltrathink?: PromptUltrathink | undefined; + /** Receives an edit of the live prompt; the picker never holds the prompt text itself. */ + onPromptEdit?: (edit: (prompt: string) => string) => void; modelOptions?: ProviderOptions | null | undefined; reportedModelSelection?: ModelSelection | null | undefined; allowPromptInjectedEffort?: boolean; @@ -319,8 +331,8 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ instanceId, models, model, - prompt, - onPromptChange, + promptUltrathink, + onPromptEdit, modelOptions, reportedModelSelection, allowPromptInjectedEffort = true, @@ -349,7 +361,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ provider, models, model, - prompt, + promptUltrathink, modelOptions, allowPromptInjectedEffort, planModeEnabled, @@ -372,9 +384,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ descriptor: Extract, value: string, ) => { - const change = getTraitSelectChange(selected, descriptor, prompt, value); + // Whether a pick applies, and the options it writes, do not depend on the prompt text. + const change = getTraitSelectChange(selected, descriptor, "", value); if (!change) return; - if (change.prompt !== prompt) onPromptChange(change.prompt); + onPromptEdit?.( + (prompt) => getTraitSelectChange(selected, descriptor, prompt, value)?.prompt ?? prompt, + ); if ("modelOptions" in change) updateModelOptions(change.modelOptions); }; @@ -500,8 +515,8 @@ export const TraitsPicker = memo(function TraitsPicker({ instanceId, models, model, - prompt, - onPromptChange, + promptUltrathink, + onPromptEdit, modelOptions, reportedModelSelection, allowPromptInjectedEffort = true, @@ -525,7 +540,7 @@ export const TraitsPicker = memo(function TraitsPicker({ provider, models, model, - prompt, + promptUltrathink, modelOptions, allowPromptInjectedEffort, planModeEnabled, @@ -535,7 +550,7 @@ export const TraitsPicker = memo(function TraitsPicker({ provider, models, model, - prompt, + promptUltrathink, modelOptions, allowPromptInjectedEffort, planModeEnabled, @@ -611,8 +626,8 @@ export const TraitsPicker = memo(function TraitsPicker({ {...(instanceId ? { instanceId } : {})} models={models} model={model} - prompt={prompt} - onPromptChange={onPromptChange} + promptUltrathink={promptUltrathink} + {...(onPromptEdit ? { onPromptEdit } : {})} modelOptions={modelOptions} reportedModelSelection={reportedModelSelection} allowPromptInjectedEffort={allowPromptInjectedEffort} diff --git a/apps/web/src/components/chat/composerProviderState.test.tsx b/apps/web/src/components/chat/composerProviderState.test.tsx index f7f15d5bf6c32..0eb67d6daae8d 100644 --- a/apps/web/src/components/chat/composerProviderState.test.tsx +++ b/apps/web/src/components/chat/composerProviderState.test.tsx @@ -11,6 +11,7 @@ import { getComposerReasoningStep, withImplicitFastModeDefault, } from "./composerProviderState"; +import { readPromptUltrathink } from "./TraitsPicker"; const PROVIDER: ProviderDriverKind = ProviderDriverKind.make("codex"); const MODEL = "test-model"; @@ -238,6 +239,15 @@ describe("withImplicitFastModeDefault", () => { }); }); +describe("readPromptUltrathink", () => { + it("tells the Ultrathink prefix apart from the word in the body", () => { + expect(readPromptUltrathink("Fix the bug")).toBe("none"); + expect(readPromptUltrathink("Ultrathink: Fix the bug")).toBe("prefix"); + expect(readPromptUltrathink("ultrathink about the bug")).toBe("body"); + expect(readPromptUltrathink("Ultrathink: ultrathink harder")).toBe("body"); + }); +}); + describe("getComposerReasoningStep", () => { const LEVELS = [ { id: "low", label: "Low" }, diff --git a/apps/web/src/components/chat/composerProviderState.tsx b/apps/web/src/components/chat/composerProviderState.tsx index 5944b431e5108..85f725fce2b22 100644 --- a/apps/web/src/components/chat/composerProviderState.tsx +++ b/apps/web/src/components/chat/composerProviderState.tsx @@ -24,6 +24,7 @@ import { shouldRenderTraitsControls, TraitsMenuContent, TraitsPicker, + type PromptUltrathink, } from "./TraitsPicker"; export type ComposerProviderStateInput = { @@ -55,8 +56,8 @@ type TraitsRenderInput = { models: ReadonlyArray; modelOptions: ReadonlyArray | undefined; reportedModelSelection?: ModelSelection | null | undefined; - prompt: string; - onPromptChange: (prompt: string) => void; + promptUltrathink: PromptUltrathink; + onPromptEdit: (edit: (prompt: string) => string) => void; planModeEnabled: boolean; size?: ComposerControlSize; hidden?: boolean; @@ -230,8 +231,8 @@ function renderTraitsControl( models, modelOptions, reportedModelSelection, - prompt, - onPromptChange, + promptUltrathink, + onPromptEdit, planModeEnabled, size, hidden, @@ -253,7 +254,7 @@ function renderTraitsControl( models, model, modelOptions: resolvedModelOptions, - prompt, + promptUltrathink, planModeEnabled, }) ) { @@ -269,8 +270,8 @@ function renderTraitsControl( model={model} modelOptions={resolvedModelOptions} reportedModelSelection={reportedModelSelection} - prompt={prompt} - onPromptChange={onPromptChange} + promptUltrathink={promptUltrathink} + onPromptEdit={onPromptEdit} planModeEnabled={planModeEnabled} {...(size !== undefined ? { size } : {})} {...(hidden !== undefined ? { hidden } : {})} diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 2a66452edf9bb..184b66256dce3 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -191,8 +191,6 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting provider={activeEntry.driverKind} models={activeEntry.models} model={selection.model} - prompt="" - onPromptChange={() => {}} modelOptions={selection.options ?? []} allowPromptInjectedEffort={false} planModeEnabled={settings.planModeEnabled} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 5e9797f21d098..649f26ee1e7ff 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -1869,8 +1869,6 @@ export function GeneralSettingsPanel() { provider={textGenProvider} models={textGenInstanceEntry?.models ?? []} model={textGenModel} - prompt="" - onPromptChange={() => {}} modelOptions={textGenModelOptions} allowPromptInjectedEffort={false} planModeEnabled={ diff --git a/apps/web/src/components/settings/SourceControlWritingSettings.tsx b/apps/web/src/components/settings/SourceControlWritingSettings.tsx index 3c76207c4816b..99db9a118db71 100644 --- a/apps/web/src/components/settings/SourceControlWritingSettings.tsx +++ b/apps/web/src/components/settings/SourceControlWritingSettings.tsx @@ -397,8 +397,6 @@ export function SourceControlWritingSettingsSection() { provider={writerInstanceEntry.driverKind} models={writerInstanceEntry.models} model={activeSelection.model} - prompt="" - onPromptChange={() => {}} modelOptions={activeSelection.options ?? []} allowPromptInjectedEffort={false} planModeEnabled={ @@ -503,8 +501,6 @@ export function SourceControlWritingSettingsSection() { provider={reviewGuideInstanceEntry.driverKind} models={reviewGuideInstanceEntry.models} model={reviewGuideSelection.model} - prompt="" - onPromptChange={() => {}} modelOptions={reviewGuideSelection.options ?? []} allowPromptInjectedEffort={false} planModeEnabled={ From 22fd2aca1fcfc4d9d45fa7352796dc6a8d8b95a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 13:23:39 -0700 Subject: [PATCH 02/83] refactor(web): the composer's layout and provider hooks live in their own files (#23042) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 950 +----------------- .../chat/ComposerCommandMenuLayer.tsx | 94 ++ .../components/chat/useComposerImageGroups.ts | 40 + .../chat/useComposerProviderModel.ts | 100 ++ .../chat/useComposerRestingTransition.ts | 526 ++++++++++ .../useProviderWorkspaceSnapshotRefresh.ts | 137 +++ .../chat/useRestingComposerControlsLayout.ts | 84 ++ 7 files changed, 987 insertions(+), 944 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerCommandMenuLayer.tsx create mode 100644 apps/web/src/components/chat/useComposerImageGroups.ts create mode 100644 apps/web/src/components/chat/useComposerProviderModel.ts create mode 100644 apps/web/src/components/chat/useComposerRestingTransition.ts create mode 100644 apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts create mode 100644 apps/web/src/components/chat/useRestingComposerControlsLayout.ts diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 18eea30efb314..03c9a49875433 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -41,7 +41,6 @@ import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, - PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; @@ -67,7 +66,6 @@ import { useLayoutEffect, useRef, useState, - useSyncExternalStore, } from "react"; import { createPortal, flushSync } from "react-dom"; import { @@ -91,7 +89,6 @@ import { getAntigravitySendBlockReason, readFileAsDataUrl, resolveComposerInteractionMode, - resolveComposerProviderSelection, threadShellHasStarted, } from "../ChatView.logic"; import { @@ -116,8 +113,6 @@ import { hydrateImagesFromPersisted, useComposerDraftStore, useComposerThreadDraft, - deriveEffectiveComposerModelState, - useComposerDraftModelState, } from "../../composerDraftStore"; import { MAX_STASH_ENTRIES, @@ -189,13 +184,10 @@ import { toKindScopedComposerContextId, } from "@t3tools/shared/composerContextReferences"; import { - resolveRestingComposerControlsLayout, - shouldAnimateComposerRestingTransition, shouldUseCompactComposerPrimaryActions, shouldUseCompactComposerFooter, shouldUseRestingComposerLayout, } from "../composerFooterLayout"; -import { measureRestingComposerControls } from "./restingComposerControlsMeasurement"; import { type ComposerCitationCommentRequest, type ComposerPromptEditorHandle, @@ -285,7 +277,6 @@ import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic"; import { getComposerPromptInjectionState, - getComposerProviderState, getComposerReasoningStep, renderProviderTraitsMenuContent, renderProviderTraitsPicker, @@ -301,11 +292,6 @@ import { buildExpandedImagePreview, type ExpandedImagePreview, } from "./ExpandedImagePreview"; -import { - getPendingSnapShotAnimations, - pendingSnapShotAnimationIdsForTarget, - subscribeToPendingSnapShotAnimations, -} from "../../lib/snapShotAnimation"; import { resizeSnapShotSource } from "../../lib/snapShotSource"; import { cn, isMacPlatform, randomUUID } from "~/lib/utils"; import { @@ -329,631 +315,14 @@ import { } from "./composerScrollGesture"; import { observeResize } from "~/lib/observeResize"; -type ComposerCommandMenuPosition = { - bottom: number; - left: number; - maxHeight: number; - width: number; -}; - const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24; const COMPOSER_SCROLL_GESTURE_RESET_MS = 120; -const COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS = 50; -const COMPOSER_RESTING_TRANSITION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)"; -const COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX = 4; - -function useComposerRestingTransition( - isCollapsed: boolean, - isResting: boolean, - restingControlsRef: React.RefObject, - onOverlayHeightChange: (height: number) => void, - animationsActive: boolean, - animationDurationMs: number, -) { - const elementRef = useRef(null); - const isCollapsedRef = useRef(isCollapsed); - const previousCollapsedRef = useRef(isCollapsed); - const previousRestingRef = useRef(isResting); - const previousHeightRef = useRef(null); - const previousModelStripHeightRef = useRef(null); - const previousContentOffsetsRef = useRef<{ - promptFromTop: number | null; - promptHeight: number | null; - actionFromBottom: number | null; - controlsFromBottom: number | null; - controlsFromLeft: number | null; - surfaceBottomInset: number | null; - }>({ - promptFromTop: null, - promptHeight: null, - actionFromBottom: null, - controlsFromBottom: null, - controlsFromLeft: null, - surfaceBottomInset: null, - }); - const animationRef = useRef(null); - const animationTargetHeightRef = useRef(null); - const contentAnimationsRef = useRef([]); - const stateChangeAnimationsRef = useRef([]); - const pinnedOverlayRef = useRef(null); - const transitionCleanupTimeoutRef = useRef(null); - const transitionLayoutRequestRef = useRef(0); - const hasCompletedInitialLayoutRef = useRef(false); - - const clearOverlayPin = () => { - // The overlay belongs to the chat view and outlives this composer, so it - // is remembered from pin time rather than re-resolved through a ref that - // React may already have detached during unmount. - const overlay = pinnedOverlayRef.current; - pinnedOverlayRef.current = null; - overlay?.style.removeProperty("height"); - overlay?.style.removeProperty("display"); - overlay?.style.removeProperty("flex-direction"); - overlay?.style.removeProperty("justify-content"); - }; - - const clearTransitionStyles = () => { - const element = elementRef.current; - const footer = element?.querySelector('[data-chat-composer-footer="true"]'); - element?.style.removeProperty("overflow"); - element?.style.removeProperty("clip-path"); - element?.style.removeProperty("overflow-clip-margin"); - element - ?.querySelector('[data-chat-composer-surface="true"]') - ?.style.removeProperty("height"); - footer?.style.removeProperty("position"); - footer?.style.removeProperty("top"); - footer?.style.removeProperty("bottom"); - footer?.style.removeProperty("left"); - footer?.style.removeProperty("right"); - footer?.style.removeProperty("height"); - const shell = element?.closest('[data-slot="composer-shell"]'); - shell?.removeAttribute("data-model-strip-transition"); - const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); - for (const property of [ - "position", - "top", - "visibility", - "height", - "min-height", - "padding-top", - "align-items", - "z-index", - "pointer-events", - ]) { - modelStrip?.style.removeProperty(property); - } - clearOverlayPin(); - }; - - useLayoutEffect(() => { - isCollapsedRef.current = isCollapsed; - }); - - const transitionToCurrentGeometry = (stateChanged: boolean) => { - const element = elementRef.current; - const surface = element?.querySelector('[data-chat-composer-surface="true"]'); - if (!element || !surface) return; - - const nextIsCollapsed = isCollapsedRef.current; - - const visibleTransitionElement = (selector: string) => - Array.from(element.querySelectorAll(selector)).find( - (candidate) => candidate.getClientRects().length > 0, - ) ?? null; - const prompt = visibleTransitionElement( - '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', - ); - const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]'); - const footer = element.querySelector('[data-chat-composer-footer="true"]'); - const continuousControls = - element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true"; - const controls = nextIsCollapsed - ? restingControlsRef.current - : element.querySelector('[data-chat-composer-controls="left"]'); - - const shell = element.closest('[data-slot="composer-shell"]'); - const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); - const interruptedStripHeight = - animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null; - const interruptedAnimation = animationRef.current; - const interruptedPromptTop = interruptedAnimation - ? (prompt?.getBoundingClientRect().top ?? null) - : null; - const interruptedActionTop = interruptedAnimation - ? (action?.getBoundingClientRect().top ?? null) - : null; - const interruptedControlsLeft = interruptedAnimation - ? (controls?.getBoundingClientRect().left ?? null) - : null; - const interruptedControlsTop = interruptedAnimation - ? (controls?.getBoundingClientRect().top ?? null) - : null; - const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null; - const interruptedTargetHeight = animationTargetHeightRef.current; - const interruptedCurrentTime = - typeof interruptedAnimation?.currentTime === "number" - ? interruptedAnimation.currentTime - : null; - const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration; - if (transitionCleanupTimeoutRef.current !== null) { - window.clearTimeout(transitionCleanupTimeoutRef.current); - transitionCleanupTimeoutRef.current = null; - } - interruptedAnimation?.cancel(); - animationRef.current = null; - for (const animation of contentAnimationsRef.current) animation.cancel(); - contentAnimationsRef.current = []; - if (stateChanged) { - for (const animation of stateChangeAnimationsRef.current) animation.cancel(); - stateChangeAnimationsRef.current = []; - } - clearTransitionStyles(); - - const nextRect = element.getBoundingClientRect(); - const nextHeight = nextRect.height; - const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null; - // The chat view resize-observes the overlay to place the timeline - // inset, the scroll-to-end pill, and the mini player. Publishing the - // destination height here turns that feedback into one update instead - // of a ChatView re-render on every animation frame. - const overlay = element.closest('[data-chat-composer-overlay="true"]'); - const overlayRect = overlay?.getBoundingClientRect(); - const overlayHeight = overlayRect?.height ?? null; - if (overlayHeight !== null) { - onOverlayHeightChange(overlayHeight); - } - const nextPromptRect = prompt?.getBoundingClientRect() ?? null; - const nextPromptTop = nextPromptRect?.top ?? null; - const nextActionTop = action?.getBoundingClientRect().top ?? null; - const nextControlsRect = controls?.getBoundingClientRect() ?? null; - const nextControlsTop = nextControlsRect?.top ?? null; - const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1; - const previousHeight = interruptedHeight ?? previousHeightRef.current; - const targetChanged = - interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5; - const shouldAnimate = shouldAnimateComposerRestingTransition({ - hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current, - stateChanged, - hasInterruptedAnimation: interruptedHeight !== null, - }); - - if ( - shouldAnimate && - animationsActive && - previousHeight !== null && - Math.abs(previousHeight - nextHeight) >= 0.5 - ) { - const remainingDuration = - typeof interruptedDuration === "number" && interruptedCurrentTime !== null - ? Math.max(1, interruptedDuration - interruptedCurrentTime) - : animationDurationMs; - const duration = - interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs; - element.style.overflow = "clip"; - if (modelStrip) { - const controlsClearance = Math.max( - nextModelStripHeight ?? 0, - previousModelStripHeightRef.current ?? 0, - ); - element.style.overflowClipMargin = `${controlsClearance}px`; - element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`; - } - surface.style.height = "100%"; - - if (overlay && overlayHeight !== null) { - overlay.style.height = `${String(overlayHeight)}px`; - overlay.style.display = "flex"; - overlay.style.flexDirection = "column"; - overlay.style.justifyContent = "flex-end"; - pinnedOverlayRef.current = overlay; - } - - if (footer) { - footer.style.position = "absolute"; - footer.style.top = "auto"; - footer.style.bottom = `${String(footerBottom)}px`; - footer.style.height = "3rem"; - if (nextIsCollapsed) { - footer.style.left = "auto"; - footer.style.right = "1px"; - } else { - footer.style.left = "1px"; - footer.style.right = "1px"; - } - } - - let stripAnimation: Animation | null = null; - if (modelStrip) { - const stripHeight = modelStrip.getBoundingClientRect().height; - const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop); - const fromHeight = - interruptedStripHeight ?? - (previousCollapsedRef.current - ? (previousModelStripHeightRef.current ?? stripHeight) - : stripOverlap); - const toHeight = nextIsCollapsed ? stripHeight : stripOverlap; - modelStrip.style.position = "relative"; - modelStrip.style.top = "auto"; - modelStrip.style.visibility = "visible"; - modelStrip.style.minHeight = "0"; - modelStrip.style.paddingTop = "0"; - modelStrip.style.alignItems = "flex-end"; - modelStrip.style.pointerEvents = "none"; - modelStrip.style.zIndex = "20"; - shell?.setAttribute("data-model-strip-transition", "true"); - stripAnimation = modelStrip.animate( - [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }], - { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" }, - ); - } - - const animation = element.animate( - [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }], - { - duration, - easing: COMPOSER_RESTING_TRANSITION_EASING, - fill: "both", - }, - ); - animationRef.current = animation; - animationTargetHeightRef.current = nextHeight; - - const animatedRect = element.getBoundingClientRect(); - const previousBottom = - overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null - ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset - : animatedRect.bottom; - const bottomShift = previousBottom - animatedRect.bottom; - const previousPromptTop = - interruptedPromptTop ?? - (previousContentOffsetsRef.current.promptFromTop === null - ? null - : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop); - const previousActionTop = - interruptedActionTop ?? - (previousContentOffsetsRef.current.actionFromBottom === null - ? null - : previousBottom - previousContentOffsetsRef.current.actionFromBottom); - const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : []; - const animateContentPosition = ( - content: HTMLElement | null, - previousTop: number | null, - previousLeft: number | null = null, - ) => { - if (!content || previousTop === null) return; - const rect = content.getBoundingClientRect(); - const offset = previousTop - rect.top; - const offsetX = previousLeft === null ? 0 : previousLeft - rect.left; - if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return; - contentAnimations.push( - content.animate( - [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }], - { - duration, - easing: COMPOSER_RESTING_TRANSITION_EASING, - }, - ), - ); - }; - animateContentPosition(prompt, previousPromptTop); - animateContentPosition(action, previousActionTop); - if (continuousControls) { - const previousControlsTop = - interruptedControlsTop ?? - (previousContentOffsetsRef.current.controlsFromBottom === null - ? null - : previousBottom - previousContentOffsetsRef.current.controlsFromBottom); - const previousControlsLeft = - interruptedControlsLeft ?? - (previousContentOffsetsRef.current.controlsFromLeft === null - ? null - : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft); - animateContentPosition(controls, previousControlsTop, previousControlsLeft); - } - contentAnimationsRef.current = contentAnimations; - - if (stateChanged) { - const stateChangeAnimations: Animation[] = []; - - const previousPromptHeight = previousContentOffsetsRef.current.promptHeight; - if ( - !nextIsCollapsed && - prompt && - nextPromptRect && - previousPromptHeight !== null && - nextPromptRect.height - previousPromptHeight >= 0.5 - ) { - const hiddenHeight = nextPromptRect.height - previousPromptHeight; - stateChangeAnimations.push( - prompt.animate( - [ - { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` }, - { clipPath: "inset(0 0 0 0)" }, - ], - { - duration, - easing: COMPOSER_RESTING_TRANSITION_EASING, - }, - ), - ); - } - - const arrivingControls = nextIsCollapsed - ? restingControlsRef.current - : element.querySelector('[data-chat-composer-controls="left"]'); - if (arrivingControls && !continuousControls) { - const drift = nextIsCollapsed - ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX - : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX; - stateChangeAnimations.push( - arrivingControls.animate( - [ - { opacity: 0, transform: `translateY(${String(drift)}px)` }, - { opacity: 1, transform: "none" }, - ], - { - duration: nextIsCollapsed ? duration : duration / 2, - delay: nextIsCollapsed ? 0 : duration / 2, - fill: "backwards", - easing: COMPOSER_RESTING_TRANSITION_EASING, - }, - ), - ); - } - - const arrivingImagePreviews = nextIsCollapsed - ? Array.from( - element.querySelectorAll('[data-chat-composer-resting-images="true"]'), - ) - : Array.from( - element.querySelectorAll('[data-chat-composer-expanded-image="true"]'), - ); - for (const imagePreview of arrivingImagePreviews) { - stateChangeAnimations.push( - imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], { - duration: nextIsCollapsed ? duration : duration / 2, - delay: nextIsCollapsed ? 0 : duration / 2, - fill: "backwards", - easing: COMPOSER_RESTING_TRANSITION_EASING, - }), - ); - } - stateChangeAnimationsRef.current = stateChangeAnimations; - } - - const finishTransition = (cancelAnimations: boolean) => { - if (animationRef.current !== animation) return; - if (transitionCleanupTimeoutRef.current !== null) { - window.clearTimeout(transitionCleanupTimeoutRef.current); - transitionCleanupTimeoutRef.current = null; - } - if (cancelAnimations) { - animation.cancel(); - for (const contentAnimation of contentAnimationsRef.current) { - contentAnimation.cancel(); - } - for (const stateChangeAnimation of stateChangeAnimationsRef.current) { - stateChangeAnimation.cancel(); - } - } - animationRef.current = null; - animationTargetHeightRef.current = null; - contentAnimationsRef.current = []; - stateChangeAnimationsRef.current = []; - animation.cancel(); - stripAnimation?.cancel(); - clearTransitionStyles(); - }; - void animation.finished.catch(() => undefined).then(() => finishTransition(false)); - // A suspended document timeline can leave `finished` pending while - // these measurement styles remain active. Wall-clock cleanup makes - // the natural layout the eventual source of truth in that case. - transitionCleanupTimeoutRef.current = window.setTimeout( - () => finishTransition(true), - duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS, - ); - } else { - animationTargetHeightRef.current = null; - } - - previousCollapsedRef.current = nextIsCollapsed; - previousHeightRef.current = nextHeight; - previousModelStripHeightRef.current = nextModelStripHeight; - previousContentOffsetsRef.current = { - promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top, - promptHeight: nextPromptRect?.height ?? null, - actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop, - controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop, - controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left, - surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null, - }; - }; - - useLayoutEffect(() => { - const requestId = transitionLayoutRequestRef.current + 1; - transitionLayoutRequestRef.current = requestId; - const stateChanged = previousCollapsedRef.current !== isCollapsed; - // A non-Git context strip enters or leaves flow through ChatView state in - // an earlier layout effect. Let React flush that parent update before the - // FLIP reads its destination geometry, while still running before paint. - queueMicrotask(() => { - if (transitionLayoutRequestRef.current !== requestId) return; - transitionToCurrentGeometry(stateChanged); - }); - return () => { - if (transitionLayoutRequestRef.current === requestId) { - transitionLayoutRequestRef.current += 1; - } - }; - }, [isCollapsed, transitionToCurrentGeometry]); - - useLayoutEffect(() => { - if (previousRestingRef.current === isResting) return; - previousRestingRef.current = isResting; - if (animationRef.current) return; - const overlay = elementRef.current?.closest('[data-chat-composer-overlay="true"]'); - if (overlay) onOverlayHeightChange(overlay.getBoundingClientRect().height); - }, [isResting, onOverlayHeightChange]); - - useLayoutEffect(() => { - const element = elementRef.current; - if (!element) return; - - const body = element.querySelector('[data-chat-composer-body="true"]'); - return observeResize(body ? [element, body] : element, (entries) => { - if (animationRef.current) { - if (body && entries.some((entry) => entry.target === body)) { - transitionToCurrentGeometry(false); - } - return; - } - const elementRect = element.getBoundingClientRect(); - const visibleTransitionElement = (selector: string) => - Array.from(element.querySelectorAll(selector)).find( - (candidate) => candidate.getClientRects().length > 0, - ) ?? null; - const promptRect = visibleTransitionElement( - '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', - )?.getBoundingClientRect(); - const actionTop = visibleTransitionElement( - '[data-chat-composer-transition-actions="true"]', - )?.getBoundingClientRect().top; - const controlsRect = ( - isCollapsedRef.current - ? restingControlsRef.current - : visibleTransitionElement('[data-chat-composer-controls="left"]') - )?.getBoundingClientRect(); - previousHeightRef.current = elementRect.height; - previousContentOffsetsRef.current = { - promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top, - promptHeight: promptRect?.height ?? null, - actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop, - controlsFromBottom: - controlsRect === undefined ? null : elementRect.bottom - controlsRect.top, - controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left, - surfaceBottomInset: - (element - .closest('[data-chat-composer-overlay="true"]') - ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom, - }; - }); - }, [restingControlsRef, transitionToCurrentGeometry]); - - useEffect(() => { - hasCompletedInitialLayoutRef.current = true; - return () => { - if (transitionCleanupTimeoutRef.current !== null) { - window.clearTimeout(transitionCleanupTimeoutRef.current); - transitionCleanupTimeoutRef.current = null; - } - animationRef.current?.cancel(); - animationRef.current = null; - animationTargetHeightRef.current = null; - for (const animation of contentAnimationsRef.current) animation.cancel(); - contentAnimationsRef.current = []; - for (const animation of stateChangeAnimationsRef.current) animation.cancel(); - stateChangeAnimationsRef.current = []; - clearTransitionStyles(); - }; - }, [clearTransitionStyles]); - - return elementRef; -} - -function composerCommandMenuPositionsEqual( - a: ComposerCommandMenuPosition, - b: ComposerCommandMenuPosition, -): boolean { - return ( - a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width - ); -} - -function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) { - const [position, setPosition] = useState(null); - - useLayoutEffect(() => { - const anchor = props.anchor; - if (!anchor) return; - - const updatePosition = () => { - const form = anchor.closest('[data-chat-composer-form="true"]'); - const mainSurface = form?.querySelector( - '[data-chat-composer-main-surface="true"]', - ); - const rect = (mainSurface ?? form ?? anchor).getBoundingClientRect(); - const rootFontSizePx = - Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16; - const drawerInsetRem = Number.parseFloat( - window.getComputedStyle(form ?? anchor).getPropertyValue("--chat-composer-drawer-inset"), - ); - const drawerInset = drawerInsetRem * rootFontSizePx; - const width = rect.width - drawerInset * 2; - if (width <= 0) { - setPosition(null); - return; - } - const composerOverlap = rootFontSizePx + 1; - const next = { - bottom: window.innerHeight - rect.top - composerOverlap, - left: rect.left + drawerInset, - maxHeight: Math.max(96, rect.top - 24 + composerOverlap), - width, - }; - setPosition((current) => - current && composerCommandMenuPositionsEqual(current, next) ? current : next, - ); - }; - - updatePosition(); - window.addEventListener("resize", updatePosition); - window.addEventListener("scroll", updatePosition, true); - - const observed: Element[] = [anchor]; - for (let element = anchor.parentElement; element; element = element.parentElement) { - observed.push(element); - } - const stopObserving = observeResize(observed, updatePosition); - - return () => { - stopObserving(); - window.removeEventListener("resize", updatePosition); - window.removeEventListener("scroll", updatePosition, true); - }; - }, [props.anchor]); - - if (!props.anchor || !position) return null; - - return createPortal( -
- {props.children} -
, - document.body, - ); -} import { toastManager } from "../ui/toast"; import { CircleAlertIcon, PlayIcon, ShieldIcon } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { hasProviderSetup } from "./ProviderStatusBanner"; -import { - applyProviderInstanceSettings, - deriveProviderInstanceEntries, - NO_PROVIDER_MODEL_SELECTION, - sortProviderInstanceEntries, - type ProviderInstanceEntry, -} from "../../providerInstances"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; import { @@ -981,8 +350,6 @@ import { } from "@t3tools/client-runtime/state/composer-dispatch"; import type { ContextWindowSnapshot } from "../../lib/contextWindow"; import { - hasCompleteProviderWorkspaceSnapshot, - hasCurrentProviderWorkspaceSnapshot, resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "@t3tools/client-runtime/providerSkills"; @@ -993,10 +360,13 @@ import { useStableCallback } from "../../hooks/useStableCallback"; import { usePanelAnimationSettings } from "../../panelAnimations"; import { useAtomCommand } from "../../state/use-atom-command"; import { readEnvironmentScope } from "../../state/session"; -import { serverEnvironment } from "../../state/server"; import type { ReviewCommentContext } from "../../reviewCommentContext"; - -const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000; +import { useComposerRestingTransition } from "./useComposerRestingTransition"; +import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer"; +import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout"; +import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh"; +import { useComposerProviderModel } from "./useComposerProviderModel"; +import { useComposerImageGroups } from "./useComposerImageGroups"; /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -1025,83 +395,6 @@ const extendReplacementRangeForTrailingSpace = ( return text[rangeEnd] === " " ? rangeEnd + 1 : rangeEnd; }; -function useRestingComposerControlsLayout(host: HTMLDivElement | null, useControlsAsHost = false) { - const [controls, setControls] = useState(null); - const controlsRef = useRef(null); - const attachControls = (element: HTMLDivElement | null) => { - controlsRef.current = element; - setControls(element); - }; - const [layout, setLayout] = useState<{ - hiddenCount: number; - iconOnlyCount?: number; - visible: boolean; - }>({ hiddenCount: 0, visible: true }); - - const measure = () => { - const currentHost = useControlsAsHost ? controls : host; - if (currentHost === null || !controls) return; - - const measurement = measureRestingComposerControls(controls); - if (!measurement) return; - const style = getComputedStyle(currentHost); - const hostWidth = - currentHost.clientWidth - - (Number.parseFloat(style.paddingInlineStart) || 0) - - (Number.parseFloat(style.paddingInlineEnd) || 0); - - setLayout((current) => { - const next = resolveRestingComposerControlsLayout({ - ...measurement, - hostWidth, - previous: current, - }); - return next.hiddenCount === current.hiddenCount && - next.iconOnlyCount === current.iconOnlyCount && - next.visible === current.visible - ? current - : next; - }); - }; - - useLayoutEffect(() => { - const currentHost = useControlsAsHost ? controls : host; - if (!currentHost || !controls) return; - let stopObserving = () => {}; - const observeControls = () => { - stopObserving(); - stopObserving = observeResize( - [ - currentHost, - controls, - ...controls.querySelectorAll( - "[data-resting-block], [data-composer-control-label], [data-chat-provider-model-picker-label]", - ), - ], - measure, - ); - measure(); - }; - observeControls(); - const mutations = new MutationObserver(observeControls); - mutations.observe(controls, { childList: true, subtree: true, characterData: true }); - document.fonts.addEventListener("loadingdone", measure); - return () => { - stopObserving(); - mutations.disconnect(); - document.fonts.removeEventListener("loadingdone", measure); - }; - }, [host, controls, useControlsAsHost, measure]); - - return { - controlsRef, - attachControls, - hiddenBlockCount: layout.hiddenCount, - iconOnlyBlockCount: layout.iconOnlyCount ?? 0, - controlsVisible: layout.visible, - }; -} - const runtimeModeOptions = runtimeModes.map((mode) => ({ mode, ...runtimeModeConfig[mode] })); export interface ChatComposerHandle { @@ -1330,237 +623,6 @@ export interface ChatComposerProps { onFileOpen: (attachment: ChatFileAttachment) => void; } -/** - * Keeps the selected provider's workspace snapshot fresh for the composer's - * cwd. Returns a check to run when the user types. - */ -function useProviderWorkspaceSnapshotRefresh(input: { - readonly environmentId: EnvironmentId; - readonly gitCwd: string | null; - readonly selectedProviderEntry: ProviderInstanceEntry | undefined; - readonly selectedProviderStatus: ServerProvider | null; -}) { - const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input; - const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { - reportFailure: false, - }); - // The last scan this composer asked for. A request inside the TTL is not - // repeated, so a client clock ahead of the server's cannot loop rescans. - const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null); - const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{ - key: string; - notBefore: number; - } | null>(null); - const workspaceRefreshScopeKey = - gitCwd && selectedProviderEntry - ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}` - : null; - const workspaceSlashCommandsPending = - selectedProviderStatus?.workspaceSnapshots?.some( - (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true, - ) ?? false; - useEffect(() => { - if ( - !workspaceSlashCommandsPending || - !workspaceRefreshRetry || - workspaceRefreshRetry.key !== workspaceRefreshScopeKey - ) - return; - const timeout = setTimeout( - () => { - setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current)); - }, - Math.max(0, workspaceRefreshRetry.notBefore - Date.now()), - ); - return () => clearTimeout(timeout); - }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]); - // Losing a snapshot (the server dropped it) lifts both the TTL and the retry - // cooldown so the next check rescans at once. - const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd); - const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot); - const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0); - if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) { - setHadWorkspaceSnapshot(hasWorkspaceSnapshot); - if (!hasWorkspaceSnapshot) { - setWorkspaceSnapshotLossCount((count) => count + 1); - setWorkspaceRefreshRetry(null); - } - } - const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount); - const refreshWorkspaceSnapshotIfStale = ( - now: number, - key: string | null, - retry: { key: string; notBefore: number } | null, - snapshotLossCount: number, - ) => { - if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) { - lastWorkspaceSnapshotLossRef.current = snapshotLossCount; - workspaceRefreshKeyRef.current = null; - } - if (key === null || !gitCwd || !selectedProviderEntry) return; - const lastRequest = workspaceRefreshKeyRef.current; - if ( - lastRequest?.key === key && - now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS - ) - return; - // A pending retry needs no clearing here: its cooldown lapses long before the TTL. - if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return; - if (retry?.key === key && now < retry.notBefore) return; - const request = { key, requestedAt: now }; - workspaceRefreshKeyRef.current = request; - const retryLater = () => { - if (workspaceRefreshKeyRef.current !== request) return; - workspaceRefreshKeyRef.current = null; - setWorkspaceRefreshRetry({ - key, - notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS, - }); - }; - void refreshProviders({ - environmentId, - input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd }, - }).then((result) => { - const refreshedSnapshot = - result._tag === "Success" && - hasCompleteProviderWorkspaceSnapshot( - result.value.providers.find( - (provider) => provider.instanceId === selectedProviderEntry.instanceId, - ), - gitCwd, - ); - if (!refreshedSnapshot) retryLater(); - }, retryLater); - }; - const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale); - useEffect(() => { - refreshWorkspaceSnapshotOnChange( - Date.now(), - workspaceRefreshScopeKey, - workspaceRefreshRetry, - workspaceSnapshotLossCount, - ); - }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]); - return useStableCallback(() => - refreshWorkspaceSnapshotIfStale( - Date.now(), - workspaceRefreshScopeKey, - workspaceRefreshRetry, - workspaceSnapshotLossCount, - ), - ); -} - -const NO_PROVIDER_MODELS: ServerProvider["models"] = []; - -/** - * The provider instances the composer offers, which one is selected, and the model and options - * the draft resolves to on it. The draft store is read first so every derivation follows the only - * hook here; in the composer body they would straddle its later hooks and lose their cache. - */ -function useComposerProviderModel( - input: Omit[0], "entries"> & { - readonly providerStatuses: ReadonlyArray; - readonly settings: UnifiedSettings; - readonly activeProjectId: ProjectId | null; - readonly threadRef: ScopedThreadRef | DraftId; - readonly threadModelSelection: ModelSelection | null | undefined; - readonly projectModelSelection: ModelSelection | null | undefined; - readonly promptInjectionState: ReturnType; - }, -) { - const { - providerStatuses, - settings, - activeProjectId, - threadRef, - threadModelSelection, - projectModelSelection, - promptInjectionState, - candidateInstanceIds, - lockedProvider, - lockedInstanceId, - } = input; - const draftModelState = useComposerDraftModelState(threadRef); - const providerInstanceEntries: ReadonlyArray = sortProviderInstanceEntries( - applyProviderInstanceSettings( - deriveProviderInstanceEntries(providerStatuses), - settings, - activeProjectId, - ), - ); - const selection = resolveComposerProviderSelection({ - entries: providerInstanceEntries, - candidateInstanceIds, - lockedProvider, - lockedInstanceId, - }); - const selectedInstanceId = - selection.selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId; - const selectedProvider: ProviderDriverKind = - selection.selectedProviderEntry?.driverKind ?? selection.requestedDriverKind; - const modelState = deriveEffectiveComposerModelState({ - draft: draftModelState, - providers: providerStatuses, - selectedProvider, - selectedInstanceId, - threadModelSelection, - projectModelSelection, - settings, - }); - const selectedProviderModels = selection.selectedProviderEntry?.models ?? NO_PROVIDER_MODELS; - const composerProviderState = getComposerProviderState({ - provider: selectedProvider, - model: modelState.selectedModel, - models: selectedProviderModels, - promptInjectionState, - modelOptions: modelState.modelOptions?.[selectedInstanceId], - planModeEnabled: settings.planModeEnabled, - }); - return { - providerInstanceEntries, - ...selection, - selectedInstanceId, - selectedProvider, - selectedProviderModels, - composerModelOptions: modelState.modelOptions, - selectedModel: modelState.selectedModel, - composerProviderState, - }; -} - -/** - * Follows the SnapShots still animating into this draft and splits the draft's images into - * pending SnapShots and standalone images. - */ -function useComposerImageGroups( - composerDraftTarget: ScopedThreadRef | DraftId, - composerImages: ReadonlyArray, - composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>, -) { - const pendingSnapShotAnimations = useSyncExternalStore( - subscribeToPendingSnapShotAnimations, - getPendingSnapShotAnimations, - getPendingSnapShotAnimations, - ); - const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget( - pendingSnapShotAnimations, - composerDraftTarget, - ); - const previewAnnotationIds = new Set( - composerPreviewAnnotations.map((annotation) => annotation.id), - ); - return { - pendingSnapShotAnimations, - pendingSnapShotIds, - pendingSnapShotIdSet: new Set(pendingSnapShotIds), - uncommittedSnapShotIds: pendingSnapShotIds.filter( - (id) => !composerImages.some((image) => image.id === id), - ), - standaloneComposerImages: composerImages.filter((image) => !previewAnnotationIds.has(image.id)), - }; -} - const NO_PROVIDER_SKILLS: ServerProvider["skills"] = []; const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; diff --git a/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx b/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx new file mode 100644 index 0000000000000..a449fc6a442af --- /dev/null +++ b/apps/web/src/components/chat/ComposerCommandMenuLayer.tsx @@ -0,0 +1,94 @@ +import { type ReactNode, useLayoutEffect, useState } from "react"; +import { createPortal } from "react-dom"; +import { observeResize } from "~/lib/observeResize"; + +type ComposerCommandMenuPosition = { + bottom: number; + left: number; + maxHeight: number; + width: number; +}; + +function composerCommandMenuPositionsEqual( + a: ComposerCommandMenuPosition, + b: ComposerCommandMenuPosition, +): boolean { + return ( + a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width + ); +} + +export function ComposerCommandMenuLayer(props: { + anchor: HTMLElement | null; + children: ReactNode; +}) { + const [position, setPosition] = useState(null); + + useLayoutEffect(() => { + const anchor = props.anchor; + if (!anchor) return; + + const updatePosition = () => { + const form = anchor.closest('[data-chat-composer-form="true"]'); + const mainSurface = form?.querySelector( + '[data-chat-composer-main-surface="true"]', + ); + const rect = (mainSurface ?? form ?? anchor).getBoundingClientRect(); + const rootFontSizePx = + Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16; + const drawerInsetRem = Number.parseFloat( + window.getComputedStyle(form ?? anchor).getPropertyValue("--chat-composer-drawer-inset"), + ); + const drawerInset = drawerInsetRem * rootFontSizePx; + const width = rect.width - drawerInset * 2; + if (width <= 0) { + setPosition(null); + return; + } + const composerOverlap = rootFontSizePx + 1; + const next = { + bottom: window.innerHeight - rect.top - composerOverlap, + left: rect.left + drawerInset, + maxHeight: Math.max(96, rect.top - 24 + composerOverlap), + width, + }; + setPosition((current) => + current && composerCommandMenuPositionsEqual(current, next) ? current : next, + ); + }; + + updatePosition(); + window.addEventListener("resize", updatePosition); + window.addEventListener("scroll", updatePosition, true); + + const observed: Element[] = [anchor]; + for (let element = anchor.parentElement; element; element = element.parentElement) { + observed.push(element); + } + const stopObserving = observeResize(observed, updatePosition); + + return () => { + stopObserving(); + window.removeEventListener("resize", updatePosition); + window.removeEventListener("scroll", updatePosition, true); + }; + }, [props.anchor]); + + if (!props.anchor || !position) return null; + + return createPortal( +
+ {props.children} +
, + document.body, + ); +} diff --git a/apps/web/src/components/chat/useComposerImageGroups.ts b/apps/web/src/components/chat/useComposerImageGroups.ts new file mode 100644 index 0000000000000..87342ae87f4fe --- /dev/null +++ b/apps/web/src/components/chat/useComposerImageGroups.ts @@ -0,0 +1,40 @@ +import { type ComposerImageAttachment, type DraftId } from "../../composerDraftStore"; +import { type ScopedThreadRef } from "@t3tools/contracts"; +import { + getPendingSnapShotAnimations, + pendingSnapShotAnimationIdsForTarget, + subscribeToPendingSnapShotAnimations, +} from "../../lib/snapShotAnimation"; +import { useSyncExternalStore } from "react"; + +/** + * Follows the SnapShots still animating into this draft and splits the draft's images into + * pending SnapShots and standalone images. + */ +export function useComposerImageGroups( + composerDraftTarget: ScopedThreadRef | DraftId, + composerImages: ReadonlyArray, + composerPreviewAnnotations: ReadonlyArray<{ readonly id: string }>, +) { + const pendingSnapShotAnimations = useSyncExternalStore( + subscribeToPendingSnapShotAnimations, + getPendingSnapShotAnimations, + getPendingSnapShotAnimations, + ); + const pendingSnapShotIds = pendingSnapShotAnimationIdsForTarget( + pendingSnapShotAnimations, + composerDraftTarget, + ); + const previewAnnotationIds = new Set( + composerPreviewAnnotations.map((annotation) => annotation.id), + ); + return { + pendingSnapShotAnimations, + pendingSnapShotIds, + pendingSnapShotIdSet: new Set(pendingSnapShotIds), + uncommittedSnapShotIds: pendingSnapShotIds.filter( + (id) => !composerImages.some((image) => image.id === id), + ), + standaloneComposerImages: composerImages.filter((image) => !previewAnnotationIds.has(image.id)), + }; +} diff --git a/apps/web/src/components/chat/useComposerProviderModel.ts b/apps/web/src/components/chat/useComposerProviderModel.ts new file mode 100644 index 0000000000000..24920d1593b45 --- /dev/null +++ b/apps/web/src/components/chat/useComposerProviderModel.ts @@ -0,0 +1,100 @@ +import { + type DraftId, + deriveEffectiveComposerModelState, + useComposerDraftModelState, +} from "../../composerDraftStore"; +import { + type ModelSelection, + type ProjectId, + ProviderDriverKind, + type ScopedThreadRef, + type ServerProvider, +} from "@t3tools/contracts"; +import { + NO_PROVIDER_MODEL_SELECTION, + type ProviderInstanceEntry, + applyProviderInstanceSettings, + deriveProviderInstanceEntries, + sortProviderInstanceEntries, +} from "../../providerInstances"; +import { type UnifiedSettings } from "@t3tools/contracts/settings"; +import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState"; +import { resolveComposerProviderSelection } from "../ChatView.logic"; + +const NO_PROVIDER_MODELS: ServerProvider["models"] = []; + +/** + * The provider instances the composer offers, which one is selected, and the model and options + * the draft resolves to on it. The draft store is read first so every derivation follows the only + * hook here; in the composer body they would straddle its later hooks and lose their cache. + */ +export function useComposerProviderModel( + input: Omit[0], "entries"> & { + readonly providerStatuses: ReadonlyArray; + readonly settings: UnifiedSettings; + readonly activeProjectId: ProjectId | null; + readonly threadRef: ScopedThreadRef | DraftId; + readonly threadModelSelection: ModelSelection | null | undefined; + readonly projectModelSelection: ModelSelection | null | undefined; + readonly promptInjectionState: ReturnType; + }, +) { + const { + providerStatuses, + settings, + activeProjectId, + threadRef, + threadModelSelection, + projectModelSelection, + promptInjectionState, + candidateInstanceIds, + lockedProvider, + lockedInstanceId, + } = input; + const draftModelState = useComposerDraftModelState(threadRef); + const providerInstanceEntries: ReadonlyArray = sortProviderInstanceEntries( + applyProviderInstanceSettings( + deriveProviderInstanceEntries(providerStatuses), + settings, + activeProjectId, + ), + ); + const selection = resolveComposerProviderSelection({ + entries: providerInstanceEntries, + candidateInstanceIds, + lockedProvider, + lockedInstanceId, + }); + const selectedInstanceId = + selection.selectedProviderEntry?.instanceId ?? NO_PROVIDER_MODEL_SELECTION.instanceId; + const selectedProvider: ProviderDriverKind = + selection.selectedProviderEntry?.driverKind ?? selection.requestedDriverKind; + const modelState = deriveEffectiveComposerModelState({ + draft: draftModelState, + providers: providerStatuses, + selectedProvider, + selectedInstanceId, + threadModelSelection, + projectModelSelection, + settings, + }); + const selectedProviderModels = selection.selectedProviderEntry?.models ?? NO_PROVIDER_MODELS; + const composerProviderState = getComposerProviderState({ + provider: selectedProvider, + model: modelState.selectedModel, + models: selectedProviderModels, + promptInjectionState, + modelOptions: modelState.modelOptions?.[selectedInstanceId], + planModeEnabled: settings.planModeEnabled, + }); + return { + providerInstanceEntries, + ...selection, + selectedInstanceId, + selectedProvider, + selectedProviderModels, + composerModelOptions: modelState.modelOptions, + selectedModel: modelState.selectedModel, + composerProviderState, + }; +} diff --git a/apps/web/src/components/chat/useComposerRestingTransition.ts b/apps/web/src/components/chat/useComposerRestingTransition.ts new file mode 100644 index 0000000000000..64b18b6778019 --- /dev/null +++ b/apps/web/src/components/chat/useComposerRestingTransition.ts @@ -0,0 +1,526 @@ +import { observeResize } from "~/lib/observeResize"; +import { shouldAnimateComposerRestingTransition } from "../composerFooterLayout"; +import { useEffect, useLayoutEffect, useRef } from "react"; + +const COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS = 50; +const COMPOSER_RESTING_TRANSITION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)"; +const COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX = 4; + +export function useComposerRestingTransition( + isCollapsed: boolean, + isResting: boolean, + restingControlsRef: React.RefObject, + onOverlayHeightChange: (height: number) => void, + animationsActive: boolean, + animationDurationMs: number, +) { + const elementRef = useRef(null); + const isCollapsedRef = useRef(isCollapsed); + const previousCollapsedRef = useRef(isCollapsed); + const previousRestingRef = useRef(isResting); + const previousHeightRef = useRef(null); + const previousModelStripHeightRef = useRef(null); + const previousContentOffsetsRef = useRef<{ + promptFromTop: number | null; + promptHeight: number | null; + actionFromBottom: number | null; + controlsFromBottom: number | null; + controlsFromLeft: number | null; + surfaceBottomInset: number | null; + }>({ + promptFromTop: null, + promptHeight: null, + actionFromBottom: null, + controlsFromBottom: null, + controlsFromLeft: null, + surfaceBottomInset: null, + }); + const animationRef = useRef(null); + const animationTargetHeightRef = useRef(null); + const contentAnimationsRef = useRef([]); + const stateChangeAnimationsRef = useRef([]); + const pinnedOverlayRef = useRef(null); + const transitionCleanupTimeoutRef = useRef(null); + const transitionLayoutRequestRef = useRef(0); + const hasCompletedInitialLayoutRef = useRef(false); + + const clearOverlayPin = () => { + // The overlay belongs to the chat view and outlives this composer, so it + // is remembered from pin time rather than re-resolved through a ref that + // React may already have detached during unmount. + const overlay = pinnedOverlayRef.current; + pinnedOverlayRef.current = null; + overlay?.style.removeProperty("height"); + overlay?.style.removeProperty("display"); + overlay?.style.removeProperty("flex-direction"); + overlay?.style.removeProperty("justify-content"); + }; + + const clearTransitionStyles = () => { + const element = elementRef.current; + const footer = element?.querySelector('[data-chat-composer-footer="true"]'); + element?.style.removeProperty("overflow"); + element?.style.removeProperty("clip-path"); + element?.style.removeProperty("overflow-clip-margin"); + element + ?.querySelector('[data-chat-composer-surface="true"]') + ?.style.removeProperty("height"); + footer?.style.removeProperty("position"); + footer?.style.removeProperty("top"); + footer?.style.removeProperty("bottom"); + footer?.style.removeProperty("left"); + footer?.style.removeProperty("right"); + footer?.style.removeProperty("height"); + const shell = element?.closest('[data-slot="composer-shell"]'); + shell?.removeAttribute("data-model-strip-transition"); + const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); + for (const property of [ + "position", + "top", + "visibility", + "height", + "min-height", + "padding-top", + "align-items", + "z-index", + "pointer-events", + ]) { + modelStrip?.style.removeProperty(property); + } + clearOverlayPin(); + }; + + useLayoutEffect(() => { + isCollapsedRef.current = isCollapsed; + }); + + const transitionToCurrentGeometry = (stateChanged: boolean) => { + const element = elementRef.current; + const surface = element?.querySelector('[data-chat-composer-surface="true"]'); + if (!element || !surface) return; + + const nextIsCollapsed = isCollapsedRef.current; + + const visibleTransitionElement = (selector: string) => + Array.from(element.querySelectorAll(selector)).find( + (candidate) => candidate.getClientRects().length > 0, + ) ?? null; + const prompt = visibleTransitionElement( + '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', + ); + const action = visibleTransitionElement('[data-chat-composer-transition-actions="true"]'); + const footer = element.querySelector('[data-chat-composer-footer="true"]'); + const continuousControls = + element.dataset.inlineRestingControls === "true" || element.dataset.modelOnlyStrip === "true"; + const controls = nextIsCollapsed + ? restingControlsRef.current + : element.querySelector('[data-chat-composer-controls="left"]'); + + const shell = element.closest('[data-slot="composer-shell"]'); + const modelStrip = shell?.querySelector('[data-composer-model-strip="true"]'); + const interruptedStripHeight = + animationRef.current && modelStrip ? modelStrip.getBoundingClientRect().height : null; + const interruptedAnimation = animationRef.current; + const interruptedPromptTop = interruptedAnimation + ? (prompt?.getBoundingClientRect().top ?? null) + : null; + const interruptedActionTop = interruptedAnimation + ? (action?.getBoundingClientRect().top ?? null) + : null; + const interruptedControlsLeft = interruptedAnimation + ? (controls?.getBoundingClientRect().left ?? null) + : null; + const interruptedControlsTop = interruptedAnimation + ? (controls?.getBoundingClientRect().top ?? null) + : null; + const interruptedHeight = interruptedAnimation ? element.getBoundingClientRect().height : null; + const interruptedTargetHeight = animationTargetHeightRef.current; + const interruptedCurrentTime = + typeof interruptedAnimation?.currentTime === "number" + ? interruptedAnimation.currentTime + : null; + const interruptedDuration = interruptedAnimation?.effect?.getComputedTiming().duration; + if (transitionCleanupTimeoutRef.current !== null) { + window.clearTimeout(transitionCleanupTimeoutRef.current); + transitionCleanupTimeoutRef.current = null; + } + interruptedAnimation?.cancel(); + animationRef.current = null; + for (const animation of contentAnimationsRef.current) animation.cancel(); + contentAnimationsRef.current = []; + if (stateChanged) { + for (const animation of stateChangeAnimationsRef.current) animation.cancel(); + stateChangeAnimationsRef.current = []; + } + clearTransitionStyles(); + + const nextRect = element.getBoundingClientRect(); + const nextHeight = nextRect.height; + const nextModelStripHeight = modelStrip?.getBoundingClientRect().height ?? null; + // The chat view resize-observes the overlay to place the timeline + // inset, the scroll-to-end pill, and the mini player. Publishing the + // destination height here turns that feedback into one update instead + // of a ChatView re-render on every animation frame. + const overlay = element.closest('[data-chat-composer-overlay="true"]'); + const overlayRect = overlay?.getBoundingClientRect(); + const overlayHeight = overlayRect?.height ?? null; + if (overlayHeight !== null) { + onOverlayHeightChange(overlayHeight); + } + const nextPromptRect = prompt?.getBoundingClientRect() ?? null; + const nextPromptTop = nextPromptRect?.top ?? null; + const nextActionTop = action?.getBoundingClientRect().top ?? null; + const nextControlsRect = controls?.getBoundingClientRect() ?? null; + const nextControlsTop = nextControlsRect?.top ?? null; + const footerBottom = footer ? nextRect.bottom - footer.getBoundingClientRect().bottom : 1; + const previousHeight = interruptedHeight ?? previousHeightRef.current; + const targetChanged = + interruptedTargetHeight === null || Math.abs(interruptedTargetHeight - nextHeight) >= 0.5; + const shouldAnimate = shouldAnimateComposerRestingTransition({ + hasCompletedInitialLayout: hasCompletedInitialLayoutRef.current, + stateChanged, + hasInterruptedAnimation: interruptedHeight !== null, + }); + + if ( + shouldAnimate && + animationsActive && + previousHeight !== null && + Math.abs(previousHeight - nextHeight) >= 0.5 + ) { + const remainingDuration = + typeof interruptedDuration === "number" && interruptedCurrentTime !== null + ? Math.max(1, interruptedDuration - interruptedCurrentTime) + : animationDurationMs; + const duration = + interruptedHeight !== null && !targetChanged ? remainingDuration : animationDurationMs; + element.style.overflow = "clip"; + if (modelStrip) { + const controlsClearance = Math.max( + nextModelStripHeight ?? 0, + previousModelStripHeightRef.current ?? 0, + ); + element.style.overflowClipMargin = `${controlsClearance}px`; + element.style.clipPath = `inset(0 0 -${controlsClearance}px 0)`; + } + surface.style.height = "100%"; + + if (overlay && overlayHeight !== null) { + overlay.style.height = `${String(overlayHeight)}px`; + overlay.style.display = "flex"; + overlay.style.flexDirection = "column"; + overlay.style.justifyContent = "flex-end"; + pinnedOverlayRef.current = overlay; + } + + if (footer) { + footer.style.position = "absolute"; + footer.style.top = "auto"; + footer.style.bottom = `${String(footerBottom)}px`; + footer.style.height = "3rem"; + if (nextIsCollapsed) { + footer.style.left = "auto"; + footer.style.right = "1px"; + } else { + footer.style.left = "1px"; + footer.style.right = "1px"; + } + } + + let stripAnimation: Animation | null = null; + if (modelStrip) { + const stripHeight = modelStrip.getBoundingClientRect().height; + const stripOverlap = -Number.parseFloat(getComputedStyle(modelStrip).marginTop); + const fromHeight = + interruptedStripHeight ?? + (previousCollapsedRef.current + ? (previousModelStripHeightRef.current ?? stripHeight) + : stripOverlap); + const toHeight = nextIsCollapsed ? stripHeight : stripOverlap; + modelStrip.style.position = "relative"; + modelStrip.style.top = "auto"; + modelStrip.style.visibility = "visible"; + modelStrip.style.minHeight = "0"; + modelStrip.style.paddingTop = "0"; + modelStrip.style.alignItems = "flex-end"; + modelStrip.style.pointerEvents = "none"; + modelStrip.style.zIndex = "20"; + shell?.setAttribute("data-model-strip-transition", "true"); + stripAnimation = modelStrip.animate( + [{ height: `${fromHeight}px` }, { height: `${toHeight}px` }], + { duration, easing: COMPOSER_RESTING_TRANSITION_EASING, fill: "both" }, + ); + } + + const animation = element.animate( + [{ height: `${previousHeight}px` }, { height: `${nextHeight}px` }], + { + duration, + easing: COMPOSER_RESTING_TRANSITION_EASING, + fill: "both", + }, + ); + animationRef.current = animation; + animationTargetHeightRef.current = nextHeight; + + const animatedRect = element.getBoundingClientRect(); + const previousBottom = + overlayRect && previousContentOffsetsRef.current.surfaceBottomInset !== null + ? overlayRect.bottom - previousContentOffsetsRef.current.surfaceBottomInset + : animatedRect.bottom; + const bottomShift = previousBottom - animatedRect.bottom; + const previousPromptTop = + interruptedPromptTop ?? + (previousContentOffsetsRef.current.promptFromTop === null + ? null + : animatedRect.top + bottomShift + previousContentOffsetsRef.current.promptFromTop); + const previousActionTop = + interruptedActionTop ?? + (previousContentOffsetsRef.current.actionFromBottom === null + ? null + : previousBottom - previousContentOffsetsRef.current.actionFromBottom); + const contentAnimations: Animation[] = stripAnimation ? [stripAnimation] : []; + const animateContentPosition = ( + content: HTMLElement | null, + previousTop: number | null, + previousLeft: number | null = null, + ) => { + if (!content || previousTop === null) return; + const rect = content.getBoundingClientRect(); + const offset = previousTop - rect.top; + const offsetX = previousLeft === null ? 0 : previousLeft - rect.left; + if (Math.abs(offset) < 0.5 && Math.abs(offsetX) < 0.5) return; + contentAnimations.push( + content.animate( + [{ transform: `translate(${offsetX}px, ${offset}px)` }, { transform: "none" }], + { + duration, + easing: COMPOSER_RESTING_TRANSITION_EASING, + }, + ), + ); + }; + animateContentPosition(prompt, previousPromptTop); + animateContentPosition(action, previousActionTop); + if (continuousControls) { + const previousControlsTop = + interruptedControlsTop ?? + (previousContentOffsetsRef.current.controlsFromBottom === null + ? null + : previousBottom - previousContentOffsetsRef.current.controlsFromBottom); + const previousControlsLeft = + interruptedControlsLeft ?? + (previousContentOffsetsRef.current.controlsFromLeft === null + ? null + : animatedRect.left + previousContentOffsetsRef.current.controlsFromLeft); + animateContentPosition(controls, previousControlsTop, previousControlsLeft); + } + contentAnimationsRef.current = contentAnimations; + + if (stateChanged) { + const stateChangeAnimations: Animation[] = []; + + const previousPromptHeight = previousContentOffsetsRef.current.promptHeight; + if ( + !nextIsCollapsed && + prompt && + nextPromptRect && + previousPromptHeight !== null && + nextPromptRect.height - previousPromptHeight >= 0.5 + ) { + const hiddenHeight = nextPromptRect.height - previousPromptHeight; + stateChangeAnimations.push( + prompt.animate( + [ + { clipPath: `inset(0 0 ${String(hiddenHeight)}px 0)` }, + { clipPath: "inset(0 0 0 0)" }, + ], + { + duration, + easing: COMPOSER_RESTING_TRANSITION_EASING, + }, + ), + ); + } + + const arrivingControls = nextIsCollapsed + ? restingControlsRef.current + : element.querySelector('[data-chat-composer-controls="left"]'); + if (arrivingControls && !continuousControls) { + const drift = nextIsCollapsed + ? -COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX + : COMPOSER_RESTING_CONTROLS_ARRIVAL_DRIFT_PX; + stateChangeAnimations.push( + arrivingControls.animate( + [ + { opacity: 0, transform: `translateY(${String(drift)}px)` }, + { opacity: 1, transform: "none" }, + ], + { + duration: nextIsCollapsed ? duration : duration / 2, + delay: nextIsCollapsed ? 0 : duration / 2, + fill: "backwards", + easing: COMPOSER_RESTING_TRANSITION_EASING, + }, + ), + ); + } + + const arrivingImagePreviews = nextIsCollapsed + ? Array.from( + element.querySelectorAll('[data-chat-composer-resting-images="true"]'), + ) + : Array.from( + element.querySelectorAll('[data-chat-composer-expanded-image="true"]'), + ); + for (const imagePreview of arrivingImagePreviews) { + stateChangeAnimations.push( + imagePreview.animate([{ opacity: 0 }, { opacity: 1 }], { + duration: nextIsCollapsed ? duration : duration / 2, + delay: nextIsCollapsed ? 0 : duration / 2, + fill: "backwards", + easing: COMPOSER_RESTING_TRANSITION_EASING, + }), + ); + } + stateChangeAnimationsRef.current = stateChangeAnimations; + } + + const finishTransition = (cancelAnimations: boolean) => { + if (animationRef.current !== animation) return; + if (transitionCleanupTimeoutRef.current !== null) { + window.clearTimeout(transitionCleanupTimeoutRef.current); + transitionCleanupTimeoutRef.current = null; + } + if (cancelAnimations) { + animation.cancel(); + for (const contentAnimation of contentAnimationsRef.current) { + contentAnimation.cancel(); + } + for (const stateChangeAnimation of stateChangeAnimationsRef.current) { + stateChangeAnimation.cancel(); + } + } + animationRef.current = null; + animationTargetHeightRef.current = null; + contentAnimationsRef.current = []; + stateChangeAnimationsRef.current = []; + animation.cancel(); + stripAnimation?.cancel(); + clearTransitionStyles(); + }; + void animation.finished.catch(() => undefined).then(() => finishTransition(false)); + // A suspended document timeline can leave `finished` pending while + // these measurement styles remain active. Wall-clock cleanup makes + // the natural layout the eventual source of truth in that case. + transitionCleanupTimeoutRef.current = window.setTimeout( + () => finishTransition(true), + duration + COMPOSER_RESTING_TRANSITION_CLEANUP_BUFFER_MS, + ); + } else { + animationTargetHeightRef.current = null; + } + + previousCollapsedRef.current = nextIsCollapsed; + previousHeightRef.current = nextHeight; + previousModelStripHeightRef.current = nextModelStripHeight; + previousContentOffsetsRef.current = { + promptFromTop: nextPromptTop === null ? null : nextPromptTop - nextRect.top, + promptHeight: nextPromptRect?.height ?? null, + actionFromBottom: nextActionTop === null ? null : nextRect.bottom - nextActionTop, + controlsFromBottom: nextControlsTop === null ? null : nextRect.bottom - nextControlsTop, + controlsFromLeft: nextControlsRect === null ? null : nextControlsRect.left - nextRect.left, + surfaceBottomInset: overlayRect ? overlayRect.bottom - nextRect.bottom : null, + }; + }; + + useLayoutEffect(() => { + const requestId = transitionLayoutRequestRef.current + 1; + transitionLayoutRequestRef.current = requestId; + const stateChanged = previousCollapsedRef.current !== isCollapsed; + // A non-Git context strip enters or leaves flow through ChatView state in + // an earlier layout effect. Let React flush that parent update before the + // FLIP reads its destination geometry, while still running before paint. + queueMicrotask(() => { + if (transitionLayoutRequestRef.current !== requestId) return; + transitionToCurrentGeometry(stateChanged); + }); + return () => { + if (transitionLayoutRequestRef.current === requestId) { + transitionLayoutRequestRef.current += 1; + } + }; + }, [isCollapsed, transitionToCurrentGeometry]); + + useLayoutEffect(() => { + if (previousRestingRef.current === isResting) return; + previousRestingRef.current = isResting; + if (animationRef.current) return; + const overlay = elementRef.current?.closest('[data-chat-composer-overlay="true"]'); + if (overlay) onOverlayHeightChange(overlay.getBoundingClientRect().height); + }, [isResting, onOverlayHeightChange]); + + useLayoutEffect(() => { + const element = elementRef.current; + if (!element) return; + + const body = element.querySelector('[data-chat-composer-body="true"]'); + return observeResize(body ? [element, body] : element, (entries) => { + if (animationRef.current) { + if (body && entries.some((entry) => entry.target === body)) { + transitionToCurrentGeometry(false); + } + return; + } + const elementRect = element.getBoundingClientRect(); + const visibleTransitionElement = (selector: string) => + Array.from(element.querySelectorAll(selector)).find( + (candidate) => candidate.getClientRects().length > 0, + ) ?? null; + const promptRect = visibleTransitionElement( + '[data-composer-prompt-surface="true"], [data-chat-composer-transition-prompt="true"]', + )?.getBoundingClientRect(); + const actionTop = visibleTransitionElement( + '[data-chat-composer-transition-actions="true"]', + )?.getBoundingClientRect().top; + const controlsRect = ( + isCollapsedRef.current + ? restingControlsRef.current + : visibleTransitionElement('[data-chat-composer-controls="left"]') + )?.getBoundingClientRect(); + previousHeightRef.current = elementRect.height; + previousContentOffsetsRef.current = { + promptFromTop: promptRect === undefined ? null : promptRect.top - elementRect.top, + promptHeight: promptRect?.height ?? null, + actionFromBottom: actionTop === undefined ? null : elementRect.bottom - actionTop, + controlsFromBottom: + controlsRect === undefined ? null : elementRect.bottom - controlsRect.top, + controlsFromLeft: controlsRect === undefined ? null : controlsRect.left - elementRect.left, + surfaceBottomInset: + (element + .closest('[data-chat-composer-overlay="true"]') + ?.getBoundingClientRect().bottom ?? elementRect.bottom) - elementRect.bottom, + }; + }); + }, [restingControlsRef, transitionToCurrentGeometry]); + + useEffect(() => { + hasCompletedInitialLayoutRef.current = true; + return () => { + if (transitionCleanupTimeoutRef.current !== null) { + window.clearTimeout(transitionCleanupTimeoutRef.current); + transitionCleanupTimeoutRef.current = null; + } + animationRef.current?.cancel(); + animationRef.current = null; + animationTargetHeightRef.current = null; + for (const animation of contentAnimationsRef.current) animation.cancel(); + contentAnimationsRef.current = []; + for (const animation of stateChangeAnimationsRef.current) animation.cancel(); + stateChangeAnimationsRef.current = []; + clearTransitionStyles(); + }; + }, [clearTransitionStyles]); + + return elementRef; +} diff --git a/apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts b/apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts new file mode 100644 index 0000000000000..bda0641e90917 --- /dev/null +++ b/apps/web/src/components/chat/useProviderWorkspaceSnapshotRefresh.ts @@ -0,0 +1,137 @@ +import { + type EnvironmentId, + PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS, + type ServerProvider, +} from "@t3tools/contracts"; +import { type ProviderInstanceEntry } from "../../providerInstances"; +import { + hasCompleteProviderWorkspaceSnapshot, + hasCurrentProviderWorkspaceSnapshot, +} from "@t3tools/client-runtime/providerSkills"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useEffect, useEffectEvent, useRef, useState } from "react"; +import { useStableCallback } from "../../hooks/useStableCallback"; + +const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000; + +/** + * Keeps the selected provider's workspace snapshot fresh for the composer's + * cwd. Returns a check to run when the user types. + */ +export function useProviderWorkspaceSnapshotRefresh(input: { + readonly environmentId: EnvironmentId; + readonly gitCwd: string | null; + readonly selectedProviderEntry: ProviderInstanceEntry | undefined; + readonly selectedProviderStatus: ServerProvider | null; +}) { + const { environmentId, gitCwd, selectedProviderEntry, selectedProviderStatus } = input; + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { + reportFailure: false, + }); + // The last scan this composer asked for. A request inside the TTL is not + // repeated, so a client clock ahead of the server's cannot loop rescans. + const workspaceRefreshKeyRef = useRef<{ key: string; requestedAt: number } | null>(null); + const [workspaceRefreshRetry, setWorkspaceRefreshRetry] = useState<{ + key: string; + notBefore: number; + } | null>(null); + const workspaceRefreshScopeKey = + gitCwd && selectedProviderEntry + ? `${environmentId}:${selectedProviderEntry.instanceId}:${gitCwd}` + : null; + const workspaceSlashCommandsPending = + selectedProviderStatus?.workspaceSnapshots?.some( + (snapshot) => snapshot.cwd === gitCwd && snapshot.slashCommandsPending === true, + ) ?? false; + useEffect(() => { + if ( + !workspaceSlashCommandsPending || + !workspaceRefreshRetry || + workspaceRefreshRetry.key !== workspaceRefreshScopeKey + ) + return; + const timeout = setTimeout( + () => { + setWorkspaceRefreshRetry((current) => (current === workspaceRefreshRetry ? null : current)); + }, + Math.max(0, workspaceRefreshRetry.notBefore - Date.now()), + ); + return () => clearTimeout(timeout); + }, [workspaceRefreshRetry, workspaceRefreshScopeKey, workspaceSlashCommandsPending]); + // Losing a snapshot (the server dropped it) lifts both the TTL and the retry + // cooldown so the next check rescans at once. + const hasWorkspaceSnapshot = hasCompleteProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd); + const [hadWorkspaceSnapshot, setHadWorkspaceSnapshot] = useState(hasWorkspaceSnapshot); + const [workspaceSnapshotLossCount, setWorkspaceSnapshotLossCount] = useState(0); + if (hadWorkspaceSnapshot !== hasWorkspaceSnapshot) { + setHadWorkspaceSnapshot(hasWorkspaceSnapshot); + if (!hasWorkspaceSnapshot) { + setWorkspaceSnapshotLossCount((count) => count + 1); + setWorkspaceRefreshRetry(null); + } + } + const lastWorkspaceSnapshotLossRef = useRef(workspaceSnapshotLossCount); + const refreshWorkspaceSnapshotIfStale = ( + now: number, + key: string | null, + retry: { key: string; notBefore: number } | null, + snapshotLossCount: number, + ) => { + if (lastWorkspaceSnapshotLossRef.current !== snapshotLossCount) { + lastWorkspaceSnapshotLossRef.current = snapshotLossCount; + workspaceRefreshKeyRef.current = null; + } + if (key === null || !gitCwd || !selectedProviderEntry) return; + const lastRequest = workspaceRefreshKeyRef.current; + if ( + lastRequest?.key === key && + now - lastRequest.requestedAt < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS + ) + return; + // A pending retry needs no clearing here: its cooldown lapses long before the TTL. + if (hasCurrentProviderWorkspaceSnapshot(selectedProviderStatus, gitCwd, now)) return; + if (retry?.key === key && now < retry.notBefore) return; + const request = { key, requestedAt: now }; + workspaceRefreshKeyRef.current = request; + const retryLater = () => { + if (workspaceRefreshKeyRef.current !== request) return; + workspaceRefreshKeyRef.current = null; + setWorkspaceRefreshRetry({ + key, + notBefore: Date.now() + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS, + }); + }; + void refreshProviders({ + environmentId, + input: { instanceId: selectedProviderEntry.instanceId, cwd: gitCwd }, + }).then((result) => { + const refreshedSnapshot = + result._tag === "Success" && + hasCompleteProviderWorkspaceSnapshot( + result.value.providers.find( + (provider) => provider.instanceId === selectedProviderEntry.instanceId, + ), + gitCwd, + ); + if (!refreshedSnapshot) retryLater(); + }, retryLater); + }; + const refreshWorkspaceSnapshotOnChange = useEffectEvent(refreshWorkspaceSnapshotIfStale); + useEffect(() => { + refreshWorkspaceSnapshotOnChange( + Date.now(), + workspaceRefreshScopeKey, + workspaceRefreshRetry, + workspaceSnapshotLossCount, + ); + }, [workspaceRefreshScopeKey, workspaceRefreshRetry, workspaceSnapshotLossCount]); + return useStableCallback(() => + refreshWorkspaceSnapshotIfStale( + Date.now(), + workspaceRefreshScopeKey, + workspaceRefreshRetry, + workspaceSnapshotLossCount, + ), + ); +} diff --git a/apps/web/src/components/chat/useRestingComposerControlsLayout.ts b/apps/web/src/components/chat/useRestingComposerControlsLayout.ts new file mode 100644 index 0000000000000..e75aab3a117fd --- /dev/null +++ b/apps/web/src/components/chat/useRestingComposerControlsLayout.ts @@ -0,0 +1,84 @@ +import { measureRestingComposerControls } from "./restingComposerControlsMeasurement"; +import { observeResize } from "~/lib/observeResize"; +import { resolveRestingComposerControlsLayout } from "../composerFooterLayout"; +import { useLayoutEffect, useRef, useState } from "react"; + +export function useRestingComposerControlsLayout( + host: HTMLDivElement | null, + useControlsAsHost = false, +) { + const [controls, setControls] = useState(null); + const controlsRef = useRef(null); + const attachControls = (element: HTMLDivElement | null) => { + controlsRef.current = element; + setControls(element); + }; + const [layout, setLayout] = useState<{ + hiddenCount: number; + iconOnlyCount?: number; + visible: boolean; + }>({ hiddenCount: 0, visible: true }); + + const measure = () => { + const currentHost = useControlsAsHost ? controls : host; + if (currentHost === null || !controls) return; + + const measurement = measureRestingComposerControls(controls); + if (!measurement) return; + const style = getComputedStyle(currentHost); + const hostWidth = + currentHost.clientWidth - + (Number.parseFloat(style.paddingInlineStart) || 0) - + (Number.parseFloat(style.paddingInlineEnd) || 0); + + setLayout((current) => { + const next = resolveRestingComposerControlsLayout({ + ...measurement, + hostWidth, + previous: current, + }); + return next.hiddenCount === current.hiddenCount && + next.iconOnlyCount === current.iconOnlyCount && + next.visible === current.visible + ? current + : next; + }); + }; + + useLayoutEffect(() => { + const currentHost = useControlsAsHost ? controls : host; + if (!currentHost || !controls) return; + let stopObserving = () => {}; + const observeControls = () => { + stopObserving(); + stopObserving = observeResize( + [ + currentHost, + controls, + ...controls.querySelectorAll( + "[data-resting-block], [data-composer-control-label], [data-chat-provider-model-picker-label]", + ), + ], + measure, + ); + measure(); + }; + observeControls(); + const mutations = new MutationObserver(observeControls); + mutations.observe(controls, { childList: true, subtree: true, characterData: true }); + document.fonts.addEventListener("loadingdone", measure); + return () => { + stopObserving(); + mutations.disconnect(); + document.fonts.removeEventListener("loadingdone", measure); + }; + }, [host, controls, useControlsAsHost, measure]); + + return { + controlsRef, + attachControls, + hiddenBlockCount: layout.hiddenCount, + iconOnlyBlockCount: layout.iconOnlyCount ?? 0, + controlsVisible: layout.visible, + }; +} From 0755f98401fec0f3400d4c4ef2294aa92ace39d1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 13:23:39 -0700 Subject: [PATCH 03/83] refactor(web): the prompt stash lives in useComposerStash (#23046) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 660 +--------------- .../src/components/chat/useComposerStash.ts | 745 ++++++++++++++++++ 2 files changed, 788 insertions(+), 617 deletions(-) create mode 100644 apps/web/src/components/chat/useComposerStash.ts diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 03c9a49875433..de7dea54f9fed 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -103,23 +103,14 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftId, - type PersistedComposerFileAttachment, type PersistedComposerImageAttachment, - composerFileDedupKey, composerFileMatchesReattachMarker, composerFileNeedsReattach, composerDraftHasUserContent, composerTargetKey, - hydrateImagesFromPersisted, useComposerDraftStore, useComposerThreadDraft, } from "../../composerDraftStore"; -import { - MAX_STASH_ENTRIES, - partitionStashAttachments, - usePromptStashStore, - type PromptStashEntry, -} from "../../promptStashStore"; import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; @@ -146,7 +137,7 @@ import { type ComposerBannerStackContent, type ComposerBannerStackItem, } from "./ComposerBannerStack"; -import { compressImageForStash, prepareImageForAttachment } from "../../lib/imageCompression"; +import { prepareImageForAttachment } from "../../lib/imageCompression"; import { fileAttachmentTooLargeMessage, formatAttachmentSize, @@ -162,27 +153,19 @@ import { shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { - readAttachmentUpload, releaseAttachmentUpload, releaseDraftAttachment, - releasePersistedAttachmentUpload, startAttachmentUpload, useAttachmentUploadStore, - verifyStashedAttachmentUpload, } from "../../lib/attachmentUploadQueue"; import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState"; -import { isCommandPaletteOpen } from "../../commandPaletteBus"; -import { getTerminalFocusOwner } from "../../lib/terminalFocus"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; -import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings"; +import { shortcutLabelForCommand } from "../../keybindings"; import { type TerminalContextDraft, type TerminalContextSelection, } from "../../lib/terminalContext"; -import { - replaceComposerContextReferences, - toKindScopedComposerContextId, -} from "@t3tools/shared/composerContextReferences"; +import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences"; import { shouldUseCompactComposerPrimaryActions, shouldUseCompactComposerFooter, @@ -292,7 +275,6 @@ import { buildExpandedImagePreview, type ExpandedImagePreview, } from "./ExpandedImagePreview"; -import { resizeSnapShotSource } from "../../lib/snapShotSource"; import { cn, isMacPlatform, randomUUID } from "~/lib/utils"; import { getComposerPromptLengthValidationMessage, @@ -301,10 +283,7 @@ import { } from "./composerSubmission"; import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation"; import { pendingDraftWork } from "./pendingDraftWork"; -import { - importComposerThreadAttachment, - remainingComposerAttachmentSlots, -} from "./composerThreadImport"; +import { importComposerThreadAttachment } from "./composerThreadImport"; import { isTimelineScrollTarget } from "./timelineScrollTarget"; import { createComposerScrollGestureState, @@ -367,6 +346,7 @@ import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLa import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh"; import { useComposerProviderModel } from "./useComposerProviderModel"; import { useComposerImageGroups } from "./useComposerImageGroups"; +import { useComposerStash } from "./useComposerStash"; /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -939,12 +919,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const clearComposerDraftPersistedAttachments = useComposerDraftStore( (store) => store.clearPersistedAttachments, ); - const clearComposerDraftTerminalContexts = useComposerDraftStore( - (store) => store.clearTerminalContexts, - ); - const clearComposerDraftPromptAndImages = useComposerDraftStore( - (store) => store.clearComposerPromptAndImages, - ); const syncComposerDraftPersistedAttachments = useComposerDraftStore( (store) => store.syncPersistedAttachments, ); @@ -1198,12 +1172,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const [composerMenuAnchor, setComposerMenuAnchor] = useState(null); const hasWrappedPrompt = useComposerMultilinePrompt(composerMenuAnchor); const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt; - const [isStashMenuOpen, setIsStashMenuOpen] = useState(false); const [isTasksDrawerOpen, setIsTasksDrawerOpen] = useState(false); - const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({ - key: 0, - active: false, - }); // A pending question stays expanded: its card moves into the banner dock, // so collapsing would leave the surface empty and squashed beneath it. const isComposerCollapsedMobile = @@ -1234,9 +1203,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerScrollCollapseEligibleRef = useRef(false); const windowRefocusInFlightRef = useRef(false); const composerScrollGestureRef = useRef(createComposerScrollGestureState()); - const stashPulseKeyRef = useRef(0); - const stashPulseTimeoutRef = useRef(null); - const stashInFlightRef = useRef>(new Set()); const pendingImageCompressionsRef = useRef>(new Map()); const pendingThreadImportsRef = useRef>(new Map()); const isRevertingCheckpointRef = useRef(isRevertingCheckpoint); @@ -2786,536 +2752,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; }; - const stashQueue = usePromptStashStore((state) => state.entries); - const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry); - const takeStashEntry = usePromptStashStore((state) => state.takeEntry); - const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages); - - useEffect(() => { - return () => { - if (stashPulseTimeoutRef.current !== null) { - window.clearTimeout(stashPulseTimeoutRef.current); - } - }; - }, []); - - const pulseStashBadge = () => { - stashPulseKeyRef.current += 1; - setStashPulse({ key: stashPulseKeyRef.current, active: true }); - if (stashPulseTimeoutRef.current !== null) { - window.clearTimeout(stashPulseTimeoutRef.current); - } - stashPulseTimeoutRef.current = window.setTimeout(() => { - stashPulseTimeoutRef.current = null; - setStashPulse((current) => ({ ...current, active: false })); - }, 1200); - }; - - const restoreStashEntry = async (menuEntry: PromptStashEntry) => { - const filesToVerify = menuEntry.files ?? []; - if (filesToVerify.some((file) => file.environmentId !== environmentId)) { - toastManager.add({ - type: "error", - title: "Stashed files belong to another environment", - description: "Restore this prompt in the environment that received its files.", - }); - return; - } - setIsStashMenuOpen(false); - - // An expired upload restores as a needs-reattach row instead of a reference - // the next send would fail to verify. Verify BEFORE taking: the take - // removes the entry from durable storage, and a tab closed during this - // await must still find it there after reload. - const verifications = await Promise.all( - filesToVerify.map((file) => - verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }), - ), - ); - const expiredAttachmentIds = new Set( - filesToVerify - .filter((_, index) => verifications[index]?.status === "missing") - .map((file) => file.attachmentId), - ); - - // A thread switch during the verify await would mix the new thread's - // prompt with this invocation's captured target. Nothing was taken yet, - // so abort and leave the entry restorable where the user now is. - if ( - isRevertingCheckpointRef.current || - composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current - ) { - return; - } - - const { entry, durable } = takeStashEntry(menuEntry.id); - if (!entry) return; - if (!durable) { - toastManager.add({ - type: "warning", - title: "Restored prompt may reappear in the stash", - description: - "Browser storage rejected the update, so this entry could still be there after a reload.", - data: { hideCopyButton: true }, - }); - } - - const rewrittenContextIds = entry.records - ? importContextRecords(entry.records, null, composerDraftTarget) - : new Map(); - const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { - const contextId = rewrittenContextIds.get(reference.contextId); - return contextId - ? formatInlineContextReference({ - ...reference, - contextId, - kind: reference.kind === "element" ? "preview-annotation" : reference.kind, - }) - : reference.source; - }); - const currentPrompt = promptRef.current; - const nextPrompt = - restoredPrompt.length === 0 - ? currentPrompt - : currentPrompt.trim().length - ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}` - : restoredPrompt; - let promptChanged = nextPrompt !== currentPrompt; - if (promptChanged) { - promptRef.current = nextPrompt; - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); - setComposerTrigger(null); - } - - let unrestoredFileNames: string[] = []; - const expiredFileNames: string[] = []; - let restoredFileCount = 0; - const stashedFiles = entry.files ?? []; - if (stashedFiles.length > 0) { - const composerFilesNow = composerFilesRef.current; - const existingFileIds = new Set(composerFilesNow.map((file) => file.id)); - const retainedUploadIds = new Set( - composerFilesNow.flatMap((file) => - file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [], - ), - ); - const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey)); - const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach); - const restoredMarkerIds = new Set(); - const duplicateFiles: PersistedComposerFileAttachment[] = []; - const markerReplacements: ComposerFileAttachment[] = []; - const appendedFiles: ComposerFileAttachment[] = []; - for (const file of stashedFiles) { - const expired = expiredAttachmentIds.has(file.attachmentId); - const key = composerFileDedupKey(file); - const restored: ComposerFileAttachment = { - type: "file", - id: file.id, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - file: null, - ...(file.source ? { source: file.source } : {}), - ...(expired - ? {} - : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }), - }; - if (existingFileIds.has(file.id)) { - if (!expired && !retainedUploadIds.has(file.attachmentId)) { - duplicateFiles.push(file); - } - continue; - } - const reattachMarker = reattachMarkers.find( - (marker) => - !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file), - ); - if (reattachMarker) { - restoredMarkerIds.add(reattachMarker.id); - existingFileIds.add(file.id); - existingFileKeys.add(key); - if (expired) { - expiredFileNames.push(file.name); - } else { - retainedUploadIds.add(file.attachmentId); - markerReplacements.push(restored); - } - continue; - } - if (existingFileKeys.has(key)) { - if (!expired && !retainedUploadIds.has(file.attachmentId)) { - duplicateFiles.push(file); - } - continue; - } - existingFileIds.add(file.id); - existingFileKeys.add(key); - if (expired) { - expiredFileNames.push(file.name); - } else { - retainedUploadIds.add(file.attachmentId); - } - appendedFiles.push(restored); - } - const capacity = remainingComposerAttachmentSlots( - composerImagesRef.current.length + composerFilesNow.length, - pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, - ); - const filesToAppend = appendedFiles.slice(0, capacity); - const skippedFiles = appendedFiles.slice(capacity); - unrestoredFileNames = skippedFiles.map((file) => file.name); - // A non-durable take can resurrect the stash entry after a reload; - // deleting these uploads would leave it pointing at nothing. - if (durable) { - for (const file of duplicateFiles) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId, - attachmentId: file.attachmentId, - }); - } - for (const file of skippedFiles) { - if (file.uploadedAttachmentId) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId, - attachmentId: file.uploadedAttachmentId, - }); - } - } - } - const restoredFiles = [...markerReplacements, ...filesToAppend]; - if (restoredFiles.length > 0) { - addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true }); - const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt; - if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) { - promptRef.current = restoredFilePrompt; - setComposerCursor( - collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length), - ); - setComposerTrigger(null); - promptChanged = true; - } - restoredFileCount = filesToAppend.length; - } - } - - let unrestoredImageNames: string[] = []; - if (entry.attachments.length > 0) { - const existingIds = new Set(composerImagesRef.current.map((image) => image.id)); - // The draft store also dedupes by mimeType+sizeBytes+name, so filter - // on the same key here. Counting a duplicate against capacity would - // burn a slot the store then refuses to fill, pushing a genuinely - // unique image into the overflow list for nothing. - const existingDedupKeys = new Set( - composerImagesRef.current.map( - (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`, - ), - ); - const capacity = remainingComposerAttachmentSlots( - composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount, - pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, - ); - const pending = entry.attachments.filter( - (attachment) => - !existingIds.has(attachment.id) && - !existingDedupKeys.has( - `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`, - ), - ); - unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name); - const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity)); - if (restoredImages.length > 0) { - addComposerDraftImages(composerDraftTarget, restoredImages); - } - } - - const missingImageReasons: string[] = []; - if (entry.droppedImageNames.length > 0) { - missingImageReasons.push( - `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, - ); - } - if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) { - missingImageReasons.push( - `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`, - ); - } - if (unrestoredImageNames.length > 0) { - missingImageReasons.push( - `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (unrestoredFileNames.length > 0) { - missingImageReasons.push( - `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (expiredFileNames.length > 0) { - missingImageReasons.push( - `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`, - ); - } - if (missingImageReasons.length > 0) { - toastManager.add({ - type: "warning", - title: "Some attachments were not restored", - description: missingImageReasons.join(" "), - }); - } - - if (promptChanged) { - window.requestAnimationFrame(() => { - composerEditorRef.current?.focusAtEnd(); - }); - } - }; - const restoreStashEntryStable = useStableCallback(restoreStashEntry); - - const deleteStashEntry = (entry: PromptStashEntry) => { - const { entry: removed, durable } = takeStashEntry(entry.id); - if (!stashQueue.some((candidate) => candidate.id !== entry.id)) { - setIsStashMenuOpen(false); - } - if (durable && removed) { - for (const file of removed.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - } - if (!durable) { - toastManager.add({ - type: "warning", - title: "Stash entry may come back", - description: - "Browser storage rejected the delete, so this prompt could reappear after a reload.", - data: { hideCopyButton: true }, - }); - } - }; - const deleteStashEntryStable = useStableCallback(deleteStashEntry); - - const stashCurrentPrompt = async () => { - // Stashing clears the draft. A pasted attachment still downloading would then land in the - // emptied composer instead of travelling with the entry it belongs to. - if (pendingDraftWork.has(attachmentTargetKeyRef.current)) { - toastManager.add({ - type: "info", - title: "Still bringing attached context into this message.", - description: "Stash again once its chip resolves.", - }); - return; - } - const prompt = promptRef.current.trim(); - const images = [...composerImagesRef.current]; - const files = [...composerFilesRef.current]; - const stashedRecords: ComposerContextRecord[] = [ - ...composerThreadContexts, - ...composerTerminalContextsRef.current.map(terminalContextRecord), - ...composerReviewComments.map(reviewCommentContextRecord), - ...composerPreviewAnnotations.map((annotation) => - previewAnnotationContextRecord(annotation, { - screenshotContextId: images.some((image) => image.id === annotation.id) - ? annotation.id - : undefined, - }), - ), - ]; - if (prompt.length === 0 && images.length === 0 && files.length === 0) { - const entries = usePromptStashStore.getState().entries; - const entry = entries.length === 1 ? entries[0] : undefined; - if (entry && !entry.pendingImageCount) { - await restoreStashEntry(entry); - } else { - setIsStashMenuOpen((open) => !open); - } - return; - } - const stashedFiles: PersistedComposerFileAttachment[] = []; - for (const file of files) { - if (composerFileNeedsReattach(file)) { - toastManager.add({ - type: "error", - title: "Attach dropped files again or remove them before stashing", - }); - return; - } - const upload = readAttachmentUpload(file.id); - if (upload?.status !== "ready" || upload.environmentId !== environmentId) { - toastManager.add({ - type: "error", - title: "Wait for file uploads before stashing this prompt", - }); - return; - } - stashedFiles.push({ - id: file.id, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - attachmentId: upload.attachmentId, - environmentId, - ...(file.source ? { source: file.source } : {}), - }); - } - // A repeat ⌘S on the *same* still-unencoded snapshot would stash it - // twice. Guard on the snapshot itself rather than a bare boolean: once - // the composer has been cleared the user can type something genuinely - // new (or switch threads) while encoding continues, and that deserves its - // own entry. - const attachmentKey = images - .map((image) => `image:${image.id}`) - .concat(files.map((file) => `file:${file.id}`)) - .join(","); - const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n"); - if (stashInFlightRef.current.has(snapshotKey)) return; - stashInFlightRef.current.add(snapshotKey); - - const stashTarget = composerDraftTarget; - const entryId = randomUUID(); - const stashAndEncode = async () => { - // Ordering matters in both directions: writing before clearing means a - // crash or closed tab mid-encode still leaves the prompt recoverable, - // while clearing before the async image work means edits typed during - // encoding are not wiped. - const { evicted, written, durable } = stashEntryToQueue({ - id: entryId, - createdAt: new Date().toISOString(), - prompt, - attachments: [], - ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}), - droppedImageNames: [], - unreadableImageNames: [], - pendingImageCount: images.length, - ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}), - }); - - // If it was rejected (quota) the store has already rolled itself back, - // so leave the composer untouched rather than making it the second - // casualty of a reload. - if (!written) { - toastManager.add({ - type: "error", - title: "Could not stash this prompt", - description: - "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.", - data: { hideCopyButton: true }, - }); - return; - } - if (!durable) { - toastManager.add({ - type: "warning", - title: "Stashed prompt will not survive a reload", - description: - "Browser storage is unavailable, so this stash is kept in memory only for this session.", - data: { hideCopyButton: true }, - }); - } - - promptRef.current = ""; - clearComposerDraftPromptAndImages(stashTarget); - clearComposerDraftTerminalContexts(stashTarget); - setComposerDraftThreadContexts(stashTarget, []); - for (const comment of composerReviewComments) { - removeComposerDraftReviewComment(stashTarget, comment.id); - } - for (const annotation of composerPreviewAnnotations) { - releaseAttachmentUpload(annotation.id); - removeComposerDraftPreviewAnnotation(stashTarget, annotation.id); - } - setComposerDraftPrompt(stashTarget, ""); - for (const image of images) { - releaseAttachmentUpload(image.id); - } - setComposerCursor(0); - setComposerTrigger(null); - pulseStashBadge(); - - if (evicted) { - for (const file of evicted.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - toastManager.add({ - type: "warning", - title: "Oldest stashed prompt discarded", - description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`, - data: { hideCopyButton: true }, - }); - } - - // Images are re-encoded for the stash rather than stored verbatim: the - // composer allows up to 10MB per image, but localStorage gives the whole - // origin ~5MB. - const candidateAttachments: PersistedComposerImageAttachment[] = []; - const oversizedImageNames: string[] = []; - const unreadableImageNames: string[] = []; - for (const image of images) { - const result = await compressImageForStash(image.file); - if (!result.ok) { - (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push( - image.name, - ); - continue; - } - candidateAttachments.push({ - id: image.id, - name: image.name, - mimeType: result.image.mimeType, - sizeBytes: result.image.sizeBytes, - dataUrl: result.image.dataUrl, - ...(image.source - ? { source: resizeSnapShotSource(image.source, result.image.imageSize) } - : {}), - }); - } - const { kept, droppedNames } = partitionStashAttachments(candidateAttachments); - - const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, { - attachments: kept, - droppedImageNames: [...oversizedImageNames, ...droppedNames], - unreadableImageNames, - }); - if (attached) { - if (!imagesDurable && durable && images.length > 0) { - toastManager.add({ - type: "warning", - title: "Stashed images were not saved", - description: - "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.", - data: { hideCopyButton: true }, - }); - } - } else if (kept.length > 0) { - toastManager.add({ - type: "warning", - title: "Stashed images did not attach", - description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`, - data: { hideCopyButton: true }, - }); - } - }; - await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey)); - }; - const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt); - - const toggleStashMenu = () => { - if (isComposerCollapsedMobile) { - expandMobileComposer(); - setIsStashMenuOpen(true); - return; - } - setIsStashMenuOpen((open) => !open); - }; - const toggleStashMenuStable = useStableCallback(toggleStashMenu); + const { + stashQueue, + isStashMenuOpen, + setIsStashMenuOpen, + stashPulse, + restoreStashEntryStable, + deleteStashEntryStable, + toggleStashMenuStable, + } = useComposerStash({ + environmentId, + composerDraftTarget, + promptRef, + composerImagesRef, + composerFilesRef, + composerTerminalContextsRef, + keybindings, + terminalOpen, + projectSelectionRequired, + isRevertingCheckpoint, + pendingUserInputs, + activePendingProgress, + prompt, + composerMenuOpen, + isComposerModelPickerOpen, + isComposerCollapsedMobile, + composerPreviewAnnotations, + composerReviewComments, + composerThreadContexts, + attachmentTargetKeyRef, + composerDraftTargetKeyRef, + composerEditorRef, + isRevertingCheckpointRef, + pendingThreadImportsRef, + setComposerCursor, + setComposerTrigger, + importContextRecords, + expandMobileComposer: expandMobileComposerStable, + }); const toggleTasksDrawer = () => { setIsTasksDrawerOpen((open) => !open); }; @@ -3755,54 +3229,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (tasksDrawerThreadId !== activeThreadId) setTasksDrawerThreadId(activeThreadId); - const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen }); - if ( - stashMenuClosesOn.prompt !== prompt || - stashMenuClosesOn.composerMenuOpen !== composerMenuOpen - ) { - setStashMenuClosesOn({ prompt, composerMenuOpen }); - if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false); - } - - useEffect(() => { - const handler = (event: globalThis.KeyboardEvent) => { - const command = resolveShortcutCommand(event, keybindings, { - context: { - terminalFocus: getTerminalFocusOwner() !== null, - terminalOpen, - modelPickerOpen: isComposerModelPickerOpen, - }, - }); - if (command !== "composer.stash") return; - // Always claim the shortcut so the browser save dialog never opens, - // even when the composer is in a state that can't stash. - event.preventDefault(); - event.stopPropagation(); - if (isCommandPaletteOpen() || isRevertingCheckpoint) { - return; - } - if (pendingUserInputs.length > 0) { - setIsStashMenuOpen((open) => !open); - return; - } - if (projectSelectionRequired || activePendingProgress !== null) { - return; - } - void stashCurrentPromptStable(); - }; - window.addEventListener("keydown", handler, true); - return () => window.removeEventListener("keydown", handler, true); - }, [ - activePendingProgress, - isComposerModelPickerOpen, - keybindings, - pendingUserInputs.length, - projectSelectionRequired, - stashCurrentPromptStable, - isRevertingCheckpoint, - terminalOpen, - ]); - const insertComposerText = ( text: string, position: "cursor" | "end", diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts new file mode 100644 index 0000000000000..04fa4864bd73c --- /dev/null +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -0,0 +1,745 @@ +import type { ChatComposerProps } from "./ChatComposer"; +import { + type ComposerContextRecord, + type EnvironmentId, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + type PreviewAnnotationPayload, + type ThreadContextRecord, +} from "@t3tools/contracts"; +import { + type ComposerFileAttachment, + type PersistedComposerFileAttachment, + type PersistedComposerImageAttachment, + composerFileDedupKey, + composerFileMatchesReattachMarker, + composerFileNeedsReattach, + composerTargetKey, + hydrateImagesFromPersisted, + useComposerDraftStore, +} from "../../composerDraftStore"; +import { type ComposerPromptEditorHandle } from "../ComposerPromptEditor"; +import { + MAX_STASH_ENTRIES, + type PromptStashEntry, + partitionStashAttachments, + usePromptStashStore, +} from "../../promptStashStore"; +import { type PendingUserInput } from "../../session-logic"; +import { type ReviewCommentContext } from "../../reviewCommentContext"; +import { collapseExpandedComposerCursor } from "../../composer-logic"; +import { compressImageForStash } from "../../lib/imageCompression"; +import { formatInlineContextReference } from "~/lib/composerContextReferences"; +import { getTerminalFocusOwner } from "../../lib/terminalFocus"; +import { isCommandPaletteOpen } from "../../commandPaletteBus"; +import { pendingDraftWork } from "./pendingDraftWork"; +import { + previewAnnotationContextRecord, + reviewCommentContextRecord, + terminalContextRecord, +} from "~/lib/composerContextRecords"; +import { randomUUID } from "~/lib/utils"; +import { + readAttachmentUpload, + releaseAttachmentUpload, + releasePersistedAttachmentUpload, + verifyStashedAttachmentUpload, +} from "../../lib/attachmentUploadQueue"; +import { remainingComposerAttachmentSlots } from "./composerThreadImport"; +import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { resizeSnapShotSource } from "../../lib/snapShotSource"; +import { resolveShortcutCommand } from "../../keybindings"; +import { toastManager } from "../ui/toast"; +import type { useComposerTriggerState } from "./useComposerTriggerState"; +import { + type Dispatch, + type RefObject, + type SetStateAction, + useEffect, + useRef, + useState, +} from "react"; +import { useStableCallback } from "../../hooks/useStableCallback"; + +/** + * The prompt stash: saving the draft aside, restoring or deleting an entry, the badge pulse, + * and the stash shortcut. Its state lives here so the composer body only wires it up. + */ +export function useComposerStash(input: { + readonly environmentId: EnvironmentId; + readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"]; + readonly promptRef: ChatComposerProps["promptRef"]; + readonly composerImagesRef: ChatComposerProps["composerImagesRef"]; + readonly composerFilesRef: ChatComposerProps["composerFilesRef"]; + readonly composerTerminalContextsRef: ChatComposerProps["composerTerminalContextsRef"]; + readonly keybindings: ChatComposerProps["keybindings"]; + readonly terminalOpen: boolean; + readonly projectSelectionRequired: boolean; + readonly isRevertingCheckpoint: boolean; + readonly pendingUserInputs: ReadonlyArray; + readonly activePendingProgress: ChatComposerProps["activePendingProgress"]; + readonly prompt: string; + readonly composerMenuOpen: boolean; + readonly isComposerModelPickerOpen: boolean; + readonly isComposerCollapsedMobile: boolean; + readonly composerPreviewAnnotations: ReadonlyArray; + readonly composerReviewComments: ReadonlyArray; + readonly composerThreadContexts: ReadonlyArray; + readonly attachmentTargetKeyRef: RefObject; + readonly composerDraftTargetKeyRef: RefObject; + readonly composerEditorRef: RefObject; + readonly isRevertingCheckpointRef: RefObject; + readonly pendingThreadImportsRef: RefObject>; + readonly setComposerCursor: Dispatch>; + readonly setComposerTrigger: ReturnType["setTrigger"]; + readonly importContextRecords: ( + records: ReadonlyArray, + sourceEnvironmentId: EnvironmentId | null, + threadDraftTarget?: ChatComposerProps["composerDraftTarget"], + ) => ReadonlyMap; + readonly expandMobileComposer: () => void; +}) { + const { + environmentId, + composerDraftTarget, + promptRef, + composerImagesRef, + composerFilesRef, + composerTerminalContextsRef, + keybindings, + terminalOpen, + projectSelectionRequired, + isRevertingCheckpoint, + pendingUserInputs, + activePendingProgress, + prompt, + composerMenuOpen, + isComposerModelPickerOpen, + isComposerCollapsedMobile, + composerPreviewAnnotations, + composerReviewComments, + composerThreadContexts, + attachmentTargetKeyRef, + composerDraftTargetKeyRef, + composerEditorRef, + isRevertingCheckpointRef, + pendingThreadImportsRef, + setComposerCursor, + setComposerTrigger, + importContextRecords, + expandMobileComposer, + } = input; + const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); + const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); + const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); + const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles); + const removeComposerDraftPreviewAnnotation = useComposerDraftStore( + (store) => store.removePreviewAnnotation, + ); + const removeComposerDraftReviewComment = useComposerDraftStore( + (store) => store.removeReviewComment, + ); + const clearComposerDraftTerminalContexts = useComposerDraftStore( + (store) => store.clearTerminalContexts, + ); + const clearComposerDraftPromptAndImages = useComposerDraftStore( + (store) => store.clearComposerPromptAndImages, + ); + const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts); + const [isStashMenuOpen, setIsStashMenuOpen] = useState(false); + const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({ + key: 0, + active: false, + }); + const stashPulseKeyRef = useRef(0); + const stashPulseTimeoutRef = useRef(null); + const stashInFlightRef = useRef>(new Set()); + + const stashQueue = usePromptStashStore((state) => state.entries); + const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry); + const takeStashEntry = usePromptStashStore((state) => state.takeEntry); + const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages); + + useEffect(() => { + return () => { + if (stashPulseTimeoutRef.current !== null) { + window.clearTimeout(stashPulseTimeoutRef.current); + } + }; + }, []); + + const pulseStashBadge = () => { + stashPulseKeyRef.current += 1; + setStashPulse({ key: stashPulseKeyRef.current, active: true }); + if (stashPulseTimeoutRef.current !== null) { + window.clearTimeout(stashPulseTimeoutRef.current); + } + stashPulseTimeoutRef.current = window.setTimeout(() => { + stashPulseTimeoutRef.current = null; + setStashPulse((current) => ({ ...current, active: false })); + }, 1200); + }; + + const restoreStashEntry = async (menuEntry: PromptStashEntry) => { + const filesToVerify = menuEntry.files ?? []; + if (filesToVerify.some((file) => file.environmentId !== environmentId)) { + toastManager.add({ + type: "error", + title: "Stashed files belong to another environment", + description: "Restore this prompt in the environment that received its files.", + }); + return; + } + setIsStashMenuOpen(false); + + // An expired upload restores as a needs-reattach row instead of a reference + // the next send would fail to verify. Verify BEFORE taking: the take + // removes the entry from durable storage, and a tab closed during this + // await must still find it there after reload. + const verifications = await Promise.all( + filesToVerify.map((file) => + verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }), + ), + ); + const expiredAttachmentIds = new Set( + filesToVerify + .filter((_, index) => verifications[index]?.status === "missing") + .map((file) => file.attachmentId), + ); + + // A thread switch during the verify await would mix the new thread's + // prompt with this invocation's captured target. Nothing was taken yet, + // so abort and leave the entry restorable where the user now is. + if ( + isRevertingCheckpointRef.current || + composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current + ) { + return; + } + + const { entry, durable } = takeStashEntry(menuEntry.id); + if (!entry) return; + if (!durable) { + toastManager.add({ + type: "warning", + title: "Restored prompt may reappear in the stash", + description: + "Browser storage rejected the update, so this entry could still be there after a reload.", + data: { hideCopyButton: true }, + }); + } + + const rewrittenContextIds = entry.records + ? importContextRecords(entry.records, null, composerDraftTarget) + : new Map(); + const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { + const contextId = rewrittenContextIds.get(reference.contextId); + return contextId + ? formatInlineContextReference({ + ...reference, + contextId, + kind: reference.kind === "element" ? "preview-annotation" : reference.kind, + }) + : reference.source; + }); + const currentPrompt = promptRef.current; + const nextPrompt = + restoredPrompt.length === 0 + ? currentPrompt + : currentPrompt.trim().length + ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}` + : restoredPrompt; + let promptChanged = nextPrompt !== currentPrompt; + if (promptChanged) { + promptRef.current = nextPrompt; + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); + setComposerTrigger(null); + } + + let unrestoredFileNames: string[] = []; + const expiredFileNames: string[] = []; + let restoredFileCount = 0; + const stashedFiles = entry.files ?? []; + if (stashedFiles.length > 0) { + const composerFilesNow = composerFilesRef.current; + const existingFileIds = new Set(composerFilesNow.map((file) => file.id)); + const retainedUploadIds = new Set( + composerFilesNow.flatMap((file) => + file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [], + ), + ); + const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey)); + const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach); + const restoredMarkerIds = new Set(); + const duplicateFiles: PersistedComposerFileAttachment[] = []; + const markerReplacements: ComposerFileAttachment[] = []; + const appendedFiles: ComposerFileAttachment[] = []; + for (const file of stashedFiles) { + const expired = expiredAttachmentIds.has(file.attachmentId); + const key = composerFileDedupKey(file); + const restored: ComposerFileAttachment = { + type: "file", + id: file.id, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + file: null, + ...(file.source ? { source: file.source } : {}), + ...(expired + ? {} + : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }), + }; + if (existingFileIds.has(file.id)) { + if (!expired && !retainedUploadIds.has(file.attachmentId)) { + duplicateFiles.push(file); + } + continue; + } + const reattachMarker = reattachMarkers.find( + (marker) => + !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file), + ); + if (reattachMarker) { + restoredMarkerIds.add(reattachMarker.id); + existingFileIds.add(file.id); + existingFileKeys.add(key); + if (expired) { + expiredFileNames.push(file.name); + } else { + retainedUploadIds.add(file.attachmentId); + markerReplacements.push(restored); + } + continue; + } + if (existingFileKeys.has(key)) { + if (!expired && !retainedUploadIds.has(file.attachmentId)) { + duplicateFiles.push(file); + } + continue; + } + existingFileIds.add(file.id); + existingFileKeys.add(key); + if (expired) { + expiredFileNames.push(file.name); + } else { + retainedUploadIds.add(file.attachmentId); + } + appendedFiles.push(restored); + } + const capacity = remainingComposerAttachmentSlots( + composerImagesRef.current.length + composerFilesNow.length, + pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, + ); + const filesToAppend = appendedFiles.slice(0, capacity); + const skippedFiles = appendedFiles.slice(capacity); + unrestoredFileNames = skippedFiles.map((file) => file.name); + // A non-durable take can resurrect the stash entry after a reload; + // deleting these uploads would leave it pointing at nothing. + if (durable) { + for (const file of duplicateFiles) { + releasePersistedAttachmentUpload({ + id: file.id, + environmentId, + attachmentId: file.attachmentId, + }); + } + for (const file of skippedFiles) { + if (file.uploadedAttachmentId) { + releasePersistedAttachmentUpload({ + id: file.id, + environmentId, + attachmentId: file.uploadedAttachmentId, + }); + } + } + } + const restoredFiles = [...markerReplacements, ...filesToAppend]; + if (restoredFiles.length > 0) { + addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true }); + const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt; + if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) { + promptRef.current = restoredFilePrompt; + setComposerCursor( + collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length), + ); + setComposerTrigger(null); + promptChanged = true; + } + restoredFileCount = filesToAppend.length; + } + } + + let unrestoredImageNames: string[] = []; + if (entry.attachments.length > 0) { + const existingIds = new Set(composerImagesRef.current.map((image) => image.id)); + // The draft store also dedupes by mimeType+sizeBytes+name, so filter + // on the same key here. Counting a duplicate against capacity would + // burn a slot the store then refuses to fill, pushing a genuinely + // unique image into the overflow list for nothing. + const existingDedupKeys = new Set( + composerImagesRef.current.map( + (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`, + ), + ); + const capacity = remainingComposerAttachmentSlots( + composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount, + pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, + ); + const pending = entry.attachments.filter( + (attachment) => + !existingIds.has(attachment.id) && + !existingDedupKeys.has( + `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`, + ), + ); + unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name); + const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity)); + if (restoredImages.length > 0) { + addComposerDraftImages(composerDraftTarget, restoredImages); + } + } + + const missingImageReasons: string[] = []; + if (entry.droppedImageNames.length > 0) { + missingImageReasons.push( + `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, + ); + } + if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) { + missingImageReasons.push( + `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`, + ); + } + if (unrestoredImageNames.length > 0) { + missingImageReasons.push( + `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, + ); + } + if (unrestoredFileNames.length > 0) { + missingImageReasons.push( + `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, + ); + } + if (expiredFileNames.length > 0) { + missingImageReasons.push( + `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`, + ); + } + if (missingImageReasons.length > 0) { + toastManager.add({ + type: "warning", + title: "Some attachments were not restored", + description: missingImageReasons.join(" "), + }); + } + + if (promptChanged) { + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAtEnd(); + }); + } + }; + const restoreStashEntryStable = useStableCallback(restoreStashEntry); + + const deleteStashEntry = (entry: PromptStashEntry) => { + const { entry: removed, durable } = takeStashEntry(entry.id); + if (!stashQueue.some((candidate) => candidate.id !== entry.id)) { + setIsStashMenuOpen(false); + } + if (durable && removed) { + for (const file of removed.files ?? []) { + releasePersistedAttachmentUpload({ + id: file.id, + environmentId: file.environmentId, + attachmentId: file.attachmentId, + }); + } + } + if (!durable) { + toastManager.add({ + type: "warning", + title: "Stash entry may come back", + description: + "Browser storage rejected the delete, so this prompt could reappear after a reload.", + data: { hideCopyButton: true }, + }); + } + }; + const deleteStashEntryStable = useStableCallback(deleteStashEntry); + + const stashCurrentPrompt = async () => { + // Stashing clears the draft. A pasted attachment still downloading would then land in the + // emptied composer instead of travelling with the entry it belongs to. + if (pendingDraftWork.has(attachmentTargetKeyRef.current)) { + toastManager.add({ + type: "info", + title: "Still bringing attached context into this message.", + description: "Stash again once its chip resolves.", + }); + return; + } + const prompt = promptRef.current.trim(); + const images = [...composerImagesRef.current]; + const files = [...composerFilesRef.current]; + const stashedRecords: ComposerContextRecord[] = [ + ...composerThreadContexts, + ...composerTerminalContextsRef.current.map(terminalContextRecord), + ...composerReviewComments.map(reviewCommentContextRecord), + ...composerPreviewAnnotations.map((annotation) => + previewAnnotationContextRecord(annotation, { + screenshotContextId: images.some((image) => image.id === annotation.id) + ? annotation.id + : undefined, + }), + ), + ]; + if (prompt.length === 0 && images.length === 0 && files.length === 0) { + const entries = usePromptStashStore.getState().entries; + const entry = entries.length === 1 ? entries[0] : undefined; + if (entry && !entry.pendingImageCount) { + await restoreStashEntry(entry); + } else { + setIsStashMenuOpen((open) => !open); + } + return; + } + const stashedFiles: PersistedComposerFileAttachment[] = []; + for (const file of files) { + if (composerFileNeedsReattach(file)) { + toastManager.add({ + type: "error", + title: "Attach dropped files again or remove them before stashing", + }); + return; + } + const upload = readAttachmentUpload(file.id); + if (upload?.status !== "ready" || upload.environmentId !== environmentId) { + toastManager.add({ + type: "error", + title: "Wait for file uploads before stashing this prompt", + }); + return; + } + stashedFiles.push({ + id: file.id, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + attachmentId: upload.attachmentId, + environmentId, + ...(file.source ? { source: file.source } : {}), + }); + } + // A repeat ⌘S on the *same* still-unencoded snapshot would stash it + // twice. Guard on the snapshot itself rather than a bare boolean: once + // the composer has been cleared the user can type something genuinely + // new (or switch threads) while encoding continues, and that deserves its + // own entry. + const attachmentKey = images + .map((image) => `image:${image.id}`) + .concat(files.map((file) => `file:${file.id}`)) + .join(","); + const snapshotKey = [String(composerDraftTarget), prompt, attachmentKey].join("\n"); + if (stashInFlightRef.current.has(snapshotKey)) return; + stashInFlightRef.current.add(snapshotKey); + + const stashTarget = composerDraftTarget; + const entryId = randomUUID(); + const stashAndEncode = async () => { + // Ordering matters in both directions: writing before clearing means a + // crash or closed tab mid-encode still leaves the prompt recoverable, + // while clearing before the async image work means edits typed during + // encoding are not wiped. + const { evicted, written, durable } = stashEntryToQueue({ + id: entryId, + createdAt: new Date().toISOString(), + prompt, + attachments: [], + ...(stashedFiles.length > 0 ? { files: stashedFiles } : {}), + droppedImageNames: [], + unreadableImageNames: [], + pendingImageCount: images.length, + ...(stashedRecords.length > 0 ? { records: stashedRecords } : {}), + }); + + // If it was rejected (quota) the store has already rolled itself back, + // so leave the composer untouched rather than making it the second + // casualty of a reload. + if (!written) { + toastManager.add({ + type: "error", + title: "Could not stash this prompt", + description: + "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.", + data: { hideCopyButton: true }, + }); + return; + } + if (!durable) { + toastManager.add({ + type: "warning", + title: "Stashed prompt will not survive a reload", + description: + "Browser storage is unavailable, so this stash is kept in memory only for this session.", + data: { hideCopyButton: true }, + }); + } + + promptRef.current = ""; + clearComposerDraftPromptAndImages(stashTarget); + clearComposerDraftTerminalContexts(stashTarget); + setComposerDraftThreadContexts(stashTarget, []); + for (const comment of composerReviewComments) { + removeComposerDraftReviewComment(stashTarget, comment.id); + } + for (const annotation of composerPreviewAnnotations) { + releaseAttachmentUpload(annotation.id); + removeComposerDraftPreviewAnnotation(stashTarget, annotation.id); + } + setComposerDraftPrompt(stashTarget, ""); + for (const image of images) { + releaseAttachmentUpload(image.id); + } + setComposerCursor(0); + setComposerTrigger(null); + pulseStashBadge(); + + if (evicted) { + for (const file of evicted.files ?? []) { + releasePersistedAttachmentUpload({ + id: file.id, + environmentId: file.environmentId, + attachmentId: file.attachmentId, + }); + } + toastManager.add({ + type: "warning", + title: "Oldest stashed prompt discarded", + description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`, + data: { hideCopyButton: true }, + }); + } + + // Images are re-encoded for the stash rather than stored verbatim: the + // composer allows up to 10MB per image, but localStorage gives the whole + // origin ~5MB. + const candidateAttachments: PersistedComposerImageAttachment[] = []; + const oversizedImageNames: string[] = []; + const unreadableImageNames: string[] = []; + for (const image of images) { + const result = await compressImageForStash(image.file); + if (!result.ok) { + (result.reason === "too-large" ? oversizedImageNames : unreadableImageNames).push( + image.name, + ); + continue; + } + candidateAttachments.push({ + id: image.id, + name: image.name, + mimeType: result.image.mimeType, + sizeBytes: result.image.sizeBytes, + dataUrl: result.image.dataUrl, + ...(image.source + ? { source: resizeSnapShotSource(image.source, result.image.imageSize) } + : {}), + }); + } + const { kept, droppedNames } = partitionStashAttachments(candidateAttachments); + + const { attached, durable: imagesDurable } = finalizeStashEntryImages(entryId, { + attachments: kept, + droppedImageNames: [...oversizedImageNames, ...droppedNames], + unreadableImageNames, + }); + if (attached) { + if (!imagesDurable && durable && images.length > 0) { + toastManager.add({ + type: "warning", + title: "Stashed images were not saved", + description: + "The prompt was stashed, but browser storage rejected its images. They will be missing if you reload.", + data: { hideCopyButton: true }, + }); + } + } else if (kept.length > 0) { + toastManager.add({ + type: "warning", + title: "Stashed images did not attach", + description: `That prompt was restored or deleted before ${kept.length} image${kept.length === 1 ? "" : "s"} finished saving. Re-attach ${kept.length === 1 ? "it" : "them"} if you still need ${kept.length === 1 ? "it" : "them"}.`, + data: { hideCopyButton: true }, + }); + } + }; + await stashAndEncode().finally(() => stashInFlightRef.current.delete(snapshotKey)); + }; + const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt); + + const toggleStashMenu = () => { + if (isComposerCollapsedMobile) { + expandMobileComposer(); + setIsStashMenuOpen(true); + return; + } + setIsStashMenuOpen((open) => !open); + }; + const toggleStashMenuStable = useStableCallback(toggleStashMenu); + + const [stashMenuClosesOn, setStashMenuClosesOn] = useState({ prompt, composerMenuOpen }); + if ( + stashMenuClosesOn.prompt !== prompt || + stashMenuClosesOn.composerMenuOpen !== composerMenuOpen + ) { + setStashMenuClosesOn({ prompt, composerMenuOpen }); + if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false); + } + + useEffect(() => { + const handler = (event: globalThis.KeyboardEvent) => { + const command = resolveShortcutCommand(event, keybindings, { + context: { + terminalFocus: getTerminalFocusOwner() !== null, + terminalOpen, + modelPickerOpen: isComposerModelPickerOpen, + }, + }); + if (command !== "composer.stash") return; + // Always claim the shortcut so the browser save dialog never opens, + // even when the composer is in a state that can't stash. + event.preventDefault(); + event.stopPropagation(); + if (isCommandPaletteOpen() || isRevertingCheckpoint) { + return; + } + if (pendingUserInputs.length > 0) { + setIsStashMenuOpen((open) => !open); + return; + } + if (projectSelectionRequired || activePendingProgress !== null) { + return; + } + void stashCurrentPromptStable(); + }; + window.addEventListener("keydown", handler, true); + return () => window.removeEventListener("keydown", handler, true); + }, [ + activePendingProgress, + isComposerModelPickerOpen, + keybindings, + pendingUserInputs.length, + projectSelectionRequired, + stashCurrentPromptStable, + isRevertingCheckpoint, + terminalOpen, + ]); + + return { + stashQueue, + isStashMenuOpen, + setIsStashMenuOpen, + stashPulse, + restoreStashEntryStable, + deleteStashEntryStable, + toggleStashMenuStable, + }; +} From fa3700214ec1701c9b28d1ab5debcc1d66bbb2c9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 13:23:40 -0700 Subject: [PATCH 04/83] refactor(web): composer context imports live in useComposerContextImport (#23048) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 342 ++------------- .../chat/useComposerContextImport.ts | 398 ++++++++++++++++++ 2 files changed, 424 insertions(+), 316 deletions(-) create mode 100644 apps/web/src/components/chat/useComposerContextImport.ts diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index de7dea54f9fed..127b6a940f9e3 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,10 +6,8 @@ import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; import { useRightPanelStore } from "~/rightPanelStore"; import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste"; -import { elementContextToPreviewAnnotation } from "../../lib/elementContext"; import { questionAttachmentDraftId, - countQuestionAttachments, trackOpenQuestionAttachmentDraft, useQuestionAttachmentPreparation, changeQuestionAttachmentPreparation, @@ -179,7 +177,6 @@ import { import { ComposerContextActionsContext, composerContextRecordsFromDraft, - uploadedContextRecordFromDraft, } from "../composerContextPresentation"; import { useOpenPrLink } from "~/lib/openPullRequestLink"; import { @@ -192,44 +189,26 @@ import { inlineContextReferenceReplacement, } from "~/lib/composerContextReferences"; import { - asKnownContextRecord, attachmentContextRecord, - composerContextImportLookupIds, - isSameComposerContextPayload, uploadedAttachmentContextRecord, fileContextReference, imageContextReference, previewAnnotationContextId, previewAnnotationContextRecord, - previewAnnotationFromRecord, reviewCommentContextId, reviewCommentContextReference, reviewCommentContextRecord, - reviewCommentFromRecord, - terminalContextDraftFromRecord, terminalContextReference, terminalContextRecord, threadContextRecord, threadContextReference, } from "~/lib/composerContextRecords"; -import { - copiedComposerAttachmentFile, - rememberCopiedComposerAttachments, -} from "~/lib/copiedComposerAttachments"; +import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; import { readThreadShell } from "~/state/entities"; import { requestConfirmDialog } from "~/confirmDialog"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import type { - ComposerContextClipboardFragment, - ComposerContextRecord, - ThreadPullRequestLink, -} from "@t3tools/contracts"; -import { resolveAssetUrl } from "~/assets/assetUrls"; -import { assetEnvironment } from "~/state/assets"; -import { readPreparedConnection } from "~/state/session"; -import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; -import { orchestrationEnvironment } from "~/state/orchestration"; +import type { ComposerContextRecord, ThreadPullRequestLink } from "@t3tools/contracts"; import { threadContextAttachment } from "~/lib/threadContextAttachment"; import { type ComposerCommandItem, @@ -337,7 +316,6 @@ import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; import { useStableCallback } from "../../hooks/useStableCallback"; import { usePanelAnimationSettings } from "../../panelAnimations"; -import { useAtomCommand } from "../../state/use-atom-command"; import { readEnvironmentScope } from "../../state/session"; import type { ReviewCommentContext } from "../../reviewCommentContext"; import { useComposerRestingTransition } from "./useComposerRestingTransition"; @@ -347,6 +325,7 @@ import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnaps import { useComposerProviderModel } from "./useComposerProviderModel"; import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; +import { useComposerContextImport } from "./useComposerContextImport"; /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -355,15 +334,6 @@ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { return armed; } -async function downloadAttachmentBlob(url: string): Promise { - try { - const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); - return response.ok ? await response.blob() : null; - } catch { - return null; - } -} - const extendReplacementRangeForTrailingSpace = ( text: string, rangeEnd: number, @@ -1462,9 +1432,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) removeComposerDraftFile(attachmentDraftTarget, fileId); }; - const addComposerDraftTerminalContexts = useComposerDraftStore( - (store) => store.addTerminalContexts, - ); const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment); const addComposerDraftPreviewAnnotation = useComposerDraftStore( (store) => store.addPreviewAnnotation, @@ -1524,287 +1491,30 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return fragment; }; const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); - const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false }); - const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { - reportFailure: false, + const { + loadThreadTranscript, + countReservedAttachments, + countReservedAttachmentsStable, + importContextRecords, + importContextFragment, + importContextFragmentStable, + } = useComposerContextImport({ + environmentId, + activeThread, + activeThreadId, + composerDraftTarget, + attachmentDraftTarget, + attachmentTargetKey, + attachmentTargetKeyRef, + questionAttachmentTarget, + pendingUserInputs, + composerContextRecords, + composerImages, + composerFilesRef, + pendingImageCompressionsRef, + pendingThreadImportsRef, + addComposerFilesToDraft, }); - const countReservedAttachments = () => { - const questionRequest = pendingUserInputs[0]; - const otherQuestionKeys = - questionAttachmentTarget && questionRequest && activeThreadId - ? questionRequest.questions - .map((question) => - questionAttachmentDraftId( - environmentId, - activeThreadId, - questionRequest.requestId, - question.id, - ), - ) - .filter((key) => key !== questionAttachmentTarget) - : []; - const draft = getComposerDraft(attachmentDraftTarget); - return ( - (draft?.images.length ?? 0) + - (draft?.files.length ?? 0) + - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) + - (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) + - countQuestionAttachments(otherQuestionKeys) - ); - }; - const countReservedAttachmentsStable = useStableCallback(countReservedAttachments); - const runAttachmentImport = async ( - record: Extract, - localId: string, - sourceEnvironmentId: EnvironmentId, - importTargetKey: string, - ) => { - const fail = (reason: string) => { - toastManager.add({ - type: "error", - title: `Couldn't bring ${record.name} into this message`, - description: `${reason} Remove the chip or attach the file again.`, - }); - }; - let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId); - if (!file) { - const sourceConnection = readPreparedConnection(sourceEnvironmentId); - if (!sourceConnection) { - fail("The environment it came from is not connected."); - return; - } - const result = await createAssetUrl({ - environmentId: sourceEnvironmentId, - input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } }, - }); - const url = - result._tag === "Success" - ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl) - : null; - if (!url) { - fail("The original attachment is no longer available."); - return; - } - const blob = await downloadAttachmentBlob(url); - if (!blob) { - fail("Downloading it from the source failed."); - return; - } - file = new File([blob], record.name, { type: record.mimeType || blob.type }); - } - // The draft these bytes belong to may have been sent or switched away from while they - // downloaded. Dropping them here keeps them out of whatever draft is open now. - if (attachmentTargetKeyRef.current !== importTargetKey) return; - const replacesFileMarker = - record.kind === "file" && - composerFilesRef.current.some( - (candidate) => - composerFileNeedsReattach(candidate) && - composerFileMatchesReattachMarker(candidate, { - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - }), - ); - if ( - !replacesFileMarker && - (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 && - countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS - ) { - fail("The attachment limit has been reached."); - return; - } - if (record.kind === "image") { - const accepted = addComposerDraftImages( - attachmentDraftTarget, - [ - { - type: "image", - id: localId, - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - previewUrl: URL.createObjectURL(file), - file, - }, - ], - { - allowDuplicates: - getComposerDraft(composerDraftTarget)?.previewAnnotations.some( - (annotation) => annotation.id === localId, - ) ?? false, - }, - ); - if (!accepted.includes(localId)) - fail("The draft rejected this attachment (duplicate or attachment limit reached)."); - } else { - const accepted = addComposerFilesToDraft([ - { - type: "file", - id: localId, - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - file, - }, - ]); - if (!accepted.includes(localId)) - fail("The draft rejected this attachment (duplicate or attachment limit reached)."); - } - }; - const importAttachmentRecord = async ( - record: Extract, - localId: string, - sourceEnvironmentId: EnvironmentId, - ) => { - // The chip lands in the draft immediately while these bytes are still downloading. Count - // the transfer against its own draft so a send cannot snapshot a message whose chip has no - // attachment behind it, and so bytes for an abandoned draft never enter the next one. - const importTargetKey = attachmentTargetKey; - pendingDraftWork.begin(importTargetKey); - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => - pendingDraftWork.end(importTargetKey), - ); - }; - const importContextRecords = ( - records: ReadonlyArray, - sourceEnvironmentId: EnvironmentId | null, - threadDraftTarget = attachmentDraftTarget, - ): ReadonlyMap => { - const rewritten = new Map(); - const dependentAttachmentLocalIds = new Map(); - const skippedDependentAttachmentIds = new Set(); - // Resolve annotations before their dependent screenshot records even if a foreign - // clipboard producer emitted the records in a different order. - const orderedRecords = records.toSorted((left, right) => - left.kind === "preview-annotation" && right.kind !== "preview-annotation" - ? -1 - : right.kind === "preview-annotation" && left.kind !== "preview-annotation" - ? 1 - : 0, - ); - for (const candidate of orderedRecords) { - // Producer ids fold into context ids, so two different excerpts can collide. Only skip - // when the draft already holds the same payload; a colliding but different record is - // re-minted under a fresh id so both survive the paste. - const record = asKnownContextRecord(candidate); - if (!record) continue; - // A reminted annotation needs its screenshot under the new annotation id. - const existing = dependentAttachmentLocalIds.has(record.contextId) - ? undefined - : composerContextImportLookupIds(record).flatMap((contextId) => { - const found = composerContextRecords.get(contextId); - return found ? [found] : []; - })[0]; - // Upload completion can change the server id since copy; the local bytes still match. - if ( - sourceEnvironmentId !== null && - (record.kind === "image" || record.kind === "file") && - (existing?.kind === "image" || existing?.kind === "file") && - existing.record.file !== null && - existing.record.file === - copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId) - ) - continue; - const existingRecord = - existing?.kind === "terminal" - ? terminalContextRecord(existing.record) - : existing?.kind === "review-comment" - ? reviewCommentContextRecord(existing.record) - : existing?.kind === "preview-annotation" - ? previewAnnotationContextRecord(existing.record, { - screenshotContextId: composerImages.some( - (image) => image.id === existing.record.id, - ) - ? existing.record.id - : undefined, - }) - : existing?.kind === "thread" - ? existing.record - : existing - ? (uploadedContextRecordFromDraft(existing) ?? undefined) - : undefined; - if ( - existingRecord && - isSameComposerContextPayload(existingRecord, record) && - (record.kind !== "thread" || threadDraftTarget === attachmentDraftTarget) - ) { - if (record.kind === "preview-annotation" && record.screenshotContextId) { - skippedDependentAttachmentIds.add(record.screenshotContextId); - } - continue; - } - const conflicts = existing !== undefined; - switch (record.kind) { - case "terminal": { - const threadId = activeThread?.id ?? activeThreadId; - if (!threadId) break; - const imported = terminalContextDraftFromRecord(record, threadId); - const draft = conflicts ? { ...imported, id: randomUUID() } : imported; - addComposerDraftTerminalContexts(composerDraftTarget, [draft], { - appendReference: false, - }); - rewritten.set(record.contextId, terminalContextReference(draft).contextId); - break; - } - case "review-comment": { - const imported = reviewCommentFromRecord(record); - const comment = conflicts ? { ...imported, id: randomUUID() } : imported; - addComposerDraftReviewComment(composerDraftTarget, comment, { - appendReference: false, - }); - rewritten.set(record.contextId, reviewCommentContextId(comment.id)); - break; - } - case "element": - case "preview-annotation": { - const imported = - record.kind === "element" - ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString()) - : previewAnnotationFromRecord(record); - const annotation = conflicts ? { ...imported, id: randomUUID() } : imported; - if (record.kind === "preview-annotation" && record.screenshotContextId) { - dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id); - } - addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, { - appendReference: false, - }); - rewritten.set(record.contextId, previewAnnotationContextId(annotation.id)); - break; - } - case "thread": { - // The agent can only read threads on its own server; a pasted foreign one is dropped. - if (record.environmentId !== environmentId) break; - addComposerDraftThreadContexts(threadDraftTarget, [record], { - appendReference: false, - }); - rewritten.set(record.contextId, record.contextId); - break; - } - case "image": - case "file": { - if (skippedDependentAttachmentIds.has(record.contextId)) break; - if (sourceEnvironmentId === null && !conflicts) { - rewritten.set(record.contextId, record.contextId); - break; - } - if (sourceEnvironmentId === null) break; - const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID(); - rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId)); - void importAttachmentRecord(record, localId, sourceEnvironmentId); - break; - } - default: - break; - } - } - return rewritten; - }; - const importContextFragment = ( - fragment: ComposerContextClipboardFragment, - ): ReadonlyMap => - importContextRecords(fragment.records, fragment.source.environmentId); - const importContextFragmentStable = useStableCallback(importContextFragment); useEffect(() => { if (isLiteralPendingAnswer) return; diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts new file mode 100644 index 0000000000000..9fedbee2f579e --- /dev/null +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -0,0 +1,398 @@ +import type { RefObject } from "react"; +import type { ChatComposerProps } from "./ChatComposer"; +import { + type ComposerContextClipboardFragment, + type ComposerContextRecord, + type EnvironmentId, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, +} from "@t3tools/contracts"; +import { + type ComposerFileAttachment, + type ComposerImageAttachment, + type DraftId, + composerFileMatchesReattachMarker, + composerFileNeedsReattach, + useComposerDraftStore, +} from "../../composerDraftStore"; +import { type PendingUserInput } from "../../session-logic"; +import { + asKnownContextRecord, + composerContextImportLookupIds, + isSameComposerContextPayload, + previewAnnotationContextId, + previewAnnotationContextRecord, + previewAnnotationFromRecord, + reviewCommentContextId, + reviewCommentContextRecord, + reviewCommentFromRecord, + terminalContextDraftFromRecord, + terminalContextRecord, + terminalContextReference, +} from "~/lib/composerContextRecords"; +import { assetEnvironment } from "~/state/assets"; +import { copiedComposerAttachmentFile } from "~/lib/copiedComposerAttachments"; +import { countQuestionAttachments, questionAttachmentDraftId } from "../../questionAttachments"; +import { elementContextToPreviewAnnotation } from "../../lib/elementContext"; +import { orchestrationEnvironment } from "~/state/orchestration"; +import { pendingDraftWork } from "./pendingDraftWork"; +import { randomUUID } from "~/lib/utils"; +import { readPreparedConnection } from "~/state/session"; +import { resolveAssetUrl } from "~/assets/assetUrls"; +import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences"; +import { toastManager } from "../ui/toast"; +import { + type ComposerDraftContextRecords, + uploadedContextRecordFromDraft, +} from "../composerContextPresentation"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; +import { useStableCallback } from "../../hooks/useStableCallback"; + +async function downloadAttachmentBlob(url: string): Promise { + try { + const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); + return response.ok ? await response.blob() : null; + } catch { + return null; + } +} + +/** + * Imports copied composer context (terminal output, review comments, annotations, threads, + * images and files) into the open draft, and counts the attachment slots already spoken for. + */ +export function useComposerContextImport(input: { + readonly environmentId: EnvironmentId; + readonly activeThread: ChatComposerProps["activeThread"]; + readonly activeThreadId: ChatComposerProps["activeThreadId"]; + readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"]; + readonly attachmentDraftTarget: ChatComposerProps["composerDraftTarget"]; + readonly attachmentTargetKey: string; + readonly attachmentTargetKeyRef: RefObject; + readonly questionAttachmentTarget: DraftId | null; + readonly pendingUserInputs: ReadonlyArray; + readonly composerContextRecords: ComposerDraftContextRecords; + readonly composerImages: ReadonlyArray; + readonly composerFilesRef: ChatComposerProps["composerFilesRef"]; + readonly pendingImageCompressionsRef: RefObject>; + readonly pendingThreadImportsRef: RefObject>; + readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; +}) { + const { + environmentId, + activeThread, + activeThreadId, + composerDraftTarget, + attachmentDraftTarget, + attachmentTargetKey, + attachmentTargetKeyRef, + questionAttachmentTarget, + pendingUserInputs, + composerContextRecords, + composerImages, + composerFilesRef, + pendingImageCompressionsRef, + pendingThreadImportsRef, + addComposerFilesToDraft, + } = input; + const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); + const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); + const addComposerDraftTerminalContexts = useComposerDraftStore( + (store) => store.addTerminalContexts, + ); + const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment); + const addComposerDraftPreviewAnnotation = useComposerDraftStore( + (store) => store.addPreviewAnnotation, + ); + const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts); + const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false }); + const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { + reportFailure: false, + }); + const countReservedAttachments = () => { + const questionRequest = pendingUserInputs[0]; + const otherQuestionKeys = + questionAttachmentTarget && questionRequest && activeThreadId + ? questionRequest.questions + .map((question) => + questionAttachmentDraftId( + environmentId, + activeThreadId, + questionRequest.requestId, + question.id, + ), + ) + .filter((key) => key !== questionAttachmentTarget) + : []; + const draft = getComposerDraft(attachmentDraftTarget); + return ( + (draft?.images.length ?? 0) + + (draft?.files.length ?? 0) + + (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) + + (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) + + countQuestionAttachments(otherQuestionKeys) + ); + }; + const countReservedAttachmentsStable = useStableCallback(countReservedAttachments); + const runAttachmentImport = async ( + record: Extract, + localId: string, + sourceEnvironmentId: EnvironmentId, + importTargetKey: string, + ) => { + const fail = (reason: string) => { + toastManager.add({ + type: "error", + title: `Couldn't bring ${record.name} into this message`, + description: `${reason} Remove the chip or attach the file again.`, + }); + }; + let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId); + if (!file) { + const sourceConnection = readPreparedConnection(sourceEnvironmentId); + if (!sourceConnection) { + fail("The environment it came from is not connected."); + return; + } + const result = await createAssetUrl({ + environmentId: sourceEnvironmentId, + input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } }, + }); + const url = + result._tag === "Success" + ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl) + : null; + if (!url) { + fail("The original attachment is no longer available."); + return; + } + const blob = await downloadAttachmentBlob(url); + if (!blob) { + fail("Downloading it from the source failed."); + return; + } + file = new File([blob], record.name, { type: record.mimeType || blob.type }); + } + // The draft these bytes belong to may have been sent or switched away from while they + // downloaded. Dropping them here keeps them out of whatever draft is open now. + if (attachmentTargetKeyRef.current !== importTargetKey) return; + const replacesFileMarker = + record.kind === "file" && + composerFilesRef.current.some( + (candidate) => + composerFileNeedsReattach(candidate) && + composerFileMatchesReattachMarker(candidate, { + name: record.name, + mimeType: file.type, + sizeBytes: file.size, + }), + ); + if ( + !replacesFileMarker && + (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 && + countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS + ) { + fail("The attachment limit has been reached."); + return; + } + if (record.kind === "image") { + const accepted = addComposerDraftImages( + attachmentDraftTarget, + [ + { + type: "image", + id: localId, + name: record.name, + mimeType: file.type, + sizeBytes: file.size, + previewUrl: URL.createObjectURL(file), + file, + }, + ], + { + allowDuplicates: + getComposerDraft(composerDraftTarget)?.previewAnnotations.some( + (annotation) => annotation.id === localId, + ) ?? false, + }, + ); + if (!accepted.includes(localId)) + fail("The draft rejected this attachment (duplicate or attachment limit reached)."); + } else { + const accepted = addComposerFilesToDraft([ + { + type: "file", + id: localId, + name: record.name, + mimeType: file.type, + sizeBytes: file.size, + file, + }, + ]); + if (!accepted.includes(localId)) + fail("The draft rejected this attachment (duplicate or attachment limit reached)."); + } + }; + const importAttachmentRecord = async ( + record: Extract, + localId: string, + sourceEnvironmentId: EnvironmentId, + ) => { + // The chip lands in the draft immediately while these bytes are still downloading. Count + // the transfer against its own draft so a send cannot snapshot a message whose chip has no + // attachment behind it, and so bytes for an abandoned draft never enter the next one. + const importTargetKey = attachmentTargetKey; + pendingDraftWork.begin(importTargetKey); + await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => + pendingDraftWork.end(importTargetKey), + ); + }; + const importContextRecords = ( + records: ReadonlyArray, + sourceEnvironmentId: EnvironmentId | null, + threadDraftTarget = attachmentDraftTarget, + ): ReadonlyMap => { + const rewritten = new Map(); + const dependentAttachmentLocalIds = new Map(); + const skippedDependentAttachmentIds = new Set(); + // Resolve annotations before their dependent screenshot records even if a foreign + // clipboard producer emitted the records in a different order. + const orderedRecords = records.toSorted((left, right) => + left.kind === "preview-annotation" && right.kind !== "preview-annotation" + ? -1 + : right.kind === "preview-annotation" && left.kind !== "preview-annotation" + ? 1 + : 0, + ); + for (const candidate of orderedRecords) { + // Producer ids fold into context ids, so two different excerpts can collide. Only skip + // when the draft already holds the same payload; a colliding but different record is + // re-minted under a fresh id so both survive the paste. + const record = asKnownContextRecord(candidate); + if (!record) continue; + // A reminted annotation needs its screenshot under the new annotation id. + const existing = dependentAttachmentLocalIds.has(record.contextId) + ? undefined + : composerContextImportLookupIds(record).flatMap((contextId) => { + const found = composerContextRecords.get(contextId); + return found ? [found] : []; + })[0]; + // Upload completion can change the server id since copy; the local bytes still match. + if ( + sourceEnvironmentId !== null && + (record.kind === "image" || record.kind === "file") && + (existing?.kind === "image" || existing?.kind === "file") && + existing.record.file !== null && + existing.record.file === + copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId) + ) + continue; + const existingRecord = + existing?.kind === "terminal" + ? terminalContextRecord(existing.record) + : existing?.kind === "review-comment" + ? reviewCommentContextRecord(existing.record) + : existing?.kind === "preview-annotation" + ? previewAnnotationContextRecord(existing.record, { + screenshotContextId: composerImages.some( + (image) => image.id === existing.record.id, + ) + ? existing.record.id + : undefined, + }) + : existing?.kind === "thread" + ? existing.record + : existing + ? (uploadedContextRecordFromDraft(existing) ?? undefined) + : undefined; + if ( + existingRecord && + isSameComposerContextPayload(existingRecord, record) && + (record.kind !== "thread" || threadDraftTarget === attachmentDraftTarget) + ) { + if (record.kind === "preview-annotation" && record.screenshotContextId) { + skippedDependentAttachmentIds.add(record.screenshotContextId); + } + continue; + } + const conflicts = existing !== undefined; + switch (record.kind) { + case "terminal": { + const threadId = activeThread?.id ?? activeThreadId; + if (!threadId) break; + const imported = terminalContextDraftFromRecord(record, threadId); + const draft = conflicts ? { ...imported, id: randomUUID() } : imported; + addComposerDraftTerminalContexts(composerDraftTarget, [draft], { + appendReference: false, + }); + rewritten.set(record.contextId, terminalContextReference(draft).contextId); + break; + } + case "review-comment": { + const imported = reviewCommentFromRecord(record); + const comment = conflicts ? { ...imported, id: randomUUID() } : imported; + addComposerDraftReviewComment(composerDraftTarget, comment, { + appendReference: false, + }); + rewritten.set(record.contextId, reviewCommentContextId(comment.id)); + break; + } + case "element": + case "preview-annotation": { + const imported = + record.kind === "element" + ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString()) + : previewAnnotationFromRecord(record); + const annotation = conflicts ? { ...imported, id: randomUUID() } : imported; + if (record.kind === "preview-annotation" && record.screenshotContextId) { + dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id); + } + addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, { + appendReference: false, + }); + rewritten.set(record.contextId, previewAnnotationContextId(annotation.id)); + break; + } + case "thread": { + // The agent can only read threads on its own server; a pasted foreign one is dropped. + if (record.environmentId !== environmentId) break; + addComposerDraftThreadContexts(threadDraftTarget, [record], { + appendReference: false, + }); + rewritten.set(record.contextId, record.contextId); + break; + } + case "image": + case "file": { + if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (sourceEnvironmentId === null && !conflicts) { + rewritten.set(record.contextId, record.contextId); + break; + } + if (sourceEnvironmentId === null) break; + const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID(); + rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId)); + void importAttachmentRecord(record, localId, sourceEnvironmentId); + break; + } + default: + break; + } + } + return rewritten; + }; + const importContextFragment = ( + fragment: ComposerContextClipboardFragment, + ): ReadonlyMap => + importContextRecords(fragment.records, fragment.source.environmentId); + const importContextFragmentStable = useStableCallback(importContextFragment); + + return { + loadThreadTranscript, + countReservedAttachments, + countReservedAttachmentsStable, + importContextRecords, + importContextFragment, + importContextFragmentStable, + }; +} From 98c494ec69a47871d8544e45df23d61928326692 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 13:23:40 -0700 Subject: [PATCH 05/83] refactor(web): composer file intake lives in useComposerAttachmentIntake (#23049) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 357 ++------------- .../chat/useComposerAttachmentIntake.ts | 423 ++++++++++++++++++ 2 files changed, 450 insertions(+), 330 deletions(-) create mode 100644 apps/web/src/components/chat/useComposerAttachmentIntake.ts diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 127b6a940f9e3..e6f68ec3fde56 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -10,7 +10,6 @@ import { questionAttachmentDraftId, trackOpenQuestionAttachmentDraft, useQuestionAttachmentPreparation, - changeQuestionAttachmentPreparation, } from "../../questionAttachments"; import type { KeybindingCommand, @@ -37,18 +36,11 @@ import { ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, - PROVIDER_SEND_TURN_MAX_INPUT_CHARS, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import * as Schema from "effect/Schema"; -import { - isPasteAsTextShortcut, - nextPastedTextFileName, - pastedTextDisposition, - wouldTextPasteExceedLimit, -} from "@t3tools/client-runtime/text-paste"; +import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; import { splitTransferredFiles } from "./workspaceFileDrop"; @@ -102,7 +94,6 @@ import { type ComposerImageAttachment, type DraftId, type PersistedComposerImageAttachment, - composerFileMatchesReattachMarker, composerFileNeedsReattach, composerDraftHasUserContent, composerTargetKey, @@ -135,19 +126,12 @@ import { type ComposerBannerStackContent, type ComposerBannerStackItem, } from "./ComposerBannerStack"; -import { prepareImageForAttachment } from "../../lib/imageCompression"; -import { - fileAttachmentTooLargeMessage, - formatAttachmentSize, -} from "@t3tools/client-runtime/state/attachments"; import { attachmentsToReleaseOnUploadCapabilityLoss, composerOtherFilesForPresentation, - classifyComposerAttachmentFile, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -181,7 +165,6 @@ import { import { useOpenPrLink } from "~/lib/openPullRequestLink"; import { collectInlineContextIds, - stripInlineContextReferences, type ComposerContextReference, ensureInlineContextReferences, formatInlineContextReference, @@ -191,8 +174,6 @@ import { import { attachmentContextRecord, uploadedAttachmentContextRecord, - fileContextReference, - imageContextReference, previewAnnotationContextId, previewAnnotationContextRecord, reviewCommentContextId, @@ -206,7 +187,6 @@ import { import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; import { readThreadShell } from "~/state/entities"; -import { requestConfirmDialog } from "~/confirmDialog"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; import type { ComposerContextRecord, ThreadPullRequestLink } from "@t3tools/contracts"; import { threadContextAttachment } from "~/lib/threadContextAttachment"; @@ -289,7 +269,6 @@ import { type SessionPhase, type Thread, type ThreadShell, - videoMimeType, } from "../../types"; import { buildComposerPromptHistoryEntries, @@ -326,6 +305,7 @@ import { useComposerProviderModel } from "./useComposerProviderModel"; import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; +import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -1154,10 +1134,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); - const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set }>({ - targetKey: "", - names: new Set(), - }); const composerFormRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); @@ -3015,312 +2991,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); }; - const addComposerAttachments = async ( - files: File[], - options?: { - readonly source?: ChatFileAttachment["source"]; - readonly selection?: { start: number; end: number }; - readonly skipImageInlineChip?: boolean; - }, - ): Promise => { - if (!activeThreadId || files.length === 0 || isRevertingCheckpointRef.current) return false; - if ( - pendingUserInputs.length > 0 && - (!supportsQuestionAttachments || - activePendingProgress?.activeQuestion?.allowCustomAnswer === false || - activePendingIsResponding) - ) { - toastManager.add({ - type: "error", - title: "This question cannot accept attachments.", - }); - return false; - } - // Captured before the awaits below: the user may switch threads while a - // large image is being compressed, and the attachments and errors belong - // to the thread the paste happened in. - const threadId = activeThreadId; - const imageAttachmentsGetChips = - !options?.skipImageInlineChip && - (options?.selection !== undefined || - isConnecting || - pendingUserInputs.length > 0 || - projectSelectionRequired || - stripInlineContextReferences(promptRef.current).trim().length > 0); - - // Validation happens synchronously so concurrent pastes see each other: - // accepted files reserve their attachment slots (via the pending counter) - // before the first await, keeping the total under the limit. - const pendingCount = pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0; - let reservedCount = countReservedAttachments(); - // A pick that matches a needs-reattach marker replaces it in the draft, so - // it must not consume a slot; a draft full of markers would otherwise hit - // the capacity error before the replacement path could run. - const reattachMarkers = composerFilesRef.current.filter(composerFileNeedsReattach); - const replacedReattachMarkerIds = new Set(); - const acceptedImages: File[] = []; - const acceptedFiles: ComposerFileAttachment[] = []; - let error: string | null = null; - for (const file of files) { - const attachmentKind = classifyComposerAttachmentFile(file); - const fileMimeType = - attachmentKind === "file" - ? (videoMimeType({ name: file.name, mimeType: file.type }) ?? - (file.type || "application/octet-stream")) - : file.type; - const matchingReattachMarker = - attachmentKind === "file" - ? reattachMarkers.find( - (marker) => - !replacedReattachMarkerIds.has(marker.id) && - composerFileMatchesReattachMarker(marker, { - name: file.name || "file", - mimeType: fileMimeType, - sizeBytes: file.size, - }), - ) - : undefined; - if (matchingReattachMarker) { - replacedReattachMarkerIds.add(matchingReattachMarker.id); - } - if (!matchingReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { - error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`; - continue; - } - if (attachmentKind === "unsupported-image") { - error = `'${file.name}' is not a supported image type. Attach GIF, HEIC, HEIF, JPEG, PNG, or WebP images.`; - continue; - } - if (attachmentKind === "image") { - acceptedImages.push(normalizeComposerImageFileMimeType(file)); - } else { - if (fileStagingLimit === null) { - error = "This server does not support file attachments."; - continue; - } - if (file.size <= 0) { - error = `'${file.name}' is empty or could not be read.`; - continue; - } - if (file.size > fileStagingLimit) { - error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit); - continue; - } - const attachmentFile = - file.type === fileMimeType - ? file - : new File([file], file.name, { type: fileMimeType, lastModified: file.lastModified }); - acceptedFiles.push({ - type: "file", - id: randomUUID(), - name: attachmentFile.name || "file", - mimeType: fileMimeType, - sizeBytes: attachmentFile.size, - file: attachmentFile, - ...(options?.source ? { source: options.source } : {}), - }); - } - if (!matchingReattachMarker) { - reservedCount += 1; - } - } - setThreadError(threadId, error); - let insertedAny = false; - if (acceptedFiles.length > 0) { - const storedIds = new Set(addComposerFilesToDraft(acceptedFiles)); - const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id)); - if (storedFiles.length > 0) { - insertedAny = insertAttachmentReferences( - storedFiles.map(fileContextReference), - options?.selection, - ); - } - if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) { - const attached = storedFiles[0]!; - toastManager.add({ - type: "info", - title: `Large paste attached as ${attached.name}`, - description: `${formatAttachmentSize(attached.sizeBytes)} · Use ${ - isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V" - } to keep a large paste inline.`, - data: { hideCopyButton: true }, - }); - } - } - if (acceptedImages.length === 0) return insertedAny; - - pendingImageCompressionsRef.current.set( + const { addComposerAttachments, removeComposerImage, foldPastedText } = + useComposerAttachmentIntake({ + activeThreadId, + activePendingProgress, + activePendingIsResponding, + pendingUserInputs, + supportsQuestionAttachments, + isLiteralPendingAnswer, + isConnecting, + projectSelectionRequired, + questionAttachmentTarget, attachmentTargetKey, - pendingCount + acceptedImages.length, - ); - if (questionAttachmentTarget) - changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length); - const compressAndStoreImages = async (): Promise => { - const nextImages: ComposerImageAttachment[] = []; - let compressionError: string | null = null; - for (const file of acceptedImages) { - const compressed = await prepareImageForAttachment( - file, - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, - ); - if (!compressed.ok) { - compressionError = - compressed.reason === "unreadable" - ? `'${file.name}' could not be read as an image.` - : `'${file.name}' is too large to attach, even after compression.`; - continue; - } - const attachmentFile = compressed.file; - const previewUrl = URL.createObjectURL(attachmentFile); - nextImages.push({ - type: "image", - id: randomUUID(), - name: attachmentFile.name || "image", - mimeType: attachmentFile.type, - sizeBytes: attachmentFile.size, - previewUrl, - file: attachmentFile, - }); - } - if ( - questionAttachmentTarget && - !useQuestionAttachmentPreparation.getState().counts[questionAttachmentTarget] - ) { - for (const image of nextImages) URL.revokeObjectURL(image.previewUrl); - return false; - } - const storedImageIds = new Set( - nextImages.length === 1 && nextImages[0] - ? addComposerImage(nextImages[0]) - : nextImages.length > 1 - ? addComposerImagesToDraft(nextImages) - : [], - ); - const storedImages = nextImages.filter((image) => storedImageIds.has(image.id)); - if (storedImages.length > 0 && imageAttachmentsGetChips) { - insertedAny = - insertAttachmentReferences(storedImages.map(imageContextReference)) || insertedAny; - } - // Only failures are reported here. Success must not pass `null`: by - // now other work (a failed send, an overlapping paste) may have set a - // thread error this call knows nothing about, and clearing it would - // swallow that message. - if (compressionError !== null) { - setThreadError(threadId, compressionError); - } - return insertedAny; - }; - return await compressAndStoreImages().finally(() => { - if (questionAttachmentTarget) - changeQuestionAttachmentPreparation(questionAttachmentTarget, -acceptedImages.length); - const remaining = - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) - acceptedImages.length; - if (remaining > 0) { - pendingImageCompressionsRef.current.set(attachmentTargetKey, remaining); - } else { - pendingImageCompressionsRef.current.delete(attachmentTargetKey); - } - }); - }; - - const removeComposerImage = (imageId: string) => { - const image = composerImagesRef.current.find((candidate) => candidate.id === imageId); - const referenced = collectInlineContextIds(promptRef.current).includes( - image ? imageContextReference(image).contextId : "", - ); - if (!referenced) { - removeComposerImageFromDraft(imageId); - return; - } - const confirmation = requestConfirmDialog( - `Remove ${image?.name ?? "this image"} from the message?\nIt is referenced in your text; removing it also removes every reference.`, - { variant: "destructive" }, - ); - if (!confirmation) { - removeComposerImageFromDraft(imageId); - return; - } - void confirmation.then((confirmed) => { - if (confirmed) removeComposerImageFromDraft(imageId); - }); - }; - - const foldPastedText = ( - plainText: string, - bypassAutoAttachment: boolean, - selectionOverride?: { start: number; end: number }, - ): boolean => { - if (isLiteralPendingAnswer) return false; - const questionCanAttach = - pendingUserInputs.length === 0 || - (supportsQuestionAttachments && - activePendingProgress?.activeQuestion?.allowCustomAnswer !== false && - !activePendingIsResponding); - const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS; - const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange(); - const wouldExceedInputLimit = wouldTextPasteExceedLimit({ - valueLength: promptRef.current.length, - selection: selection ?? { start: 0, end: 0 }, - textLength: plainText.length, - maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS, - }); - const shouldFold = - pastedTextDisposition({ - text: plainText, - bypassAutoAttachment, - wouldExceedInputLimit, - canAttach: true, - }) === "attachment"; - if (!shouldFold) { - return false; - } - - const canStageAttachment = - Boolean(activeThreadId) && - !isRevertingCheckpointRef.current && - questionCanAttach && - hasAttachmentSlot; - if (!canStageAttachment || fileStagingLimit === null) { - if (!wouldExceedInputLimit) { - return false; - } - toastManager.add({ - type: "error", - title: "Pasted text is too large for this message", - description: "Remove some text or an attachment, then paste again.", - data: { hideCopyButton: true }, - }); - return true; - } - - if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) { - pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() }; - } - const reservedNames = pastedTextFileNamesRef.current.names; - for (const file of composerFilesRef.current) reservedNames.add(file.name); - const foldedFileName = nextPastedTextFileName([...reservedNames]); - reservedNames.add(foldedFileName); - const foldedFile = new File([plainText], foldedFileName, { - type: "text/plain;charset=utf-8", - }); - if (foldedFile.size > fileStagingLimit) { - reservedNames.delete(foldedFileName); - if (!wouldExceedInputLimit) return false; - toastManager.add({ - type: "error", - title: "Pasted text is too large to attach", - description: "Reduce the clipboard contents or save a smaller excerpt as a file.", - data: { hideCopyButton: true }, - }); - return true; - } - - void addComposerAttachments([foldedFile], { - source: { _tag: "pasted-text" }, - ...(selection ? { selection } : {}), + fileStagingLimit, + promptRef, + composerImagesRef, + composerFilesRef, + composerEditorRef, + isRevertingCheckpointRef, + pendingImageCompressionsRef, + setThreadError, + countReservedAttachments, + addComposerImage, + addComposerImagesToDraft, + addComposerFilesToDraft, + removeComposerImageFromDraft, + insertAttachmentReferences, }); - return true; - }; const onComposerCommandKeyStable = useStableCallback(onComposerCommandKey); const isPathQueryActiveStable = useStableCallback( diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts new file mode 100644 index 0000000000000..36ffebd4fd285 --- /dev/null +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -0,0 +1,423 @@ +import type { ChatComposerProps } from "./ChatComposer"; +import { + type ChatFileAttachment, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + PROVIDER_SEND_TURN_MAX_INPUT_CHARS, +} from "@t3tools/contracts"; +import { + type ComposerContextReference, + collectInlineContextIds, + stripInlineContextReferences, +} from "~/lib/composerContextReferences"; +import { + type ComposerFileAttachment, + type ComposerImageAttachment, + type DraftId, + composerFileMatchesReattachMarker, + composerFileNeedsReattach, +} from "../../composerDraftStore"; +import { type ComposerPromptEditorHandle } from "../ComposerPromptEditor"; +import { type PendingUserInput } from "../../session-logic"; +import { + changeQuestionAttachmentPreparation, + useQuestionAttachmentPreparation, +} from "../../questionAttachments"; +import { + classifyComposerAttachmentFile, + normalizeComposerImageFileMimeType, +} from "./composerAttachmentFiles"; +import { + fileAttachmentTooLargeMessage, + formatAttachmentSize, +} from "@t3tools/client-runtime/state/attachments"; +import { fileContextReference, imageContextReference } from "~/lib/composerContextRecords"; +import { isMacPlatform, randomUUID } from "~/lib/utils"; +import { + nextPastedTextFileName, + pastedTextDisposition, + wouldTextPasteExceedLimit, +} from "@t3tools/client-runtime/text-paste"; +import { prepareImageForAttachment } from "../../lib/imageCompression"; +import { requestConfirmDialog } from "~/confirmDialog"; +import { toastManager } from "../ui/toast"; +import { type RefObject, useRef } from "react"; +import { videoMimeType } from "../../types"; + +/** + * Takes files into the draft: validates and reserves slots, compresses images, inserts + * their inline chips, folds large pastes into text attachments, and confirms removing a referenced image. + */ +export function useComposerAttachmentIntake(input: { + readonly activeThreadId: ChatComposerProps["activeThreadId"]; + readonly activePendingProgress: ChatComposerProps["activePendingProgress"]; + readonly activePendingIsResponding: boolean; + readonly pendingUserInputs: ReadonlyArray; + readonly supportsQuestionAttachments: boolean; + readonly isLiteralPendingAnswer: boolean; + readonly isConnecting: boolean; + readonly projectSelectionRequired: boolean; + readonly questionAttachmentTarget: DraftId | null; + readonly attachmentTargetKey: string; + readonly fileStagingLimit: number | null; + readonly promptRef: ChatComposerProps["promptRef"]; + readonly composerImagesRef: ChatComposerProps["composerImagesRef"]; + readonly composerFilesRef: ChatComposerProps["composerFilesRef"]; + readonly composerEditorRef: RefObject; + readonly isRevertingCheckpointRef: RefObject; + readonly pendingImageCompressionsRef: RefObject>; + readonly setThreadError: ChatComposerProps["setThreadError"]; + readonly countReservedAttachments: () => number; + readonly addComposerImage: (image: ComposerImageAttachment) => string[]; + readonly addComposerImagesToDraft: (images: ComposerImageAttachment[]) => string[]; + readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + readonly removeComposerImageFromDraft: (imageId: string) => void; + readonly insertAttachmentReferences: ( + references: ReadonlyArray, + selection?: { start: number; end: number }, + ) => boolean; +}) { + const { + activeThreadId, + activePendingProgress, + activePendingIsResponding, + pendingUserInputs, + supportsQuestionAttachments, + isLiteralPendingAnswer, + isConnecting, + projectSelectionRequired, + questionAttachmentTarget, + attachmentTargetKey, + fileStagingLimit, + promptRef, + composerImagesRef, + composerFilesRef, + composerEditorRef, + isRevertingCheckpointRef, + pendingImageCompressionsRef, + setThreadError, + countReservedAttachments, + addComposerImage, + addComposerImagesToDraft, + addComposerFilesToDraft, + removeComposerImageFromDraft, + insertAttachmentReferences, + } = input; + const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set }>({ + targetKey: "", + names: new Set(), + }); + + const addComposerAttachments = async ( + files: File[], + options?: { + readonly source?: ChatFileAttachment["source"]; + readonly selection?: { start: number; end: number }; + readonly skipImageInlineChip?: boolean; + }, + ): Promise => { + if (!activeThreadId || files.length === 0 || isRevertingCheckpointRef.current) return false; + if ( + pendingUserInputs.length > 0 && + (!supportsQuestionAttachments || + activePendingProgress?.activeQuestion?.allowCustomAnswer === false || + activePendingIsResponding) + ) { + toastManager.add({ + type: "error", + title: "This question cannot accept attachments.", + }); + return false; + } + // Captured before the awaits below: the user may switch threads while a + // large image is being compressed, and the attachments and errors belong + // to the thread the paste happened in. + const threadId = activeThreadId; + const imageAttachmentsGetChips = + !options?.skipImageInlineChip && + (options?.selection !== undefined || + isConnecting || + pendingUserInputs.length > 0 || + projectSelectionRequired || + stripInlineContextReferences(promptRef.current).trim().length > 0); + + // Validation happens synchronously so concurrent pastes see each other: + // accepted files reserve their attachment slots (via the pending counter) + // before the first await, keeping the total under the limit. + const pendingCount = pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0; + let reservedCount = countReservedAttachments(); + // A pick that matches a needs-reattach marker replaces it in the draft, so + // it must not consume a slot; a draft full of markers would otherwise hit + // the capacity error before the replacement path could run. + const reattachMarkers = composerFilesRef.current.filter(composerFileNeedsReattach); + const replacedReattachMarkerIds = new Set(); + const acceptedImages: File[] = []; + const acceptedFiles: ComposerFileAttachment[] = []; + let error: string | null = null; + for (const file of files) { + const attachmentKind = classifyComposerAttachmentFile(file); + const fileMimeType = + attachmentKind === "file" + ? (videoMimeType({ name: file.name, mimeType: file.type }) ?? + (file.type || "application/octet-stream")) + : file.type; + const matchingReattachMarker = + attachmentKind === "file" + ? reattachMarkers.find( + (marker) => + !replacedReattachMarkerIds.has(marker.id) && + composerFileMatchesReattachMarker(marker, { + name: file.name || "file", + mimeType: fileMimeType, + sizeBytes: file.size, + }), + ) + : undefined; + if (matchingReattachMarker) { + replacedReattachMarkerIds.add(matchingReattachMarker.id); + } + if (!matchingReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`; + continue; + } + if (attachmentKind === "unsupported-image") { + error = `'${file.name}' is not a supported image type. Attach GIF, HEIC, HEIF, JPEG, PNG, or WebP images.`; + continue; + } + if (attachmentKind === "image") { + acceptedImages.push(normalizeComposerImageFileMimeType(file)); + } else { + if (fileStagingLimit === null) { + error = "This server does not support file attachments."; + continue; + } + if (file.size <= 0) { + error = `'${file.name}' is empty or could not be read.`; + continue; + } + if (file.size > fileStagingLimit) { + error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit); + continue; + } + const attachmentFile = + file.type === fileMimeType + ? file + : new File([file], file.name, { type: fileMimeType, lastModified: file.lastModified }); + acceptedFiles.push({ + type: "file", + id: randomUUID(), + name: attachmentFile.name || "file", + mimeType: fileMimeType, + sizeBytes: attachmentFile.size, + file: attachmentFile, + ...(options?.source ? { source: options.source } : {}), + }); + } + if (!matchingReattachMarker) { + reservedCount += 1; + } + } + setThreadError(threadId, error); + let insertedAny = false; + if (acceptedFiles.length > 0) { + const storedIds = new Set(addComposerFilesToDraft(acceptedFiles)); + const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id)); + if (storedFiles.length > 0) { + insertedAny = insertAttachmentReferences( + storedFiles.map(fileContextReference), + options?.selection, + ); + } + if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) { + const attached = storedFiles[0]!; + toastManager.add({ + type: "info", + title: `Large paste attached as ${attached.name}`, + description: `${formatAttachmentSize(attached.sizeBytes)} · Use ${ + isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V" + } to keep a large paste inline.`, + data: { hideCopyButton: true }, + }); + } + } + if (acceptedImages.length === 0) return insertedAny; + + pendingImageCompressionsRef.current.set( + attachmentTargetKey, + pendingCount + acceptedImages.length, + ); + if (questionAttachmentTarget) + changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length); + const compressAndStoreImages = async (): Promise => { + const nextImages: ComposerImageAttachment[] = []; + let compressionError: string | null = null; + for (const file of acceptedImages) { + const compressed = await prepareImageForAttachment( + file, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + if (!compressed.ok) { + compressionError = + compressed.reason === "unreadable" + ? `'${file.name}' could not be read as an image.` + : `'${file.name}' is too large to attach, even after compression.`; + continue; + } + const attachmentFile = compressed.file; + const previewUrl = URL.createObjectURL(attachmentFile); + nextImages.push({ + type: "image", + id: randomUUID(), + name: attachmentFile.name || "image", + mimeType: attachmentFile.type, + sizeBytes: attachmentFile.size, + previewUrl, + file: attachmentFile, + }); + } + if ( + questionAttachmentTarget && + !useQuestionAttachmentPreparation.getState().counts[questionAttachmentTarget] + ) { + for (const image of nextImages) URL.revokeObjectURL(image.previewUrl); + return false; + } + const storedImageIds = new Set( + nextImages.length === 1 && nextImages[0] + ? addComposerImage(nextImages[0]) + : nextImages.length > 1 + ? addComposerImagesToDraft(nextImages) + : [], + ); + const storedImages = nextImages.filter((image) => storedImageIds.has(image.id)); + if (storedImages.length > 0 && imageAttachmentsGetChips) { + insertedAny = + insertAttachmentReferences(storedImages.map(imageContextReference)) || insertedAny; + } + // Only failures are reported here. Success must not pass `null`: by + // now other work (a failed send, an overlapping paste) may have set a + // thread error this call knows nothing about, and clearing it would + // swallow that message. + if (compressionError !== null) { + setThreadError(threadId, compressionError); + } + return insertedAny; + }; + return await compressAndStoreImages().finally(() => { + if (questionAttachmentTarget) + changeQuestionAttachmentPreparation(questionAttachmentTarget, -acceptedImages.length); + const remaining = + (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) - acceptedImages.length; + if (remaining > 0) { + pendingImageCompressionsRef.current.set(attachmentTargetKey, remaining); + } else { + pendingImageCompressionsRef.current.delete(attachmentTargetKey); + } + }); + }; + + const removeComposerImage = (imageId: string) => { + const image = composerImagesRef.current.find((candidate) => candidate.id === imageId); + const referenced = collectInlineContextIds(promptRef.current).includes( + image ? imageContextReference(image).contextId : "", + ); + if (!referenced) { + removeComposerImageFromDraft(imageId); + return; + } + const confirmation = requestConfirmDialog( + `Remove ${image?.name ?? "this image"} from the message?\nIt is referenced in your text; removing it also removes every reference.`, + { variant: "destructive" }, + ); + if (!confirmation) { + removeComposerImageFromDraft(imageId); + return; + } + void confirmation.then((confirmed) => { + if (confirmed) removeComposerImageFromDraft(imageId); + }); + }; + + const foldPastedText = ( + plainText: string, + bypassAutoAttachment: boolean, + selectionOverride?: { start: number; end: number }, + ): boolean => { + if (isLiteralPendingAnswer) return false; + const questionCanAttach = + pendingUserInputs.length === 0 || + (supportsQuestionAttachments && + activePendingProgress?.activeQuestion?.allowCustomAnswer !== false && + !activePendingIsResponding); + const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS; + const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange(); + const wouldExceedInputLimit = wouldTextPasteExceedLimit({ + valueLength: promptRef.current.length, + selection: selection ?? { start: 0, end: 0 }, + textLength: plainText.length, + maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS, + }); + const shouldFold = + pastedTextDisposition({ + text: plainText, + bypassAutoAttachment, + wouldExceedInputLimit, + canAttach: true, + }) === "attachment"; + if (!shouldFold) { + return false; + } + + const canStageAttachment = + Boolean(activeThreadId) && + !isRevertingCheckpointRef.current && + questionCanAttach && + hasAttachmentSlot; + if (!canStageAttachment || fileStagingLimit === null) { + if (!wouldExceedInputLimit) { + return false; + } + toastManager.add({ + type: "error", + title: "Pasted text is too large for this message", + description: "Remove some text or an attachment, then paste again.", + data: { hideCopyButton: true }, + }); + return true; + } + + if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) { + pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() }; + } + const reservedNames = pastedTextFileNamesRef.current.names; + for (const file of composerFilesRef.current) reservedNames.add(file.name); + const foldedFileName = nextPastedTextFileName([...reservedNames]); + reservedNames.add(foldedFileName); + const foldedFile = new File([plainText], foldedFileName, { + type: "text/plain;charset=utf-8", + }); + if (foldedFile.size > fileStagingLimit) { + reservedNames.delete(foldedFileName); + if (!wouldExceedInputLimit) return false; + toastManager.add({ + type: "error", + title: "Pasted text is too large to attach", + description: "Reduce the clipboard contents or save a smaller excerpt as a file.", + data: { hideCopyButton: true }, + }); + return true; + } + + void addComposerAttachments([foldedFile], { + source: { _tag: "pasted-text" }, + ...(selection ? { selection } : {}), + }); + return true; + }; + + return { + addComposerAttachments, + removeComposerImage, + foldPastedText, + }; +} From 1444b3f99442630c92abfb5157840d500487d145 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 13:23:40 -0700 Subject: [PATCH 06/83] refactor(web): the composer's footer controls render in ComposerControlsBar (#23058) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 246 +++---------- .../components/chat/ComposerControlsBar.tsx | 331 ++++++++++++++++++ 2 files changed, 376 insertions(+), 201 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerControlsBar.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index e6f68ec3fde56..becc6beafdda1 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -196,7 +196,6 @@ import { composerSuggestionOptionId, } from "./ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; -import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu"; import { ComposerAttachButton, ComposerAttachmentFileList, @@ -206,23 +205,13 @@ import { ComposerRestingImagePreviews, } from "./ComposerAttachmentStrip"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; -import { - ComposerFooterModeControls, - ComposerFooterPrimaryActions, - ComposerModelPicker, -} from "./ComposerFooterControls"; +import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; -import { ComposerControl, ComposerControlSeparator } from "./ComposerControl"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic"; -import { - getComposerPromptInjectionState, - getComposerReasoningStep, - renderProviderTraitsMenuContent, - renderProviderTraitsPicker, -} from "./composerProviderState"; +import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState"; import { readPromptUltrathink } from "./TraitsPicker"; import { providerSupportsManualCompaction, @@ -258,7 +247,7 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24; const COMPOSER_SCROLL_GESTURE_RESET_MS = 120; import { toastManager } from "../ui/toast"; -import { CircleAlertIcon, PlayIcon, ShieldIcon } from "lucide-react"; +import { PlayIcon, ShieldIcon } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -306,6 +295,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { ComposerControlsBar } from "./ComposerControlsBar"; /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -1300,34 +1290,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const editPromptFromTraitsStable = useStableCallback(editPromptFromTraits); const promptUltrathink = readPromptUltrathink(prompt); - const providerTraitsMenuContent = renderProviderTraitsMenuContent({ - provider: selectedProvider, - instanceId: selectedInstanceId, - ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), - ...(routeKind === "draft" && draftId ? { draftId } : {}), - model: selectedModel, - models: selectedProviderModels, - modelOptions: composerModelOptions?.[selectedInstanceId], - reportedModelSelection, - promptUltrathink, - onPromptEdit: editPromptFromTraitsStable, - planModeEnabled: settings.planModeEnabled, - }); - const providerTraitsPickerInput = { - provider: selectedProvider, - instanceId: selectedInstanceId, - ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), - ...(routeKind === "draft" && draftId ? { draftId } : {}), - model: selectedModel, - models: selectedProviderModels, - modelOptions: composerModelOptions?.[selectedInstanceId], - reportedModelSelection, - promptUltrathink, - onPromptEdit: editPromptFromTraitsStable, - planModeEnabled: settings.planModeEnabled, - isComposerOwned: true, - } satisfies Parameters[0]; - const providerTraitsPicker = renderProviderTraitsPicker(providerTraitsPickerInput); const [inlineRestingControlsHost, setInlineRestingControlsHost] = useState( null, ); @@ -2699,179 +2661,61 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const iconOnlyBlockCount = composerControlsCollapsed ? restingControlsIconOnlyBlockCount : expandedControlsIconOnlyBlockCount; - const restingProviderTraitsPicker = renderProviderTraitsPicker({ - ...providerTraitsPickerInput, - size: composerControlsCollapsed ? "xs" : "sm", - hidden: composerControlsHidden || restingHiddenBlockCount > 1, - }); - const restingBlockDefs = [ - ...(providerTraitsPicker - ? [ - { - id: "traits", - content: ( - <> - - {restingProviderTraitsPicker} - - ), - }, - ] - : []), - { - id: "mode", - content: ( -