The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts"; |
| 2 | import { markdownProseDirection, textDirection } from "~/textDirection"; |
| 3 | import { useGT } from "gt-react"; |
| 4 | import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react"; |
| 5 | import { BackgroundThreadContext } from "./backgroundThread"; |
| 6 | import { useStableCallback } from "~/hooks/useStableCallback"; |
| 7 | import { type PendingUserInput } from "../../session-logic"; |
| 8 | import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; |
| 9 | import { derivePendingUserInputProgress } from "../../pendingUserInput"; |
| 10 | import { CheckboxMark } from "../ui/checkbox"; |
| 11 | import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; |
| 12 | import { Kbd } from "../ui/kbd"; |
| 13 | import { cn } from "~/lib/utils"; |
| 14 | import { isInSideChatPane } from "~/lib/sideChatPane"; |
| 15 | import { ComposerBanner } from "./ComposerBanner"; |
| 16 | import ChatMarkdown from "../ChatMarkdown"; |
| 17 | |
| 18 | interface PendingUserInputPanelProps { |
| 19 | pendingUserInputs: PendingUserInput[]; |
| 20 | cwd: string | undefined; |
| 21 | threadRef: ScopedThreadRef; |
| 22 | disabled?: boolean; |
| 23 | respondingRequestIds: RuntimeRequestId[]; |
| 24 | answers: Record<string, PendingUserInputDraftAnswer>; |
| 25 | questionIndex: number; |
| 26 | onToggleOption: (questionId: string, optionValue: string) => void; |
| 27 | onAdvance: () => void; |
| 28 | onDismiss: (requestId: RuntimeRequestId) => void; |
| 29 | } |
| 30 | |
| 31 | export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({ |
| 32 | pendingUserInputs, |
| 33 | cwd, |
| 34 | threadRef, |
| 35 | disabled = false, |
| 36 | respondingRequestIds, |
| 37 | answers, |
| 38 | questionIndex, |
| 39 | onToggleOption, |
| 40 | onAdvance, |
| 41 | onDismiss, |
| 42 | }: PendingUserInputPanelProps) { |
| 43 | if (pendingUserInputs.length === 0) return null; |
| 44 | const activePrompt = pendingUserInputs[0]; |
| 45 | if (!activePrompt) return null; |
| 46 | |
| 47 | return ( |
| 48 | <ComposerPendingUserInputCard |
| 49 | key={activePrompt.requestId} |
| 50 | prompt={activePrompt} |
| 51 | cwd={cwd} |
| 52 | threadRef={threadRef} |
| 53 | disabled={disabled} |
| 54 | isResponding={respondingRequestIds.includes(activePrompt.requestId)} |
| 55 | answers={answers} |
| 56 | questionIndex={questionIndex} |
| 57 | onToggleOption={onToggleOption} |
| 58 | onAdvance={onAdvance} |
| 59 | onDismiss={onDismiss} |
| 60 | /> |
| 61 | ); |
| 62 | }); |
| 63 | |
| 64 | const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({ |
| 65 | prompt, |
| 66 | cwd, |
| 67 | threadRef, |
| 68 | disabled, |
| 69 | isResponding, |
| 70 | answers, |
| 71 | questionIndex, |
| 72 | onToggleOption, |
| 73 | onAdvance, |
| 74 | onDismiss, |
| 75 | }: { |
| 76 | prompt: PendingUserInput; |
| 77 | cwd: string | undefined; |
| 78 | threadRef: ScopedThreadRef; |
| 79 | disabled: boolean; |
| 80 | isResponding: boolean; |
| 81 | answers: Record<string, PendingUserInputDraftAnswer>; |
| 82 | questionIndex: number; |
| 83 | onToggleOption: (questionId: string, optionValue: string) => void; |
| 84 | onAdvance: () => void; |
| 85 | onDismiss: (requestId: RuntimeRequestId) => void; |
| 86 | }) { |
| 87 | const gt = useGT(); |
| 88 | // Message-mode requests remain answerable after their provider turn ends. |
| 89 | const canRespond = prompt.responseCapability !== "not_resumable"; |
| 90 | const responseDisabled = disabled || isResponding || !canRespond; |
| 91 | const autoAdvanceTimerRef = useRef<number | null>(null); |
| 92 | const advance = useStableCallback(onAdvance); |
| 93 | const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{ |
| 94 | questionId: string; |
| 95 | optionValue: string; |
| 96 | } | null>(null); |
| 97 | const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null); |
| 98 | // Keep question identity stable for its shortcut listener. |
| 99 | const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex); |
| 100 | const activeQuestion = progress.activeQuestion; |
| 101 | const customAnswerActive = progress.customAnswer.trim().length > 0; |
| 102 | // Read before later hooks to preserve the question's compiler cache. |
| 103 | const draftSelectedOptions = activeQuestion?.options.map( |
| 104 | (option) => |
| 105 | !customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label), |
| 106 | ); |
| 107 | const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id; |
| 108 | |
| 109 | if ( |
| 110 | optimisticSingleSelect && |
| 111 | activeQuestion && |
| 112 | !activeQuestion.multiSelect && |
| 113 | (optimisticSingleSelect.questionId !== activeQuestion.id || |
| 114 | (!customAnswerActive && |
| 115 | progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue))) |
| 116 | ) { |
| 117 | setOptimisticSingleSelect(null); |
| 118 | } |
| 119 | |
| 120 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the auto-advance timer when the question changes, input is disabled, or the panel unmounts |
| 121 | useEffect(() => { |
| 122 | const clearAutoAdvance = () => { |
| 123 | if (autoAdvanceTimerRef.current !== null) { |
| 124 | window.clearTimeout(autoAdvanceTimerRef.current); |
| 125 | autoAdvanceTimerRef.current = null; |
| 126 | } |
| 127 | }; |
| 128 | if (disabled || activeQuestion?.id === undefined) clearAutoAdvance(); |
| 129 | return clearAutoAdvance; |
| 130 | }, [activeQuestion?.id, disabled]); |
| 131 | |
| 132 | const handleOptionSelection = (questionId: string, optionValue: string) => { |
| 133 | if (disabled || isResponding) return; |
| 134 | if (activeQuestion?.multiSelect) { |
| 135 | onToggleOption(questionId, optionValue); |
| 136 | return; |
| 137 | } |
| 138 | setOptimisticSingleSelect({ questionId, optionValue }); |
| 139 | onToggleOption(questionId, optionValue); |
| 140 | if (autoAdvanceTimerRef.current !== null) { |
| 141 | window.clearTimeout(autoAdvanceTimerRef.current); |
| 142 | } |
| 143 | autoAdvanceTimerRef.current = window.setTimeout(() => { |
| 144 | autoAdvanceTimerRef.current = null; |
| 145 | advance(); |
| 146 | }, 200); |
| 147 | }; |
| 148 | |
| 149 | const selectOptionFromShortcut = useEffectEvent(handleOptionSelection); |
| 150 | const backgroundThread = use(BackgroundThreadContext); |
| 151 | |
| 152 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a document keydown listener for digit shortcuts while a question is answerable |
| 153 | useEffect(() => { |
| 154 | if (!activeQuestion || responseDisabled || isCollapsed || backgroundThread) return; |
| 155 | const handler = (event: globalThis.KeyboardEvent) => { |
| 156 | if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return; |
| 157 | const target = event.target; |
| 158 | if (isInSideChatPane(target)) return; |
| 159 | if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { |
| 160 | return; |
| 161 | } |
| 162 | if ( |
| 163 | target instanceof HTMLElement && |
| 164 | target.closest( |
| 165 | 'select, [contenteditable]:not([contenteditable="false"]), [role="dialog"], [aria-modal="true"], [role="menu"], [role="combobox"], [data-slot$="popup"]', |
| 166 | ) |
| 167 | ) { |
| 168 | return; |
| 169 | } |
| 170 | const digit = Number.parseInt(event.key, 10); |
| 171 | if (Number.isNaN(digit) || digit < 1 || digit > 9) return; |
| 172 | const optionIndex = digit - 1; |
| 173 | if (optionIndex >= activeQuestion.options.length) return; |
| 174 | const option = activeQuestion.options[optionIndex]; |
| 175 | if (!option) return; |
| 176 | event.preventDefault(); |
| 177 | selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label); |
| 178 | }; |
| 179 | document.addEventListener("keydown", handler); |
| 180 | return () => document.removeEventListener("keydown", handler); |
| 181 | }, [activeQuestion, backgroundThread, isCollapsed, responseDisabled]); |
| 182 | |
| 183 | if (!activeQuestion) { |
| 184 | return null; |
| 185 | } |
| 186 | |
| 187 | const promptDirection = markdownProseDirection( |
| 188 | prompt.questions |
| 189 | .flatMap((question) => [ |
| 190 | question.header, |
| 191 | question.question, |
| 192 | ...question.options.flatMap((option) => [option.label, option.description ?? ""]), |
| 193 | ]) |
| 194 | .join(" "), |
| 195 | ); |
| 196 | const questionTextAlign = promptDirection === "rtl" ? "text-right" : "text-left"; |
| 197 | |
| 198 | return ( |
| 199 | <Collapsible |
| 200 | dir={promptDirection} |
| 201 | open={!isCollapsed} |
| 202 | onOpenChange={(open) => { |
| 203 | setCollapsedQuestionId(open ? null : activeQuestion.id); |
| 204 | }} |
| 205 | > |
| 206 | <CollapsibleTrigger |
| 207 | render={<ComposerBanner.Row render={<button type="button" />} />} |
| 208 | title={ |
| 209 | isCollapsed |
| 210 | ? gt("Show the question and its options") |
| 211 | : gt("Hide the question and its options") |
| 212 | } |
| 213 | data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"} |
| 214 | className="px-4 py-1.5" |
| 215 | > |
| 216 | <ComposerBanner.Content> |
| 217 | <span |
| 218 | className={cn("min-w-0 truncate text-muted-foreground", isCollapsed && "max-w-1/2")} |
| 219 | dir={textDirection(activeQuestion.header)} |
| 220 | > |
| 221 | {activeQuestion.header} |
| 222 | </span> |
| 223 | {isCollapsed ? ( |
| 224 | <> |
| 225 | <ComposerBanner.Separator /> |
| 226 | <span |
| 227 | className={cn("min-w-0 flex-1 truncate text-secondary-label", questionTextAlign)} |
| 228 | dir={markdownProseDirection(activeQuestion.question)} |
| 229 | > |
| 230 | {activeQuestion.question} |
| 231 | </span> |
| 232 | </> |
| 233 | ) : null} |
| 234 | </ComposerBanner.Content> |
| 235 | <ComposerBanner.Actions className="gap-0"> |
| 236 | {prompt.questions.length > 1 ? ( |
| 237 | <ComposerBanner.Count> |
| 238 | {questionIndex + 1}/{prompt.questions.length} |
| 239 | </ComposerBanner.Count> |
| 240 | ) : null} |
| 241 | <ComposerBanner.ToggleIcon expanded={!isCollapsed} /> |
| 242 | {prompt.dismissible ? ( |
| 243 | <ComposerBanner.Dismiss |
| 244 | render={<span role="button" tabIndex={0} />} |
| 245 | aria-label={gt("Dismiss question without answering")} |
| 246 | title={gt("Dismiss question without answering")} |
| 247 | disabled={isResponding} |
| 248 | data-pending-user-input-dismiss |
| 249 | onClick={(event) => { |
| 250 | event.preventDefault(); |
| 251 | event.stopPropagation(); |
| 252 | onDismiss(prompt.requestId); |
| 253 | }} |
| 254 | onKeyDown={(event) => { |
| 255 | if (event.key !== "Enter" && event.key !== " ") return; |
| 256 | event.preventDefault(); |
| 257 | event.stopPropagation(); |
| 258 | onDismiss(prompt.requestId); |
| 259 | }} |
| 260 | /> |
| 261 | ) : null} |
| 262 | </ComposerBanner.Actions> |
| 263 | </CollapsibleTrigger> |
| 264 | <CollapsiblePanel> |
| 265 | <ComposerBanner.Scroll> |
| 266 | <ComposerBanner.Body className="ps-6 pe-4 pb-1 wrap-anywhere sm:ps-5.5"> |
| 267 | <ChatMarkdown |
| 268 | text={activeQuestion.question} |
| 269 | cwd={cwd} |
| 270 | threadRef={threadRef} |
| 271 | lineBreaks |
| 272 | className={cn("pt-0.5 text-foreground/85", questionTextAlign)} |
| 273 | /> |
| 274 | {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */} |
| 275 | <div className="-ms-2 mt-1.5 sm:-ms-1.5"> |
| 276 | {activeQuestion.options.map((option, index) => { |
| 277 | const optionValue = option.value ?? option.label; |
| 278 | const isOptimisticallySelected = |
| 279 | optimisticSingleSelect?.questionId === activeQuestion.id && |
| 280 | optimisticSingleSelect.optionValue === optionValue; |
| 281 | const isSelected = |
| 282 | isOptimisticallySelected || draftSelectedOptions?.[index] === true; |
| 283 | const className = cn( |
| 284 | questionTextAlign, |
| 285 | "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25", |
| 286 | isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30", |
| 287 | (disabled || isResponding) && "opacity-50 cursor-not-allowed", |
| 288 | !disabled && !isResponding && "cursor-pointer", |
| 289 | ); |
| 290 | // The h-5 slots match the label's line box, so the indicator and shortcut stay on its first line. |
| 291 | const content = ( |
| 292 | <> |
| 293 | <span className="pointer-events-none flex h-5 shrink-0 items-center"> |
| 294 | {activeQuestion.multiSelect ? ( |
| 295 | <CheckboxMark checked={isSelected} variant="contrast" /> |
| 296 | ) : ( |
| 297 | <OptionRadio checked={isSelected} /> |
| 298 | )} |
| 299 | </span> |
| 300 | <div className="min-w-0 flex-1 flex flex-col gap-0.5"> |
| 301 | <span className="text-sm font-medium" dir={textDirection(option.label)}> |
| 302 | {option.label} |
| 303 | </span> |
| 304 | {option.description && option.description !== option.label ? ( |
| 305 | <span |
| 306 | className="text-secondary-label text-2xs" |
| 307 | dir={textDirection(option.description)} |
| 308 | > |
| 309 | {option.description} |
| 310 | </span> |
| 311 | ) : null} |
| 312 | </div> |
| 313 | {index < 9 ? ( |
| 314 | <span className="flex h-5 w-7 shrink-0 items-center justify-center sm:w-6"> |
| 315 | <Kbd>{index + 1}</Kbd> |
| 316 | </span> |
| 317 | ) : null} |
| 318 | </> |
| 319 | ); |
| 320 | // The preview sits outside the button: it can hold links, and a click on a single-select option advances. |
| 321 | return ( |
| 322 | <div key={`${activeQuestion.id}:${optionValue}`}> |
| 323 | <button |
| 324 | type="button" |
| 325 | aria-pressed={isSelected} |
| 326 | disabled={disabled || isResponding} |
| 327 | onClick={() => { |
| 328 | handleOptionSelection(activeQuestion.id, optionValue); |
| 329 | }} |
| 330 | className={className} |
| 331 | > |
| 332 | {content} |
| 333 | </button> |
| 334 | {option.preview ? ( |
| 335 | <ChatMarkdown |
| 336 | text={option.preview} |
| 337 | cwd={cwd} |
| 338 | threadRef={threadRef} |
| 339 | lineBreaks |
| 340 | className="ps-9 pe-2 pb-1.5 text-xs text-foreground/70 sm:ps-8" |
| 341 | /> |
| 342 | ) : null} |
| 343 | </div> |
| 344 | ); |
| 345 | })} |
| 346 | </div> |
| 347 | </ComposerBanner.Body> |
| 348 | </ComposerBanner.Scroll> |
| 349 | </CollapsiblePanel> |
| 350 | </Collapsible> |
| 351 | ); |
| 352 | }); |
| 353 | |
| 354 | // Drawn with ui/radio-group's look instead of using its Radio: Radio only checks inside a |
| 355 | // RadioGroup, whose arrow keys select options and would trip the single-select auto-advance. |
| 356 | function OptionRadio({ checked }: { checked: boolean }) { |
| 357 | return ( |
| 358 | <span |
| 359 | aria-hidden |
| 360 | className={cn( |
| 361 | "relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-full border border-foreground/55 bg-background not-dark:bg-clip-padding sm:size-4 dark:bg-input/32", |
| 362 | checked ? "shadow-none" : "shadow-xs/5", |
| 363 | )} |
| 364 | > |
| 365 | {checked ? ( |
| 366 | <span className="-inset-px absolute flex items-center justify-center rounded-full bg-primary before:size-2 before:rounded-full before:bg-primary-foreground sm:before:size-1.5" /> |
| 367 | ) : null} |
| 368 | </span> |
| 369 | ); |
| 370 | } |