The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useComposerAttachmentActions } from "./use-composer-attachment-actions"; |
| 2 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Dialog from "../components/ui/Dialog"; |
| 5 | import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; |
| 6 | import { readEnvironmentScope } from "./session"; |
| 7 | import { useAtomValue } from "@effect/atom-react"; |
| 8 | import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window"; |
| 9 | import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; |
| 10 | import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; |
| 11 | import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; |
| 12 | import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; |
| 13 | import { |
| 14 | announcedRun, |
| 15 | isDetailBehindShell, |
| 16 | } from "@t3tools/client-runtime/state/thread-activity-announcement"; |
| 17 | import { |
| 18 | canResumeThread, |
| 19 | deriveProviderSubagentStatus, |
| 20 | deriveProviderExtensionStatuses, |
| 21 | deriveResumableRunId, |
| 22 | deriveLatestThreadRun, |
| 23 | deriveRunlessWorkStartedAt, |
| 24 | deriveThreadActivityRun, |
| 25 | deriveThreadRuntime, |
| 26 | threadRuntimeHasInterruptibleRun, |
| 27 | } from "@t3tools/client-runtime/state/thread-execution"; |
| 28 | import { useEffect, useRef, useState } from "react"; |
| 29 | |
| 30 | import { |
| 31 | CommandId, |
| 32 | DEFAULT_PROVIDER_INTERACTION_MODE, |
| 33 | MessageId, |
| 34 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 35 | type EnvironmentId, |
| 36 | type ModelSelection, |
| 37 | type RuntimeMode, |
| 38 | type ScopedThreadRef, |
| 39 | type ThreadId, |
| 40 | } from "@t3tools/contracts"; |
| 41 | |
| 42 | import { |
| 43 | parseCodexFeedbackCommand, |
| 44 | submitCodexFeedback, |
| 45 | type CodexFeedbackSubmission, |
| 46 | } from "@t3tools/client-runtime/state/threads"; |
| 47 | import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models"; |
| 48 | import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; |
| 49 | import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy"; |
| 50 | import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; |
| 51 | import { |
| 52 | composerContextSendBlockReason, |
| 53 | reidentifyComposerContext, |
| 54 | serializeComposerMessageForServer, |
| 55 | uploadedComposerContext, |
| 56 | } from "../lib/composerContext"; |
| 57 | import { uuidv4 } from "../lib/uuid"; |
| 58 | import { useNowMinuteMs } from "../lib/clock"; |
| 59 | |
| 60 | import { makeQueuedMessageMetadata } from "../lib/commandMetadata"; |
| 61 | import { |
| 62 | describeUnavailableModelSelection, |
| 63 | isModelSelectionUnavailable, |
| 64 | } from "../lib/modelOptions"; |
| 65 | |
| 66 | import { |
| 67 | type DraftComposerImageAttachment, |
| 68 | isFileBackedComposerAttachment, |
| 69 | } from "../lib/composerImages"; |
| 70 | import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention"; |
| 71 | import { scopedThreadKey } from "../lib/scopedEntities"; |
| 72 | import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity"; |
| 73 | import { |
| 74 | acknowledgedThreadMessagesAtom, |
| 75 | pruneCaughtUpAcknowledgedThreadMessages, |
| 76 | } from "./acknowledged-thread-messages"; |
| 77 | import { |
| 78 | appendAcceptedThreadMessages, |
| 79 | selectPendingAcknowledgedMessages, |
| 80 | } from "../features/threads/pending-thread-feed"; |
| 81 | import { threadAllowsProviderSwitch } from "./thread-provider-switching"; |
| 82 | import { appAtomRegistry } from "./atom-registry"; |
| 83 | import { pendingThreadCreationMessage } from "./pending-thread-creation"; |
| 84 | import type { SideChatMessage } from "../features/threads/useStartSideChat"; |
| 85 | import { |
| 86 | composerAttachmentUploadBlockReason, |
| 87 | composerAttachmentUploadsAtom, |
| 88 | uploadComposerAttachmentShared, |
| 89 | } from "./composer-attachment-uploads"; |
| 90 | import { |
| 91 | appendComposerDraftAttachments, |
| 92 | insertComposerDraftContext, |
| 93 | clearComposerDraft, |
| 94 | clearComposerDraftContent, |
| 95 | composerContextImportsAtom, |
| 96 | getComposerDraftSnapshot, |
| 97 | isFreshSessionPending, |
| 98 | mergeComposerDraftContent, |
| 99 | removeComposerDraftAttachment, |
| 100 | scheduleUnusedComposerAttachmentCleanup, |
| 101 | setComposerDraftText, |
| 102 | setFreshSessionPending, |
| 103 | useComposerDraft, |
| 104 | useComposerDraftSettings, |
| 105 | } from "./use-composer-drafts"; |
| 106 | import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger"; |
| 107 | import { orchestrationV2WorktreePending } from "@t3tools/shared/orchestrationV2ThreadError"; |
| 108 | import { |
| 109 | compactionBlocksSteering, |
| 110 | resolveComposerDispatchMode, |
| 111 | type ActiveTurnComposerAction, |
| 112 | } from "@t3tools/client-runtime/state/composer-dispatch"; |
| 113 | import { Atom } from "effect/reactivity"; |
| 114 | import { AsyncResult } from "effect/reactivity"; |
| 115 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 116 | import { prepareTurnAttachments } from "../lib/attachmentUpload"; |
| 117 | import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior"; |
| 118 | import { mobilePreferencesAtom } from "./preferences"; |
| 119 | import { environmentThreadDetails } from "./threads"; |
| 120 | import { |
| 121 | endQueuedRunEdit, |
| 122 | getQueuedRunEdit, |
| 123 | queuedEditDraftKey, |
| 124 | removeQueuedRunEditAttachment, |
| 125 | resolveQueuedEditPayload, |
| 126 | startQueuedRunEditSave, |
| 127 | useQueuedRunEdit, |
| 128 | } from "./queued-run-edit"; |
| 129 | import { msg, useLocale, useMessages } from "gt-react-native"; |
| 130 | import { m } from "../i18n/messages"; |
| 131 | import { setPendingConnectionError } from "./use-remote-environment-registry"; |
| 132 | import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error"; |
| 133 | import { |
| 134 | useSelectedThreadProjection, |
| 135 | useSelectedThreadVisibleTurnItems, |
| 136 | } from "./use-thread-detail"; |
| 137 | import { useThreadSelection } from "./use-thread-selection"; |
| 138 | import { enqueueThreadOutboxMessage } from "./thread-outbox"; |
| 139 | import { dispatchingQueuedMessageIdsAtom, useThreadOutboxMessages } from "./use-thread-outbox"; |
| 140 | import { threadEnvironment } from "./threads"; |
| 141 | import { useAtomCommand } from "./use-atom-command"; |
| 142 | |
| 143 | const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe( |
| 144 | Atom.withLabel("mobile-thread-queue-workflow:empty"), |
| 145 | ); |
| 146 | // Threads whose next send keeps the full history instead of compacting first. |
| 147 | const fullHistoryThreadKeysAtom = Atom.make<Readonly<Record<string, true>>>({}).pipe( |
| 148 | Atom.keepAlive, |
| 149 | ); |
| 150 | |
| 151 | function setKeepFullHistory(threadKey: string, keep: boolean) { |
| 152 | const { [threadKey]: kept, ...rest } = appAtomRegistry.get(fullHistoryThreadKeysAtom); |
| 153 | if ((kept === true) === keep) return; |
| 154 | appAtomRegistry.set(fullHistoryThreadKeysAtom, keep ? { ...rest, [threadKey]: true } : rest); |
| 155 | } |
| 156 | |
| 157 | const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]); |
| 158 | const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0); |
| 159 | |
| 160 | export function appendReviewCommentToDraft(input: { |
| 161 | readonly environmentId: EnvironmentId; |
| 162 | readonly threadId: ThreadId; |
| 163 | readonly text: string; |
| 164 | readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>; |
| 165 | }): void { |
| 166 | const threadKey = scopedThreadKey(input.environmentId, input.threadId); |
| 167 | const upgraded = upgradeLegacyContextMessage(input.text); |
| 168 | if ( |
| 169 | !insertComposerDraftContext( |
| 170 | threadKey, |
| 171 | reidentifyComposerContext(upgraded.text, upgraded.records, uuidv4), |
| 172 | ) |
| 173 | ) { |
| 174 | Dialog.alert( |
| 175 | m(msg("Too many context items")), |
| 176 | m(msg("Remove some context from the draft and try again.")), |
| 177 | ); |
| 178 | return; |
| 179 | } |
| 180 | if (input.attachments && input.attachments.length > 0) { |
| 181 | const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, { |
| 182 | appendReference: true, |
| 183 | }); |
| 184 | if (rejectedCount > 0) { |
| 185 | setPendingConnectionError( |
| 186 | m( |
| 187 | msg( |
| 188 | "{count, plural, one {{count} comment attachment was not added. Messages can contain at most {max} attachments.} other {{count} comment attachments were not added. Messages can contain at most {max} attachments.}}", |
| 189 | { count: rejectedCount, max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }, |
| 190 | ), |
| 191 | ), |
| 192 | ); |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /** Resolve per call so callbacks created before editing still target the current draft. */ |
| 198 | function activeComposerDraftKey(thread: { |
| 199 | readonly environmentId: EnvironmentId; |
| 200 | readonly id: ThreadId; |
| 201 | }): string { |
| 202 | const threadKey = scopedThreadKey(thread.environmentId, thread.id); |
| 203 | const edit = getQueuedRunEdit(threadKey); |
| 204 | return edit === null ? threadKey : queuedEditDraftKey(threadKey, edit.runId); |
| 205 | } |
| 206 | |
| 207 | export function useThreadDraftForThread(input: { |
| 208 | readonly environmentId?: EnvironmentId; |
| 209 | readonly threadId?: ThreadId; |
| 210 | }) { |
| 211 | const threadKey = |
| 212 | input.environmentId && input.threadId |
| 213 | ? scopedThreadKey(input.environmentId, input.threadId) |
| 214 | : null; |
| 215 | const draft = useComposerDraft(threadKey); |
| 216 | |
| 217 | return { |
| 218 | draftMessage: draft.text, |
| 219 | draftContext: draft.context, |
| 220 | draftAttachments: draft.attachments, |
| 221 | }; |
| 222 | } |
| 223 | |
| 224 | export function useThreadComposerState(input: { |
| 225 | /** Forks the thread into a side chat that gets `message`; resolves false when it did not start. */ |
| 226 | readonly startSideChat: ( |
| 227 | source: ScopedThreadRef, |
| 228 | message: SideChatMessage, |
| 229 | settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection }, |
| 230 | ) => Promise<boolean>; |
| 231 | }) { |
| 232 | const { |
| 233 | selectedThread: selectedThreadShell, |
| 234 | selectedThreadCreation, |
| 235 | selectedThreadDetailRef, |
| 236 | selectedEnvironmentRuntime, |
| 237 | } = useThreadSelection(); |
| 238 | const resolve = useMessages(); |
| 239 | const locale = useLocale(); |
| 240 | const selectedThreadProjection = useSelectedThreadProjection(); |
| 241 | const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems(); |
| 242 | const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom); |
| 243 | const queuedMessagesByThreadKey = useThreadOutboxMessages(); |
| 244 | const dispatchingQueuedMessageIds = useAtomValue(dispatchingQueuedMessageIdsAtom); |
| 245 | const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState< |
| 246 | Record<string, ReadonlyArray<CodexFeedbackSubmission>> |
| 247 | >({}); |
| 248 | const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, { |
| 249 | reportFailure: false, |
| 250 | }); |
| 251 | const editQueuedRun = useAtomCommand(threadEnvironment.editQueuedRun, { |
| 252 | label: "edit queued message", |
| 253 | reportFailure: false, |
| 254 | }); |
| 255 | const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false); |
| 256 | const savingQueuedEditRef = useRef(false); |
| 257 | const startingSideChatRef = useRef(false); |
| 258 | |
| 259 | const selectedThreadKey = selectedThreadShell |
| 260 | ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id) |
| 261 | : null; |
| 262 | const selectedThreadQueuedMessages = selectedThreadKey |
| 263 | ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter( |
| 264 | (message) => message.creation === undefined, |
| 265 | ) |
| 266 | : []; |
| 267 | // The thread sends one message at a time, the head of its queue. |
| 268 | const dispatchingQueuedMessageId = |
| 269 | selectedThreadQueuedMessages.find((message) => dispatchingQueuedMessageIds[message.messageId]) |
| 270 | ?.messageId ?? null; |
| 271 | const feedbackSubmissions = selectedThreadKey |
| 272 | ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? []) |
| 273 | : []; |
| 274 | const dismissFeedback = (id: MessageId) => { |
| 275 | if (!selectedThreadKey) return; |
| 276 | setFeedbackSubmissionsByThreadKey((current) => ({ |
| 277 | ...current, |
| 278 | [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id), |
| 279 | })); |
| 280 | }; |
| 281 | const selectedThreadMessages = selectedThreadProjection?.projection.messages; |
| 282 | const selectedThreadAttempts = selectedThreadProjection?.projection.attempts; |
| 283 | const selectedThreadNodes = selectedThreadProjection?.projection.nodes; |
| 284 | const selectedThreadSequence = useAtomValue( |
| 285 | selectedThreadDetailRef === null |
| 286 | ? EMPTY_THREAD_SEQUENCE_ATOM |
| 287 | : environmentThreadDetails.sequenceAtom(selectedThreadDetailRef), |
| 288 | ); |
| 289 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes the app-wide acknowledged atom when the mounted thread catches up |
| 290 | useEffect(() => { |
| 291 | if (selectedThreadKey === null || acknowledgedMessages.length === 0) return; |
| 292 | pruneCaughtUpAcknowledgedThreadMessages(selectedThreadKey, { |
| 293 | sequence: selectedThreadSequence, |
| 294 | messages: selectedThreadMessages, |
| 295 | }); |
| 296 | }, [acknowledgedMessages, selectedThreadKey, selectedThreadSequence, selectedThreadMessages]); |
| 297 | const checkpointSummaries = useAtomValue( |
| 298 | selectedThreadDetailRef === null |
| 299 | ? EMPTY_CHECKPOINT_SUMMARIES_ATOM |
| 300 | : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef), |
| 301 | ); |
| 302 | // A thread whose creation has not delivered its turn yet: the prompt only |
| 303 | // exists in the outbox, so it is appended to whatever the server has. The |
| 304 | // detail is usually present but empty during a worktree checkout, so this |
| 305 | // cannot be an either/or with the loaded messages. |
| 306 | const pendingCreationMessage = selectedThreadCreation?.message ?? null; |
| 307 | const [feedCache] = useState(createThreadFeedCache); |
| 308 | const selectedThreadFeed = (() => { |
| 309 | const pendingCreation = |
| 310 | pendingCreationMessage !== null && |
| 311 | !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId) |
| 312 | ? [pendingThreadCreationMessage(pendingCreationMessage)] |
| 313 | : []; |
| 314 | const feed = buildThreadFeed(selectedThreadVisibleTurnItems, { |
| 315 | anchoredMessages: pendingCreation, |
| 316 | attempts: selectedThreadAttempts, |
| 317 | nodes: selectedThreadNodes, |
| 318 | checkpointSummaries, |
| 319 | cache: feedCache, |
| 320 | resolve, |
| 321 | locale, |
| 322 | }); |
| 323 | const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, { |
| 324 | threadKey: selectedThreadKey, |
| 325 | queuedMessages: selectedThreadQueuedMessages, |
| 326 | sequence: selectedThreadSequence, |
| 327 | projectedMessages: selectedThreadMessages, |
| 328 | }); |
| 329 | return appendAcceptedThreadMessages( |
| 330 | feed, |
| 331 | pendingAcknowledgments, |
| 332 | pendingCreation.length > 0 ? pendingCreationMessage : null, |
| 333 | ); |
| 334 | })(); |
| 335 | |
| 336 | const preferencesResult = useAtomValue(mobilePreferencesAtom); |
| 337 | const followUpBehavior = AsyncResult.isSuccess(preferencesResult) |
| 338 | ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR) |
| 339 | : DEFAULT_FOLLOW_UP_BEHAVIOR; |
| 340 | const queueWorkflow = useAtomValue( |
| 341 | selectedThreadDetailRef === null |
| 342 | ? EMPTY_QUEUE_WORKFLOW_ATOM |
| 343 | : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef), |
| 344 | ); |
| 345 | const queuedRunEdit = useQueuedRunEdit(selectedThreadKey); |
| 346 | const composerDraftKey = |
| 347 | selectedThreadKey === null |
| 348 | ? null |
| 349 | : queuedRunEdit === null |
| 350 | ? selectedThreadKey |
| 351 | : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId); |
| 352 | const selectedDraft = useComposerDraftSettings(selectedThreadKey); |
| 353 | const selectedThreadQueueCount = selectedThreadQueuedMessages.length; |
| 354 | const selectedThread = selectedThreadShell; |
| 355 | const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; |
| 356 | const serverConfig = selectedEnvironmentRuntime?.serverConfig; |
| 357 | const pendingHandoff = resolvePendingHandoff( |
| 358 | selectedThreadProjection?.projection, |
| 359 | isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null) |
| 360 | ? null |
| 361 | : modelSelection, |
| 362 | serverConfig?.providers ?? [], |
| 363 | ); |
| 364 | const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null; |
| 365 | // Plan mode is not offered to users; every send runs in build mode. |
| 366 | const interactionMode = selectedThread ? DEFAULT_PROVIDER_INTERACTION_MODE : null; |
| 367 | const canSwitchThreadProvider = threadAllowsProviderSwitch({ |
| 368 | thread: selectedThreadShell, |
| 369 | projection: selectedThreadProjection?.projection, |
| 370 | }); |
| 371 | const selectedThreadRuntime = selectedThreadProjection |
| 372 | ? deriveThreadRuntime(selectedThreadProjection.projection) |
| 373 | : (selectedThreadShell?.runtime ?? null); |
| 374 | const selectedThreadActivityRun = selectedThreadProjection |
| 375 | ? deriveThreadActivityRun(selectedThreadProjection.projection) |
| 376 | : (selectedThreadShell?.latestRun ?? null); |
| 377 | const selectedThreadAnnouncedRun = announcedRun( |
| 378 | selectedThreadActivityRun, |
| 379 | selectedThreadProjection?.projection.runs ?? [], |
| 380 | ); |
| 381 | const selectedThreadDetailBehindShell = isDetailBehindShell( |
| 382 | selectedThreadProjection ? deriveLatestThreadRun(selectedThreadProjection.projection) : null, |
| 383 | selectedThreadShell?.latestRun ?? null, |
| 384 | ); |
| 385 | |
| 386 | const activeRunId = |
| 387 | selectedThreadRuntime?.activeRunId && threadRuntimeIsActive(selectedThreadRuntime) |
| 388 | ? selectedThreadRuntime.activeRunId |
| 389 | : null; |
| 390 | const compactCommandIsActive = (() => { |
| 391 | const queuedCompact = selectedThreadQueuedMessages.some( |
| 392 | (message) => |
| 393 | message.messageId === dispatchingQueuedMessageId && |
| 394 | message.text.trim().toLowerCase() === "/compact" && |
| 395 | message.attachments.length === 0, |
| 396 | ); |
| 397 | if (queuedCompact) return true; |
| 398 | if (!activeRunId) return false; |
| 399 | const compactMessage = selectedThreadVisibleTurnItems.findLast( |
| 400 | ({ item }) => |
| 401 | item.runId === activeRunId && |
| 402 | item.type === "user_message" && |
| 403 | item.text.trim().toLowerCase() === "/compact" && |
| 404 | item.attachments.length === 0, |
| 405 | ); |
| 406 | if (!compactMessage) return false; |
| 407 | return !selectedThreadVisibleTurnItems.some( |
| 408 | ({ item }) => |
| 409 | item.runId === activeRunId && |
| 410 | item.type === "compaction" && |
| 411 | (item.status === "completed" || |
| 412 | item.status === "failed" || |
| 413 | item.status === "interrupted" || |
| 414 | item.status === "cancelled"), |
| 415 | ); |
| 416 | })(); |
| 417 | const compactionRunning = |
| 418 | activeRunId !== null && |
| 419 | selectedThreadVisibleTurnItems.some( |
| 420 | ({ item }) => |
| 421 | item.runId === activeRunId && item.type === "compaction" && item.status === "running", |
| 422 | ); |
| 423 | const isCompacting = compactCommandIsActive || compactionRunning; |
| 424 | const compactionBlocksSteer = compactionBlocksSteering({ |
| 425 | compactCommandIsActive, |
| 426 | compactionRunning, |
| 427 | steersDuringCompaction: threadSteersDuringCompaction(selectedThreadProjection?.projection), |
| 428 | run: selectedThreadProjection?.projection.runs.find((run) => run.id === activeRunId), |
| 429 | messages: selectedThreadMessages, |
| 430 | }); |
| 431 | const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !compactionBlocksSteer; |
| 432 | // A stop or a restart holds the queue, completion wakes included, until it |
| 433 | // is resumed; the queue sheet lists only the user's own messages. |
| 434 | const queueHeld = queueWorkflow?.isHeld === true; |
| 435 | const resumableRunId = selectedThreadProjection |
| 436 | ? deriveResumableRunId(selectedThreadProjection.projection, selectedThreadRuntime) |
| 437 | : null; |
| 438 | const canResume = selectedThreadProjection |
| 439 | ? canResumeThread(selectedThreadProjection.projection, resumableRunId, queueHeld) |
| 440 | : queueHeld; |
| 441 | |
| 442 | const runlessWorkStartedAt = selectedThreadProjection |
| 443 | ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection) |
| 444 | : null; |
| 445 | const activeWorkStartedAt = (() => { |
| 446 | if (!selectedThreadShell) { |
| 447 | return null; |
| 448 | } |
| 449 | return ( |
| 450 | resolveThreadWorkingStartedAt({ |
| 451 | latestRun: selectedThreadActivityRun, |
| 452 | runtime: selectedThreadRuntime, |
| 453 | }) ?? runlessWorkStartedAt |
| 454 | ); |
| 455 | })(); |
| 456 | const runlessWorkActive = runlessWorkStartedAt !== null; |
| 457 | |
| 458 | const providerSubagentStatus = selectedThreadProjection |
| 459 | ? deriveProviderSubagentStatus(selectedThreadProjection.projection) |
| 460 | : null; |
| 461 | |
| 462 | const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime); |
| 463 | const resumeCompactionTokens = (selection: ModelSelection | null, text: string, now: string) => |
| 464 | selectedEnvironmentRuntime?.connectionState === "connected" && |
| 465 | selectedThreadProjection !== null && |
| 466 | serverConfig != null && |
| 467 | selection !== null |
| 468 | ? compactBeforeSendTokens({ |
| 469 | projection: selectedThreadProjection.projection, |
| 470 | visibleTurnItems: selectedThreadVisibleTurnItems, |
| 471 | selection, |
| 472 | providers: serverConfig.providers, |
| 473 | settings: serverConfig.settings, |
| 474 | text, |
| 475 | threadIdle: |
| 476 | !activeThreadBusy && |
| 477 | !runlessWorkActive && |
| 478 | !isCompacting && |
| 479 | selectedThreadQueuedMessages.length === 0, |
| 480 | now, |
| 481 | }) |
| 482 | : null; |
| 483 | const nowMinuteMs = useNowMinuteMs(); |
| 484 | const compactTokens = |
| 485 | selectedDraft.freshContext === true |
| 486 | ? null |
| 487 | : resumeCompactionTokens(modelSelection, "", new Date(nowMinuteMs).toISOString()); |
| 488 | const fullHistoryThreadKeys = useAtomValue(fullHistoryThreadKeysAtom); |
| 489 | const keepFullHistory = |
| 490 | selectedThreadKey !== null && fullHistoryThreadKeys[selectedThreadKey] === true; |
| 491 | const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime) |
| 492 | ? (selectedThreadRuntime?.activeRunId ?? null) |
| 493 | : null; |
| 494 | |
| 495 | const cancelQueuedRunEdit = () => { |
| 496 | if (selectedThreadKey === null || savingQueuedEditRef.current) return; |
| 497 | endQueuedRunEdit(selectedThreadKey); |
| 498 | }; |
| 499 | |
| 500 | const onRemoveQueuedEditAttachment = (attachmentId: string) => { |
| 501 | if (selectedThreadKey === null) return; |
| 502 | removeQueuedRunEditAttachment(selectedThreadKey, attachmentId); |
| 503 | }; |
| 504 | |
| 505 | const saveQueuedRunEdit = async () => { |
| 506 | const thread = selectedThreadShell; |
| 507 | if (!thread || savingQueuedEditRef.current) return; |
| 508 | const threadKey = scopedThreadKey(thread.environmentId, thread.id); |
| 509 | const edit = getQueuedRunEdit(threadKey); |
| 510 | if (edit === null) return; |
| 511 | const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId)); |
| 512 | const text = draft.text.trim(); |
| 513 | if ( |
| 514 | text.length === 0 && |
| 515 | edit.existingAttachments.length === 0 && |
| 516 | draft.attachments.length === 0 |
| 517 | ) { |
| 518 | Dialog.alert(m(msg("Add a message")), m(msg("A queued message cannot be left empty."))); |
| 519 | return; |
| 520 | } |
| 521 | if ( |
| 522 | edit.existingAttachments.length + draft.attachments.length > |
| 523 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS |
| 524 | ) { |
| 525 | Dialog.alert( |
| 526 | m(msg("Too many attachments")), |
| 527 | m( |
| 528 | msg("Remove attachments until there are at most {max}.", { |
| 529 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 530 | }), |
| 531 | ), |
| 532 | ); |
| 533 | return; |
| 534 | } |
| 535 | // A queued message stays in its thread, so saving `/side` would send it to main. |
| 536 | if (parseSideChatCommand(text)) { |
| 537 | Dialog.alert( |
| 538 | m(msg("Queued message not updated")), |
| 539 | m( |
| 540 | msg("A queued message can't move to a side chat. Remove {side} or {btw} to save it.", { |
| 541 | side: "/side", |
| 542 | btw: "/btw", |
| 543 | }), |
| 544 | ), |
| 545 | ); |
| 546 | return; |
| 547 | } |
| 548 | const finishSave = startQueuedRunEditSave(threadKey); |
| 549 | if (finishSave === null) return; |
| 550 | savingQueuedEditRef.current = true; |
| 551 | setIsSavingQueuedEdit(true); |
| 552 | const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities; |
| 553 | const prepared = await settlePromise(() => |
| 554 | Effect.runPromise( |
| 555 | prepareTurnAttachments({ |
| 556 | environmentId: thread.environmentId, |
| 557 | attachments: draft.attachments, |
| 558 | supportsImageUploads: capabilities !== undefined, |
| 559 | uploadAttachment: (attachment) => |
| 560 | uploadComposerAttachmentShared(thread.environmentId, attachment), |
| 561 | }), |
| 562 | ), |
| 563 | ); |
| 564 | if (AsyncResult.isFailure(prepared)) { |
| 565 | savingQueuedEditRef.current = false; |
| 566 | setIsSavingQueuedEdit(false); |
| 567 | finishSave(false); |
| 568 | const error = squashAtomCommandFailure(prepared); |
| 569 | Dialog.alert( |
| 570 | m(msg("Could not save the queued message")), |
| 571 | errorDisplayMessage(error, m) ?? m(msg("Your edit is still in the composer.")), |
| 572 | ); |
| 573 | return; |
| 574 | } |
| 575 | if (prepared.value.status !== "ready") { |
| 576 | savingQueuedEditRef.current = false; |
| 577 | setIsSavingQueuedEdit(false); |
| 578 | finishSave(false); |
| 579 | return; |
| 580 | } |
| 581 | const payload = resolveQueuedEditPayload({ |
| 582 | edit, |
| 583 | draftContext: draft.context, |
| 584 | draftAttachments: draft.attachments, |
| 585 | uploaded: prepared.value.attachments, |
| 586 | }); |
| 587 | const result = await editQueuedRun({ |
| 588 | environmentId: thread.environmentId, |
| 589 | input: { |
| 590 | threadId: thread.id, |
| 591 | runId: edit.runId, |
| 592 | text: restoreAttachmentOnlyBootstrapPrompt(text, payload.attachments.length > 0), |
| 593 | edit: { |
| 594 | messageId: edit.messageId, |
| 595 | attachments: payload.attachments, |
| 596 | ...(payload.context ? { context: payload.context } : {}), |
| 597 | }, |
| 598 | }, |
| 599 | }); |
| 600 | savingQueuedEditRef.current = false; |
| 601 | setIsSavingQueuedEdit(false); |
| 602 | if (result._tag !== "Success") { |
| 603 | // The run left the queue during the save; its exit already told the composer what happened. |
| 604 | if (!finishSave(false)) return; |
| 605 | Dialog.alert( |
| 606 | m(msg("Could not save the queued message")), |
| 607 | m(msg("It may have already started. Your edit is still in the composer.")), |
| 608 | ); |
| 609 | return; |
| 610 | } |
| 611 | // False when the edit was cancelled or begun again meanwhile; its draft is the newer edit's. |
| 612 | if (finishSave(true)) { |
| 613 | clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), { |
| 614 | deferAttachmentCleanup: true, |
| 615 | }); |
| 616 | } |
| 617 | scheduleUnusedComposerAttachmentCleanup(draft.attachments); |
| 618 | }; |
| 619 | |
| 620 | const onSendMessage = async ( |
| 621 | followUpOverride?: ActiveTurnComposerAction, |
| 622 | beforeDispatch?: ( |
| 623 | text: string, |
| 624 | hasAttachmentsOrContext: boolean, |
| 625 | ) => Promise<boolean | "responded">, |
| 626 | onWillEnqueue?: () => void, |
| 627 | ) => { |
| 628 | if ( |
| 629 | selectedThreadShell && |
| 630 | selectedEnvironmentRuntime?.connectionState === "connected" && |
| 631 | !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope) |
| 632 | ) |
| 633 | return null; |
| 634 | if (!selectedThreadShell) { |
| 635 | return null; |
| 636 | } |
| 637 | // Before thread creation succeeds, follow-ups could become orphaned and be dropped by the drain. |
| 638 | if (selectedThreadCreation !== null) { |
| 639 | return null; |
| 640 | } |
| 641 | |
| 642 | const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id); |
| 643 | if (getQueuedRunEdit(editKey) !== null) { |
| 644 | await saveQueuedRunEdit(); |
| 645 | return null; |
| 646 | } |
| 647 | |
| 648 | // Until a side chat start settles, its draft may be only partly back in the composer. |
| 649 | if (startingSideChatRef.current) return null; |
| 650 | const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id); |
| 651 | const draft = getComposerDraftSnapshot(threadKey); |
| 652 | if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null; |
| 653 | const thread = selectedThreadShell; |
| 654 | const text = draft.text.trim(); |
| 655 | const attachments = draft.attachments; |
| 656 | if ( |
| 657 | composerAttachmentUploadBlockReason({ |
| 658 | environmentId: selectedThreadShell.environmentId, |
| 659 | attachments, |
| 660 | connected: selectedEnvironmentRuntime?.connectionState === "connected", |
| 661 | serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null, |
| 662 | states: appAtomRegistry.get(composerAttachmentUploadsAtom), |
| 663 | }) !== null |
| 664 | ) |
| 665 | return null; |
| 666 | if (text.length === 0 && attachments.length === 0) { |
| 667 | return null; |
| 668 | } |
| 669 | const modelSelection = draft.modelSelection ?? thread.modelSelection; |
| 670 | const serverConfig = selectedEnvironmentRuntime?.serverConfig; |
| 671 | const modelUnavailable = |
| 672 | selectedEnvironmentRuntime?.connectionState === "connected" && |
| 673 | isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId); |
| 674 | const alertModelUnavailable = () => { |
| 675 | const { title, detail } = describeUnavailableModelSelection( |
| 676 | serverConfig, |
| 677 | modelSelection, |
| 678 | thread.projectId, |
| 679 | ); |
| 680 | Dialog.alert(title, detail); |
| 681 | }; |
| 682 | // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely. |
| 683 | if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { |
| 684 | Dialog.alert( |
| 685 | m(msg("Too many attachments")), |
| 686 | m( |
| 687 | msg("Remove attachments until there are at most {max}.", { |
| 688 | max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 689 | }), |
| 690 | ), |
| 691 | ); |
| 692 | return null; |
| 693 | } |
| 694 | |
| 695 | const contextBlockReason = composerContextSendBlockReason(draft.context); |
| 696 | if (contextBlockReason) { |
| 697 | Dialog.alert(m(msg("Too much context")), contextBlockReason); |
| 698 | return null; |
| 699 | } |
| 700 | |
| 701 | // A redirect's text answers its approval, so `/side` there is that text, not the command. |
| 702 | const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null; |
| 703 | if (sideChatCommand) { |
| 704 | if (sideChatUnavailableReason !== null) { |
| 705 | Dialog.alert(m(msg("Side chat not started")), sideChatUnavailableReason); |
| 706 | } else if ( |
| 707 | sideChatCommand.prompt.length === 0 && |
| 708 | attachments.length === 0 && |
| 709 | (draft.context?.records.length ?? 0) === 0 |
| 710 | ) { |
| 711 | Dialog.alert( |
| 712 | m(msg("Ask a side question")), |
| 713 | m(msg("Type the question after {command}, then send it.", { command: "/side" })), |
| 714 | ); |
| 715 | } else if (modelUnavailable) { |
| 716 | alertModelUnavailable(); |
| 717 | } else { |
| 718 | startingSideChatRef.current = true; |
| 719 | // Cleared at send, like a queued message, so nothing in it can vanish mid-start. The |
| 720 | // holds keep the local files until the side chat has them or the draft has them back. |
| 721 | const fileHolds = attachments |
| 722 | .filter(isFileBackedComposerAttachment) |
| 723 | .map(retainComposerAttachmentFileForPreview); |
| 724 | clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true }); |
| 725 | const started = await settlePromise(async () => { |
| 726 | const prepared = await Effect.runPromise( |
| 727 | prepareTurnAttachments({ |
| 728 | environmentId: thread.environmentId, |
| 729 | attachments, |
| 730 | supportsImageUploads: true, |
| 731 | uploadAttachment: (attachment) => |
| 732 | uploadComposerAttachmentShared(thread.environmentId, attachment), |
| 733 | }), |
| 734 | ); |
| 735 | if (prepared.status !== "ready") return false; |
| 736 | return input.startSideChat( |
| 737 | { environmentId: thread.environmentId, threadId: thread.id }, |
| 738 | { |
| 739 | ...serializeComposerMessageForServer( |
| 740 | restoreAttachmentOnlyBootstrapPrompt( |
| 741 | sideChatCommand.prompt, |
| 742 | prepared.attachments.length > 0, |
| 743 | ), |
| 744 | uploadedComposerContext(draft.context, attachments, prepared.attachments), |
| 745 | ), |
| 746 | attachments: prepared.attachments, |
| 747 | titleSeed: deriveThreadTitleSeed({ text: sideChatCommand.prompt, attachments }, m), |
| 748 | }, |
| 749 | { |
| 750 | runtimeMode: draft.runtimeMode ?? thread.runtimeMode, |
| 751 | modelSelection, |
| 752 | }, |
| 753 | ); |
| 754 | }); |
| 755 | if (AsyncResult.isSuccess(started) && started.value) { |
| 756 | scheduleUnusedComposerAttachmentCleanup(attachments); |
| 757 | } else { |
| 758 | // Restore with uncapped append; a capped merge could drop attachments added meanwhile. |
| 759 | // A failed disk write still leaves the merged draft in memory, and the append saves again. |
| 760 | await mergeComposerDraftContent(threadKey, { |
| 761 | text: draft.text, |
| 762 | context: draft.context, |
| 763 | attachments: [], |
| 764 | }).catch(() => undefined); |
| 765 | appendComposerDraftAttachments(threadKey, attachments, { restore: true }); |
| 766 | if (AsyncResult.isFailure(started)) { |
| 767 | const error = squashAtomCommandFailure(started); |
| 768 | Dialog.alert( |
| 769 | m(msg("Side chat not started")), |
| 770 | error instanceof Error ? error.message : m(msg("Could not start a side chat.")), |
| 771 | ); |
| 772 | } |
| 773 | } |
| 774 | startingSideChatRef.current = false; |
| 775 | for (const release of fileHolds) release(); |
| 776 | } |
| 777 | return null; |
| 778 | } |
| 779 | // A redirect's text answers its approval, so /clear there is that text, not the command. |
| 780 | if ( |
| 781 | beforeDispatch === undefined && |
| 782 | selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.freshContext === true && |
| 783 | thread.latestRun != null && |
| 784 | attachments.length === 0 && |
| 785 | draft.context === undefined && |
| 786 | isClearComposerCommand(text) |
| 787 | ) { |
| 788 | setFreshSessionPending(threadKey, true); |
| 789 | clearComposerDraftContent(threadKey); |
| 790 | return null; |
| 791 | } |
| 792 | |
| 793 | if (modelUnavailable) { |
| 794 | alertModelUnavailable(); |
| 795 | return null; |
| 796 | } |
| 797 | const provider = serverConfig?.providers.find( |
| 798 | (entry) => entry.instanceId === modelSelection.instanceId, |
| 799 | ); |
| 800 | const feedbackCommand = |
| 801 | attachments.length === 0 && provider?.driver === "codex" |
| 802 | ? parseCodexFeedbackCommand(text) |
| 803 | : null; |
| 804 | if (feedbackCommand) { |
| 805 | if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)) |
| 806 | return null; |
| 807 | if (thread.activeProviderThreadId === null) { |
| 808 | Dialog.alert( |
| 809 | m(msg("Start a {provider} thread first", { provider: "Codex" })), |
| 810 | m(msg("Send a message before you submit feedback.")), |
| 811 | ); |
| 812 | return null; |
| 813 | } |
| 814 | const metadata = makeQueuedMessageMetadata(); |
| 815 | await submitCodexFeedback( |
| 816 | { |
| 817 | submission: { |
| 818 | id: MessageId.make(metadata.messageId), |
| 819 | command: text, |
| 820 | createdAt: metadata.createdAt, |
| 821 | }, |
| 822 | clearDraft: () => clearComposerDraftContent(threadKey), |
| 823 | onUpdate: (submission) => { |
| 824 | setFeedbackSubmissionsByThreadKey((current) => { |
| 825 | const existing = current[threadKey] ?? []; |
| 826 | const found = existing.some((entry) => entry.id === submission.id); |
| 827 | return { |
| 828 | ...current, |
| 829 | [threadKey]: found |
| 830 | ? existing.map((entry) => (entry.id === submission.id ? submission : entry)) |
| 831 | : [...existing, submission], |
| 832 | }; |
| 833 | }); |
| 834 | }, |
| 835 | upload: () => |
| 836 | uploadThreadFeedback({ |
| 837 | environmentId: thread.environmentId, |
| 838 | input: { threadId: thread.id, ...feedbackCommand }, |
| 839 | }), |
| 840 | }, |
| 841 | m, |
| 842 | ); |
| 843 | return null; |
| 844 | } |
| 845 | |
| 846 | if (beforeDispatch !== undefined) { |
| 847 | const response = await beforeDispatch( |
| 848 | text, |
| 849 | attachments.length > 0 || draft.context !== undefined, |
| 850 | ); |
| 851 | if (!response) return null; |
| 852 | // A context paste still landing, or any draft or settings change while approvals were |
| 853 | // declined, means this snapshot is no longer what the user sent. |
| 854 | if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null; |
| 855 | const current = getComposerDraftSnapshot(threadKey); |
| 856 | if ( |
| 857 | current.text !== draft.text || |
| 858 | JSON.stringify(current.context) !== JSON.stringify(draft.context) || |
| 859 | JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) || |
| 860 | current.runtimeMode !== draft.runtimeMode || |
| 861 | current.interactionMode !== draft.interactionMode || |
| 862 | current.attachments.length !== attachments.length || |
| 863 | current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id) |
| 864 | ) |
| 865 | return null; |
| 866 | if (response === "responded") { |
| 867 | clearComposerDraftContent(threadKey); |
| 868 | return null; |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | // Resolve at send time because outbox delivery may be delayed. |
| 873 | // Steering uses "auto" so an ended turn queues a run instead of restoring the draft. |
| 874 | // An approval redirect must steer the waiting turn instead of queueing behind it. |
| 875 | const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior; |
| 876 | const followUpAction = resolveComposerDispatchMode({ |
| 877 | running: activeThreadBusy && canSteerActiveTurn, |
| 878 | alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault, |
| 879 | activeTurnDefault, |
| 880 | }); |
| 881 | const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some( |
| 882 | (status) => status === "preparing" || status === "starting", |
| 883 | ); |
| 884 | const followUpDispatchMode = setupRunning |
| 885 | ? "queue" |
| 886 | : followUpAction === "auto" |
| 887 | ? null |
| 888 | : followUpAction === "queue" |
| 889 | ? "queue" |
| 890 | : "auto"; |
| 891 | |
| 892 | // A redirect belongs to the approval it answers; the armed session waits for the next message. |
| 893 | const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey); |
| 894 | const metadata = makeQueuedMessageMetadata(); |
| 895 | // A fresh session drops the context a compaction would summarize. Only a send the notice |
| 896 | // announced compacts, since the notice's minute clock can trail the exact deadline. |
| 897 | const compactBeforeSend = |
| 898 | compactTokens !== null && |
| 899 | !freshContext && |
| 900 | followUpDispatchMode === null && |
| 901 | appAtomRegistry.get(fullHistoryThreadKeysAtom)[threadKey] !== true && |
| 902 | resumeCompactionTokens(modelSelection, text, metadata.createdAt) !== null; |
| 903 | const messageId = MessageId.make(metadata.messageId); |
| 904 | onWillEnqueue?.(); |
| 905 | clearThreadComposerError(threadKey); |
| 906 | const enqueuePromise = enqueueThreadOutboxMessage({ |
| 907 | environmentId: selectedThreadShell.environmentId, |
| 908 | threadId: selectedThreadShell.id, |
| 909 | messageId, |
| 910 | commandId: CommandId.make(metadata.commandId), |
| 911 | text, |
| 912 | attachments, |
| 913 | context: draft.context, |
| 914 | modelSelection, |
| 915 | runtimeMode: draft.runtimeMode ?? thread.runtimeMode, |
| 916 | interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, |
| 917 | ...(compactBeforeSend |
| 918 | ? { compactBeforeSend, dispatchMode: "queue" as const } |
| 919 | : followUpDispatchMode === null |
| 920 | ? {} |
| 921 | : { dispatchMode: followUpDispatchMode }), |
| 922 | ...(freshContext ? { freshContext: true } : {}), |
| 923 | createdAt: metadata.createdAt, |
| 924 | }); |
| 925 | clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true }); |
| 926 | if (freshContext) setFreshSessionPending(threadKey, false); |
| 927 | enqueuePromise.then( |
| 928 | () => { |
| 929 | setKeepFullHistory(threadKey, false); |
| 930 | scheduleUnusedComposerAttachmentCleanup(attachments); |
| 931 | }, |
| 932 | (error: unknown) => { |
| 933 | // Restore with uncapped append; capped merge could drop attachments added during the failed write. |
| 934 | void mergeComposerDraftContent(threadKey, { |
| 935 | text, |
| 936 | context: draft.context, |
| 937 | attachments: [], |
| 938 | }); |
| 939 | appendComposerDraftAttachments(threadKey, attachments, { restore: true }); |
| 940 | if (freshContext) setFreshSessionPending(threadKey, true); |
| 941 | setThreadComposerError( |
| 942 | threadKey, |
| 943 | errorDisplayMessage(error, m) ?? m(msg("Failed to save the queued message.")), |
| 944 | ); |
| 945 | }, |
| 946 | ); |
| 947 | return messageId; |
| 948 | }; |
| 949 | |
| 950 | // Side chats do not nest or start from subagents, and need a server that forks them. |
| 951 | const sideChatUnavailableReason = (() => { |
| 952 | const serverConfig = selectedEnvironmentRuntime?.serverConfig; |
| 953 | if (selectedThreadShell?.lineage.sideChat === true) |
| 954 | return resolve(msg("Side chats cannot start side chats.")); |
| 955 | if (selectedThreadShell?.lineage.relationshipToParent === "subagent") { |
| 956 | return resolve(msg("Subagent threads cannot start side chats.")); |
| 957 | } |
| 958 | if (!selectedThreadShell || !serverConfig) { |
| 959 | return resolve(msg("Side chats are not ready yet. Try again in a moment.")); |
| 960 | } |
| 961 | if (serverConfig.environment.capabilities.sideChats !== true) { |
| 962 | return resolve( |
| 963 | msg("Update this environment's {product} server to use side chats.", { |
| 964 | product: "T3 Code", |
| 965 | }), |
| 966 | ); |
| 967 | } |
| 968 | if (selectedThreadCreation !== null) { |
| 969 | return resolve(msg("Side chats start after the first message.")); |
| 970 | } |
| 971 | if ( |
| 972 | orchestrationV2WorktreePending( |
| 973 | selectedThreadShell.worktreePath ?? null, |
| 974 | selectedThreadProjection?.projection.runs ?? [], |
| 975 | ) |
| 976 | ) { |
| 977 | return resolve(msg("Available once the thread's worktree is set up.")); |
| 978 | } |
| 979 | return null; |
| 980 | })(); |
| 981 | |
| 982 | /** Queues a standalone text command such as `/goal clear` and leaves the composer draft alone. */ |
| 983 | const onSendCommand = async (text: string) => { |
| 984 | if ( |
| 985 | !selectedThreadShell || |
| 986 | selectedThreadCreation !== null || |
| 987 | (selectedEnvironmentRuntime?.connectionState === "connected" && |
| 988 | !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)) |
| 989 | ) { |
| 990 | return null; |
| 991 | } |
| 992 | const thread = selectedThreadShell; |
| 993 | // Goal commands belong to the thread itself, not the model or modes picked in the draft. |
| 994 | const modelSelection = thread.modelSelection; |
| 995 | const serverConfig = selectedEnvironmentRuntime?.serverConfig; |
| 996 | if ( |
| 997 | selectedEnvironmentRuntime?.connectionState === "connected" && |
| 998 | isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId) |
| 999 | ) { |
| 1000 | const { title, detail } = describeUnavailableModelSelection( |
| 1001 | serverConfig, |
| 1002 | modelSelection, |
| 1003 | thread.projectId, |
| 1004 | ); |
| 1005 | Dialog.alert(title, detail); |
| 1006 | return null; |
| 1007 | } |
| 1008 | const metadata = makeQueuedMessageMetadata(); |
| 1009 | const messageId = MessageId.make(metadata.messageId); |
| 1010 | await enqueueThreadOutboxMessage({ |
| 1011 | environmentId: thread.environmentId, |
| 1012 | threadId: thread.id, |
| 1013 | messageId, |
| 1014 | commandId: CommandId.make(metadata.commandId), |
| 1015 | text, |
| 1016 | restoreToDraft: false, |
| 1017 | attachments: [], |
| 1018 | modelSelection, |
| 1019 | runtimeMode: thread.runtimeMode, |
| 1020 | interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, |
| 1021 | createdAt: metadata.createdAt, |
| 1022 | }); |
| 1023 | return messageId; |
| 1024 | }; |
| 1025 | |
| 1026 | const onChangeDraftMessage = (value: string) => { |
| 1027 | if (!selectedThreadShell) { |
| 1028 | return; |
| 1029 | } |
| 1030 | |
| 1031 | const threadKey = activeComposerDraftKey(selectedThreadShell); |
| 1032 | setComposerDraftText(threadKey, value); |
| 1033 | }; |
| 1034 | |
| 1035 | const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } = |
| 1036 | useComposerAttachmentActions({ |
| 1037 | draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null, |
| 1038 | serverConfig: selectedEnvironmentRuntime?.serverConfig, |
| 1039 | }); |
| 1040 | |
| 1041 | const onRemoveDraftImage = (imageId: string) => { |
| 1042 | if (!selectedThreadShell) { |
| 1043 | return; |
| 1044 | } |
| 1045 | |
| 1046 | const threadKey = activeComposerDraftKey(selectedThreadShell); |
| 1047 | removeComposerDraftAttachment(threadKey, imageId); |
| 1048 | }; |
| 1049 | |
| 1050 | return { |
| 1051 | feedbackSubmissions, |
| 1052 | dismissFeedback, |
| 1053 | selectedThreadFeed, |
| 1054 | selectedThreadActivityRun, |
| 1055 | selectedThreadAnnouncedRun, |
| 1056 | selectedThreadDetailBehindShell, |
| 1057 | selectedThreadQueueCount, |
| 1058 | selectedThreadQueuedMessages, |
| 1059 | dispatchingQueuedMessageId, |
| 1060 | activeWorkStartedAt, |
| 1061 | runlessWorkActive, |
| 1062 | extensionStatuses: deriveProviderExtensionStatuses( |
| 1063 | selectedThreadProjection?.projection ?? null, |
| 1064 | ), |
| 1065 | providerSubagentStatus, |
| 1066 | isCompacting, |
| 1067 | compactBeforeSend: |
| 1068 | compactTokens === null || selectedThreadKey === null |
| 1069 | ? null |
| 1070 | : { |
| 1071 | tokens: compactTokens, |
| 1072 | keepFullHistory, |
| 1073 | toggleKeepFullHistory: () => setKeepFullHistory(selectedThreadKey, !keepFullHistory), |
| 1074 | }, |
| 1075 | composerDraftKey, |
| 1076 | followUpBehavior, |
| 1077 | canSteerActiveTurn, |
| 1078 | queueHeld, |
| 1079 | resumableRunId, |
| 1080 | canResume, |
| 1081 | queuedRunEdit, |
| 1082 | isSavingQueuedEdit, |
| 1083 | cancelQueuedRunEdit, |
| 1084 | onRemoveQueuedEditAttachment, |
| 1085 | modelSelection, |
| 1086 | pendingHandoff, |
| 1087 | canSwitchThreadProvider, |
| 1088 | runtimeMode, |
| 1089 | interactionMode, |
| 1090 | activeThreadBusy, |
| 1091 | interruptibleRunId, |
| 1092 | onChangeDraftMessage, |
| 1093 | onPickDraftMedia, |
| 1094 | onPickDraftFiles, |
| 1095 | onNativePasteImages, |
| 1096 | onNativePasteText, |
| 1097 | onRemoveDraftImage, |
| 1098 | onSendMessage, |
| 1099 | onSendCommand, |
| 1100 | sideChatUnavailableReason, |
| 1101 | }; |
| 1102 | } |