The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-react"; |
| 2 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { m } from "~/i18n/messages"; |
| 4 | import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; |
| 5 | import { |
| 6 | AuthOrchestrationOperateScope, |
| 7 | type EnvironmentId, |
| 8 | type ProviderApprovalDecision, |
| 9 | type RuntimeRequestId, |
| 10 | type ScopedThreadRef, |
| 11 | type ThreadId, |
| 12 | type UserInputAttachments, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import { |
| 15 | derivePendingThreadRequests, |
| 16 | seedUserInputDraftAnswers, |
| 17 | userInputDraftKey, |
| 18 | } from "@t3tools/client-runtime/state/thread-requests"; |
| 19 | import { |
| 20 | isAtomCommandInterrupted, |
| 21 | squashAtomCommandFailure, |
| 22 | } from "@t3tools/client-runtime/state/runtime"; |
| 23 | import { useRef, useState, type RefObject, type SetStateAction } from "react"; |
| 24 | import { useShallow } from "zustand/react/shallow"; |
| 25 | import { |
| 26 | type ComposerThreadDraftState, |
| 27 | type DraftId, |
| 28 | useComposerDraftStore, |
| 29 | } from "../../composerDraftStore"; |
| 30 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 31 | import { |
| 32 | getUploadedAttachments, |
| 33 | refreshExpiredAttachmentUploads, |
| 34 | useAttachmentUploadStore, |
| 35 | } from "../../lib/attachmentUploadQueue"; |
| 36 | import { composerDraftContentChanged } from "./composerSend.logic"; |
| 37 | import { |
| 38 | buildPendingUserInputAnswers, |
| 39 | setPendingUserInputCustomAnswer, |
| 40 | togglePendingUserInputOptionSelection, |
| 41 | type PendingUserInputDraftAnswer, |
| 42 | } from "@t3tools/client-runtime/state/pending-user-input"; |
| 43 | import { |
| 44 | carryDisplacedCustomAnswerIntoPrompt, |
| 45 | withdrawDisplacedCustomAnswerFromPrompt, |
| 46 | derivePendingUserInputProgress, |
| 47 | answerContextRecords, |
| 48 | projectPendingUserInputAnswer, |
| 49 | threadContextsReferencedByAnswer, |
| 50 | } from "../../pendingUserInput"; |
| 51 | import { |
| 52 | questionAttachmentDraftId, |
| 53 | usePendingUserInputAnswers, |
| 54 | usePendingUserInputQuestionIndex, |
| 55 | useQuestionAttachmentPreparation, |
| 56 | } from "../../questionAttachments"; |
| 57 | import { |
| 58 | derivePendingApprovals, |
| 59 | derivePendingUserInputs, |
| 60 | type PendingUserInput, |
| 61 | } from "../../session-logic"; |
| 62 | import { readEnvironmentScope } from "../../state/session"; |
| 63 | import { threadEnvironment } from "../../state/threads"; |
| 64 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 65 | import { useOrchestrationCommand } from "../../state/use-orchestration-command"; |
| 66 | import { toastManager } from "../ui/toast"; |
| 67 | |
| 68 | import type { ChatComposerHandle } from "./ChatComposer"; |
| 69 | |
| 70 | const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {}; |
| 71 | const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const; |
| 72 | const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = []; |
| 73 | const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = []; |
| 74 | |
| 75 | interface PendingUserInputDraftScope { |
| 76 | readonly environmentId: EnvironmentId; |
| 77 | readonly activeThreadId: ThreadId | null; |
| 78 | readonly activePendingUserInput: PendingUserInput | null; |
| 79 | readonly supportsQuestionAttachments: boolean; |
| 80 | } |
| 81 | |
| 82 | function pendingUserInputDraftKeys(scope: PendingUserInputDraftScope) { |
| 83 | const { environmentId, activeThreadId, activePendingUserInput } = scope; |
| 84 | return { |
| 85 | requestKey: userInputDraftKey(environmentId, activeThreadId, activePendingUserInput?.requestId), |
| 86 | questionKeys: |
| 87 | activeThreadId && activePendingUserInput |
| 88 | ? activePendingUserInput.questions.map((question) => |
| 89 | questionAttachmentDraftId( |
| 90 | environmentId, |
| 91 | activeThreadId, |
| 92 | activePendingUserInput.requestId, |
| 93 | question.id, |
| 94 | ), |
| 95 | ) |
| 96 | : [], |
| 97 | }; |
| 98 | } |
| 99 | |
| 100 | const selectQuestionComposerDrafts = |
| 101 | (keys: ReadonlyArray<string>) => |
| 102 | (state: { readonly draftsByThreadKey: Record<string, ComposerThreadDraftState> }) => |
| 103 | Object.fromEntries(keys.map((key) => [key, state.draftsByThreadKey[key]])); |
| 104 | |
| 105 | const selectQuestionUploadsBlocked = |
| 106 | ( |
| 107 | keys: ReadonlyArray<string>, |
| 108 | questionComposerDrafts: Record<string, ComposerThreadDraftState | undefined>, |
| 109 | environmentId: EnvironmentId, |
| 110 | ) => |
| 111 | (state: ReturnType<typeof useAttachmentUploadStore.getState>) => |
| 112 | Object.fromEntries( |
| 113 | keys.map((key) => { |
| 114 | const draft = questionComposerDrafts[key]; |
| 115 | const attachments = draft ? [...draft.images, ...draft.files] : []; |
| 116 | return [ |
| 117 | key, |
| 118 | attachments.some((attachment) => { |
| 119 | const upload = state.uploadsByImageId[attachment.id]; |
| 120 | return upload?.status !== "ready" || upload.environmentId !== environmentId; |
| 121 | }), |
| 122 | ]; |
| 123 | }), |
| 124 | ); |
| 125 | |
| 126 | const selectQuestionPreparations = |
| 127 | (keys: ReadonlyArray<string>) => (state: { readonly counts: Record<string, number> }) => |
| 128 | Object.fromEntries(keys.map((key) => [key, state.counts[key] ?? 0])); |
| 129 | |
| 130 | function deriveActivePendingDraft( |
| 131 | scope: PendingUserInputDraftScope, |
| 132 | storedPendingAnswerDrafts: Record<string, PendingUserInputDraftAnswer>, |
| 133 | activePendingQuestionIndex: number, |
| 134 | questionComposerDrafts: Record<string, ComposerThreadDraftState | undefined>, |
| 135 | questionUploadsBlocked: Record<string, boolean>, |
| 136 | questionPreparations: Record<string, number>, |
| 137 | ) { |
| 138 | const { environmentId, activeThreadId, activePendingUserInput, supportsQuestionAttachments } = |
| 139 | scope; |
| 140 | // Suggested answers are shown until the user edits them; only edits are stored. |
| 141 | const activePendingAnswerDrafts: Record<string, PendingUserInputDraftAnswer> = |
| 142 | activePendingUserInput |
| 143 | ? seedUserInputDraftAnswers(activePendingUserInput.questions, storedPendingAnswerDrafts) |
| 144 | : storedPendingAnswerDrafts; |
| 145 | const activePendingDraftAnswers = |
| 146 | !activePendingUserInput || !activeThreadId |
| 147 | ? EMPTY_PENDING_USER_INPUT_ANSWERS |
| 148 | : Object.fromEntries( |
| 149 | activePendingUserInput.questions.map((question) => { |
| 150 | const key = questionAttachmentDraftId( |
| 151 | environmentId, |
| 152 | activeThreadId, |
| 153 | activePendingUserInput.requestId, |
| 154 | question.id, |
| 155 | ); |
| 156 | const draft = questionComposerDrafts[key]; |
| 157 | const attachments = draft ? [...draft.images, ...draft.files] : []; |
| 158 | return [ |
| 159 | question.id, |
| 160 | { |
| 161 | ...activePendingAnswerDrafts[question.id], |
| 162 | attachmentCount: attachments.length, |
| 163 | attachmentsBlocked: |
| 164 | (attachments.length > 0 && !supportsQuestionAttachments) || |
| 165 | (questionPreparations[key] ?? 0) > 0 || |
| 166 | questionUploadsBlocked[key] === true, |
| 167 | }, |
| 168 | ]; |
| 169 | }), |
| 170 | ); |
| 171 | const activePendingProgress = activePendingUserInput |
| 172 | ? derivePendingUserInputProgress( |
| 173 | activePendingUserInput.questions, |
| 174 | activePendingDraftAnswers, |
| 175 | activePendingQuestionIndex, |
| 176 | ) |
| 177 | : null; |
| 178 | const activePendingResolvedAnswers = activePendingUserInput |
| 179 | ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers) |
| 180 | : null; |
| 181 | return { |
| 182 | activePendingDraftAnswers, |
| 183 | activePendingQuestionIndex, |
| 184 | activePendingProgress, |
| 185 | activePendingResolvedAnswers, |
| 186 | }; |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * The open question's answers, position and progress. These change on every keystroke, so |
| 191 | * the composer subscribes to them rather than the chat view. |
| 192 | */ |
| 193 | export function usePendingUserInputDraft(scope: PendingUserInputDraftScope) { |
| 194 | const { requestKey, questionKeys: keys } = pendingUserInputDraftKeys(scope); |
| 195 | const storedPendingAnswerDrafts = usePendingUserInputAnswers( |
| 196 | (state) => state[requestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS, |
| 197 | ); |
| 198 | const activePendingQuestionIndex = usePendingUserInputQuestionIndex( |
| 199 | (state) => state[requestKey] ?? 0, |
| 200 | ); |
| 201 | const questionComposerDrafts = useComposerDraftStore( |
| 202 | useShallow(selectQuestionComposerDrafts(keys)), |
| 203 | ); |
| 204 | const questionUploadsBlocked = useAttachmentUploadStore( |
| 205 | useShallow(selectQuestionUploadsBlocked(keys, questionComposerDrafts, scope.environmentId)), |
| 206 | ); |
| 207 | const questionPreparations = useQuestionAttachmentPreparation( |
| 208 | useShallow(selectQuestionPreparations(keys)), |
| 209 | ); |
| 210 | return deriveActivePendingDraft( |
| 211 | scope, |
| 212 | storedPendingAnswerDrafts, |
| 213 | activePendingQuestionIndex, |
| 214 | questionComposerDrafts, |
| 215 | questionUploadsBlocked, |
| 216 | questionPreparations, |
| 217 | ); |
| 218 | } |
| 219 | |
| 220 | // Request callbacks read drafts when called, so the chat view never subscribes to them. |
| 221 | function readPendingUserInputDraft(scope: PendingUserInputDraftScope) { |
| 222 | const { requestKey, questionKeys: keys } = pendingUserInputDraftKeys(scope); |
| 223 | const questionComposerDrafts = selectQuestionComposerDrafts(keys)( |
| 224 | useComposerDraftStore.getState(), |
| 225 | ); |
| 226 | return deriveActivePendingDraft( |
| 227 | scope, |
| 228 | usePendingUserInputAnswers.getState()[requestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS, |
| 229 | usePendingUserInputQuestionIndex.getState()[requestKey] ?? 0, |
| 230 | questionComposerDrafts, |
| 231 | selectQuestionUploadsBlocked( |
| 232 | keys, |
| 233 | questionComposerDrafts, |
| 234 | scope.environmentId, |
| 235 | )(useAttachmentUploadStore.getState()), |
| 236 | selectQuestionPreparations(keys)(useQuestionAttachmentPreparation.getState()), |
| 237 | ); |
| 238 | } |
| 239 | |
| 240 | function makePendingCustomAnswerSetter(input: { |
| 241 | readonly activePendingUserInput: PendingUserInput | null; |
| 242 | readonly activePendingRequestKey: string; |
| 243 | readonly writePrompt: (prompt: string) => void; |
| 244 | readonly withdrawRestoredAnswer: (questionId: string, value: string) => void; |
| 245 | readonly setPendingUserInputAnswersByRequestId: ( |
| 246 | update: SetStateAction<Record<string, Record<string, PendingUserInputDraftAnswer>>>, |
| 247 | ) => void; |
| 248 | }) { |
| 249 | return (questionId: string, value: string) => { |
| 250 | const { activePendingUserInput, activePendingRequestKey } = input; |
| 251 | if (!activePendingUserInput) { |
| 252 | return; |
| 253 | } |
| 254 | const question = activePendingUserInput.questions.find((entry) => entry.id === questionId); |
| 255 | if (!question || question.allowCustomAnswer === false) { |
| 256 | return; |
| 257 | } |
| 258 | input.writePrompt(value); |
| 259 | input.withdrawRestoredAnswer(questionId, value); |
| 260 | input.setPendingUserInputAnswersByRequestId((existing) => ({ |
| 261 | ...existing, |
| 262 | [activePendingRequestKey]: { |
| 263 | ...existing[activePendingRequestKey], |
| 264 | [questionId]: setPendingUserInputCustomAnswer( |
| 265 | question, |
| 266 | existing[activePendingRequestKey]?.[questionId], |
| 267 | value, |
| 268 | ), |
| 269 | }, |
| 270 | })); |
| 271 | // Resetting selection before rendering can re-enter Lexical with stale skill-token offsets. |
| 272 | }; |
| 273 | } |
| 274 | |
| 275 | export function usePendingThreadRequests(input: { |
| 276 | readonly environmentId: EnvironmentId; |
| 277 | readonly activeThreadId: ThreadId | null; |
| 278 | readonly serverProjection: ThreadStructure | null; |
| 279 | readonly supportsQuestionAttachments: boolean; |
| 280 | readonly composerDraftTarget: ScopedThreadRef | DraftId; |
| 281 | readonly setComposerDraftPrompt: (target: ScopedThreadRef | DraftId, prompt: string) => void; |
| 282 | readonly promptRef: { current: string }; |
| 283 | readonly composerRef: RefObject<ChatComposerHandle | null>; |
| 284 | readonly setThreadError: (threadId: ThreadId, error: string | null) => void; |
| 285 | }) { |
| 286 | const { |
| 287 | environmentId, |
| 288 | activeThreadId, |
| 289 | serverProjection, |
| 290 | supportsQuestionAttachments, |
| 291 | composerDraftTarget, |
| 292 | setComposerDraftPrompt, |
| 293 | promptRef, |
| 294 | composerRef, |
| 295 | setThreadError, |
| 296 | } = input; |
| 297 | const respondToThreadApproval = useOrchestrationCommand(threadEnvironment.respondToApproval, { |
| 298 | reportFailure: false, |
| 299 | }); |
| 300 | const respondToThreadUserInput = useOrchestrationCommand(threadEnvironment.respondToUserInput, { |
| 301 | reportFailure: false, |
| 302 | }); |
| 303 | const dismissThreadUserInput = useAtomCommand(threadEnvironment.dismissUserInput, { |
| 304 | reportFailure: false, |
| 305 | }); |
| 306 | const userInputResponsesInFlight = useRef(new Set<string>()); |
| 307 | // In the order the text went into the thread draft, which is how a copy is found again. |
| 308 | const displacedAnswers = useRef< |
| 309 | Array<{ readonly draft: string; readonly key: string; readonly text: string }> |
| 310 | >([]); |
| 311 | // This hook outlives a thread switch, and each thread has its own draft. |
| 312 | const displacedDraftKey = |
| 313 | typeof composerDraftTarget === "string" |
| 314 | ? composerDraftTarget |
| 315 | : `${composerDraftTarget.environmentId}:${composerDraftTarget.threadId}`; |
| 316 | const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]); |
| 317 | const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState< |
| 318 | RuntimeRequestId[] |
| 319 | >([]); |
| 320 | const setPendingUserInputAnswersByRequestId = usePendingUserInputAnswers.setState; |
| 321 | const setPendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex.setState; |
| 322 | const pendingRequests = |
| 323 | serverProjection !== null && serverProjection.thread.id === activeThreadId |
| 324 | ? derivePendingThreadRequests(serverProjection) |
| 325 | : NO_PENDING_REQUESTS; |
| 326 | // The projection changes on every streamed event, so shared empties keep the |
| 327 | // composer and approval panel from re-rendering while nothing is pending. |
| 328 | const pendingApprovals = |
| 329 | pendingRequests.approvals.length === 0 |
| 330 | ? NO_PENDING_APPROVALS |
| 331 | : derivePendingApprovals(pendingRequests.approvals); |
| 332 | const pendingUserInputs = |
| 333 | pendingRequests.userInputs.length === 0 |
| 334 | ? NO_PENDING_USER_INPUTS |
| 335 | : derivePendingUserInputs(pendingRequests.userInputs); |
| 336 | const activePendingUserInput = pendingUserInputs[0] ?? null; |
| 337 | const activePendingRequestKey = userInputDraftKey( |
| 338 | environmentId, |
| 339 | activeThreadId, |
| 340 | activePendingUserInput?.requestId, |
| 341 | ); |
| 342 | const draftScope = { |
| 343 | environmentId, |
| 344 | activeThreadId, |
| 345 | activePendingUserInput, |
| 346 | supportsQuestionAttachments, |
| 347 | }; |
| 348 | const activePendingIsResponding = activePendingUserInput |
| 349 | ? activePendingUserInput.responseCapability === "not_resumable" || |
| 350 | respondingUserInputRequestIds.includes(activePendingUserInput.requestId) |
| 351 | : false; |
| 352 | const activePendingApproval = pendingApprovals[0] ?? null; |
| 353 | |
| 354 | const onRespondToApproval = async ( |
| 355 | requestId: RuntimeRequestId, |
| 356 | decision: ProviderApprovalDecision, |
| 357 | feedback?: string, |
| 358 | ) => { |
| 359 | if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) |
| 360 | return; |
| 361 | if ( |
| 362 | pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !== |
| 363 | "live" |
| 364 | ) |
| 365 | return; |
| 366 | |
| 367 | setRespondingRequestIds((existing) => |
| 368 | existing.includes(requestId) ? existing : [...existing, requestId], |
| 369 | ); |
| 370 | const result = await respondToThreadApproval({ |
| 371 | environmentId, |
| 372 | input: { |
| 373 | threadId: activeThreadId, |
| 374 | requestId, |
| 375 | decision, |
| 376 | ...(feedback === undefined ? {} : { feedback }), |
| 377 | }, |
| 378 | }); |
| 379 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 380 | const error = squashAtomCommandFailure(result); |
| 381 | setThreadError( |
| 382 | activeThreadId, |
| 383 | thrownErrorMessage(error, m) ?? m(msg("Failed to submit approval decision.")), |
| 384 | ); |
| 385 | } |
| 386 | setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); |
| 387 | return result; |
| 388 | }; |
| 389 | const onRespondToApprovalStable = useStableCallback(onRespondToApproval); |
| 390 | |
| 391 | const onRespondToUserInput = async ( |
| 392 | requestId: RuntimeRequestId, |
| 393 | answers: Record<string, unknown>, |
| 394 | ) => { |
| 395 | if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) |
| 396 | return; |
| 397 | const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId); |
| 398 | if (!pendingInput || pendingInput.responseCapability === "not_resumable") return; |
| 399 | const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]); |
| 400 | if (userInputResponsesInFlight.current.has(responseKey)) return; |
| 401 | userInputResponsesInFlight.current.add(responseKey); |
| 402 | const answerDraftKey = userInputDraftKey(environmentId, activeThreadId, requestId); |
| 403 | const answerDraftBeforePreparation = usePendingUserInputAnswers.getState()[answerDraftKey]; |
| 404 | setRespondingUserInputRequestIds((existing) => |
| 405 | existing.includes(requestId) ? existing : [...existing, requestId], |
| 406 | ); |
| 407 | const prepareAndRespond = async () => { |
| 408 | const attachmentsByQuestionId = new Map<string, UserInputAttachments[string]>(); |
| 409 | const providerAnswers = { ...answers }; |
| 410 | const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); |
| 411 | const questionDrafts = pendingInput.questions.map((question) => { |
| 412 | const target = questionAttachmentDraftId( |
| 413 | environmentId, |
| 414 | activeThreadId, |
| 415 | requestId, |
| 416 | question.id, |
| 417 | ); |
| 418 | const draft = useComposerDraftStore.getState().getComposerDraft(target); |
| 419 | return { question, target, draft }; |
| 420 | }); |
| 421 | for (const { question, target, draft } of questionDrafts) { |
| 422 | if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return; |
| 423 | providerAnswers[question.id] = projectPendingUserInputAnswer( |
| 424 | answers[question.id], |
| 425 | answerContextRecords(draft, threadDraft), |
| 426 | ); |
| 427 | const attachments = draft ? [...draft.images, ...draft.files] : []; |
| 428 | if (attachments.length === 0) continue; |
| 429 | await refreshExpiredAttachmentUploads({ |
| 430 | environmentId, |
| 431 | images: attachments, |
| 432 | draftTarget: target, |
| 433 | }); |
| 434 | if ( |
| 435 | composerDraftContentChanged( |
| 436 | draft, |
| 437 | useComposerDraftStore.getState().getComposerDraft(target), |
| 438 | ) |
| 439 | ) { |
| 440 | setThreadError( |
| 441 | activeThreadId, |
| 442 | m(msg("Answer changed while preparing attachments. Review it and send again.")), |
| 443 | ); |
| 444 | return; |
| 445 | } |
| 446 | const uploaded = getUploadedAttachments({ environmentId, images: attachments }); |
| 447 | if (!uploaded) { |
| 448 | setThreadError( |
| 449 | activeThreadId, |
| 450 | m(msg("Wait for attachments to finish uploading, or remove failed uploads.")), |
| 451 | ); |
| 452 | return; |
| 453 | } |
| 454 | attachmentsByQuestionId.set(question.id, uploaded as UserInputAttachments[string]); |
| 455 | } |
| 456 | if ( |
| 457 | usePendingUserInputAnswers.getState()[answerDraftKey] !== answerDraftBeforePreparation || |
| 458 | questionDrafts.some( |
| 459 | ({ target, draft }) => |
| 460 | (useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0 || |
| 461 | composerDraftContentChanged( |
| 462 | draft, |
| 463 | useComposerDraftStore.getState().getComposerDraft(target), |
| 464 | ), |
| 465 | ) |
| 466 | ) { |
| 467 | setThreadError( |
| 468 | activeThreadId, |
| 469 | m(msg("Answer changed while preparing attachments. Review it and send again.")), |
| 470 | ); |
| 471 | return; |
| 472 | } |
| 473 | const result = await respondToThreadUserInput({ |
| 474 | environmentId, |
| 475 | input: { |
| 476 | threadId: activeThreadId, |
| 477 | requestId, |
| 478 | answers: providerAnswers, |
| 479 | ...(attachmentsByQuestionId.size > 0 |
| 480 | ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) } |
| 481 | : {}), |
| 482 | }, |
| 483 | }); |
| 484 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 485 | const error = squashAtomCommandFailure(result); |
| 486 | setThreadError( |
| 487 | activeThreadId, |
| 488 | thrownErrorMessage(error, m) ?? m(msg("Failed to submit user input.")), |
| 489 | ); |
| 490 | } |
| 491 | return result; |
| 492 | }; |
| 493 | return prepareAndRespond().finally(() => { |
| 494 | userInputResponsesInFlight.current.delete(responseKey); |
| 495 | setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); |
| 496 | }); |
| 497 | }; |
| 498 | |
| 499 | const onDismissUserInput = async (requestId: RuntimeRequestId) => { |
| 500 | if (!activeThreadId) return; |
| 501 | |
| 502 | setRespondingUserInputRequestIds((existing) => |
| 503 | existing.includes(requestId) ? existing : [...existing, requestId], |
| 504 | ); |
| 505 | const result = await dismissThreadUserInput({ |
| 506 | environmentId, |
| 507 | input: { threadId: activeThreadId, requestId }, |
| 508 | }); |
| 509 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 510 | const error = squashAtomCommandFailure(result); |
| 511 | setThreadError( |
| 512 | activeThreadId, |
| 513 | thrownErrorMessage(error, m) ?? m(msg("Failed to dismiss the question.")), |
| 514 | ); |
| 515 | } |
| 516 | setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); |
| 517 | return result; |
| 518 | }; |
| 519 | const onDismissUserInputStable = useStableCallback(onDismissUserInput); |
| 520 | |
| 521 | const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => { |
| 522 | if (!activePendingUserInput) { |
| 523 | return; |
| 524 | } |
| 525 | setPendingUserInputQuestionIndexByRequestId((existing) => ({ |
| 526 | ...existing, |
| 527 | [activePendingRequestKey]: nextQuestionIndex, |
| 528 | })); |
| 529 | }; |
| 530 | |
| 531 | const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => { |
| 532 | if (!activePendingUserInput) { |
| 533 | return; |
| 534 | } |
| 535 | // The option replaces the custom answer. Anything typed there is the |
| 536 | // user's text, so it goes back to the thread draft instead of vanishing. |
| 537 | const displacedAnswer = |
| 538 | readPendingUserInputDraft(draftScope).activePendingDraftAnswers[questionId]?.customAnswer; |
| 539 | const currentPrompt = |
| 540 | useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? ""; |
| 541 | const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer); |
| 542 | if (nextPrompt !== currentPrompt) { |
| 543 | setComposerDraftPrompt(composerDraftTarget, nextPrompt); |
| 544 | displacedAnswers.current.push({ |
| 545 | draft: displacedDraftKey, |
| 546 | key: `${activePendingRequestKey}:${questionId}`, |
| 547 | text: displacedAnswer ?? "", |
| 548 | }); |
| 549 | toastManager.add({ |
| 550 | type: "info", |
| 551 | title: m(msg("Your typed text was set aside")), |
| 552 | description: m(msg("It will be back in the composer once the question is answered.")), |
| 553 | data: { threadRef: activeThreadId ? { environmentId, threadId: activeThreadId } : null }, |
| 554 | }); |
| 555 | if (activeThreadId) { |
| 556 | const store = useComposerDraftStore.getState(); |
| 557 | const questionTarget = questionAttachmentDraftId( |
| 558 | environmentId, |
| 559 | activeThreadId, |
| 560 | activePendingUserInput.requestId, |
| 561 | questionId, |
| 562 | ); |
| 563 | store.addThreadContexts( |
| 564 | composerDraftTarget, |
| 565 | threadContextsReferencedByAnswer( |
| 566 | displacedAnswer ?? "", |
| 567 | store.getComposerDraft(questionTarget)?.threadContexts ?? [], |
| 568 | ), |
| 569 | { appendReference: false }, |
| 570 | ); |
| 571 | } |
| 572 | } |
| 573 | setPendingUserInputAnswersByRequestId((existing) => { |
| 574 | const question = activePendingUserInput.questions.find((entry) => entry.id === questionId); |
| 575 | if (!question) { |
| 576 | return existing; |
| 577 | } |
| 578 | |
| 579 | return { |
| 580 | ...existing, |
| 581 | [activePendingRequestKey]: { |
| 582 | ...existing[activePendingRequestKey], |
| 583 | [questionId]: togglePendingUserInputOptionSelection( |
| 584 | question, |
| 585 | existing[activePendingRequestKey]?.[questionId], |
| 586 | optionValue, |
| 587 | ), |
| 588 | }, |
| 589 | }; |
| 590 | }); |
| 591 | promptRef.current = ""; |
| 592 | composerRef.current?.resetCursorState({ cursor: 0 }); |
| 593 | }; |
| 594 | const onSelectActivePendingUserInputOptionStable = useStableCallback( |
| 595 | onSelectActivePendingUserInputOption, |
| 596 | ); |
| 597 | |
| 598 | const writePrompt = useStableCallback((prompt: string) => { |
| 599 | promptRef.current = prompt; |
| 600 | }); |
| 601 | // Undo can put set-aside text back into the answer; left in the draft too, it is sent twice. |
| 602 | const withdrawRestoredAnswer = useStableCallback((questionId: string, value: string) => { |
| 603 | const key = `${activePendingRequestKey}:${questionId}`; |
| 604 | const entries = displacedAnswers.current; |
| 605 | const index = entries.findLastIndex( |
| 606 | (entry) => |
| 607 | entry.draft === displacedDraftKey && |
| 608 | entry.key === key && |
| 609 | entry.text.trim() === value.trim(), |
| 610 | ); |
| 611 | const displaced = entries[index]; |
| 612 | if (displaced === undefined) return; |
| 613 | const later = entries |
| 614 | .slice(index + 1) |
| 615 | .filter((entry) => entry.draft === displaced.draft) |
| 616 | .map((entry) => entry.text); |
| 617 | displacedAnswers.current = entries.filter((entry) => entry !== displaced); |
| 618 | const currentPrompt = |
| 619 | useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? ""; |
| 620 | const nextPrompt = withdrawDisplacedCustomAnswerFromPrompt( |
| 621 | currentPrompt, |
| 622 | displaced.text, |
| 623 | later, |
| 624 | ); |
| 625 | if (nextPrompt !== currentPrompt) setComposerDraftPrompt(composerDraftTarget, nextPrompt); |
| 626 | }); |
| 627 | const onChangeActivePendingUserInputCustomAnswer = makePendingCustomAnswerSetter({ |
| 628 | activePendingUserInput, |
| 629 | activePendingRequestKey, |
| 630 | writePrompt, |
| 631 | withdrawRestoredAnswer, |
| 632 | setPendingUserInputAnswersByRequestId, |
| 633 | }); |
| 634 | |
| 635 | const onAdvanceActivePendingUserInput = () => { |
| 636 | if (!activePendingUserInput || activePendingUserInput.responseCapability === "not_resumable") { |
| 637 | return; |
| 638 | } |
| 639 | const { activePendingProgress, activePendingResolvedAnswers } = |
| 640 | readPendingUserInputDraft(draftScope); |
| 641 | if (!activePendingProgress) return; |
| 642 | if (activePendingProgress.isLastQuestion) { |
| 643 | if (activePendingResolvedAnswers) { |
| 644 | void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers); |
| 645 | } |
| 646 | return; |
| 647 | } |
| 648 | if (!activePendingProgress.canAdvance) return; |
| 649 | setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1); |
| 650 | }; |
| 651 | const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput); |
| 652 | |
| 653 | const onPreviousActivePendingUserInputQuestion = () => { |
| 654 | const { activePendingProgress } = readPendingUserInputDraft(draftScope); |
| 655 | if (!activePendingProgress) { |
| 656 | return; |
| 657 | } |
| 658 | setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0)); |
| 659 | }; |
| 660 | const onPreviousActivePendingUserInputQuestionStable = useStableCallback( |
| 661 | onPreviousActivePendingUserInputQuestion, |
| 662 | ); |
| 663 | |
| 664 | return { |
| 665 | pendingApprovals, |
| 666 | pendingUserInputs, |
| 667 | activePendingApproval, |
| 668 | activePendingUserInput, |
| 669 | activePendingIsResponding, |
| 670 | respondingRequestIds, |
| 671 | onRespondToApproval: onRespondToApprovalStable, |
| 672 | onDismissUserInput: onDismissUserInputStable, |
| 673 | onSelectActivePendingUserInputOption: onSelectActivePendingUserInputOptionStable, |
| 674 | onChangeActivePendingUserInputCustomAnswer, |
| 675 | onAdvanceActivePendingUserInput, |
| 676 | onAdvanceActivePendingUserInputStable, |
| 677 | onPreviousActivePendingUserInputQuestion: onPreviousActivePendingUserInputQuestionStable, |
| 678 | }; |
| 679 | } |